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: verified delivery and honest write surfaces (v1.95.0) (#280)
Serg Eroshe88c118aa4644
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex f49101b5..cabd946d 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.94.0",+ "version": "1.95.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 4b55a9e3..44865ab6 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.94.0",+ "version": "1.95.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/CHANGELOG.md b/CHANGELOG.mdindex 234df34d..d53f3528 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,22 @@ 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.95.0] - 2026-10-27++Open Second Brain 1.95.0 is the verified delivery and honest write surfaces release: every surface that hands an agent context or writes on its behalf now states what it actually did - what was trimmed from a delivered pack, what was injected and never consulted by the answer, what a privacy reservation held back from an export, what failed part way through a multi-artifact write and how to finish it. The delivery side gains an opt-in score-aware tail trim that names every drop and offers the freed budget back by priority, and a reply-presence receipt that joins what a session injected to what its answer verifiably used. The capture side keeps its failures recoverable - the dead-letter record freezes the payload it failed on and one command re-runs it - and gains a standalone commit-blocking validation gate for writers no hook reaches. The organization side moves whole folders under the same occupancy-checked, failure-naming discipline the file surface set, every shared export names the pages a privacy reservation held back, and the operator surfaces state exactly what they can and cannot measure: the search writer lock reads held, free, or unknown - never a guessed free - and the doctor's client-version probe reports what it could not read instead of failing the machine.++### Added++- **Score-aware tail trim for delivered context-pack evidence.** With `tail_trim_context_pack: "true"` in the machine-local main config (or the env override `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`; default off), `brain_context_pack` - MCP only; the o2b brain context-pack verb never reads the gate - runs one score-aware trim over the unified tier-and-budget walk whenever the call carries a query: the top three delivered items are immune, any later item whose query-term coverage - the fraction of the query's tokens it carries - is at least 0.8 of the top delivered score is kept - it restates the question's terms nearly as fully as the top hit - and the rest drop whole with a `tail-trim` skip reason, never partially re-cut. The freed budget is then offered back to `over-budget` candidates in priority order, the only path by which a page can cross tiers, spending the tokens the trim freed and no more, and never reordering or dropping the synthesized attention item. The response carries a conditional `tail_trim` block (`dropped`, `kept_by_query_terms`, `rescued`, `tokens_saved`) only when the trim actually ran, counted over the items that actually ship; the same four counters ride the `context_receipt`'s `budget` block and the `context_pack` telemetry record's `metadata`, and each dropped item's skip reason surfaces as the telemetry gap `tail_trim`. With the key off - the default - packs are byte-identical, and the `packing_policy` branch never trims.+- **Reply-presence receipts join what was injected to what the answer used.** The answer-quote-check Stop hook now folds one session-keyed `reply_presence` continuity record per checked turn, beside the annotation it already wrote: a verdict per injected note - `verified` when a reply span checked out against it, the strongest miss verdict otherwise, and `absent` for a note that was injected into context but that no reply span was ever measured against, the row this record exists to surface; a span that verifies records only the note that carries it, so an uncited span's other candidates are never named by a verdict that is not theirs. Exactly one record per checked turn, written even when every span verified, and only when the turn had injected candidates at all; the payload carries identifiers, the per-note verdicts, the reply-span count and a hash binding the verdicts to the exact answer text checked - never the answer text itself. The verdict vocabulary gains a sixth member, `absent`, which is per-note presence only: every span still gets one of the five original verdicts, so a consumer reading per-span outcomes never sees it. The receipt read surfaces join on it: `o2b brain context-receipts show` and the MCP `brain_context_receipts` `show` answer with a join matched by exact `session_id` and folded over every presence record the session wrote at or after the receipt's own creation, chronologically, with `verified` winning across turns - `absent` never upgrades or downgrades one - and the folded rows restricted to the notes the receipt itself injected; a receipt with no readable record in that window names the `unjoined` outcome honestly, saying which of the two it was: a receipt that names no session at all, or one whose session wrote no record at or after it. `list` stays a summary.+- **`session_inject` receipts carry the session key.** The SessionStart active-inject receipt records the payload's real session id as its `session_id` member - the join key the reply-presence read matches on - and stays absent when the host sent nothing real, never invented. Receipts written before this release carry no key and read as unjoined, which is what they are.+- **Privacy-marker denials are named in every shared export.** A preference the privacy deny markers reserve (`visibility: private`, or an informal marker saying the same) now leaves the `o2b brain export` json and llms-txt preference dumps and the `o2b brain bank-export` bundle before their bytes are composed, is blocked by the knowledge pack's selection step beside the existing `visibility` and `owner` blocks, and is withheld from the static `o2b brain explorer --export` HTML too: the export narrows its graph by the same denial judgment over its preference and retired nodes, the node count answers for what was actually written, and the same stderr notice names what stayed out - while the live server, the operator's own view, keeps every node. Every lane names what it held back: the json envelope carries an `omitted` field and the bundle a `preferences_omitted` report (the pack names the page in its `blocked` list), the stderr notice names each denied row with the frontmatter key that denied it (`denied_by`: `visibility`, `access`, `confidentiality` or `sensitivity`), and every field is absent when nothing was denied - a vault with no reservations produces byte-identical output, so a smaller export is never a silent one. `bank-export --include-reserved` is the one override for the reservation itself, for this verb's documented purpose - the one-file personal backup - and carries the reserved rows into the bundle whole, with an inclusion notice naming each carried row and the flag where the denial notice would have been; the default run is unchanged. And the SDK facade carries `exportPreferencesLlmsTxtDetailed` beside its string-only form, returning the same text beside the omission report the json envelope names, so an in-process caller no longer watches reserved rows leave the text silently; the string form is deprecated and keeps its exact bytes.+- **`o2b brain dead-letters`: the failed extraction write gets an exit.** A multi-artifact extraction write that failed part way already left a durable dead-letter record; the letters were write-only. The dead-letter schema moves to v2 and freezes the failing payload into the letter, so what the write meant to land survives the failure - each frozen item redacted at freeze time by the same redaction the write path runs, with the raw-text dedup hash stored beside it so a recovery still dedups against the original identity, and `list --json` rows carrying only `has_payload`, so the bulk surface agents and cron logs read never prints a payload (`show --json` keeps the frozen items for the operator's one-letter read); v1 letters (written before the payload was frozen) parse unchanged and classify `re-extract`. The new verb lists every letter with its classification - `recover` (the session is still capture-classified with undelivered missing items), `pending` (the items sit staged in the write-approval queue), `re-extract`, `not_recoverable`, `resolved` (every missing key exists on disk) - and the exact copy-paste command that resolves it; a letter whose every undelivered item the durability gate will never accept classifies `not_recoverable` before any command promises a re-run, with the gate and its denial named. `show <id>` prints one letter in full, missing keys and frozen payload named; `recover <id>` re-runs a schema-2 letter's frozen payload through the extraction commit at CURRENT vault state, where a v2 item counts as delivered on its stored hash or - the v1 topic measure, extended to v2 - when the session already holds a signal page on its topic, and a topic-delivered item is left out of the plan and the apply entirely, so a re-extract's reworded text is never replayed as a second signal while already-written items still dedup away. Recover is dry-run by default and previews the per-item verdicts; `--apply` performs the re-run and requires `--yes` under `--json` or a non-TTY stdin, and an apply that comes back with nothing written and nothing staged exits 1 naming the accounting instead of printing a green zero-write success; a frozen vault refuses and an unknown id is a usage error. NOTHING here deletes a letter: a recovered letter is retained, and removing it stays an operator's hand action on the named file.+- **`o2b brain validate`: a standalone, commit-blocking validation gate for hook-less writers.** A writer with no hook harness had no way to block its own commit - `brain lint` always exits 0. The new gate runs the exact write-receipt page lint over exactly one caller-named page set - `--paths <path>` (vault-relative, repeatable, one flag per page) or `--dirty` (every git-dirty Markdown note: modified, added and untracked) - and nothing else, so it is safe inside any gate. The exit code is the product, byte-for-byte the doctor contract: an error finding exits 1, warnings exit 2 under `--strict`, a named page the lint could not read exits 1, clean exits 0; a vault that is not inside a git worktree - or that its enclosing repository ignores, where git cannot measure dirt at all - refuses `--dirty` with exit 2 naming `--paths` as the remedy, and giving neither or both selectors is a usage error. Report-only: the fixes stay with `brain doctor --repair --apply` and `brain lint --consolidate --apply`, which every finding's `next_command` names.+- **Whole-folder move and rename on the note-lifecycle surface.** `o2b brain note-lifecycle move-folder` relocates a whole folder under a destination parent and `rename-folder` renames it within its parent - split for the same reason the file `rename` and `move` are split, so a caller that meant one and spells the other is refused `wrong_action` rather than moved by accident - and the MCP `brain_note_lifecycle` tool accepts both through the same action enum. The folder surface mirrors the file envelope rung for rung (vault-relative, no traversal, the `Brain/` machinery root refused, the vault-identity write guard) minus the `.md` requirement, and every destination is checked free BEFORE the first rename - the closest thing to atomicity the operation honestly has - so an occupied destination refuses with nothing moved and the source untouched. The move set is the folder's Markdown only, judged by where a file really lives: a symlinked directory or note under the source is excluded and named in the receipt's residue instead of being pulled into the move or hard-linked into a dangling name, a source reached through an alias moves under its real name, and the destination-inside-source guard compares real paths, so an alias of the source is refused as nesting rather than linked into itself. The rename-intent reading applies only when the named destination directory does not exist - an existing sibling folder is a real move target, movable in one call. Because a folder move never changes a basename, the move set's inbound path-spelled wikilinks are rewritten in one pass over the successfully moved set, to the minimal spelling that still resolves; bare-basename links are untouched and keep resolving, and the receipt names the settled cost of a Markdown-only move: what stayed behind in the source folder (`left_behind`, absent when the folder emptied) and, per moved note, the relative Markdown links and images whose targets stayed behind (`dangling_relative_links`, absent when nothing dangles), so a zero rewrite count never reads as nothing broke. There is no rollback, on purpose and by name: a mid-set failure is named per file in `moveFailures` with the pairs computed from what actually moved, never a silently shorter move. Dry-run is the default.+- **The operator surfaces state what they measure about the store and the clients.** `o2b brain status` gains a `store` group: the search writer lock's three-state read - `held` (a live writer holds it, with its age), `free` (no live holder at the instant of the read), `unknown` (the probe could not be taken, with the reason) - a state that could not be measured is never rendered as `free`; `thisCaller: "read-only"` states the snapshot's own standing, and while a lock is held the line scopes its refusal warning to the writes the lock gates - an index write (`o2b search index` / reindex) would refuse with `INDEX_LOCKED`, while vault and memory writes serialize on the brain lane's own lock files and are not gated by it; and `writerLockOwner` is `null` while a lock is held because the lock record carries no identity - a measurement, not an omission, and the renderer says so. A held lock is informational and never flips the snapshot unhealthy, and the MCP `brain_status` withholds the resolved lock path below local reach while keeping every state field. `o2b doctor --readiness` gains the `client_versions` probe: each detected agent client is asked its version through its own version argv under the per-probe timeout, one row per target - `pass` with the raw first stdout line, `unknown` naming why (a thrown runner, a non-zero exit, a timeout, empty stdout), or `skipped` when the target has no version command. The ask settles on the child's own exit rather than on stdout closing, so a forked helper that inherits the pipe cannot turn an answered version into a timeout, and a client that outlives the cut is SIGKILLed after the TERM grace, so nothing the probe spawned outlives doctor. An all-unknown probe keeps doctor at exit 6, never 1, because a version it cannot read proves nothing broken.+- **Docs:** `docs/cli-reference.md` gains the `o2b brain dead-letters` and `o2b brain validate` rows, the `move-folder`/`rename-folder` actions on the note-lifecycle row, the tail trim on the context-pack row, the reply-presence join on the context-receipts row, the denial naming on the export and bank-export rows, the store group on the brain status row and the client_versions probe on the doctor row; `docs/mcp.md` documents the `tail_trim` block on `brain_context_pack`, the `reply_presence` join on `brain_context_receipts` `show`, the folder actions on `brain_note_lifecycle`, the `brain_status` store group and the CLI-only validate/dead-letters pointer for hook-less agents; `docs/observability.md` states the tail-trim telemetry counters; `docs/how-it-works.md` describes the trim engine; `hooks/README.md` documents the reply-presence record on the Stop row, the session key on the SessionStart receipt and the transcript-availability caveat; the CLI help surfaces (command manifest and `o2b brain --help`) name the folder actions.+## [1.94.0] - 2026-10-26Open Second Brain 1.94.0 gives the continuity ledger its intended readback path. The Hermes provider's native memory writes have been mirrored into the ledger as durable, attributable records for some time, but the ledger was write-only for recall purposes: a fact the host wrote could be exported for audit and never recalled by the memory system itself. The new `o2b brain continuity promote` verb turns those records into ordinary preference pages, dry-run by default and sealed by an approval digest on apply, so a mirrored fact becomes recallable only through a review that says exactly what will land. The ledger itself stays write-only audit substrate, and the full-fidelity export keeps its job.@@ -8750,6 +8766,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.95.0]: https://github.com/itechmeat/open-second-brain/compare/v1.94.0...v1.95.0[1.94.0]: https://github.com/itechmeat/open-second-brain/compare/v1.93.0...v1.94.0[1.93.0]: https://github.com/itechmeat/open-second-brain/compare/v1.92.0...v1.93.0[1.92.0]: https://github.com/itechmeat/open-second-brain/compare/v1.91.0...v1.92.0diff --git a/docs/brainstorm/verified-delivery-honest-writes/cli-output/consultant.md b/docs/brainstorm/verified-delivery-honest-writes/cli-output/consultant.mdnew file mode 100644index 00000000..10a163f8--- /dev/null+++ b/docs/brainstorm/verified-delivery-honest-writes/cli-output/consultant.md@@ -0,0 +1,77 @@+Consultant ran as the host orchestrator's in-session subagent (host execution mode); no external CLI was invoked.++### Variant A1: In-walker trim with comparator score reuse; presence as a sibling continuity record+- **Approach**: The trim runs after the unified walker in `packContext`, reusing the ranked-mode jaccard kernel (`relevanceById`) the comparator already computes: top-3 keep, restatement keep-rule at a fixed fraction, whole-item drops with a new `"tail-trim"` skip reason, and freed budget offered back to `over-budget` candidates in priority order behind a config flag that defaults off. Reply presence is folded by the existing answer-quote-check Stop loop into a sibling `reply_presence` continuity record joined to the context receipt by `session_id`, extending `ANSWER_QUOTE_VERDICT` with `absent` and fixing the `session_inject` receipt's missing session key at the source.+- **Trade-offs**:+ - Pros: zero duplicate scoring work and a byte-identical off-path; the context receipt stays automatically correct because finalize maps `report.items`; rescue is expressible because skipped candidates are still in hand; one verdict vocabulary and an append-only record respect the store's contract; the join key is fixed at the source, not inferred from time windows.+ - Cons: covers the unified path only until extended to the `packingPolicy` branch (out of v1); a new continuity kind obligates the fold-decision row and a documented join contract; presence rows grow the ledger per checked turn.+- **Complexity**: medium+- **Risk**: low++### Variant A2: Post-finalize delivery stage; presence via the existing log channel+- **Approach**: Apply the trim inside `finalizeContextPackReport` over `report.items`, uniformly across the unified and packing-policy return paths. Carry reply presence only through the channels the Stop hook already writes - the `additionalContext` annotation and the enforce-mode Brain-log `note` event - with no new continuity kind.+- **Trade-offs**:+ - Pros: one trim site covering both return paths; no new record kind, fold decision or join contract; the ledger stays quieter.+ - Cons: rescue is impossible at that point - skipped candidates are resolved and their budget accounting closed, so the card's term-aware rescue cannot exist; substring and semantic modes need score recomputation at finalize; Brain-log events are local, unsynced and unread by the receipt surface, so `brain_context_receipts` cannot serve presence; the enforce log exists only under `enforce`, so shadow-mode operators get nothing.+- **Complexity**: medium+- **Risk**: high++### Recommended: Variant A1+**Rationale**: The rescue rule and the receipt join are the two behaviors the cards name as their value, and only A1 can express either: rescue needs the walker's live skip list, and presence needs a store the receipt read surface can join against. A1 also reuses both verified seams with no duplicated computation, and its costs are census-silent or single-row decisions.++### Variant B1: Collector-level denial with named omissions everywhere+- **Approach**: Compute the denial once in `collectPreferenceRows` from the frontmatter map the collector already parsed, as a report beside complete `rows`; teach the json envelope (additive `omitted`, absent when empty), a detailed llms-txt variant, the bank bundle and the knowledge pack to drop denied rows and name each omission with reason `"visibility"`, with no override flag.+- **Trade-offs**:+ - Pros: one deny judgment reused by every consumer; `rows` stays complete so import-side topic maps keep seeing every preference; shared surfaces name their omissions per the v1.92.0 convention; byte-identity holds because `omitted` is absent-when-empty; SDK signatures stay stable behind delegating detail functions.+ - Cons: touches five source files across the shared surfaces; the bundle consistency extension is wider than the validator's narrowest reading; the absent-when-empty discipline needs its own pins.+- **Complexity**: medium+- **Risk**: low++### Variant B2: Verb-layer filtering+- **Approach**: Leave the collectors untouched; filter denied preferences inside `brain export` and `brain bank-export` by re-reading frontmatter at the verb layer, with the knowledge pack left as-is.+- **Trade-offs**:+ - Pros: the core export module and its envelope schema stay untouched; zero byte-identity pressure; the smallest diff for the CLI lane alone.+ - Cons: the SDK façade and `exportBankBundle` call the collectors directly, so those shared surfaces keep shipping marked preferences - the exact failure mode the card names; frontmatter is parsed twice per file; the knowledge pack keeps carrying rows every other lane denies, so surfaces disagree; the deny logic lives where it is hardest to test.+- **Complexity**: small+- **Risk**: high++### Recommended: Variant B1+**Rationale**: The card's value is a privacy class honored by shared surfaces, and B2 leaves the SDK and bundle lanes leaking by construction. B1 computes the deny once at the seam where the data is already in hand and makes every consumer name what it leaves out; its extra breadth is three small, independently testable surfaces.++### Variant C1: New flat verbs with a core classifier module+- **Approach**: `o2b brain dead-letters` (list/show/recover) over a new core `dead-letter-recovery.ts` classifier, with dead-letter schema v2 freezing the payload at failure time and v1 letters classifying as re-extract; `o2b brain validate` as a read-only selection-driven gate (`--paths`/`--dirty`) reusing the write-receipt page-lint pass verbatim behind a tiny git-dirty helper. One lane owns the four CLI wiring files.+- **Trade-offs**:+ - Pros: each surface carries one contract - the recovery verb can implement the consent ladder without negotiating with a pinned behavior; the classifier is core-testable over fixture vaults; validate's exit code is unambiguous; manifest rows make both verbs discoverable through the derived help surfaces for free.+ - Cons: two new verbs and four wiring rows to land; both cards' mechanical edits concentrate in one lane's wiring files.+- **Complexity**: medium+- **Risk**: low++### Variant C2: Overload the existing verbs+- **Approach**: Recovery as a subcommand of `brain repair-lane`; validation as `--paths`/`--dirty` flags on `brain lint`, changing its exit code to block.+- **Trade-offs**:+ - Pros: no new manifest rows or wiring edits; repair-lane is an established destructive-consent surface; lint already runs non-interactively.+ - Cons: repair-lane is memory-graph repair - dead extraction writes are a different domain with a different retention rule; lint's always-exit-0 report contract is pinned by tests and relied on by callers, so repurposing it is a breaking change smuggled into a flag; validate would inherit `--consolidate`'s required-flag grammar it does not use; the recovery verb still needs its own dry-run/apply grammar, so the overload saves nothing.+- **Complexity**: medium+- **Risk**: high++### Recommended: Variant C1+**Rationale**: Both cards are new operator surfaces with new contracts; the flat-verb convention plus manifest-derived help make new verbs cheaper than overloads that break lint's pinned exit contract. The wiring-file concentration is real but is exactly what the lane ownership rule absorbs.++### Variant D1: Extensions on the existing surfaces+- **Approach**: Two folder actions on the note-lifecycle verb and MCP tool, backed by a new core module that reuses the relocation primitive and the pair-list rewrite engine; the status `store` group inside the operator snapshot with an injected lock-probe seam; a `client_versions` probe appended to the readiness registry beside `registered_commands`, fail-soft over the install manifest with an async spawn.+- **Trade-offs**:+ - Pros: the file surface's rename/move mistake-guard extends to folders from day one; occupancy pre-flight, partial-failure reporting and the count guard keep their established meanings; the snapshot already resolves the dbPath and additive fields flow to MCP with zero plumbing; the probe inherits the timeout machinery, grading vocabulary and manifest detection; none of it needs the CLI wiring files another lane owns.+ - Cons: the lifecycle module gains the action vocabulary in an already large file (mitigated by putting the core logic in a new module); the snapshot field must be documented as search-lock-scoped; the version command table needs per-adapter verification beyond the two confirmed binary names.+- **Complexity**: medium+- **Risk**: low++### Variant D2: Dedicated new surfaces+- **Approach**: A new `brain folder` verb with its own MCP tool for folder operations; a separate `brain lock-status` verb for store ownership; a standalone `--client-versions` doctor flag outside the probe registry.+- **Trade-offs**:+ - Pros: zero contact with existing modules' shapes; each surface ships independently.+ - Cons: a new folder verb duplicates the envelope, relocation and rewrite machinery note-lifecycle already composes, and a new verb requires exactly the wiring files assigned to the capture-writes lane - structurally non-viable under the ownership rule; a lock-status verb re-composes the snapshot it already builds to answer one question a group can carry; a doctor flag outside the registry drifts from the shared timeout, grading and reporting machinery.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant D1+**Rationale**: All three cards ask for visibility on surfaces operators already use, and D1 is the only variant that respects both the surface economy and the lane contract: extensions carry the established guards, reporting shapes and census discipline with additive fields, while D2 would need another lane's wiring files and would fragment three surfaces that are already composed.diff --git a/docs/brainstorm/verified-delivery-honest-writes/cli-output/prompt.md b/docs/brainstorm/verified-delivery-honest-writes/cli-output/prompt.mdnew file mode 100644index 00000000..603f6f3a--- /dev/null+++ b/docs/brainstorm/verified-delivery-honest-writes/cli-output/prompt.md@@ -0,0 +1,70 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Release wave cycle-20261026 for Open Second Brain, branch `feat/verified-delivery-honest-writes`. Eight kanban cards, grouped into four implementation lanes that must have disjoint file sets. The wave theme: verified delivery and honest writes - every surface states what it measured, classified or refused instead of staying silent.++Lane A - delivery:+- `t_cb6a5558` Score-aware tail trim for delivered evidence that keeps query restatements. Today the context-pack comparator sorts tier above query relevance (`src/core/brain/context-pack.ts:925-948`) and the budget walker reports only `over-budget` skips (1205-1223), while the ranked-mode jaccard scorer (897-905) already computes query-term overlap. Upstream ships an opt-in trim with delivered-token telemetry.+- `t_f8510c55` Receipts that confirm injected memories appear in the agent reply. Delivery receipts stop at rendering (`src/core/brain/context-receipts.ts:149` records a final-text hash); a Claude Code Stop hook (`hooks/answer-quote-check.ts`, registered in `hooks/hooks.json:159`) already reads the turn's assistant messages and checks quoted spans against the injection ledger. Per-injected-note presence verdicts do not exist. The continuity ledger is append-only.++Lane B - export privacy:+- `t_b88c2190` Per-memory privacy markers honored by shared surfaces. Narrowed by the validator: the knowledge pack already blocks privacy-marked pages (`pageBlockReason`, `src/core/brain/portability/knowledge-pack.ts:421-436`); the one residual lane is the preferences bank/llms-txt export (`src/core/brain/export.ts`), which filters by status only. Teach it the existing deny markers (`visibility: private` token, informal `access`/`confidentiality`/`sensitivity` markers); do not invent a new privacy class.++Lane C - capture writes:+- `t_50794f57` One-command recovery for dead extraction writes. Dead letters (`src/core/brain/dead-letter.ts`, schema 1, lane union with one member) name the payload but carry no classifier and no command; `listDeadLetters` has zero non-test callers. The signal lane has no revision counter - concurrency is a content-derived dedup hash, so re-admission means re-running the recorded payload at current vault state. Retention rule: nothing deletes a letter.+- `t_dc782fd5` Standalone validation gate for hook-less agents. `brain lint` always exits 0 even with findings (`src/cli/brain/verbs/lint.ts:31`); doctor exits non-zero but is a whole-vault pass with no file selection. The write-receipt page-lint pass (`lintPagesWithContext`, `src/core/brain/page-lint.ts:863`) is directly callable over a path set; no git-dirty helper exists.++Lane D - operator surfaces:+- `t_9571a47f` Folder-level note moves with inbound link rewriting. Note lifecycle is per file; `src/core/brain/notes/lifecycle.ts:623` refuses any rename that changes directory. The rewrite engine `retargetWikilinks` already applies a list of path pairs in one vault walk. No folder verb exists.+- `t_cfe2ce5d` Status surfaces which process owns the memory store and that this caller is read-only. `isWriterLockHeld` (`src/core/search/store/writer-lock.ts:74`) is called by nothing in status; the lock is a bare `proper-lockfile` directory carrying no owner identity (mtime only). The operator snapshot (`src/core/brain/operator-snapshot.ts`) composes doctor, hygiene and state health with no store field.+- `t_8e49ec96` Doctor reports the installed version of each detected agent client. The `registered_commands` readiness probe (`src/core/doctor-readiness.ts`) only resolves executables into resolves/absent/unresolved; nothing reports a client's own version. Version probing must be read-only and fail soft (unknown on no answer).++# Project context++Open Second Brain - a memory layer for AI agents living in an Obsidian vault. Bun + TypeScript; tests via `bun test`; formatter `oxfmt`, linter `oxlint`; CLI `o2b`; MCP servers plus lifecycle hooks reach one core.++Recent commits:+- b784126f chore(deps): bump the github-actions group with 2 updates (#276)+- c435bee9 chore(deps-dev): bump the bun-minor-and-patch group with 2 updates (#275)+- 61a7ff1d feat: continuity promote - the host-memory readback path for mirrored host memory writes (v1.94.0) (#278)+- 3064defd feat: embedding-window chunk fit, sharded retirement links, decision-model provider chain and local thresholds, self-healing launchers (v1.93.0) (#274)+- 5572997d feat: write-time honesty and egress consent (v1.92.0) (#273)++Related files:+- src/core/brain/context-pack.ts, src/core/config.ts, src/mcp/brain/pack-tools.ts (Lane A, trim)+- hooks/answer-quote-check.ts, src/core/brain/continuity/types.ts, src/core/brain/context-receipts.ts, hooks/active-inject.ts (Lane A, presence)+- src/core/brain/export.ts, src/core/brain/portability/knowledge-pack.ts, src/core/brain/portability/bundle.ts (Lane B)+- src/core/brain/dead-letter.ts, src/core/brain/extract-signals.ts, src/core/brain/page-lint.ts (Lane C)+- src/core/brain/notes/lifecycle.ts, src/core/search/store/writer-lock.ts, src/core/brain/operator-snapshot.ts, src/core/doctor-readiness.ts (Lane D)+- CLI wiring shared by any new verb: src/cli/brain.ts, src/cli/brain/verbs/index.ts, src/cli/command-manifest.ts, src/cli/brain/help-text.ts++Conventions:+- Config flags: `resolveConfigFlag(envKey, configKey, configPath)`, default off, absent option byte-identical; MCP-first (no CLI flag follows the query_mode, packing-policy and entity-facts precedents).+- Closed vocabularies are census-registered; entries self-derive from the source constants, so extending a registered vocabulary needs no census edit, but a new vocabulary or a new continuity record kind does (a new kind requires a fold-decision row or the fold-decision census fails).+- Destructive verbs follow the consent ladder: dry-run default, `--apply` requiring `--yes` under `--json` or non-TTY, frozen-vault and vault-identity guards.+- Exports name every omission (v1.92.0 convention: `blocked` arrays, stderr omission notices in the `contentClassOmissionNotice` shape); nothing shrinks silently.+- Partial-failure doctrine: a rewrite that could not be written is named, never rolled back.+- New verbs are flat (`o2b brain dead-letters`, not nested nouns); manifest rows feed derived help and completions tests.++Constraints:+- The four lanes must own disjoint file sets; the four CLI wiring files above may be owned by at most one lane.+- No new external dependencies. No change to the locking strategy, the append-only continuity store, or the closed dead-letter lane union.+- Honest reporting: a fact not measured is reported as unknown, never inferred (lock owner, presence joins).++# Required output format++The wave has four lanes. For EACH lane, produce exactly 2 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the two variants of each lane, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the other, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/verified-delivery-honest-writes/design.md b/docs/brainstorm/verified-delivery-honest-writes/design.mdnew file mode 100644index 00000000..f8d32374--- /dev/null+++ b/docs/brainstorm/verified-delivery-honest-writes/design.md@@ -0,0 +1,117 @@+# Cycle 20261026 - verified delivery and honest writes: what the delivery trims, what the reply contained, what the store refuses to leak, and what every write surface admits++**Status:** draft+**Author:** orchestrator (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain's delivery and write surfaces stop one step short of the truth in eight places. Delivery bounds context packs with a tier-dominant budget, so a peripheral page restating the agent's question is dropped before a core page that does not, and nothing records whether an injected memory ever surfaced in the agent's reply. The preferences bank and llms-txt export filter by status only, so a rule the operator marked private rides out to shared surfaces that every other exporter already blocks. Dead extraction writes leave durable letters that name their payload but offer no classification and no one-command recovery, and an agent that patches vault files outside a hook or tool call has no gate that exits non-zero. The operator status says nothing about who holds the writer lock or that the status caller itself is read-only, folder reorganization must move notes one file at a time through a surface that refuses directory changes, and doctor resolves client commands without reporting which version of each client answered. Every one of the eight features replaces one of those silences with a measured, classified or scope-honest fact.++## Scope++Eight features, each with its kanban card, grouped into four implementation lanes:++- `t_cb6a5558` (Lane A) - Score-aware tail trim for delivered evidence: a config-gated trim after the tier gate that keeps the top 3 delivered items and any tail item whose query-term overlap nearly matches the top hit, drops the rest whole as a new `tail-trim` skip reason, and offers the freed budget back to `over-budget` candidates in priority order; telemetry reports dropped, kept-by-query-terms, rescued and tokens-saved.+- `t_f8510c55` (Lane A) - Reply-presence receipts: the answer-quote-check Stop hook folds per-injected-note presence verdicts (including an explicit `absent` for notes no reply span touched) into a sibling continuity record joined to the context receipt by `session_id`; the `session_inject` receipt gains its missing `session_id`.+- `t_b88c2190` (Lane B) - The preferences bank/llms-txt export learns the existing privacy deny markers: `visibility: private` and the informal `access`/`confidentiality`/`sensitivity` markers deny a preference from every shared lane (json export, llms-txt, bank bundle, knowledge pack), each omission named, with no override flag.+- `t_50794f57` (Lane C) - One-command recovery for dead extraction writes: dead-letter schema v2 freezes the payload at failure time; a classifier labels every row `recover`, `pending`, `re-extract`, `not_recoverable` or `resolved` with the exact copy-paste command; `o2b brain dead-letters recover` re-runs the recorded payload at current vault state behind the established consent ladder.+- `t_dc782fd5` (Lane C) - Standalone validation gate: `o2b brain validate --paths <p>... | --dirty` runs the exact write-receipt page-lint vocabulary over a caller-named page set or every git-dirty note and maps findings to doctor's exit-code contract, so an unhooked agent or cron script can block its own commit.+- `t_9571a47f` (Lane D) - Folder-level note moves and renames: two new actions on the existing note-lifecycle surface move or rename a whole folder, refuse occupied destinations before the first byte moves, and rewrite inbound path-spelled wikilinks in a single pass over the successfully moved set.+- `t_cfe2ce5d` (Lane D) - Status store-ownership honesty: the operator snapshot gains a `store` group reporting the search writer lock as `held`/`free`/`unknown` with age, an owner field that truthfully reads null because the lock record carries no identity, and a `thisCaller: read-only` statement.+- `t_8e49ec96` (Lane D) - Doctor client versions: a `client_versions` readiness probe beside `registered_commands` asks each manifest-recorded client its version with a fail-soft read-only async spawn and grades rows pass/unknown/skipped, never fail.++Plus the integrator/docs phase (outside the four lanes): `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md`, and the two wiring-file description lines that belong to Lane C-owned files.++## Out of scope++- Writer-lock owner identity stamping (an owner record written inside the lock directory at acquire time) - deferred; v1 reports `writerLockOwner: null` and says so in the renderer rather than inventing a holder. The brain-lane `.lock` files stamp a pid, but no surface reads it back and the status field is scoped to the search writer lock only, stated in the docblock.+- Dead-letter deletion on recovery - the retention rule stands: nothing in the project deletes a dead letter; a successful recovery says so and names the file the operator may delete by hand.+- A CLI flag for the tail trim - the established MCP-first precedent (`query_mode`, packing-policy, entity-facts): the config key and env var resolve for MCP callers; the CLI context-pack verb reads no config gates today and gains none here.+- Extending the trim to the `packingPolicy` branch of `packContext` - the unified path only in v1, with a note in the module where the policy branch begins.+- Reply presence for the `pre_compress` injection lane - the card and the Stop hook cover the recall/active/subagent phases; pre-compression presence is a follow-up.+- Inventing a privacy class for preferences - the export teaches the existing deny markers (`pageVisibility` token plus `hasPrivacyDenyMarker`); the knowledge pack already blocks class-marked pages.+- Auto-fix in the validate gate - report-only in v1; findings carry their existing `next_command` pointers to `brain doctor --repair` and `brain lint --consolidate --apply`, and no third fix vocabulary is grown.+- A minimum-version table for doctor client versions - no `minVersion` column, no config surface; the grading vocabulary stays without `fail`.+- Lane edits to `docs/cli-reference.md`, `docs/mcp.md` and `CHANGELOG.md` - all integrator/docs phase.+- The doctor message touch-up in `src/core/brain/doctor/privacy-marker-check.ts` (naming the preference export as a marker reader) - deferred as behavior-neutral; the existing sentence stays true after this change.+- Changing the locking strategy, the append-only continuity store, or the closed dead-letter lane union.++## Premise verification++All eight premises were verified against live source by read-only recon; each holds in a narrowed form that the scope above encodes:++- `t_cb6a5558` - holds (narrowed): the comparator at `src/core/brain/context-pack.ts:925-948` sorts tier first and the walker at 1205-1223 reports only `over-budget` with no term-aware rescue, while the ranked-mode jaccard scorer at 897-905 already supplies the lexical overlap to reuse; the config-gated trim is fully specified and buildable now. (The card's 642-653 anchor had drifted; the validator's corrected anchor holds.)+- `t_f8510c55` - partly false, corrected: per-injected-note reply-presence receipts genuinely do not exist, but the premise that nothing reads the answer is stale - the Claude Code Stop hook (`answer-quote-check`) already reads the turn's assistant messages from the transcript, and context receipts record a hash and char count of the final text. The build extends the existing Stop lane; no transcript reading is built from scratch.+- `t_b88c2190` - partly false, narrowed to the preferences bank/llms-txt export lane (`src/core/brain/export.ts`): the knowledge pack already blocks privacy-marked pages via `pageBlockReason` and informal markers deny at every remote read root, so the claim "no export surface reads a privacy marker" is refuted for the main lanes; the residual status-only export is the one real lane, and it is taught the existing deny markers rather than a new class.+- `t_50794f57` - holds (narrowed): dead letters already carry lane, error and payload identity but `listDeadLetters` is the only API and no classifier or command exists. The signal lane carries no revision counter, so re-admission re-runs the recorded payload at current vault state rather than at a recorded revision; the dead-letter schema bumps to v2 with an optional frozen payload, and v1 letters classify as `re-extract`.+- `t_dc782fd5` - holds: `brain lint` returns 0 even with unresolved findings (`src/cli/brain/verbs/lint.ts:31`), no CLI verb exits non-zero for note-content findings, and a git-dirty gate reusing the write-receipt page-lint vocabulary and doctor's exit contract is actionable now.+- `t_9571a47f` - holds: note lifecycle is defined for note files one at a time and `src/core/brain/notes/lifecycle.ts:623` refuses any rename that changes directory, so folder-level one-pass inbound rewrite is an identified deterministic extension with no invariant tension against the existing rename/move split.+- `t_cfe2ce5d` - holds (narrowed): `isWriterLockHeld` exists but nothing in status calls it, and the writer lock is a bare `proper-lockfile` directory carrying no owner identity - mtime only. V1 therefore reports `writerLockOwner: null` plus `held`/`free`/`unknown` and a this-caller read-only statement; identity stamping is explicitly deferred.+- `t_8e49ec96` - holds: the `registered_commands` probe only resolves executables into `resolves`/`absent`/`unresolved` (`src/core/install/command-probe.ts:73-80`) and nothing reports a client's own version; a fail-soft, read-only version row slotted beside it is actionable now.++## Chosen approach++Four parallel lanes on provably disjoint file sets, each reusing the seam its recon verified rather than building a parallel surface. Lane A reuses the ranked-mode jaccard kernel inside the unified `packContext` walker for the trim (flag off stays byte-identical) and the existing Stop-hook check loop for presence, emitting an append-only sibling record because the continuity store cannot amend the receipt written at injection time. Lane B computes denials once at the collector seam where the frontmatter map is already parsed, keeps `rows` complete for the import topic maps, and lets the json envelope, llms-txt variant, bank bundle and knowledge pack each name what they leave out. Lane C adds the two new flat verbs (`dead-letters`, `validate`) with a core classifier and a tiny git-dirty helper, owning all four CLI wiring files exclusively. Lane D extends the note-lifecycle action vocabulary and the operator snapshot and the readiness probe registry - no new verbs, so it needs none of the wiring files. Every destructive path follows the repo's established consent ladder (dry-run default, headless `--yes`, frozen-vault and vault-identity guards), and every new reportable fact is named in an existing reporting contract (`omitted`/`blocked` arrays, skip reasons with gap telemetry, readiness rows, snapshot groups) rather than a second vocabulary.++## Design decisions++### Lane A - delivery (`t_cb6a5558`, `t_f8510c55`)++1. Trim lives after the unified walker, reusing comparator scores. The trim applies once `opts.tailTrim` is on and a query is present: the first 3 delivered items are immune (module constant `CONTEXT_PACK_TAIL_TRIM_KEEP`), a tail item whose jaccard score against the query is at least `TAIL_TRIM_KEEP_FRACTION` (0.8) of the top delivered score is kept, everything lower is dropped whole with a new `"tail-trim"` skip reason, and the freed budget is offered to `over-budget` candidates in priority order - rescue is the only path across tiers, bounded by the same `maxTokens`, and never reorders the attention item. In `ranked` mode the scores already sit in `relevanceById` and are reused; in other modes they are computed under the flag only. Rationale: the validator's "after the tier gate" phrasing and the named-constant-not-knob precedent (`CONTEXT_PACK_ENTITY_FACTS_MAX_ENTITIES`); in-walker placement keeps the off-path byte-identical and makes the receipt correct for free, since finalize maps `report.items`.+2. Trim reporting rides the existing conditional-member shape: `tailTrim?: { dropped; keptByQueryTerms; rescued; tokensSaved }` on `ContextPackReport`, attached in `finalizeContextPackReport` only when the option ran, with the counters echoed into `contextPackBudgetMetadata` so receipt `budget` and telemetry `metadata` carry them and `contextPackGaps` surfaces the new reason as gap `tail_trim` automatically. Names echo upstream's `delivery.tail_trim` without copying its envelope.+3. Flag resolver follows the precedent family: `resolveTailTrimContextPack` (config key `tail_trim_context_pack`, env `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`) beside the entity-facts resolver at `src/core/config.ts:862-876`, default off, absent option documented as byte-identical.+4. Presence is a sibling continuity record, not a receipt amendment. The continuity ledger is append-only, so the Stop hook cannot revise the receipt written at injection time; instead it appends `kind: "reply_presence"` with `{ session_id, per-note verdicts, checked, source_hash? }`, and the receipt read surface gains a conditional join. The new kind joins `CONTINUITY_RECORD_KINDS` (same-edit rule) and gets a keep row in `FOLDABLE_CONTINUITY_KINDS`' sibling `KEPT_CONTINUITY_KINDS` - the fold-decision census fails on any kind without exactly one decision, and per-turn verdict rows are not fold candidates in v1.+5. Per-note outcomes reuse `ANSWER_QUOTE_VERDICT`, extended with `absent`: a note at least one reply span verified against reads `verified`; a note whose spans all miss reads its strongest miss verdict; a note no span touched reads `absent` - the row this feature exists to surface. One vocabulary, census-silent (the census entry self-derives from the constant); no second per-note set.+6. The join key is fixed at the source: `hooks/active-inject.ts` adds `sessionId` to the `session_inject` receipt (additive payload member), so receipt-to-presence joins do not depend on time windows. Where no session id exists on either side the read reports `unjoined` - honest absence, never an inferred match - and the join runs at the caller's reach: a note row the reach view hides is dropped from `per_note` and counted in `withheld`, so a filtered join never reads as a smaller check (the receipts-reach clause in the follow-up docs wave names this). Presence rides the existing per-phase `quote_check.*` modes (off/shadow/enforce, default shadow): no new config key, and operators who want silence set the phase off. Codex and grok stay annotation-silent as today, but the presence record writes wherever a transcript exists; `hooks/README.md` states this beside the existing annotation caveat.++### Lane B - export privacy (`t_b88c2190`)++7. Denial is computed once at the collector seam. `collectPreferenceRows` already holds the parsed frontmatter map at `src/core/brain/export.ts:269` and discards it; the denied array is computed from `hasPrivacyDenyMarker(meta)` and `pageVisibility(meta)` right there - no extra file read. `rows` stays complete because the import-side topic maps (`preference-restore.ts:592`, `knowledge-pack.ts:878`) must keep seeing every row; denial is a report beside the rows, not a filter inside the collector.+8. The deny is unconditional and named everywhere. There is no `--include-private` remedy (the knowledge pack carries none for its visibility blocks); a deny reason is `"visibility"` matching `pageBlockReason`'s vocabulary. The json envelope gains `omitted: [{id, reason}]`, absent when empty so the byte-identity redaction fixtures hold and the schema stays 1 (additive per the module's own versioning rule); llms-txt gains a detailed `{text, omitted}` variant with the stable string signature delegating to it (SDK stability); the export verb writes a stderr omission notice in the `contentClassOmissionNotice` shape whose remedy sentence names the reservation key, not a flag.+9. Shared surfaces follow so no two exporters disagree about the same directory: the bank bundle filters denied preferences and `brain bank-export` names the omissions on stderr (same shape as its existing content-class notice), and the knowledge pack converts collector denials into `blocked` entries `{kind: "preference", id, reason: "visibility"}` so its name-every-omission contract holds. A denied preference cannot ride redacted (the pack carries preferences with empty body), so this is drop-and-name.++### Lane C - capture writes (`t_50794f57`, `t_dc782fd5`)++10. Schema v2 freezes the payload at failure time. `DEAD_LETTER_SCHEMA_VERSION` bumps to 2 with an optional `payload` field (the validated items array, bounded by the existing 12-item per-session cap) written by `extract-signals.ts` when the mid-payload write throws; parsing stays strict per version, v1 letters keep parsing and classify as `re-extract`, unknown versions still refuse. No config key gates capture - the growth is small JSON and a knob here would silently downgrade the one fact recovery depends on.+11. The classifier has five honest states. `recover` (v2 payload, session still capture-classified, missing items not already deduped away), `pending` (staged items sit in the write-approval queue; the command names `brain pending apply`), `re-extract` (a payload-less v1 letter, or a frozen payload that no longer passes the lane's own shape and semantic validation; the command names `brain extract-signals <reference>`), `not_recoverable` (session unknown or boundary now refuses; no command, reason rendered), and `resolved` (every missing key now exists on disk) - the fifth state is required by the retention rule, else a reconciled row reads as still-broken forever. Unknown future lanes refuse by name as `not_recoverable`; the lane union stays closed on purpose.+12. Re-admission means re-run at current state, never at a recorded revision. The extraction-signal lane carries no revision counter - its concurrency story is the content-derived dedup hash plus atomic writes - so `recover --apply` calls `commitExtractedSignals` with exactly the MISSING items the letter names - never the whole payload, which would resurrect a delivered item an operator later removed (a deleted signal, a rejected queue row the dedup index never walks) - and lets it re-derive the capture boundary, dedup index and staging lane at call time; nothing stale is replayed by construction. `expectRevision` becomes load-bearing only if a preference-writing lane ever joins the union.+13. `o2b brain dead-letters` is a new flat verb (list default, `show <id>`, `recover <id>`): dry-run default with per-item verdicts, `--apply` requiring `--yes` under `--json` or non-TTY (the `brain lint`/`brain doctor --repair` rule), frozen-vault and vault-identity guards inherited, and the record id serving as the pin (the `writes revert --apply <digest>` pattern). The record's `DIAGNOSTIC_SIGNALS` entry points the `ExtractSignalsWriteError` message at the surface so the MCP error boundary - which never sees the typed write error today - can name the next command.+14. `o2b brain validate` is read-only and non-interactive by construction. Selection is exactly one of `--paths` (vault-relative, canonicalized, escape refused by name) or `--dirty` (a new tiny helper running `git status --porcelain` on the vault, including modified, added and untracked Markdown - an agent-created new note is exactly the target population; a non-worktree vault is a named refusal with exit 2, never a silent clean pass). Checks reuse `lintWrittenPages` verbatim - the write-receipt vocabulary plus `validateArtifact`'s error-severity document checks, and nothing new. Exit contract byte-for-byte doctor's lint ladder: errors or an unreadable named page 1 (a gate that could not read what it was pointed at may not report clean), `--strict` warnings 2, clean 0; exit 2 is SHARED with the verb's own usage refusals - the non-worktree `--dirty` refusal, an escaping `--paths` value, a bad selector - the same overlap doctor's usage paths accept, and a cron caller distinguishes them by the printed reason, not the code alone; `--json` reuses `PageLintReport` field names with no advisory-rail lines. The documented split keeps it from duplicating doctor: doctor is the whole-vault structural invariant pass with repair modes; validate is per-page authored-content lint over a named subset with the exit code as the product.++### Lane D - operator surfaces (`t_9571a47f`, `t_cfe2ce5d`, `t_8e49ec96`)++15. Folder moves are two new actions on the existing note-lifecycle surface, split from day one: `move-folder <folder> <toDir>` (destination parent must differ) and `rename-folder <folder> <newName>` (single segment, same parent), mirroring the file surface's rename/move discipline that catches caller mistakes. The vocabulary extends `NOTE_LIFECYCLE_ACTION` so the CLI guard, MCP enum and manifest stay in sync from one constant; `delete`/`archive` stay file-only and are refused for folder actions.+16. The folder envelope mirrors `resolveNoteTarget` minus the `.md` rung: vault-relative, realpath inside the vault, not under `Brain/`, vault-scope checks, write binding on the destination, source must stat as a directory, vault root refused. Occupancy pre-flight checks every destination path (plus the dev/ino case-only check) before the first rename and refuses with `destination_occupied` naming every collision and nothing moved. The operation is explicitly not atomic and says so: mid-set I/O failures are recorded in `moveFailures` (rendered `move_failures`), the rewrite pairs are computed from the successfully moved set only, and no rollback is attempted - the settled partial-failure doctrine. Two named additions shipped with it: a mid-set fault that linked the destination name before failing drops that second name (the source still holds the inode; declared in the destructive-sites census beside the prune), and the emptied source directories are pruned bottom-up, with the residue a prune could not remove named in `left_behind`. The refusal vocabulary grew `destination_inside_source` and `move_set_empty` beside `destination_occupied`.+17. One rewrite pass is genuinely complete for folders: a folder move never changes a basename, so bare `[[Name]]` spellings keep resolving and `decideBasename`/`bareNameRepairs` have nothing to do; only path-spelled links break, and a single `retargetWikilinks` call over all pairs (minimal spellings computed against the post-move population) fixes them, including links inside the moved folder. `--expect N` keeps its established meaning - files the apply will write (inbound referers), not files moved.+18. The status `store` group is three-state and fail-soft, wrapped exactly like `writerLockRefusal`: `writerLock: held | free | unknown` (stat failure reads `unknown` with the errno - "could not find out" is not "free"), `writerLockAgeMs` from mtime when held, `writerLockOwner: null` always in v1 (the lock is a bare directory; the renderer states `owner: unknown (the lock record carries no identity)` so absence is a measurement, not a gap), `writerLockPath` in the CLI payload only (withheld below MCP local reach, like `stateFiles.searchIndex`; the follow-up security wave extended the rule - the probe's failure reason is redacted below local reach because the fs error embeds the same path, and the browser explorer is a second below-local surface that withholds the path and scrubs it from the reason), and `thisCaller: "read-only"` with the rendered consequence, scoped to what the lock gates (an index write - `o2b search index` / reindex - while held refuses with `INDEX_LOCKED`; vault and memory writes serialize on the brain lane's own lock files and are not gated by this lock). A held lock is a live writer, not a fault: no problem line, not folded into `healthy` - the `frozen`-field precedent. An injected `writerLockHeldAt` seam (named after `MigrationPlanInput.writerLockHeldAt`) makes the states testable.+19. The `client_versions` probe is manifest-scoped and fail-soft: detection comes from the install manifest like `registered_commands` (a client installed but never registered is out of scope, stated in the docblock); a small constant table maps each target to its version argv (`generic: null`, skipped by name); execution is async spawn inside the existing per-probe timeout so the budget actually covers it; grading is `pass` (exit 0, non-empty stdout - the raw first line, never semver-parsed), `unknown` (throw, non-zero, timeout, empty - ENOENT wording points at `registered_commands` rather than duplicating a fail), or `skipped`; there is no `fail` in v1 because a version row never proves a surface broken. Aggregate and detail follow `probeRegisteredCommands`' shape; the additive optional `rows` field on `ReadinessProbeResult` rides only this probe, so the exit codes are untouched - a fully unknown probe stays exit 6, not 1 - while `readiness_summary` gains the probe's own counts like every probe before it (its `unknown` can read one higher than a pre-1.95 vault's). Binary names beyond `codex` and `copilot-cli` are confirmed against each adapter's detect logic before shipping.++### Cross-lane++20. Docs ownership keeps lane sets disjoint: lanes never edit `docs/cli-reference.md`, `docs/mcp.md` or `CHANGELOG.md` (integrator/docs phase); `docs/mcp.md` is integrator-owned because three of the four lanes need rows in it. Lane A keeps its lane-exclusive docs (`docs/how-it-works.md`, `docs/observability.md`, `hooks/README.md`).++## File changes++Per lane (exact per-task lists in `plan.md`):++- **Lane A** (20 files): `src/core/brain/context-pack.ts`, `src/core/config.ts`, `src/mcp/brain/pack-tools.ts`, `hooks/answer-quote-check.ts`, `src/core/brain/answer-quotes/check.ts`, `src/core/brain/continuity/types.ts`, `src/core/brain/receipts/types.ts`, `src/core/brain/context-receipts.ts`, `hooks/active-inject.ts`, `src/cli/brain/verbs/context-receipts.ts`, `src/core/search/visibility-surface-registry.ts`, `docs/how-it-works.md`, `docs/observability.md`, `hooks/README.md`, plus tests: `tests/core/brain/context-pack-tail-trim.test.ts` (new), `tests/core/config-counterparty-brief.test.ts`, `tests/mcp/context-pack-tool.test.ts`, `tests/hooks/answer-quote-check.test.ts`, `tests/core/brain/context-receipts.test.ts`, `tests/mcp/context-receipts-tool.test.ts`.+- **Lane B** (9 files): `src/core/brain/export.ts`, `src/cli/brain/verbs/export.ts`, `src/core/brain/portability/knowledge-pack.ts`, `src/core/brain/portability/bundle.ts`, `src/cli/brain/verbs/bank-export.ts`, plus tests: `tests/core/brain/export.test.ts`, `tests/cli/brain-export.test.ts`, `tests/cli/export-redaction.test.ts`, `tests/core/brain/portability/knowledge-pack.test.ts`.+- **Lane C** (15 files): `src/core/brain/dead-letter.ts`, `src/core/brain/extract-signals.ts`, `src/core/brain/dead-letter-recovery.ts` (new), `src/core/brain/vault-dirty.ts` (new), `src/core/brain/diagnostics.ts`, `src/cli/brain/verbs/dead-letters.ts` (new), `src/cli/brain/verbs/validate.ts` (new), `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`, plus tests: `tests/core/brain/dead-letter.test.ts`, `tests/core/brain/dead-letter-recovery.test.ts` (new), `tests/cli/brain-dead-letters.test.ts` (new), `tests/cli/brain-validate.test.ts` (new).+- **Lane D** (13 files): `src/core/brain/notes/folder-lifecycle.ts` (new), `src/core/brain/notes/lifecycle.ts`, `src/cli/brain/verbs/note-lifecycle.ts`, `src/mcp/brain/lifecycle-file-tools.ts`, `src/core/brain/operator-snapshot.ts`, `src/mcp/brain/health-tools.ts`, `src/core/doctor-readiness.ts`, `src/cli/main.ts`, plus tests: `tests/core/brain/notes/folder-lifecycle.test.ts` (new), `tests/core/brain.operator-snapshot.test.ts`, `tests/cli/status.test.ts`, `tests/mcp/maintenance-status-reach.test.ts`, `tests/core/doctor-readiness.test.ts`.+- **Integrator/docs phase** (5 files): `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md`, plus the `note-lifecycle` description line in `src/cli/command-manifest.ts` and the usage-block line in `src/cli/brain/help-text.ts` (folder actions), landed after Lane C.++The four lane sets are pairwise disjoint; no source or test file appears in two lanes. Lane-internal serial tasks may touch the same file (wiring files in Lane C, `docs/observability.md` and the folder test file within their lanes).++## Risks and open questions++- **Rescue versus tier gate.** The rescue is the only path by which a page crosses tiers; it is bounded by `maxTokens` and priority order, and the top-3 immunity anchors the head. Risk: a rescued peripheral page displacing a would-be core page - bounded because rescue runs after the walker filled every tier-affordable candidate, so only genuinely over-budget candidates compete for freed budget.+- **Skip-reason ripple.** The new `"tail-trim"` reason ripples into the gaps vocabulary; verified that consumers pass reasons through verbatim (`pack-tools.ts:582`) and existing test pins are scenario-specific, not exhaustive over the union. The new reason's pins live in the new tail-trim suite.+- **Marker durability on preference files.** Denials read live frontmatter; `mergeFrontmatterTiered` keeps user-tier keys, and `brain-preference` is in `DEFAULT_TIER_MAP`, so hand-added markers survive framework rewrites. Residual risk is an operator removing a marker to re-share - which is the intended mechanism, not a defect.+- **Byte-identity pressure on the export.** The `export-redaction` fixtures pin "nothing to redact is byte-identical"; the `omitted` field must be absent-when-empty and notices stderr-only, and both properties get their own pins.+- **Presence record volume.** One `reply_presence` record per checked Stop event grows the continuity ledger per turn; bounded and kept-never-fold in v1. If volume proves noisy, the follow-up is a mode, not silent suppression.+- **Join coverage honesty.** Receipts without `receipt_session_id` and presence records without a matching `session_id` read `unjoined`; no time-window inference. Documented in the read-surface help text.+- **Census self-derivation assumption.** Both vocabulary extensions (`ANSWER_QUOTE_VERDICT` + `absent`, `NOTE_LIFECYCLE_ACTION` + two actions) are expected census-silent because census entries derive from the live constants. If either lane discovers a required census edit, it stops and reports rather than editing the shared census file (contract item 6). The fold-decision census requires the `KEPT_CONTINUITY_KINDS` row in the same change as the record kind - that edit is Lane A's own file.+- **Version-command table accuracy.** Only `codex` and `copilot-cli` binary names are confirmed by in-repo spawn precedent; the table's remaining rows are verified against each adapter's config/detect logic before the probe ships, and a correction is a one-line follow-up in the table's own module.+- **Two doctors.** Lane D touches `src/core/doctor-readiness.ts` (the `o2b doctor --readiness` surface) while the brain doctor (`src/core/brain/doctor.ts`) is untouched; commit messages keep the distinction explicit so review does not conflate them.+- **Lock age meaningfulness.** `writerLockAgeMs` derives from the lock directory mtime, refreshed by a 30 s heartbeat; an age above the stale window reads as a stale residue the doctor's `stale-lock` probe already owns, and the status line says nothing stronger than the measurement.diff --git a/docs/brainstorm/verified-delivery-honest-writes/plan.md b/docs/brainstorm/verified-delivery-honest-writes/plan.mdnew file mode 100644index 00000000..125ee510--- /dev/null+++ b/docs/brainstorm/verified-delivery-honest-writes/plan.md@@ -0,0 +1,130 @@+# Cycle 20261026 (verified-delivery-honest-writes) - implementation plan (four parallel lanes + integrator)++Implementation runs in four parallel lanes on provably disjoint file sets, followed by an integrator/docs phase that owns every cross-lane docs surface and runs the full gates. Every feature below carries its kanban card id. Inside a lane, tasks are serial. Every task is TDD: the acceptance test is written first and must fail with the expected error before the implementation lands.++## Lane structure++| Lane | Card(s) | One-line scope | Files |+|------|---------|----------------|-------|+| A - delivery | `t_cb6a5558`, `t_f8510c55` | Score-aware tail trim in the context pack; reply-presence receipts joined by session id | 20 |+| B - export privacy | `t_b88c2190` | The preferences bank/llms-txt export learns the existing deny markers and names every omission | 9 |+| C - capture writes | `t_50794f57`, `t_dc782fd5` | Dead-letter schema v2, classification and one-command recovery; the `brain validate` git-dirty gate | 15 |+| D - operator surfaces | `t_9571a47f`, `t_cfe2ce5d`, `t_8e49ec96` | Folder moves on the note-lifecycle surface; status store-ownership honesty; doctor client versions | 13 |+| Integrator/docs phase | all | Consolidated docs rows, CHANGELOG, full gates | 5 |++Lane-owned total: 57 files (10 new; Lane A's list carries 20 files once its one stray entry is read as the registry file below). Integrator adds 5 (2 of them Lane C-owned wiring files edited only after Lane C lands). No lane ever touches a file in another lane's set.++## Cross-lane contract++1. **Shared wiring files are owned by Lane C alone**: `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`. Lane D needs none of them: the folder actions extend the existing `note-lifecycle` verb surface (`src/cli/brain/verbs/note-lifecycle.ts`, not a wiring file), the doctor probe registers in `src/core/doctor-readiness.ts`, and the status snapshot fields flow through `src/core/brain/operator-snapshot.ts` and `src/mcp/brain/health-tools.ts`. The two folder-action description lines inside Lane C-owned files (`command-manifest.ts` note-lifecycle entry, `help-text.ts` usage block) are integrator-phase line items, not Lane D work.+2. **Integrator-owned docs**: `docs/cli-reference.md` and `CHANGELOG.md` are owned by the integrator/docs phase - NO lane edits them. The same treatment extends to `docs/mcp.md`, which Lanes A, C and D all need rows in; no lane edits it either.+3. **Commits and hygiene**: each lane commits with `git commit --only <its own paths>` (stage and commit in ONE step; never `git add -A`, never a bare `git commit -am`) and runs the repo formatter and linter - `./node_modules/.bin/oxfmt` and `./node_modules/.bin/oxlint` - on its own files before every commit. If the whole-tree pre-commit hook fails because another lane has unformatted files, retry after 30 seconds, up to 5 times; only then commit with `--no-verify` after verifying its own files are clean.+4. **Tests**: every lane runs ONLY its own targeted tests (`bun test <its own files listed below>`), never the whole suite. Two pinned suites are exceptions by construction: `tests/cli/help-surface-parity.test.ts` and `tests/cli/completions.test.ts` are manifest-derived - Lane C runs them after its manifest rows land; they pass without edits.+5. **Dependencies**: none between lanes. The integrator runs the full gates (typecheck, full test suite, validate) after all four lanes land.+6. **Collision protocol**: the lane sets above are exhaustive. If a lane discovers it needs a file outside its set (for example a census edit both lanes' vocabulary extensions are expected to make unnecessary), it stops and reports to the orchestrator instead of editing.+7. **Deviations the review wave recorded** (each stopped, reported and was approved, per rule 6): the architecture censuses needed rows after all - `tests/core/architecture/claim-attribution-census.test.ts` pins the new `reply_presence` kind and `tests/core/architecture/write-site-census.test.ts` plus `src/core/brain/destructive-sites.ts` declare the folder prune (and its fault cleanup); the below-local-reach fixes touched files outside every lane - `src/core/brain/explorer.ts`, `src/mcp/tool-error-codes.ts`, `tests/hooks/active-inject-receipt-session.test.ts`, `tests/cli/doctor-exit.test.ts` - and edited Lane A's `src/core/search/visibility-surface-registry.ts` row again (the receipts-visibility entry in the lane's list below).++## Lane-exclusive file sets++- **Lane A**: `src/core/brain/context-pack.ts`, `src/core/config.ts`, `src/mcp/brain/pack-tools.ts`, `hooks/answer-quote-check.ts`, `src/core/brain/answer-quotes/check.ts`, `src/core/brain/continuity/types.ts`, `src/core/brain/receipts/types.ts`, `src/core/brain/context-receipts.ts`, `hooks/active-inject.ts`, `src/cli/brain/verbs/context-receipts.ts`, `src/core/search/visibility-surface-registry.ts` (the receipts-visibility row; listed as knowledge-tools in the design phase, corrected on review - the receipts tool lives in pack-tools.ts and knowledge-tools.ts is untouched), `docs/how-it-works.md`, `docs/observability.md`, `hooks/README.md`, `tests/core/brain/context-pack-tail-trim.test.ts`, `tests/core/config-counterparty-brief.test.ts`, `tests/mcp/context-pack-tool.test.ts`, `tests/hooks/answer-quote-check.test.ts`, `tests/core/brain/context-receipts.test.ts`, `tests/mcp/context-receipts-tool.test.ts`.+- **Lane B**: `src/core/brain/export.ts`, `src/cli/brain/verbs/export.ts`, `src/core/brain/portability/knowledge-pack.ts`, `src/core/brain/portability/bundle.ts`, `src/cli/brain/verbs/bank-export.ts`, `tests/core/brain/export.test.ts`, `tests/cli/brain-export.test.ts`, `tests/cli/export-redaction.test.ts`, `tests/core/brain/portability/knowledge-pack.test.ts`.+- **Lane C**: `src/core/brain/dead-letter.ts`, `src/core/brain/extract-signals.ts`, `src/core/brain/dead-letter-recovery.ts`, `src/core/brain/vault-dirty.ts`, `src/core/brain/diagnostics.ts`, `src/cli/brain/verbs/dead-letters.ts`, `src/cli/brain/verbs/validate.ts`, `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`, `tests/core/brain/dead-letter.test.ts`, `tests/core/brain/dead-letter-recovery.test.ts`, `tests/cli/brain-dead-letters.test.ts`, `tests/cli/brain-validate.test.ts`.+- **Lane D**: `src/core/brain/notes/folder-lifecycle.ts`, `src/core/brain/notes/lifecycle.ts`, `src/cli/brain/verbs/note-lifecycle.ts`, `src/mcp/brain/lifecycle-file-tools.ts`, `src/core/brain/operator-snapshot.ts`, `src/mcp/brain/health-tools.ts`, `src/core/doctor-readiness.ts`, `src/cli/main.ts`, `tests/core/brain/notes/folder-lifecycle.test.ts`, `tests/core/brain.operator-snapshot.test.ts`, `tests/cli/status.test.ts`, `tests/mcp/maintenance-status-reach.test.ts`, `tests/core/doctor-readiness.test.ts`.+- **Integrator/docs phase**: `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md`, `src/cli/command-manifest.ts` (note-lifecycle description line, after Lane C), `src/cli/brain/help-text.ts` (usage-block line, after Lane C).++## Tasks++### Lane A - delivery++#### Task A1: tail-trim flag resolver and pack option (Lane A, card `t_cb6a5558`)+- **Files**: `src/core/config.ts` (`resolveTailTrimContextPack`, config key `tail_trim_context_pack`, env `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`, beside the entity-facts resolver), `src/core/brain/context-pack.ts` (`tailTrim?: boolean` on `ContextPackOptions` next to `entityFacts`, byte-identity docblock; `"tail-trim"` added to the `ContextPackSkipped.reason` union; conditional `tailTrim` report member declared), `tests/core/config-counterparty-brief.test.ts` (new resolver describe beside the `resolveEntityFactsContextPack` one).+- **Acceptance**: the new resolver tests fail first (the export does not exist), then pass: default off, config key on, env override wins. Existing context-pack pins stay green unchanged - an absent option is byte-identical.+- **Depends on**: none.++#### Task A2: trim and rescue engine (Lane A)+- **Files**: `src/core/brain/context-pack.ts` (relevance computation under the flag, top-3 keep and restatement keep-rule after the unified walker, tail drop with `"tail-trim"` skips, priority-order rescue of `over-budget` candidates under freed budget, `tokensUsed` recompute, module constants `CONTEXT_PACK_TAIL_TRIM_KEEP` and `TAIL_TRIM_KEEP_FRACTION`, report member attached in `finalizeContextPackReport`, counters in `contextPackBudgetMetadata`), `tests/core/brain/context-pack-tail-trim.test.ts` (new).+- **Acceptance**: the new suite fails first (flag on, no trim happens), then passes: flag off byte-identical; top-3 immunity; restatement keep at the fraction; tail drop emits `"tail-trim"` skips and surfaces gap `tail_trim`; rescue re-admits an over-budget candidate in priority order within `maxTokens` and never touches the attention item; ranked-mode scores reused; report member absent when off; the `packingPolicy` branch untouched.+- **Depends on**: A1.++#### Task A3: MCP wiring and trim docs (Lane A)+- **Files**: `src/mcp/brain/pack-tools.ts` (flag read beside the densityRanking/entityFacts block, opts threading, conditional response member), `tests/mcp/context-pack-tool.test.ts`, `docs/how-it-works.md` (context-pack section), `docs/observability.md` (telemetry payload row).+- **Acceptance**: the MCP test extension fails first, then passes: config key on means the response carries the trim block and skip reasons; key absent means the member is absent and the response is byte-identical.+- **Depends on**: A2.++#### Task A4: reply-presence fold and record kind (Lane A, card `t_f8510c55`)+- **Files**: `hooks/answer-quote-check.ts` (per-ledger-candidate outcome fold inside the existing budget and fail-open arms; sibling `reply_presence` record emitted once per checked turn), `src/core/brain/answer-quotes/check.ts` (`ANSWER_QUOTE_VERDICT` extended with `absent`), `src/core/brain/continuity/types.ts` (`reply_presence` union member + `CONTINUITY_RECORD_KINDS` entry, same edit), `src/core/brain/receipts/types.ts` (`reply_presence` row in `KEPT_CONTINUITY_KINDS`), `tests/hooks/answer-quote-check.test.ts`.+- **Acceptance**: the hook test fails first (no presence record), then passes: exactly one record per checked turn with a verdict per injected note - `verified` when a span checked out, the strongest miss verdict otherwise, `absent` for notes no span touched; `stop_hook_active` silence; fail-open when the ledger write fails; budget-expiry arms. The vocabulary census and the fold-decision census pass WITHOUT edits (entries self-derive; the keep row is the kind's fold decision).+- **Depends on**: none.++#### Task A5: presence join, session key and read surfaces (Lane A)+- **Files**: `src/core/brain/context-receipts.ts` (conditional `reply_presence` member on the summary; sibling lookup by `session_id`; `unjoined` outcome when no key matches), `hooks/active-inject.ts` (`sessionId` added to the `session_inject` receipt payload), `src/cli/brain/verbs/context-receipts.ts` (`show` prints presence), `src/mcp/brain/pack-tools.ts` (`brain_context_receipts` conditional member), `tests/core/brain/context-receipts.test.ts`, `tests/mcp/context-receipts-tool.test.ts`, `hooks/README.md` (Stop row and file list; transcript-availability caveat).+- **Acceptance**: the context-receipts test fails first, then passes: a sibling record joins by exact `session_id`; no key match reads `unjoined`, never an inferred window match; a receipt whose notes have no presence record reports absent rather than verified; the `session_inject` receipt now carries `session_id`; CLI and MCP show surfaces always carry the member, naming either the verdicts or the explicit `unjoined` outcome.+- **Depends on**: A4.++### Lane B - export privacy++#### Task B1: collector denial reporting (Lane B, card `t_b88c2190`)+- **Files**: `src/core/brain/export.ts` (`PreferenceCollection.denied` computed in `collectPreferenceRows` from the frontmatter map already parsed there, via `hasPrivacyDenyMarker` and `pageVisibility`; `rows` stays complete), `tests/core/brain/export.test.ts`.+- **Acceptance**: the deny-matrix tests fail first, then pass: informal marker keys times values deny; `visibility: private` denies; reason is `"visibility"`; unmarked rows are untouched; an empty denial leaves the collection byte-identical; parse refusals behave exactly as before.+- **Depends on**: none.++#### Task B2: export lanes name the omission (Lane B)+- **Files**: `src/core/brain/export.ts` (denying detail path for `collectExportRows`; `exportPreferencesJson` additive `omitted` envelope field, absent when empty, schema stays 1; `exportPreferencesLlmsTxt` detailed `{text, omitted}` variant with the string signature delegating), `src/cli/brain/verbs/export.ts` (stderr omission notice in the `contentClassOmissionNotice` shape, remedy names the reservation key; exit 0), `tests/core/brain/export.test.ts`, `tests/cli/brain-export.test.ts`, `tests/cli/export-redaction.test.ts`.+- **Acceptance**: the CLI and byte-identity tests fail first, then pass: marked preferences leave the json and llms-txt outputs and appear in `omitted`; nothing-to-deny runs stay byte-identical (the existing fixtures hold); the notice goes to stderr only; no new CLI flag exists.+- **Depends on**: B1.++#### Task B3: shared surfaces stay consistent (Lane B)+- **Files**: `src/core/brain/portability/knowledge-pack.ts` (denied preferences become `blocked` entries `{kind: "preference", id, reason: "visibility"}`; the every-entry-blocked error path still reads correctly), `src/core/brain/portability/bundle.ts` (bank bundle filters denied rows), `src/cli/brain/verbs/bank-export.ts` (stderr omission notice, same shape as its content-class notice), `tests/core/brain/portability/knowledge-pack.test.ts`, `tests/cli/export-redaction.test.ts` (bundle and bank-export pins).+- **Acceptance**: the knowledge-pack test fails first, then passes: a marked preference is absent from the pack and named in `blocked`; the bank bundle excludes it and the verb names it; unmarked vaults produce byte-identical bundle output.+- **Depends on**: B1.++### Lane C - capture writes++#### Task C1: dead-letter schema v2 with frozen payload (Lane C, card `t_50794f57`)+- **Files**: `src/core/brain/dead-letter.ts` (`DEAD_LETTER_SCHEMA_VERSION` to 2; optional `payload` on `DeadLetterRecord` and `RecordDeadLetterInput`; serializer field order; strict per-version parsing, unknown versions refuse), `src/core/brain/extract-signals.ts` (the failure-time record call passes the validated items), `tests/core/brain/dead-letter.test.ts`.+- **Acceptance**: the schema tests fail first, then pass: v2 round-trips with the payload; v1 letters parse unchanged and carry no payload; an unknown version refuses with today's error; the extractor's letter carries the items it failed to write.+- **Depends on**: none.++#### Task C2: recovery classifier (Lane C)+- **Files**: `src/core/brain/dead-letter-recovery.ts` (new; `classifyDeadLetter` returning category, reason and exact command string; `planRecovery` per-item verdicts; `applyRecovery` delegating to `commitExtractedSignals` with the recorded payload), `tests/core/brain/dead-letter-recovery.test.ts` (new).+- **Acceptance**: the classifier table fails first, then passes over fixture vaults: `recover` for a v2 letter whose session is still capture-classified with undelivered missing items; `pending` when the items sit staged in the write-approval queue; `re-extract` for a v1 letter; `not_recoverable` for an unknown or now-ignored session and for an unknown lane; `resolved` when every missing key exists on disk; apply re-runs at current state and already-written items dedup away.+- **Depends on**: C1.++#### Task C3: dead-letters verb and wiring (Lane C)+- **Files**: `src/cli/brain/verbs/dead-letters.ts` (new; list default with per-row copy-paste commands, `show <id>`, `recover <id>` dry-run default, `--apply` requiring `--yes` under `--json`/non-TTY, frozen-vault and vault-identity guards, retention preserved), `src/cli/brain.ts` (imports and dispatch case), `src/cli/brain/verbs/index.ts` (export), `src/cli/command-manifest.ts` (row), `src/cli/brain/help-text.ts` (row), `src/core/brain/diagnostics.ts` (`DIAGNOSTIC_SIGNALS` entry pointing at the verb), `tests/cli/brain-dead-letters.test.ts` (new).+- **Acceptance**: the CLI test fails first, then passes: list renders classification and recovery command per row and exits 0; recover previews per-item verdicts dry; `--apply` without `--yes` under `--json`/non-TTY refuses typed; a frozen vault refuses; nothing ever deletes the letter; `help-surface-parity` and `completions` pass once the manifest row exists.+- **Depends on**: C2.++#### Task C4: standalone validation gate (Lane C, card `t_dc782fd5`)+- **Files**: `src/core/brain/vault-dirty.ts` (new; `git status --porcelain` over the vault, vault-relative Markdown paths, modified + added + untracked, named non-worktree refusal), `src/cli/brain/verbs/validate.ts` (new; `--paths`/`--dirty` exactly-one selection, `lintPagesWithContext` reuse, exit contract errors 1 / `--strict` warnings 2 / unreadable named page 1 / clean 0, `--json` in `PageLintReport` shape), `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/command-manifest.ts`, `src/cli/brain/help-text.ts`, `tests/cli/brain-validate.test.ts` (new).+- **Acceptance**: the CLI test fails first, then passes: paths mode lints the named set; dirty mode over a fixture repo picks up modified, added and untracked Markdown; the exit matrix holds including strict warnings and the unreadable-named-page block; a non-worktree vault refuses with exit 2; giving neither or both selectors is a usage error; no auto-fix exists.+- **Depends on**: none (independent of C1-C3; wiring-file edits are serial within the lane).++### Lane D - operator surfaces++#### Task D1: folder lifecycle core (Lane D, card `t_9571a47f`)+- **Files**: `src/core/brain/notes/folder-lifecycle.ts` (new; folder envelope mirroring `resolveNoteTarget` minus the `.md` rung; move-set planning; occupancy pre-flight with `destination_occupied`; per-file link-assert-unlink relocation; pairs and rewrite over the successfully moved set; `FolderLifecycleResult`), `src/core/brain/notes/lifecycle.ts` (`move-folder` and `rename-folder` added to `NOTE_LIFECYCLE_ACTION` with docblocks), `tests/core/brain/notes/folder-lifecycle.test.ts` (new).+- **Acceptance**: the suite fails first, then passes: envelope refusals (`Brain/` destination, vault root as source, scope exclusions, `source_missing`); occupied destination file or directory refuses with nothing moved and the source untouched; applied moves relocate every file, rewrite inbound path-spelled links in one pass to minimal spellings, leave bare-basename links untouched and resolving, and name mid-set failures in `moveFailures` with pairs computed from the moved set only; dry-run is the default and writes nothing.+- **Depends on**: none.++#### Task D2: folder surfaces (Lane D)+- **Files**: `src/cli/brain/verbs/note-lifecycle.ts` (action dispatch and renderer `moved`/`moveFailures` lines), `src/mcp/brain/lifecycle-file-tools.ts` (action enum flows from the extended constant; `path` description covers folders), `tests/core/brain/notes/folder-lifecycle.test.ts` (surface cases).+- **Acceptance**: the surface tests fail first, then pass: `move-folder` to a same-parent destination and `rename-folder` across parents refuse `wrong_action`; `delete`/`archive` refuse for folder actions; the MCP tool accepts the new actions through the one constant; the vocabulary census passes without census edits (the entry self-derives).+- **Depends on**: D1.++#### Task D3: status store group (Lane D, card `t_cfe2ce5d`)+- **Files**: `src/core/brain/operator-snapshot.ts` (`store` group on `OperatorSnapshot`: `writerLock` three-state fail-soft, `writerLockReason`, `writerLockAgeMs`, `writerLockOwner` always null v1, `writerLockPath`, `thisCaller: "read-only"`; injected `writerLockHeldAt` seam; renderer line on both branches), `src/mcp/brain/health-tools.ts` (`brain_status` payload carries `store`; `writerLockPath` withheld below local reach), `tests/core/brain.operator-snapshot.test.ts`, `tests/cli/status.test.ts`, `tests/mcp/maintenance-status-reach.test.ts`.+- **Acceptance**: the snapshot tests fail first, then pass: no lock dir reads `free`; a lock directory created the way `proper-lockfile` does reads `held` with a non-negative age; an injected throw reads `unknown` with the errno in the reason; owner is null with a held lock and the renderer says the record carries no identity; `healthy` stays true and `problems` unchanged when held; CLI `--json` and human output carry the group; MCP withholds the path below local reach while keeping the state fields.+- **Depends on**: none.++#### Task D4: doctor client-versions probe (Lane D, card `t_8e49ec96`)+- **Files**: `src/core/doctor-readiness.ts` (`client_versions` probe appended to `DEFAULT_PROBES` after `registered_commands`; constant target-to-argv table with `generic: null`; async spawn inside the per-probe timeout; pass/unknown/skipped grading; optional additive `rows` field on `ReadinessProbeResult`, set only here), `src/cli/main.ts` (readiness rendering lists the rows under the probe detail), `tests/core/doctor-readiness.test.ts` (new `probeClientVersions` describe).+- **Acceptance**: the probe tests fail first, then pass: an answered spawn yields `pass` with the raw first stdout line; runner throw, non-zero exit, timeout and empty stdout each yield `unknown` with the reason; null-command and manifest-less runs yield `skipped`; mixed aggregates read `unknown` with the census; `rows` appears on this probe and no other; a fully-unknown probe keeps doctor at exit 6, not 1. The table's binary names are verified against each adapter's detect logic before the task lands (only `codex` and `copilot-cli` are confirmed by in-repo precedent).+- **Depends on**: none.++### Integrator/docs phase (outside the four lanes; runs after all lanes land)++#### Task I1: consolidated docs and CHANGELOG+- **Files**: `docs/cli-reference.md` (tail-trim diagnostics wording, dead-letters and validate rows, note-lifecycle folder actions, status store line, doctor readiness probe), `docs/mcp.md` (`brain_context_pack` trim block, `brain_context_receipts` presence member, `brain_note_lifecycle` folder actions, `brain_status` store group, hook-less-agent validate pointer), `CHANGELOG.md` (one release narrative and bullets for all eight features, byte-identity guarantees named explicitly), `src/cli/command-manifest.ts` (note-lifecycle description line), `src/cli/brain/help-text.ts` (usage block with the folder actions).+- **Acceptance**: the full gates pass - typecheck, formatter and linter clean tree-wide, the full test suite green including `help-surface-parity`, `completions`, the vocabulary census and the fold-decision census; every docs row matches the shipped behavior.+- **Depends on**: Lanes A, B, C, D all landed.diff --git a/docs/brainstorm/verified-delivery-honest-writes/variants.md b/docs/brainstorm/verified-delivery-honest-writes/variants.mdnew file mode 100644index 00000000..04c193dc--- /dev/null+++ b/docs/brainstorm/verified-delivery-honest-writes/variants.md@@ -0,0 +1,91 @@+# Cycle 20261026 (verified-delivery-honest-writes) - lane variants (consultant output) and final rationale++The consultant ran in host execution mode against the wave's recon reports. Two real variants per lane, with the recommendation and the orchestrator decision. Variant content is grounded in the recons' alternatives and open questions; the design decisions in `design.md` encode the winners.++## Lane A - delivery (`t_cb6a5558`, `t_f8510c55`)++### Variant A1: in-walker trim with comparator score reuse; presence as a sibling continuity record+- **Approach**: The trim runs after the unified walker in `packContext`, reusing the ranked-mode jaccard kernel (`relevanceById`) the comparator already computes; top-3 keep, restatement keep-rule, whole-item drops with a new `"tail-trim"` skip reason, and freed budget offered back to `over-budget` candidates in priority order. Reply presence is folded by the existing answer-quote-check Stop loop into a sibling `reply_presence` continuity record joined to the receipt by `session_id`, with `ANSWER_QUOTE_VERDICT` extended by `absent` and the `session_inject` receipt gaining its missing session key.+- **Trade-offs**:+ - Pros: zero duplicate scoring work; the off-path stays byte-identical by construction; the context receipt is automatically correct because finalize maps `report.items`; rescue (the card's load-bearing behavior) is expressible because skipped candidates are still in hand; one verdict vocabulary and an append-only record respect the store's contract; the join key is fixed at the source instead of inferred from time windows.+ - Cons: the trim covers the unified path only until someone extends it to the `packingPolicy` branch (explicitly out of v1); a new continuity kind obligates the fold-decision row and a documented join contract; presence rows grow the ledger per checked turn.+- **Complexity**: medium+- **Risk**: low++### Variant A2: post-finalize delivery stage; presence via the existing log channel+- **Approach**: Apply the trim as a stage inside `finalizeContextPackReport` operating on `report.items`, uniformly across the unified and packing-policy return paths. Carry reply presence only through the channels the Stop hook already writes - the `additionalContext` annotation and the enforce-mode Brain-log `note` event - with no new continuity kind.+- **Trade-offs**:+ - Pros: one trim site covering both return paths; no new record kind, no fold decision, no join contract; the ledger stays quieter.+ - Cons: rescue is impossible at that point - `skipped` candidates are already resolved and their budget accounting closed, so the card's term-aware rescue cannot exist; in substring or semantic modes scores must be recomputed at finalize, duplicating comparator work; Brain-log events are local, unsynced and unread by the receipt surface, so presence would be unwritable into `brain_context_receipts` - the read surface the card's consumers use; the enforce log only exists under `enforce`, so shadow-mode operators get nothing.+- **Complexity**: medium+- **Risk**: high (the receipt read surface - the actual deliverable - cannot be served)++### Recommended: Variant A1+**Rationale**: The rescue rule and the receipt join are the two behaviors the cards name as their value, and only A1 can express either: rescue needs the walker's live skip list, and presence needs a store the receipt read surface can join against. A1 also reuses both verified seams (jaccard kernel, Stop-hook check loop) with no duplicated computation, and its costs - one record kind plus one verdict member - are census-silent or single-row decisions.++## Lane B - export privacy (`t_b88c2190`)++### Variant B1: collector-level denial with named omissions everywhere+- **Approach**: Compute the denial once in `collectPreferenceRows` from the frontmatter map the collector already parsed, as a report beside complete `rows`; teach the json envelope (`omitted`, absent when empty), the llms-txt detailed variant, the bank bundle and the knowledge pack to drop denied rows and name each omission with reason `"visibility"`.+- **Trade-offs**:+ - Pros: one deny judgment reused by every consumer; `rows` stays complete so the import-side topic maps keep seeing every preference; every shared surface names its omissions, so no two exporters disagree about the same directory; byte-identity holds because `omitted` is absent-when-empty; the SDK signatures stay stable behind delegating detail functions.+ - Cons: touches five source files across the shared surfaces; the bundle consistency extension is wider than the validator's narrowest reading of the card; a new envelope field requires the absent-when-empty discipline to be tested, not assumed.+- **Complexity**: medium+- **Risk**: low++### Variant B2: verb-layer filtering+- **Approach**: Leave the collectors untouched; filter denied preferences inside `brain export` and `brain bank-export` by re-reading frontmatter at the verb layer, with the knowledge pack left as-is.+- **Trade-offs**:+ - Pros: the core export module and its envelope schema are untouched; zero byte-identity pressure; the smallest possible diff for the CLI lane alone.+ - Cons: the SDK façade and `exportBankBundle` call the collectors directly, so those shared surfaces keep leaking marked preferences - the exact failure mode the card names; frontmatter is parsed twice per file; the knowledge pack keeps shipping preferences that every other lane denies, so surfaces disagree; the deny logic lives where it is hardest to test exhaustively.+- **Complexity**: small+- **Risk**: high (shared surfaces remain inconsistent - the defect survives)++### Recommended: Variant B1+**Rationale**: The card's value is a privacy class honored by shared surfaces, and B2 leaves the SDK and bundle lanes leaking by construction. B1 computes the deny once at the seam where the data is already in hand and makes every consumer name what it leaves out, matching the v1.92.0 name-every-omission convention; its extra breadth is three small, independently testable surfaces.++## Lane C - capture writes (`t_50794f57`, `t_dc782fd5`)++### Variant C1: new flat verbs with a core classifier module+- **Approach**: `o2b brain dead-letters` (list/show/recover) over a new `dead-letter-recovery.ts` classifier, dead-letter schema v2 freezing the payload at failure time; `o2b brain validate` as a read-only selection-driven gate reusing `lintPagesWithContext` verbatim; a tiny `vault-dirty.ts` helper for the git-dirty selection. Lane C owns all four wiring files.+- **Trade-offs**:+ - Pros: each surface has one contract - the recovery verb can carry the consent ladder (dry-run default, headless `--yes`) without negotiating with an existing verb's pinned behavior; the classifier is core-testable over fixture vaults independent of CLI wiring; `validate`'s exit code is unambiguous; the manifest rows make both verbs discoverable through help and completions for free.+ - Cons: two new verbs and four manifest/help rows to land; the wiring files concentrate both cards' mechanical edits in one lane (the reason for the exclusive ownership rule).+- **Complexity**: medium+- **Risk**: low++### Variant C2: overload the existing verbs+- **Approach**: Recovery as a subcommand of `brain repair-lane` (which is already a repair surface); validation as `--paths`/`--dirty` flags on `brain lint`, changing its exit code to block.+- **Trade-offs**:+ - Pros: no new manifest rows or wiring edits; the repair verb is an established destructive-consent surface; `lint` already runs non-interactively.+ - Cons: `repair-lane` is memory-graph repair - dead extraction writes are a different domain with a different retention rule, and folding them in muddies both; `brain lint`'s always-exit-0 report contract is pinned by tests and relied on by callers, so repurposing it is a breaking surface change smuggled into a flag; the validate gate would inherit `--consolidate`'s required-flag grammar it does not use; the recovery verb would still need its own dry-run/apply grammar, so the overload saves nothing real.+- **Complexity**: medium+- **Risk**: high (breaks a pinned contract and conflates two domains)++### Recommended: Variant C1+**Rationale**: Both cards are new operator surfaces with new contracts, and the repo's flat-verb convention plus the free manifest-derived help make new verbs cheaper than overloads that break `lint`'s pinned exit contract. The wiring-file concentration is real but is exactly what the lane ownership rule absorbs; the classifier and helper stay core modules testable without the CLI.++## Lane D - operator surfaces (`t_9571a47f`, `t_cfe2ce5d`, `t_8e49ec96`)++### Variant D1: extensions on the existing surfaces+- **Approach**: Two folder actions on the note-lifecycle verb and MCP tool, backed by a new core `folder-lifecycle.ts` that reuses the relocation primitive and the `retargetWikilinks` pair engine; the status `store` group inside the operator snapshot with an injected lock-probe seam; a `client_versions` probe appended to the readiness registry beside `registered_commands`.+- **Trade-offs**:+ - Pros: the file surface's rename/move mistake-guard extends to folders from day one; occupancy pre-flight, partial-failure reporting and the count guard keep their established meanings; the snapshot already resolves the dbPath and `brain_status` flows additive fields to MCP with zero plumbing; the probe inherits the timeout machinery, grading vocabulary and manifest detection; none of it touches the wiring files Lane C owns.+ - Cons: `lifecycle.ts` gains the action vocabulary in a file that is already large (the reason the core logic goes to a new module); the snapshot field must be documented as search-lock-scoped so it is not read as covering the brain `.lock` family; the version command table needs per-adapter verification beyond the two confirmed binary names.+- **Complexity**: medium+- **Risk**: low++### Variant D2: dedicated new surfaces+- **Approach**: A new `brain folder` verb with its own MCP tool for folder operations; a separate `brain lock-status` verb for store ownership; a standalone `--client-versions` doctor flag instead of a registry probe.+- **Trade-offs**:+ - Pros: zero contact with existing modules' shapes; each surface ships independently.+ - Cons: a new folder verb duplicates the envelope, relocation and rewrite machinery that `note-lifecycle` already composes, and a new verb requires exactly the wiring files the cross-lane contract assigns to Lane C - the variant is structurally non-viable under the ownership rule; a lock-status verb re-composes the snapshot it already builds (doctor, semantic health, hygiene) to answer one question the snapshot can carry as a group; a doctor flag outside the probe registry drifts from the timeout, grading and reporting machinery the other probes share.+- **Complexity**: large+- **Risk**: high (ownership violation plus surface fragmentation)++### Recommended: Variant D1+**Rationale**: All three cards ask for visibility on surfaces operators already use, and D1 is the only variant that respects both the product's surface economy and the lane contract: extensions carry the established guards, reporting shapes and census discipline with additive fields, while D2 would need Lane C's wiring files and would fragment three surfaces that are already composed.++## Orchestrator acceptance note++The orchestrator accepts the consultant's recommendations for all four lanes: A1, B1, C1, D1. The decision rule across the wave was to reuse the seam each recon verified rather than build a parallel surface, and to make every new fact land in an existing reporting contract (skip reasons and gap telemetry, `omitted`/`blocked` omission naming, readiness rows, snapshot groups, continuity record kinds) instead of a second vocabulary. The losing variants were rejected for cause, not taste: A2 cannot serve the receipt read surface the card exists for, B2 leaves two shared surfaces leaking the exact content the card denies, C2 breaks a pinned exit contract, and D2 violates the lane ownership contract while duplicating composed machinery. No variant overrides the consultant's recommendation; the honest-scope notes in `design.md` (lock owner reported as null, signal-lane re-admission at current state with schema v2) are recon-mandated narrowing, not variant substitutions.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 876742c5..44654851 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -443,8 +443,8 @@ o2b brain snapshot log (CLI-only) Newest-first listing of every recoveryo2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, or snapshot vs live Brain/o2b brain rollback (CLI-only) Restore Brain/ from a snapshot (--dry-run previews; drift abort vs --force-rollback); --list, the prompt and --json name the snapshot reason ('unknown' when the sidecar records none)o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes; --dry-run and --check also print the last failed automatic upgrade-o2b brain export Read-only dump of active preferences, or (since v1.50.0) a session-transcript dataset: --format json|llms-txt|transcripts-jsonl [--out <path>] [--force]; the transcript form takes --transcripts <file|dir> and reads no vault at all (see "The transcript corpus" below). Since v1.49.0 the preference bytes pass the shared egress redactor (stderr carries a notice when anything was removed), and a `pref-*.md` the parser cannot read is REFUSED, not skipped: exit 1 naming every unreadable file in one run rather than exit 0 over a shorter list. `o2b brain doctor` reports the same files-o2b brain bank-export (CLI-only) One-file backup bundle: preferences, the page graph, page contracts, the sources dashboard. Redacted on the way out; refuses with exit 1 on an unreadable `pref-*.md` (since v1.49.0)+o2b brain export Read-only dump of active preferences, or (since v1.50.0) a session-transcript dataset: --format json|llms-txt|transcripts-jsonl [--out <path>] [--force]; the transcript form takes --transcripts <file|dir> and reads no vault at all (see "The transcript corpus" below). Since v1.49.0 the preference bytes pass the shared egress redactor (stderr carries a notice when anything was removed), and a `pref-*.md` the parser cannot read is REFUSED, not skipped: exit 1 naming every unreadable file in one run rather than exit 0 over a shorter list. `o2b brain doctor` reports the same files. Since v1.95.0 a preference the privacy deny markers reserve (`visibility: private` or an informal marker saying the same) leaves the json and llms-txt preference dumps before the redactor runs and is named in the run's omission list - the json envelope carries an `omitted` field (absent when nothing was denied, so unmarked vaults stay byte-identical) and the stderr notice names each denied page with the reservation key that denied it; the run still exits 0+o2b brain bank-export (CLI-only) One-file backup bundle: preferences, the page graph, page contracts, the sources dashboard. Redacted on the way out; refuses with exit 1 on an unreadable `pref-*.md` (since v1.49.0). Since v1.95.0 a privacy-marker-denied preference row is filtered from the bundle's preferences section before the bundle is composed and named in its `preferences_omitted` report (absent when empty) beside the same stderr notice, so a smaller bundle is never a silent one; unmarked vaults produce byte-identical bundleso2b brain bank-import (CLI-only) Restore a bank bundle (--mode skip|overwrite|merge) [--trusted-restore]. Preference rows restore UNTRUSTED by default: every row lands `unconfirmed`, unpinned, at low confidence, on a fresh trial window dated from the restore - including a row the bundle already marked unconfirmed - and the run names each row it reset; `--trusted-restore` keeps the carried status, confidence, pin and window verbatim, for a backup you vouch for. A malformed preference already in the DESTINATION does not abort the import: the rows restore and the run prints `topic-key check incomplete: <path>` for each rule the topic-collision scan could not read, because that list is then a partial answer (since v1.49.0)o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode). Since v1.49.0 BOTH modes refuse a Brain file they cannot parse - `--export` writes nothing and exits 1, and live mode does not start, because a browser showing a silently smaller graph is the same lie as a written file - and `--export` runs the shared redactor over the graph, so its output differs from a pre-v1.49.0 export on any vault holding a credential-shaped value. Since v1.86.0 live mode serves two read-only console routes beside the graph, `/counts.json` (recall-telemetry summary, most-recalled artifacts, a written-per-day histogram over the trailing 30 days, per-surface report-snapshot dates that read as disabled while the feature is off) and `/status.json` (the operator snapshot), both re-reading the vault on every GET, and the page renders Counts and Vault status sections from them; a static export states that the live routes are unreachable instead of firing fetches that can only failo2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...). --remediate [--dry-run] plans a dependency-ordered repair and applies auto-safe content-hash re-stamps. Since v1.81.0 the report also prints a count-only archive section over Brain/.archives/ (entries, combined bytes, stamped pages whose entry is missing or mismatched, entries no page cites; silent on a vault that never archived a source) and runs the fail-soft `blank-session-identity` check, counting continuity records still carrying the legacy blank session id; both are informational and neither repairs@@ -470,7 +470,7 @@ o2b brain today Read-only today dashboard: due and overdue obligato2b brain apply-markers Turn `@osb set note=<target> field=<field> value=<value>` markers into schema-validated frontmatter writes. Report mode by default (writes nothing); --apply needs `guardrails.marker_writeback` in _brain.yaml, consumes applied markers so a re-run is idempotent, and leaves unresolvable or refused targets unconsumed; --path <subdir> (repeatable) or notes.read_pathso2b brain import-session Replay signals from a registered agent session .jsonl (or directory); --recall also stores turns in the session recall DAG. Since v1.50.0 the path argument has a machine-wide sibling: --status reports per-runtime coverage, --discover lists what has never been imported, --discover --all imports it, and --propose-backlog batches the already-imported undistilled backlog into one ask-once distill envelope (see "Session logs this machine already has" below)o2b brain session-hook Internal hook bridge: read one lifecycle payload from stdin, capture prompt markers / brain_feedback, append lifecycle audit/log rows-o2b brain context-receipts List/show opt-in prompt context receipt continuity records (since v0.29.0)+o2b brain context-receipts List/show opt-in prompt context receipt continuity records (since v0.29.0). Since v1.95.0 `show` joins the receipt to its session's `reply_presence` continuity record - the per-note verdicts the answer-quote-check Stop hook folded for the session's latest checked turn (`verified` / strongest miss / `absent` per injected note, plus the reply-span count and the answer-text hash) - keyed by exact `session_id`, never a time-window guess: a receipt whose session wrote no presence record, or that names no session at all, reports `unjoined` and names which of the two it was, so a missing join is never read as a silent all-clear. `list` stays a summary and carries no joino2b brain recall-telemetry List/summarise opt-in recall telemetry continuity records (since v0.29.0)o2b brain generation-reports Record/list/summarise opt-in inbound LLM generation traces (prompt hash + token counts only; kernel never calls an LLM)o2b brain context-presets Show/suggest/diff read-only context budget presets (since v0.29.0)@@ -481,7 +481,9 @@ o2b brain session-describe Count raw turns and deterministic summary depths fo2b brain session-expand Expand a session recall node to immediate sources and paginated raw turn content (since v0.29.0)o2b brain session-summary write|get|list a session-scoped structured digest (request/decisions/learnings/next_steps) (since v1.11.0)o2b brain idea-lineage Trace how a derived artifact was reached: observation -> synthesis -> conclusion over continuity sourceRefs or belief-evolution (since v1.11.0)-o2b brain note-lifecycle <rename|move|archive|delete> <path> [<to>] [--apply] [--confirm] [--expect N] [--strict] [--json] - note-FILE lifecycle; source and destination both go through the create-note path envelope. Dry-run without --apply; delete also needs --confirm. A relocation rewrites inbound [[wikilinks]] vault-wide to the minimal spelling that still resolves to the destination (the bare basename only when exactly one note carries it; a bare name the rename turns from unique to ambiguous is repaired to the unambiguous spelling of its pre-rename target) and the receipt names how stale the search index still is and whether the write claimed the detached refresh; delete rewrites nothing, reports the references it strands, and returns a recoverability verdict saying the archive it took does not cover a note outside Brain/+o2b brain note-lifecycle <rename|move|archive|delete|move-folder|rename-folder> <path> [<to>] [--apply] [--confirm] [--expect N] [--strict] [--json] - note-FILE lifecycle; source and destination both go through the create-note path envelope. Dry-run without --apply; delete also needs --confirm. A relocation rewrites inbound [[wikilinks]] vault-wide to the minimal spelling that still resolves to the destination (the bare basename only when exactly one note carries it; a bare name the rename turns from unique to ambiguous is repaired to the unambiguous spelling of its pre-rename target) and the receipt names how stale the search index still is and whether the write claimed the detached refresh; delete rewrites nothing, reports the references it strands, and returns a recoverability verdict saying the archive it took does not cover a note outside Brain/. Since v1.95.0 the folder actions move a whole folder: `move-folder` relocates it under a destination parent, `rename-folder` renames it within its parent (the split mirrors rename vs move - a caller that meant one and spells the other is refused `wrong_action`, not moved by accident); every destination is checked free before the first rename, so an occupied destination refuses with nothing moved and the source untouched, and the move set's inbound path-spelled links are rewritten in one pass over the successfully moved set. No rollback: a mid-set failure is named per file in `move_failures` (residue in the source folder lands in `left_behind`, absent when empty) with the pairs computed from what actually moved; dry-run is the default+o2b brain dead-letters [list] | show <id> | recover <id> [--dry-run | --apply] [--yes] [--agent <name>] [--json] (since v1.95.0) - the exit for a dead letter, the durable record of a multi-artifact extraction write that failed part way. `list` (the default) renders every letter with its classification - recover, pending, re-extract, not_recoverable, resolved - and the exact copy-paste command that resolves it; `show <id>` prints one letter in full, missing keys and frozen payload named; `recover <id>` re-runs a schema-2 letter's frozen payload through the extraction commit at CURRENT vault state, so already-written items dedup away and nothing stale is replayed. Recover is dry-run by default and previews the per-item verdicts; --apply performs the re-run and requires --yes under --json or a non-TTY stdin; a frozen vault refuses; an unknown id and passing --dry-run beside --apply are usage errors (exit 2), a refused recovery exits 1. NOTHING here deletes a letter: a recovered letter is retained, and removing it stays an operator's hand action on the named file. A v1 letter (written before the payload was frozen) classifies re-extract+o2b brain validate --paths <path> [--paths <path>...] [--strict] | --dirty [--strict] [--vault <path>] [--json] (since v1.95.0) - the standalone validation gate for hook-less writers: runs the exact write-receipt page lint over exactly one caller-named page set - --paths (vault-relative, repeatable, one flag per page) or --dirty (every git-dirty Markdown note: modified, added and untracked) - and nothing else, so it is safe inside any gate. The exit code is the product, byte-for-byte the doctor contract: an error finding exits 1, warnings exit 2 under --strict, a named page the lint could not read exits 1, clean exits 0; a vault that is not inside a git worktree refuses --dirty with exit 2 naming --paths as the remedy, and giving neither or both selectors is a usage error. Report-only: the fixes stay with `brain doctor --repair --apply` and `brain lint --consolidate --apply`, which every finding's next_command nameso2b brain scaffold-stub list [--limit N] [--json] | write <target> [--path <p>] [--source <s>...] [--if-exists refuse|skip] [--apply] [--json] - unresolved wikilink targets. list reads them from the search index and refuses with a state and a next_command when that index is missing or only partially resolved, never printing an empty list for an index nobody finished resolving; write materialises a stub whose title is the target and whose body links back to its sources. A target that already resolves, or names several notes, is refusedo2b brain note-history Decompose a note's git history into episodic phases split on a commit-time gap (since v1.11.0)o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence; --approval-digest <hex> seals the plan - non-interactive --apply must carry the digest a prior --dry-run printed and then lands exactly the approved plan or nothing (a stale digest refuses with a re-run remedy), an entry whose name cannot land a parseable tag skips as a named row instead of aborting, and a digest paired with --dry-run refuses@@ -507,7 +509,7 @@ o2b brain page-dedup Page-level duplicate detector (by content hash + fo2b brain doctor gains the `merge-chain-dangling` warning (since v1.64.0): a `merged_into:` pointer whose canonical resolves to no file - the page silently dropped out of dedup candidacy forever; chains crossing Brain/retired/ are walked, and cycle, depth and malformed intermediates stay with `o2b brain lint --consolidate`'s unresolved list; the repair is a content judgement (re-point at a surviving canonical, remove the pointer to un-merge, or restore the file), so the finding names the judgement instead of a next commando2b brain lint Self-healing structural drift fixer; --consolidate folds multi-source duplicateso2b brain token-footprint Token-budget monitor across instruction files and active.md-o2b brain context-pack Bounded-token vault slice for priming an agent's context window (--max-tokens N, --lanes for directives/constraints/consider; v0.29.0 adds opt-in --receipt, --telemetry, --cache-stable, --dedup-repeated)+o2b brain context-pack Bounded-token vault slice for priming an agent's context window (--max-tokens N, --lanes for directives/constraints/consider; v0.29.0 adds opt-in --receipt, --telemetry, --cache-stable, --dedup-repeated). Since v1.95.0 the opt-in score-aware tail trim (`tail_trim_context_pack` config key or `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`, default off) is MCP-only - `brain_context_pack` runs it; this CLI verb never reads the gate and never trims - and on the tool it drops whole low-relevance tail items after the unified walk whenever the call carries a query: the top three delivered items are immune, an item whose query-term coverage is at least 0.8 of the top delivered score is kept, the freed budget is offered back to over-budget candidates in priority order, and the response carries a conditional `tail_trim` block (`dropped`, `kept_by_query_terms`, `rescued`, `tokens_saved`) only when the trim ran; with the key off packs are byte-identicalo2b brain synthesise Concept-scoped JSON envelope: target node + linkers + optional unlinked mentionso2b brain moc-audit Per-MOC coverage audit: classify cluster members into well-covered / fragile / candidate-missingo2b brain unlinked Raw-text mentions outside `[[...]]` (Unicode-aware boundaries)@@ -725,7 +727,7 @@ o2b brain batch-plan gains --src-subpath <rel> (scope a monorepo ingesto2b brain pre-extract <file> [--json] - deterministic no-LLM code-structure extraction (classes, functions, imports, inheritance edges, and in .tsx/.jsx files uses edges to the components opening tags name, as JSON entity/edge seeds) for TypeScript, JavaScript, and Python, and Terraform (.tf, .tfvars) block seeds in address syntax (resource, data, module, variable, output, provider, locals) with depends_on and references edges and a module source as an imports seed; .tfvars yields variable names, never values; credentials in any import specifier are redacted (the userinfo of an http(s), git+http(s) or git:: specifier, a user:password pair or a bare token, and the value of a named credential query parameter such as sshkey, token or an S3 or GCS signing key, also on a specifier that is not a URL such as git@host:org/repo?sshkey=...; a conventional login such as ssh://git@ is kept, and a credential in a path segment, a fragment or an unnamed query parameter is not recognised); a specifier longer than 2048 characters is carried as the redaction placeholder; on the ingest path a source larger than 1 MiB is skipped with a reason naming the limit; relative imports are bound to files (resolved_to) only on the ingest path, which has the content manifest; unknown extensions report extracted:false with a reason, never an empty success. Terraform limits, by name: .hcl and .tf.json files, attribute values, nested blocks (lifecycle, dynamic, provisioner, connection) as entities, depends_on expressions, citations inside heredocs or template files, for_each and count expansion, moved, import, check and removed blocks, terraform {} settings and required_providers, resolution of a local module source to a directory, and a block header split across lines are not read, the items of a multi-line depends_on list are read as ordinary citations and seeded as references, not depends_on, and quotes inside an interpolation (`"${f("x")}"`) are not tracked, which can end it early and drop citations later on that lineo2b brain scan-citations [--strict] - promote structural [Source: <name>, YYYY-MM-DD] markers in note prose into dated source-citation events on the temporal timeline; dedup on normalized name + date, malformed markers are reported and skipped (--strict exits nonzero on them)o2b brain doctor gains --repair (preview targeted fixes for doctor-detected classes: dangling workrun checkpoints, dead evidence links; dry-run default) and --repair --apply (perform the fixes idempotently, one typed doctor-repair event each); unfixable classes are reported needs-review; plain doctor and --strict stay read-only-o2b brain status one consolidated operator snapshot: doctor, semantic health, hygiene, stale scan, review queue depth, active profile, and state-file health; every problem line carries the exact next command from the shared diagnostics-signal registry; healthy vaults print a compact all-clear+o2b brain status one consolidated operator snapshot: doctor, semantic health, hygiene, stale scan, review queue depth, active profile, and state-file health; every problem line carries the exact next command from the shared diagnostics-signal registry; healthy vaults print a compact all-clear. Since v1.95.0 the snapshot gains a `store` group stating what it can honestly measure about the memory store: the search writer lock's three-state read (`held` / `free` / `unknown` - "could not find out" is never rendered as "free"), a reason when unknown, the held-lock age, the lock path, and `thisCaller: "read-only"`; the owner member is `null` while a lock is held, because the lock record carries no identity, and the renderer says so; a held lock is informational and never flips the snapshot unhealthy```The hygiene file scan now honors nested `.gitignore` files with git@@ -773,7 +775,7 @@ the wait.### Trusted recall and memory write surface (since v1.35.0)```text-o2b doctor gains --readiness: six 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; since v1.64.0 every registered client command still resolvable - a proved-absent absolute path fails naming the client and `o2b install <target> --apply`, a relative path is unresolved because the client resolves it from its own working directory, an unresolvable bare name is unknown because the host spawns with its own PATH - and the workspace agent-instruction files (`AGENTS.md`, `CLAUDE.md`, `GEMINI.md`) carrying the marker write-back contract block, conforming / missing-block / malformed-block / missing-clauses / absent / symlink / unreadable; a file without the block is graded skipped because the block is not installed, while a malformed or incomplete block fails) 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-identical+o2b doctor gains --readiness: nine functional probes (model-inference key resolvable, embedding provider loadable with model and dims, the recorded provider-consent decision named beside the provider environment variables still present (skipped when none is recorded, unknown when the record cannot be read), runtime-adapter construction, installed runtimes verified off disk through each adapter's own verify; since v1.64.0 every registered client command still resolvable - a proved-absent absolute path fails naming the client and `o2b install <target> --apply`, a relative path is unresolved because the client resolves it from its own working directory, an unresolvable bare name is unknown because the host spawns with its own PATH - and the workspace agent-instruction files (`AGENTS.md`, `CLAUDE.md`, `GEMINI.md`) carrying the marker write-back contract block, conforming / missing-block / malformed-block / missing-clauses / absent / symlink / unreadable; a file without the block is graded skipped because the block is not installed, while a malformed or incomplete block fails; and the optional decision-model config checked without sending anything - skipped when the feature is off, keyless or opted out, failing only an enabled config with an invalid value; since v1.95.0 the `client_versions` probe asks each detected agent client its version through its own version argv under the per-probe timeout, one row per target (`pass` with the raw first stdout line, `unknown` naming why - a thrown runner, a non-zero exit, a timeout, empty stdout - or `skipped` when the target has no version argv or no manifest entry), and an all-unknown probe keeps doctor at exit 6, never 1, because a version it cannot read proves nothing broken) 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```diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex be39a8f6..962a0d9f 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -1284,6 +1284,24 @@ semantic_weight·cosine + link_boost + recency_boost + entity_boost)`per-memory and total character caps, and `brain_pre_compress_pack`returns a budgeted top-preferences-plus-active.md addendum forpre-compression injection.+- **Score-aware tail trim (config-gated).** With+ `tail_trim_context_pack: "true"` in the machine-local main config (or+ the env override `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`; the+ default is off), `brain_context_pack` runs one score-aware trim over+ the unified tier-and-budget walk whenever the call carries a query:+ the top three delivered items are immune, any later item whose+ query-term coverage - the fraction of the query's tokens it carries -+ is at least 0.8 of the top delivered score is kept (it restates the+ question's terms nearly as fully as the top hit), and the rest drop+ whole with a `tail-trim` skip reason - never partially re-cut. The+ freed budget is then offered back to `over-budget` candidates in+ priority order, the only path by which a page can cross tiers,+ spending the tokens the trim freed and no more, and never reordering+ or dropping the synthesized attention item. The response+ carries a conditional `tail_trim` block (`dropped`,+ `kept_by_query_terms`, `rescued`, `tokens_saved`) only when the trim+ ran. With the key off - the default - packs are byte-identical, and+ the `packing_policy` branch never trims.- **Semantic policy.** Implicit semantic (config default) warns andfalls back to keyword-only when sqlite-vec is unavailable, the keyis missing, the provider is down, or no embeddings exist yet.diff --git a/docs/mcp.md b/docs/mcp.mdindex ca472dbd..2ab0a2ed 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -382,8 +382,8 @@ flags for a narrower per-process full server.| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, a selectable recall `profile` (`fast \| balanced \| thorough`), an FTS `match_mode` (`all` \| `any`), a pushed `kind` filter (`page` \| `section`) plus SQL pushdown for the promoted `properties` keys (since v1.80.0), and since v1.82.0 an opt-in iterative recall loop (`iterative`, `iterative_token`, `iterative_payload`) whose surviving coverage gaps pause with a plan the caller answers. | `query` || `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` || `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. When the caller passes `scores` AND `match_quality` (the `idf_weighted_coverage` a search outcome reports - the two stand or fall together, and an incomplete pair is refused), also attaches an adequacy verdict (`sufficient` \| `weak` \| `insufficient`), a recommended action (`proceed` \| `re_recall` \| `abstain`), and an optional `escalate` flag. The LEVEL is decided by `match_quality` alone; the scores decide only the usable-result count. Thresholds via `recall_adequacy_sufficient` / `recall_adequacy_weak` / `recall_adequacy_min_results`. Since v1.82.0 a measured call also returns the shared graded surfacing key (`key`, `tier`) beside the binary decision. | `prompt` |-| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. Each item carries a structural `epistemic` status (`observed` \| `derived` \| `hypothesis` \| `plan` \| `unknown`) plus `evidence_refs` derived from existing graph metadata; fields are absent when the status is `unknown`. Takes the same adequacy pair as `brain_recall_gate` under its own spelling, `recall_scores` AND `match_quality`: both or neither, an incomplete pair is refused, and the schema states it as `dependentRequired` keyed on this tool's own scores name. Since v1.91.0 an opt-in `entity_facts_context_pack` config key (default off, env `OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK`) adds a conditional `entity_facts` section: the canonical-scope entities anchored from the query, at most three, each listing only ids the pack already kept whose bodies anchor it; the key is absent when off, so the default pack stays byte-identical. | `max_tokens` |-| `brain_context_receipts` | List or show opt-in prompt context receipt continuity records with budgets, hashes, source refs, safety/redaction metadata, and item IDs. | `operation` |+| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. Each item carries a structural `epistemic` status (`observed` \| `derived` \| `hypothesis` \| `plan` \| `unknown`) plus `evidence_refs` derived from existing graph metadata; fields are absent when the status is `unknown`. Takes the same adequacy pair as `brain_recall_gate` under its own spelling, `recall_scores` AND `match_quality`: both or neither, an incomplete pair is refused, and the schema states it as `dependentRequired` keyed on this tool's own scores name. Since v1.91.0 an opt-in `entity_facts_context_pack` config key (default off, env `OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK`) adds a conditional `entity_facts` section: the canonical-scope entities anchored from the query, at most three, each listing only ids the pack already kept whose bodies anchor it; the key is absent when off, so the default pack stays byte-identical. Since v1.95.0 an opt-in `tail_trim_context_pack` config key (default off, env `OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK`) adds a score-aware tail trim whenever the call carries a query: the top three delivered items are immune, an item whose query-term overlap nearly matches the top delivered score is kept, the rest drop whole with a `tail-trim` skip reason, and the freed budget is offered back to `over-budget` candidates in priority order; the response carries a conditional `tail_trim` block (`dropped`, `kept_by_query_terms`, `rescued`, `tokens_saved`) only when the trim ran, and with the key off the pack is byte-identical. | `max_tokens` |+| `brain_context_receipts` | List or show opt-in prompt context receipt continuity records with budgets, hashes, source refs, safety/redaction metadata, and item IDs. Since v1.95.0 `show` joins the receipt to its session's `reply_presence` continuity record by exact `session_id`: the per-note verdicts the answer-quote-check Stop hook folded for the session's latest checked turn (`verified` / strongest miss / `absent` per injected note, the reply-span count, the answer-text hash), or the named `unjoined` outcome when the receipt's session wrote no presence record or names none - a missing join is disclosed, never inferred from a time window. The join runs at the caller's reach: note rows for paths the reach view cannot read are withheld and counted (`withheld`). | `operation` || `brain_recall_telemetry` | List or summarise opt-in recall telemetry records for search, context-pack, and pre-compress calls; since v1.80.0 the `dead_weight` operation reports in-scope pages no recorded recall ever surfaced. | `operation` || `brain_route_metrics` | List or summarise opt-in route-level MCP tool latency (`mcp_route_latency` records); `summary` rolls each tool up into count, error count, and min/avg/max + p50/p95/p99 latency, slowest-first, plus a per-stage count/avg/p95 for a route whose records carry write stages. Emitted only when `mcp_route_metrics_enabled` is on; payload-safe (tool, scope, status, duration, arg key names, stage names). Read-only. | `operation` || `brain_retrieval_plan` | Shadow-only retrieval advisor for one `question`: composes query intent/weights, the summary-surface route, the context-pack density allocation, the token-impact ledger, and observed route p95 latency into a strategy, token-budget allocation, graph-expansion advice, reliability, and a marginal-value stop. Optional `token_budget`. Read-only; exposes no mutating parameters and changes no ranking. | `question` |@@ -406,7 +406,7 @@ flags for a narrower per-process full server.| `brain_session_expand` | Expand a raw or summary session recall node to immediate sources and paginated raw turn content. | `id` || `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — || `brain_create_note` | Write an actual vault note file (path + frontmatter + content) atomically inside the vault. Distinct from `brain_note` (log append); refuses traversal, the Brain root, excluded paths, any destination outside the declared write binding, and — by default — clobbering. Opt-in: `if_exists: "skip"` returns `outcome: "skipped"` instead of creating, `strict` validates the document before writing and reports coded violations, and `template` + `template_variables` render the body through a closed two-construct grammar (`{{name}}` substitution; `{{#name}}…{{/name}}` presence sections and list iteration with `{{.}}`). Unknown placeholders are left intact. | `path` |-| `brain_note_lifecycle` | Note-FILE lifecycle, dispatched on `action`: `rename` (new filename, same directory), `move` (new directory, same filename), `archive` (displaces the note under `Archive/`, mirroring its path), `delete` (removes it). Both the source and the destination go through the same nine-step path envelope `brain_create_note` uses, so a destination cannot reach where a create could not. Dry-run unless `apply: true`; `delete` additionally requires `confirm: true` and honours `expect` / `strict` over the inbound-reference count. A relocation rewrites inbound `[[links]]` vault-wide to the minimal spelling that still resolves to the destination - a bare basename only when exactly one note carries it, and a bare name the rename turns from unique to ambiguous repaired to the unambiguous spelling of its pre-rename target - and the result names the rewritten spellings, what it withheld, how stale the search index still is (`references.index`) and whether the write claimed the detached refresh (`references.refresh`). A delete rewrites nothing, reports the references it strands, and returns a `recoverability` verdict saying the archive it took does not cover a note living outside `Brain/`. | `action`, `path` |+| `brain_note_lifecycle` | Note-FILE lifecycle, dispatched on `action`: `rename` (new filename, same directory), `move` (new directory, same filename), `archive` (displaces the note under `Archive/`, mirroring its path), `delete` (removes it). Both the source and the destination go through the same nine-step path envelope `brain_create_note` uses, so a destination cannot reach where a create could not. Dry-run unless `apply: true`; `delete` additionally requires `confirm: true` and honours `expect` / `strict` over the inbound-reference count. A relocation rewrites inbound `[[links]]` vault-wide to the minimal spelling that still resolves to the destination - a bare basename only when exactly one note carries it, and a bare name the rename turns from unique to ambiguous repaired to the unambiguous spelling of its pre-rename target - and the result names the rewritten spellings, what it withheld, how stale the search index still is (`references.index`) and whether the write claimed the detached refresh (`references.refresh`). A delete rewrites nothing, reports the references it strands, and returns a `recoverability` verdict saying the archive it took does not cover a note living outside `Brain/`. Since v1.95.0 two folder actions join the enum: `move-folder` relocates a whole folder under a destination parent and `rename-folder` renames it within its parent, split for the same reason `rename` and `move` are (a caller that meant one and spells the other is refused `wrong_action`); every destination is checked free before the first rename so an occupied destination refuses with nothing moved, the move set's inbound path-spelled links are rewritten in one pass over the successfully moved set, a mid-set failure is named per file in `move_failures` (and any residue in the source folder in `left_behind`, absent when empty) with no rollback, and dry-run stays the default. | `action`, `path` || `brain_scaffold_stub` | Unresolved wikilink targets. `action: "list"` reads them from the search index and REFUSES - `state` plus a `next_command` - when that index is missing, unreadable or only partially resolved, rather than reporting zero: an empty list from an index nobody finished resolving is a clean bill of health for a vault nobody measured. `action: "write"` materialises a stub for one target through the same `createNote` envelope and `if_exists` semantics as `brain_create_note` - its title is the target the link spelled and its body links back to the `sources` documents, each of which must be an existing Markdown note inside the vault or the call is refused with `unknown_source` - so nothing the stub cites is invented, though whether a cited document really carries the reference is `action: "list"`'s claim, read from the index, not this write's. A target that already resolves, or that names more than one note, is refused with its candidates. Dry-run unless `apply: true`. | `action` || `brain_file_context` | Given a file path, surface prior vault work that mentions it (decisions, bug notes, refactor history) by querying the index with path-derived terms. Size gate skips trivial files. Read-only; no LLM. | `file_path` || `brain_session_summary` | Session-scoped structured digest over request/decisions/learnings/next_steps: `write` stores agent-extracted categories, `get` returns a session's latest digest, `list` returns all. Append-only, deduped; an all-empty digest is rejected. | `operation` |@@ -2804,3 +2804,23 @@ format characters), when it contains NUL, or when it exceeds the cap.already carries: a readable page may name a private page, and noper-page gate rewrites prose - a stored pledge cites bytes its sourcecontained, not a privacy guarantee over every name the source spelled.+- Since v1.95.0 `brain_status` carries a `store` group stating what the+ snapshot can honestly measure about the memory store: the search writer+ lock's three-state read (`held` / `free` / `unknown` - a state the+ probe could not take reads `unknown` with a reason, never `free`), the+ held-lock age in milliseconds, the lock path, and `thisCaller:+ "read-only"`; the `writerLockOwner` member is `null` while a lock is+ held, because the lock record carries no identity, and that null is a+ measurement, not an omission. A held lock is informational and never+ flips the snapshot unhealthy. Below local reach the lock PATH is+ withheld (a resolved host path may sit outside the vault) while every+ state field stays.+- Since v1.95.0 the receipt join and the new gates add no MCP tool of+ their own by design: `brain_context_receipts` `show` gains the+ `reply_presence` join on its existing tool (see the table above), the+ dead-letter exit+ (`o2b brain dead-letters` list / show / recover) stays CLI-only, and a+ hook-less agent that needs a commit-blocking validation gate runs+ `o2b brain validate --paths <page>... | --dirty [--strict]` - the same+ write-receipt lint the write path enforces, with the doctor's exit+ contract (errors 1, `--strict` warnings 2, clean 0) as the product.diff --git a/docs/observability.md b/docs/observability.mdindex 19c5d965..7418bb8e 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -212,6 +212,7 @@ 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_recall_telemetry` `operation: "dead_weight"` (MCP) and `o2b brain recall-telemetry dead-weight` (since v1.80.0) read the other side of the same records: pages currently in scope that no recorded recall within the telemetry window ever surfaced. The denominator is the vault walk's included paths (current on-disk truth), not the index's document table, so a deleted-but-indexed page is never reported as dead weight; the retrieved set is the union of recorded `top_artifacts` and observed-use source references, windowed by `--since`/`--until` (the report states the earliest matching record). The payload carries `pages_total`, `pages_retrieved`, `dead_count` and a capped `dead` list behind the usual `vault_path` envelope, plus a `gate_caveat`: telemetry is opt-in and records only surfaced top rows, so the report claims "no recorded retrieval surface within telemetry history", never absolute never. Read-only; at remote reach hidden rows are dropped before `total`.- `brain_context_receipts` and `o2b brain context-receipts` inspect served-context receipts.+- The score-aware tail trim (opt-in `tail_trim_context_pack` config key, default off) adds to a `context_pack` `recall_telemetry` record's `metadata` four counters, present only when the trim actually ran: `tail_trim_dropped` (tail items dropped whole), `tail_trim_kept_by_query_terms` (tail items kept because their query-term overlap nearly matched the top delivered score), `tail_trim_rescued` (former `over-budget` candidates re-admitted under the freed budget) and `tail_trim_tokens_saved` (tokens freed, net of the budget the rescue re-spent; never negative, because the rescue may spend only the budget the trim freed). The same counters ride the `context_receipt` `budget` block, and each dropped item's `tail-trim` skip reason surfaces as the telemetry gap `tail_trim`. An untrimmed pack carries none of these keys, so its records stay byte-identical.- The answer-quote-check Stop hook (since v1.81.0) is the answer-boundary counterpart of the receipts above: it verifies the quoted spans in the assistant's own answer against the evidence the turn actually had - the note a span's context names, else the injection ledger's delivered notes - and annotates the unverified ones. Verdicts: `verified`, `not-in-note`, `source-truncated`, `note-unavailable`, `not-text`; degradation never upgrades a verdict, so a truncated source arms `source-truncated` on a miss and an unreadable note arms `note-unavailable`, never an all-clear. The annotation rides the Stop `additionalContext` channel Claude Code renders; the other registered runtimes stay silent. Gated per phase by `quote_check.recall|active|subagent` in `_brain.yaml`, each `off|shadow|enforce`, default `shadow`; in `enforce` the turn also lands one Brain-log `note` event (the enforce trail in the table above), so findings survive the session. The check reads only the transcript's bounded tail window and writes nothing else; it never blocks and never edits a transcript.- The SessionStart hook writes one `context_receipt` per injection (`host: "hook"`, `trigger: "session_inject"`) with one item per source it injected. On a measured run its `budget` block carries `inject_budget_chars` (the configured value), `budgeted_source_count` and, since v1.70.0, `scoped_rules_chars`: the length of the rendered scoped operator rules block, `0` when none rendered. The scoped block is a budgeted source named `scoped-rules`, but it is subtracted from the budget rather than charged against the full ceiling: the active body was budgeted to `inject_budget_chars` minus `scoped_rules_chars` (never below zero). The `budget` block is present whenever the scoped block rendered, also when there is no `active.md`. A run that fell back to the last good cache records no `budget` block, as before, but keeps the `standing-rules` and `scoped-rules` items, which are produced outside the fail-open boundary. See "Scoped operator rules" in [`how-it-works.md`](how-it-works.md).- With `reground_parts_enabled` on, the same receipt's `extra.injection` gains the chunked re-grounding fields: `utf16_chars` (the joined payload length in UTF-16 code units), `part_ceiling_chars` (the per-part ceiling it was cut to, `null` on a runtime without the `reground-deliver` carrier or without a session id), `parts_total`, `parts_dropped` (parts past the 8-part maximum that were never queued; when it is above zero the last delivered part ends with `(context truncated: N further part(s) not delivered)`) and `over_budget` (`true` when parts were dropped, when a part is still longer than the ceiling, or when the queue could not be written and the whole payload went out as one part). That last case also sets `reground_fallback: "ledger_write_failed"`, which no other path writes, so a failed queue write is told apart from a plain over-budget payload. A part-ceiling key (`reground_part_chars`, `reground_part_chars_claudecode`, `reground_part_chars_codex`) whose value is out of range or not an integer falls through to the next level and is named in `config_invalid` (by its environment variable, such as `OPEN_SECOND_BRAIN_REGROUND_PART_CHARS`, when the rejected value came from the environment), present only then. With the flag off none of these fields appears and the receipt keeps its shape. Each part the `reground-deliver` hook hands out writes one hook-audit line (`actor: reground-deliver`, `action: reground_part_delivered`, `target` the host event `PostToolUse` or `UserPromptSubmit`) with `part` (the 1-based part number), `total`, `epoch` (the SessionStart that queued it, as `<source>:<epoch-ms>` with the source one of `startup`, `resume`, `clear` or `compact`, any other value recorded as `unknown`), `bytes` (UTF-8), `utf16_chars`, `part_ceiling_chars` and `over_budget` (the part alone is longer than the ceiling). A take that fails for a reason other than lock contention (an unreadable state directory, a full disk) writes `action: reground_take_failed` with `ok: false`, no part and `epoch` (the queue's SessionStart, `null` when unreadable), once per epoch on each machine: a state write that keeps failing leaves the queue undrained, and the repeats on later tool calls write no further line. A tool call inside a delegated sub-agent (the payload carries `agent_id`) takes no part and writes no line. A process-ceiling exit writes `action: hook_ceiling_exceeded`, `target: reground`.diff --git a/hooks/README.md b/hooks/README.mdindex 2ed7441d..63d807d6 100644--- a/hooks/README.md+++ b/hooks/README.md@@ -20,7 +20,7 @@ hook payload shape, not on the runtime.| Event | Matcher | Behaviour || ------------------ | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `SessionStart` | `startup\|resume\|clear\|compact` | Injects the budgeted `Brain/active.md` body (default 8,000 chars, `active.inject_budget_chars` in `_brain.yaml`) and records a non-blocking `session-lifecycle` observation. The `compact` matcher is the post-compaction re-injection path. |+| `SessionStart` | `startup\|resume\|clear\|compact` | Injects the budgeted `Brain/active.md` body (default 8,000 chars, `active.inject_budget_chars` in `_brain.yaml`) and records a non-blocking `session-lifecycle` observation. The `compact` matcher is the post-compaction re-injection path. Since v1.95.0 the `session_inject` context receipt this lane emits carries the payload's real session id as its `session_id` member (absent when the host sent none), the join key the receipt's `reply_presence` read joins on. || `SessionStart` | `startup\|resume\|clear\|compact` | Opt-in (`log_catchup_enabled` in the machine-local `config.yaml` - NOT `_brain.yaml`; the gate reads the main config, like every default-OFF boolean - or `OPEN_SECOND_BRAIN_LOG_CATCHUP_ENABLED`, default off): `log-catchup` hands the agent the `Brain/log` lines OTHER agents appended since its identity's last look on this device - newest 50 as one fenced `additionalContext` block, a count of older ones, every line attributed to the agent that wrote it. "Me" resolves the config-resolved agent name, else the device id; self-authored lines are filtered. A first run has no cursor to read since: its scan is bounded to five dates behind the newest real date in the log (`LOG_CATCHUP_FIRST_RUN_WINDOW_DATES`) — older days are counted, never parsed, and reported once as `N older day(s) not scanned` (as a header-only block when nothing foreign surfaced), emitted only when that run's cursor write parks below, so the report never repeats against an unreadable window. The cursor is one un-synced `(date, shardId, line)` watermark with per-shard high-water marks per reading identity, under `<vault>/.open-second-brain/log-catchup.<identity>-<digest>.cursor.json` (the identity sanitized into the file name, `<digest>` 8 hex of the raw name so colliding identities never share a file; overwrite-only, symlink-guarded, fail-soft). It is rewritten on every run that actually scanned the log - silent runs included, so an idle vault does not rescan history at each start - keeping a three-date window of marks. The lane is a pure read - `Brain/log` is byte-identical after every run and stays distinct from the session-capture lifecycle event - and exits 0 on every path.| `UserPromptSubmit` | `*` | Captures explicit `@osb feedback ...` markers from the submitted prompt immediately through the signal/dedup boundary. || `UserPromptSubmit` | `*` | Opt-in (`reground_parts_enabled`, default off): `reground-deliver` hands out the next queued part of an oversized SessionStart payload as `additionalContext`. A prompt carries a part rather than cancelling the queue, because after a manual `/compact` the next event is usually a prompt. |@@ -33,7 +33,7 @@ hook payload shape, not on the runtime.| `SubagentStart` | `*` | Primary carrier: delivers the operator's context payload into a delegated sub-agent's context at its conversation start, before its first prompt, and again if the subagent compacts - the host re-fires the event then, and the re-injection lands only if this hook answers that later event. The payload is what the session-start lane composes, through the same assembly: the standing rules, the scoped operator rules for this project and device, and the budgeted `Brain/active.md` + `Brain/lessons.md` digest under the same `active.inject_budget_chars` ceiling (runtime notices ride along when that channel is on). No tool gating - the event itself marks the sub-agent - and no ledger suppression: every SubagentStart for the id re-delivers, while the ledger it feeds after each delivery keeps the PostToolUse fallback row above to once per sub-agent per session. Runtimes without a SubagentStart event never fire this row; the fallback covers them. || `PostCompact` | `manual\|auto` | Records a post-compact lifecycle observation only. Current Claude Code has no PostCompact hook event and rejects `additionalContext` under that name - re-injection moved to the SessionStart `compact` matcher; the registration stays as a silent no-op for older runtimes. || `Stop` | (every Stop) | If the turn produced a durable artifact and none of `brain_feedback` / `brain_apply_evidence` / `brain_note` landed, continues the turn once with a one-line reminder, then lets the second Stop pass. Claude Code gets `hookSpecificOutput.additionalContext` (shown as "Stop hook feedback", not a hook error); Codex, Grok Build and unrecognised runtimes get `decision: "block"` with the same line as `reason`. |-| `Stop` | (every Stop) | `answer-quote-check` verifies the quoted spans in the assistant's answer against the evidence the turn actually had: the note a span's context names (wikilink or vault-relative path), else membership in the injection ledger's delivered notes for the phases running. Five verdicts - `verified`, `not-in-note`, `source-truncated`, `note-unavailable`, `not-text` - and degradation never upgrades one: a note whose body reached context truncated arms `source-truncated` on a miss, an unreadable note arms `note-unavailable`, never an all-clear. Per-phase config in `_brain.yaml` (`quote_check.recall`, `quote_check.active`, `quote_check.subagent`, each `off\|shadow\|enforce`, default `shadow`); `enforce` also appends exactly one Brain-log `note` event per turn so findings survive the session. One non-blocking `hookSpecificOutput.additionalContext` annotation per turn lists the unverified spans as flattened, capped previews; Claude Code renders it, other runtimes stay silent. Never blocks, never edits a transcript: bounded message-window and character reads, fail-open exit 0. |+| `Stop` | (every Stop) | `answer-quote-check` verifies the quoted spans in the assistant's answer against the evidence the turn actually had: the note a span's context names (wikilink or vault-relative path), else membership in the injection ledger's delivered notes for the phases running. Five verdicts - `verified`, `not-in-note`, `source-truncated`, `note-unavailable`, `not-text` - and degradation never upgrades one: a note whose body reached context truncated arms `source-truncated` on a miss, an unreadable note arms `note-unavailable`, never an all-clear. Per-phase config in `_brain.yaml` (`quote_check.recall`, `quote_check.active`, `quote_check.subagent`, each `off\|shadow\|enforce`, default `shadow`); `enforce` also appends exactly one Brain-log `note` event per turn so findings survive the session. One non-blocking `hookSpecificOutput.additionalContext` annotation per turn lists the unverified spans as flattened, capped previews; Claude Code renders it, other runtimes stay silent. Never blocks, never edits a transcript: bounded message-window and character reads, fail-open exit 0. Since v1.95.0 every checked turn also folds ONE session-keyed `reply_presence` continuity record - a verdict per injected note (`verified` when a reply span checked out against it, the strongest miss verdict otherwise, `absent` when no span was ever measured against it, `note-unavailable` when the hook's time budget ran out before any span reached it or the turn's reply text never arrived), written even when every span verified and only when the turn had injected candidates at all. The record carries identifiers and verdicts only - never answer text (the answer is bound by hash) - and the session's records are what the receipt read surfaces join on: a receipt join matches the session by exact session id and folds every record written at or after the receipt's own creation, chronologically, with `verified` winning across turns, so one turn's record never answers for another's. A host that sends no real session id has no injection ledger to read, so the turn writes no presence record at all, and a receipt join then reads `unjoined`, which is the honest report rather than a fault. || `Stop` | (every Stop) | Opt-in (`hygiene_digest_enabled`, default off): `hygiene-digest` surfaces pending Brain hygiene findings as one line, once per change. Artifact-writing turns run the default sweep plus the dangling-link count; findings of warning and action severity fold into counts per detector, and a hash ledger keeps an unchanged set silent. Claude Code only: the line rides its non-blocking `hookSpecificOutput.additionalContext` Stop feedback, and on runtimes where a Stop block would force a continuation turn (Codex, Grok Build, unrecognised) the hook stays silent - an opt-in digest never buys a continuation. Checked before the vault, so it is cheap when off. || `SubagentStop` | `*` | Records a non-blocking lifecycle observation for a delegated sub-agent's close, attributed to `<delegator>-sub-<agent-id>` from the `agent_id` the event carries. The sibling `agent_transcript_path` is deliberately not persisted - it is a machine-local host path, and the sub-agent's turns reach memory through `o2b brain import-session`, which reads `isSidechain` and `agentId` off the transcript itself. || `SessionEnd` | `*` | Records a non-blocking lifecycle observation for session close. |@@ -134,8 +134,14 @@ call would.note or injection-ledger evidence, checks it through`src/core/brain/answer-quotes/check.ts`, and answers with one`additionalContext` annotation listing the unverified spans; in- `enforce` it also appends one Brain-log event. Never blocks, never- edits a transcript, fail-open.+ `enforce` it also appends one Brain-log event. Since v1.95.0 it folds+ one session-keyed `reply_presence` continuity record per checked turn+ (a `verified` / strongest-miss / `absent` verdict per injected note, or `note-unavailable` for a note the time budget left unmeasured or a turn whose reply text never arrived,+ from the same measured outcomes the annotation comes from; the+ receipt read surfaces join the session's records by exact session id,+ folding every record written at or after the receipt's own creation+ with `verified` winning across turns). Never blocks,+ never edits a transcript, fail-open.- `counterparty-brief.ts` — Bun entry script for the opt-inUserPromptSubmit counterparty brief (dated-commitments wave). Thin bydesign: the flag and the trigger vocabulary are checked first, thediff --git a/hooks/active-inject.ts b/hooks/active-inject.tsindex 61367c9d..9fab791a 100644--- a/hooks/active-inject.ts+++ b/hooks/active-inject.ts@@ -282,6 +282,7 @@ async function main(): Promise<void> {context,meter,reground: delivery.meter,+ sessionId: isRealSessionId(payload.session_id) ? payload.session_id : undefined,});} finally {disarm();@@ -550,6 +551,15 @@ interface RecordInjectionSizeInput {readonly context: string;readonly meter: InjectionMeter;readonly reground: RegroundMeter | null;+ /**+ * The hook payload's session id, already validated by the caller -+ * the join key the receipt's `session_id` payload member carries+ * (t_f8510c55), so the read surface can join this receipt to the+ * session's `reply_presence` records by exact key. `undefined` when+ * the host sent nothing real; the key then stays absent, never+ * invented.+ */+ readonly sessionId: string | undefined;}/**@@ -584,7 +594,13 @@ function recordInjectionSize(vault: string, input: RecordInjectionSizeInput): voconst measured = input.loaderSource === "fresh";const totalBytes = byteLength(input.context);emitContextReceipt(vault, {- options: { host: "hook", trigger: "session_inject" },+ options: {+ host: "hook",+ trigger: "session_inject",+ // The receipt-to-presence join key (t_f8510c55): recorded when the+ // host named a session, absent otherwise.+ ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),+ },items: input.meter.sources.filter((source) => measured || source.outsideBoundary).map((source) => ({diff --git a/hooks/answer-quote-check.ts b/hooks/answer-quote-check.tsindex 5f00af93..0a0c8528 100644--- a/hooks/answer-quote-check.ts+++ b/hooks/answer-quote-check.ts@@ -37,6 +37,19 @@* them: fail-open silence, kept deliberately, with the `enforce`* Brain-log trail as the one finding surface that survives the session.*+ * Reply presence (t_f8510c55). Wherever a transcript exists - annotation+ * rendering or not - every checked turn also appends exactly one+ * `reply_presence` continuity record: per injected note, whether a+ * quoted span verified against it, its strongest miss verdict, `absent`+ * when no span was ever measured against it, or `note-unavailable` when+ * the budget cut the walk before the note could be measured. A span+ * that verified is measured against the note that carries it alone, so+ * the per-note verdicts hold whichever way the candidates sort. The+ * record is keyed by session id and joined to the session's context+ * receipts on read; identifiers and verdicts only, never answer text.+ * The presence record rides the same per-phase modes: every phase `off`+ * writes nothing.+ ** Bounded, fail-open. The step reads at most* {@link ANSWER_QUOTE_TAIL_BYTES} of the transcript, the last* {@link ANSWER_QUOTE_MAX_MESSAGES} assistant messages of the turn,@@ -58,6 +71,7 @@ import {readSync,statSync,} from "node:fs";+import { createHash } from "node:crypto";import {resolveAnswerQuoteCheckActive,@@ -87,6 +101,8 @@ import {import { appendLogEvent } from "../src/core/brain/log.ts";import { BRAIN_LOG_EVENT_KIND } from "../src/core/brain/types.ts";import { isoSecond } from "../src/core/brain/time.ts";+import { appendContinuityRecord } from "../src/core/brain/continuity/store.ts";+import { CONTINUITY_SESSION_ID_KEY } from "../src/core/brain/continuity/types.ts";import { ensureInsideVault } from "../src/core/path-safety.ts";import { asHookPayload, readHookInput } from "./lib/stdin.ts";import {@@ -107,8 +123,25 @@ export const ANSWER_QUOTE_MAX_MESSAGES = 6;/** Per-message character budget: the prefix of a message that is checked. */export const ANSWER_QUOTE_MAX_CHARS = 4000;+/** The shipped wall-clock budget for the whole check. */+const ANSWER_QUOTE_DEFAULT_BUDGET_MS = 1500;++/**+ * The wall-clock budget, resolved ONCE at module load: a spawned hook+ * process honors an `ANSWER_QUOTE_BUDGET_MS` environment override - a+ * test seam for the budget-expiry arms, read a single time so a child's+ * whole run sees one budget; anything absent, blank or unparsable keeps+ * the shipped default.+ */+function resolveBudget(): number {+ const raw = process.env["ANSWER_QUOTE_BUDGET_MS"]?.trim();+ if (raw === undefined || raw.length === 0) return ANSWER_QUOTE_DEFAULT_BUDGET_MS;+ const parsed = Number(raw);+ return Number.isFinite(parsed) ? parsed : ANSWER_QUOTE_DEFAULT_BUDGET_MS;+}+/** Wall-clock budget for the whole check; past it, unchecked spans are dropped. */-export const ANSWER_QUOTE_BUDGET_MS = 1500;+export const ANSWER_QUOTE_BUDGET_MS: number = resolveBudget();/*** Ceiling on findings rendered in one annotation - and in one enforce@@ -457,8 +490,16 @@ function compareCandidates(return (a.startLine ?? 0) - (b.startLine ?? 0) || (a.endLine ?? 0) - (b.endLine ?? 0);}-/** The dedup key of one candidate view: the path, plus any range it names. */-function candidateKey(candidate: LedgerCandidate): string {+/**+ * The dedup key of one candidate view: the path, plus any range it names.+ * Takes the shape both the ledger candidates and the merged views share,+ * so the reply-presence fold can key its measured verdicts by it too.+ */+function candidateKey(candidate: {+ readonly path: string;+ readonly startLine?: number;+ readonly endLine?: number;+}): string {return candidate.startLine === undefined || candidate.endLine === undefined? candidate.path: `${candidate.path}\0${candidate.startLine}-${candidate.endLine}`;@@ -601,7 +642,7 @@ function ledgerCandidates(const seen = new Set<string>();const candidates: LedgerCandidate[] = [];const add = (candidate: Omit<LedgerCandidate, "phase">): void => {- const key = candidateKey({ ...candidate, phase });+ const key = candidateKey(candidate);if (seen.has(key)) return;seen.add(key);candidates.push({ ...candidate, phase });@@ -639,6 +680,12 @@ function ledgerCandidates(// ----- the check ------------------------------------------------------------+/** One candidate's verdict for one span, kept for the reply-presence fold. */+interface SpanCandidateOutcome {+ readonly candidate: MergedCandidate;+ readonly verdict: AnswerQuoteVerdict;+}+/** One span's outcome under the resolved evidence, inside the budget. */interface SpanOutcome {readonly verdict: AnswerQuoteVerdict;@@ -655,6 +702,19 @@ interface SpanOutcome {* and enforced only when one of those running phases enforces.*/readonly decidingPhases: ReadonlyArray<AnswerQuoteCheckPhase>;+ /**+ * The verdicts the reply-presence fold records for this span, in check+ * order (t_f8510c55). A span that verified somewhere records ONLY the+ * verifying candidate's outcome - the span belongs to the note that+ * carries it, and a candidate that missed it before the walk reached+ * the verifier did not measure the span in any sense worth reporting.+ * A span that verified nowhere records every candidate's miss. A+ * candidate left unmeasured appears here for no span, which the fold+ * reads as `absent`; a candidate the budget cut reads+ * `note-unavailable`, never `absent`, so an unspent budget can never+ * masquerade as an untouched note.+ */+ readonly candidateOutcomes: ReadonlyArray<SpanCandidateOutcome>;}/** One span's verdict under the resolved evidence, inside the budget. */@@ -675,10 +735,33 @@ function checkSpan(spans: [span.inner],evidence: evidenceFor(vault, mark),});+ // The span was MEASURED against the cited note's evidence, so every+ // ledger candidate naming the cited note records the outcome -+ // citing an injected note is the most explicit way to surface it,+ // and an empty outcome list here would fold that note `absent`+ // ("injected, never surfaced") against what the reply just did.+ // A mark with a line range rides only on the candidate whose+ // delivered view is that same range; a whole-note candidate matches+ // any citation of its note.+ const cited = candidates.filter(+ (candidate) =>+ candidate.path === mark.path &&+ (mark.startLine === undefined ||+ // A whole-note candidate is the note itself: any citation of+ // its path names content it delivered. (The merge also folds+ // every range of a path away once the whole note was+ // delivered, so a range-only match would miss it.)+ candidate.startLine === undefined ||+ candidateKey(candidate) === candidateKey(mark)),+ );return {verdict: outcomes[0]!.verdict,preview: outcomes[0]!.span,decidingPhases: [],+ candidateOutcomes: cited.map((candidate) => ({+ candidate,+ verdict: outcomes[0]!.verdict,+ })),};}if (candidates.length === 0) {@@ -686,16 +769,31 @@ function checkSpan(verdict: mergeAnswerQuoteVerdicts([]),preview: previewAnswerQuoteSpan(span.inner),decidingPhases: [],+ candidateOutcomes: [],};}const verdicts: AnswerQuoteVerdict[] = [];const decidingPhases: AnswerQuoteCheckPhase[] = [];+ const candidateOutcomes: SpanCandidateOutcome[] = [];let preview = previewAnswerQuoteSpan(span.inner);- for (const candidate of candidates) {+ for (const [index, candidate] of candidates.entries()) {if (Date.now() > deadline) {// Budget spent with unread candidates left: the check did not- // finish, so it never reports a readable-miss verdict.- return { verdict: ANSWER_QUOTE_VERDICT.noteUnavailable, preview, decidingPhases };+ // finish, so it never reports a readable-miss verdict. Every+ // unread candidate is recorded as `note-unavailable` for this+ // span - checked-and-unresolved, never silently untouched.+ return {+ verdict: ANSWER_QUOTE_VERDICT.noteUnavailable,+ preview,+ decidingPhases,+ candidateOutcomes: [+ ...candidateOutcomes,+ ...candidates.slice(index).map((unread) => ({+ candidate: unread,+ verdict: ANSWER_QUOTE_VERDICT.noteUnavailable,+ })),+ ],+ };}const mark: CitationMark = {at: -1,@@ -719,10 +817,90 @@ function checkSpan(const verdict = outcomes[0]!.verdict;preview = outcomes[0]!.span;verdicts.push(verdict);+ candidateOutcomes.push({ candidate, verdict });for (const phase of candidate.phases) decidingPhases.push(phase);if (verdict === ANSWER_QUOTE_VERDICT.verified) break;}- return { verdict: mergeAnswerQuoteVerdicts(verdicts), preview, decidingPhases };+ const merged = mergeAnswerQuoteVerdicts(verdicts);+ // A span that verified somewhere belongs to the note it verified+ // against: only that candidate's outcome is recorded. The misses the+ // walk accumulated before reaching the verifier were measurements of+ // the span against evidence that could not carry it - recording them+ // would make an unrelated note's verdict depend on whether its path+ // sorts before or after the verifying one. Per-candidate misses stay+ // only for spans that verified nowhere, where every miss is the+ // span's own history.+ const recordedOutcomes =+ merged === ANSWER_QUOTE_VERDICT.verified+ ? candidateOutcomes.filter((outcome) => outcome.verdict === ANSWER_QUOTE_VERDICT.verified)+ : candidateOutcomes;+ return {+ verdict: merged,+ preview,+ decidingPhases,+ candidateOutcomes: recordedOutcomes,+ };+}++/**+ * The per-note presence verdicts of one checked turn (t_f8510c55), one+ * row per candidate the injection ledger offered: `verified` when at+ * least one quoted span of the reply checked out against the note;+ * otherwise the strongest miss verdict across the spans that measured+ * it - the check module's own merge ladder, so degradation still+ * outranks a readable miss per note exactly as it does per turn;+ * {@link ANSWER_QUOTE_VERDICT.absent} for a note no span was ever+ * measured against - injected into context, never surfaced in the+ * answer, the row this record exists to surface; and+ * {@link ANSWER_QUOTE_VERDICT.noteUnavailable} for a note no span+ * measured while the budget was exhausted - the transcript went unread+ * past the cut, which is not evidence the note went untouched, so the+ * fold refuses to spend `absent` on it. A span that verified somewhere+ * measured only the note that carries it ({@link checkSpan} records the+ * verifying candidate alone), so a note's verdict is a fact about the+ * reply, never about where its path sorts. Rows carry identifiers and+ * verdicts only; no answer text rides the record.+ */+function foldReplyPresence(+ candidates: ReadonlyArray<MergedCandidate>,+ outcomes: ReadonlyArray<SpanCandidateOutcome>,+ budgetExhausted: boolean,+ replyRead: boolean,+): ReadonlyArray<Record<string, unknown>> {+ const measured = new Map<string, AnswerQuoteVerdict[]>();+ for (const outcome of outcomes) {+ const key = candidateKey(outcome.candidate);+ const verdicts = measured.get(key);+ if (verdicts === undefined) measured.set(key, [outcome.verdict]);+ else verdicts.push(outcome.verdict);+ }+ return candidates.map((candidate) => {+ const verdicts = measured.get(candidateKey(candidate));+ return {+ path: candidate.path,+ ...(candidate.startLine !== undefined ? { start_line: candidate.startLine } : {}),+ ...(candidate.endLine !== undefined ? { end_line: candidate.endLine } : {}),+ verdict:+ verdicts === undefined+ ? unmeasuredPresenceVerdict(budgetExhausted, replyRead)+ : mergeAnswerQuoteVerdicts(verdicts),+ };+ });+}++/**+ * The verdict for a note no span ever measured. When the walk's budget+ * ran out, or the reply text was never readable in the first place,+ * nothing was measured FOR A REASON - `note-unavailable`, the+ * checked-and-unresolved answer - never `absent`, which claims the reply+ * had every chance to touch the note and did not.+ */+function unmeasuredPresenceVerdict(+ budgetExhausted: boolean,+ replyRead: boolean,+): AnswerQuoteVerdict {+ if (budgetExhausted || !replyRead) return ANSWER_QUOTE_VERDICT.noteUnavailable;+ return ANSWER_QUOTE_VERDICT.absent;}/** `origin` label of the annotation's framing line for the quoted spans. */@@ -860,17 +1038,29 @@ async function main(): Promise<void> {const messages = lastAssistantMessages(transcriptPath);const findings: Array<AnswerQuoteSpanFinding> = [];+ const presenceOutcomes: SpanCandidateOutcome[] = [];let checked = 0;let enforceable = 0;+ // Set when a deadline comparison cuts the walk: spans never started+ // contribute no candidate outcomes, so their candidates would otherwise+ // fold as `absent` - a verdict the fold reserves for a note the reply+ // had every chance to touch and did not.+ let budgetExhausted = false;outer: for (const [messageIndex, message] of messages.entries()) {// Before the scans of this message, not only before its spans: the// span and path scans themselves cost the budget they precede.- if (Date.now() > deadline) break outer;+ if (Date.now() > deadline) {+ budgetExhausted = true;+ break outer;+ }const scan = findQuoteSpans(message);if (scan.spans.length === 0) continue;const marks = citationMarks(message);for (const span of scan.spans) {- if (Date.now() > deadline) break outer;+ if (Date.now() > deadline) {+ budgetExhausted = true;+ break outer;+ }checked++;const quoted: QuotedSpan = {message: messageIndex,@@ -879,6 +1069,7 @@ async function main(): Promise<void> {close: span.close,};const outcome = checkSpan(quoted, marks, candidates, vault, deadline);+ presenceOutcomes.push(...outcome.candidateOutcomes);if (outcome.verdict !== ANSWER_QUOTE_VERDICT.verified) {// Attribution: the phases whose candidates decided this miss. A// miss decided only by a phase switched to `off` is not this@@ -895,6 +1086,47 @@ async function main(): Promise<void> {}}}+ // The reply-presence record (t_f8510c55): exactly one per checked+ // turn, whatever the findings - a turn whose every span verified still+ // owes its per-note verdicts, and a note no span touched reads+ // `absent`, the row this record exists to surface - except when the+ // budget cut the walk or the reply text never arrived, where an+ // unmeasured note reads `note-unavailable` (the fold's own doc names+ // the distinction: an unmeasured note never reads as an unused one).+ // A turn with no injected candidate writes nothing: with no note to+ // report on, an empty verdict list would say nothing the absence of a+ // record does not say already - and the session id rides every record,+ // since the ledger candidates are unreachable without one. Fail-open+ // like every arm: a failed append names itself on the audit line and+ // the annotation still goes out.+ if (candidates.length > 0 && sessionId !== null) {+ try {+ appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: isoSecond(new Date()),+ payload: {+ [CONTINUITY_SESSION_ID_KEY]: sessionId,+ checked,+ per_note: foldReplyPresence(+ candidates,+ presenceOutcomes,+ budgetExhausted,+ messages.length > 0,+ ),+ // The hash binds the verdicts to the exact answer text checked;+ // it carries no answer text itself.+ ...(messages.length > 0+ ? {+ source_hash: createHash("sha256").update(messages.join("\n"), "utf8").digest("hex"),+ }+ : {}),+ },+ });+ } catch (err) {+ process.stderr.write(`${AUDIT_PREFIX} ${err instanceof Error ? err.message : String(err)}\n`);+ }+ }+const unique = dedupeFindings(findings);if (unique.length === 0) return;diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 82f99d5e..6c299ddb 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.94.0",+ "version": "1.95.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex b816a609..ceec7b10 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -2310,6 +2310,7 @@ __export(exports_config, {resolveSkillsAttachTriggers: () => resolveSkillsAttachTriggers,resolveSkillsAttachUsageOrdering: () => resolveSkillsAttachUsageOrdering,resolveSkillsDir: () => resolveSkillsDir,+ resolveTailTrimContextPack: () => resolveTailTrimContextPack,resolveTelegramBotToken: () => resolveTelegramBotToken,resolveTelegramCaptureAllowlist: () => resolveTelegramCaptureAllowlist,resolveTimezone: () => resolveTimezone,@@ -2628,6 +2629,9 @@ function resolveDensityRankingContextPack(configPath) {function resolveEntityFactsContextPack(configPath) {return resolveConfigFlag("OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK", "entity_facts_context_pack", configPath);}+function resolveTailTrimContextPack(configPath) {+ return resolveConfigFlag("OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK", "tail_trim_context_pack", configPath);+}function resolveCounterpartyBriefEnabled(configPath) {return resolveConfigFlag("OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED", "counterparty_brief_enabled", configPath);}diff --git a/package.json b/package.jsonindex f1fd7410..2d3a7f6f 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.94.0",+ "version": "1.95.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 498c9b49..16be1944 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.94.0"+version: "1.95.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 341cdf20..305b8969 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.94.0",+ "version": "1.95.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 498c9b49..16be1944 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.94.0"+version: "1.95.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 c8c05ae3..b1338d98 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"# `hermes_agent.memory_providers` group, not a CLI script.[project]name = "open-second-brain"-version = "1.94.0"+version = "1.95.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.ts b/src/cli/brain.tsindex 9a85defb..2e0453d0 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -120,6 +120,7 @@ import {cmdBrainDeepSynthesis,cmdBrainDiarize,cmdBrainExtractSignals,+ cmdBrainDeadLetters,cmdBrainDesignNote,cmdBrainIdeas,cmdBrainSessionHook,@@ -156,6 +157,7 @@ import {cmdBrainSessionExpand,cmdBrainSessionGrep,cmdBrainLint,+ cmdBrainValidate,cmdBrainActions,cmdBrainSummary,cmdBrainUnlinked,@@ -434,6 +436,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainDiarize(rest);case "extract-signals":return await cmdBrainExtractSignals(rest);+ case "dead-letters":+ return await cmdBrainDeadLetters(rest);case "design-note":return await cmdBrainDesignNote(rest);case "ideas":@@ -520,6 +524,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainSessionExpand(rest);case "lint":return await cmdBrainLint(rest);+ case "validate":+ return await cmdBrainValidate(rest);case "actions":return await cmdBrainActions(rest);case "summary":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 8e65c2ed..85fac66b 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -49,7 +49,7 @@ Brain verbs (observing memory):note Append a one-line narrative milestone to Brain/log/todaylifecycle Tombstone/supersede a memory, correct one record, resolve chain tips, curator slicesexpire Set, change or clear a signal's or preference's expiration date- note-lifecycle Note FILES: rename/move/archive/delete one, rewriting inbound links+ note-lifecycle Note FILES or FOLDERS: rename/move/archive/delete a file, move/rename a folder, rewriting inbound linksscaffold-stub Unresolved wikilink targets: list them, or materialise a stubclaims Claim-graph query: current truth, truth-at-T, replaced-by, contested-bydecision Decisions: record/outcome/show/list/similar + open questions: open/list_open/show_open/resolve/discard@@ -165,6 +165,7 @@ Brain verbs (observing memory):the adaptive topic-budget report)session-expand Expand a session recall node to source turnslint Self-healing structural checks (--consolidate); --apply to write+ validate Validation gate over --paths or --dirty notes; errors exit 1, --strict warnings exit 2actions Ranked maintenance action list (dedup + lint + footprint)summary Operator dashboard: trust verdict, doctor/dream counts, actionsunlinked Raw-text mentions of an artifact's title/aliases outside [[...]]@@ -185,6 +186,7 @@ Brain verbs (observing memory):deep-synthesis Topic dossier: notes, agreements, contradictions, stale claims, gapsdiarize Subject profile: document set, stated-vs-evidenced gap, needs-llm-step skeletonextract-signals Mine taste signals from an imported session's user turns (two-phase, needs-llm-step)+ dead-letters Dead extraction writes: list (default) | show <id> | recover <id> (dry-run; --apply --yes to write)design-note One-shot design note grounded in tensions, decisions and truth recordsideas Ranked next-direction candidates from open loops (--triggers to enqueue)continuity Export ATOF/ATIF trajectories, rank records by usage decay, promote host memory writes (export and rank are read-only; promote is dry-run by default)@@ -327,7 +329,7 @@ export const VERB_HELP: Record<string, string> = {"memory. An unparseable date, or an id naming no artifact, exits 2 by name.\n" +"Create-time expirations come from `o2b brain feedback --expires` instead.\n","note-lifecycle":- "usage: o2b brain note-lifecycle <rename|move|archive|delete> <path> [<to>]\n" ++ "usage: o2b brain note-lifecycle <rename|move|archive|delete|move-folder|rename-folder> <path> [<to>]\n" +" [--apply] [--confirm] [--delete-linked] [--expect <n>] [--strict] [--vault <path>]\n" +" [--config <path>] [--json]\n" +"Note FILES, not memories: rename changes the filename in place, move changes the\n" +@@ -343,6 +345,15 @@ export const VERB_HELP: Record<string, string> = {"as is a page citing a second source, as is every user note; the receipt prints\n" +"the deletion set and the reported set separately, names the scope it scanned,\n" +"and --expect then counts the deletion set.\n" ++ "The folder actions move a WHOLE folder: move-folder relocates it under a\n" ++ "destination parent, rename-folder renames it within its parent - the same\n" ++ "rename/move split as the file actions, so a caller that meant one and spells\n" ++ "the other is refused wrong_action rather than moved by accident. Every\n" ++ "destination is checked free before the first rename, so an occupied destination\n" ++ "refuses with nothing moved and the source untouched; the move set's inbound\n" ++ "path-spelled links are rewritten in one pass over the successfully moved set,\n" ++ "and a mid-set failure is named per file (the move_failures response keys, with\n" ++ "left_behind naming what stayed in the source) with no rollback.\n" +"Inbound [[wikilinks]] are rewritten across the vault, minus what vault scope\n" +"excludes, minus code fences, and minus Brain/log, which is append-only. The\n" +"receipt names how stale the search index now is and the command that fixes it.\n" +@@ -956,6 +967,24 @@ export const VERB_HELP: Record<string, string> = {"The note must weigh named alternatives and mark EXACTLY ONE recommended:\n" +"zero and two-plus are both refused, and the refusal states the count.\n" +"A note for the same topic on the same day is refused, never overwritten.\n",+ "dead-letters":+ "usage: o2b brain dead-letters [list] [--vault <path>] [--json]\n" ++ " o2b brain dead-letters show <id> [--vault <path>] [--json]\n" ++ " o2b brain dead-letters recover <id> [--dry-run] [--apply] [--yes]\n" ++ " [--agent <name>] [--vault <path>] [--json]\n" ++ "The exit for a dead letter - the durable record of a multi-artifact\n" ++ "extraction write that failed part way. `list` (the default) renders\n" ++ "every letter with its classification - recover, pending, re-extract,\n" ++ "not_recoverable, resolved - and the exact copy-paste command that\n" ++ "resolves it; `show <id>` prints one letter in full, missing keys and\n" ++ "frozen payload named; `recover <id>` re-runs a schema-2 letter's\n" ++ "frozen payload through the extraction commit at CURRENT vault state,\n" ++ "so already-written items dedup away and nothing stale is replayed.\n" ++ "Recover is dry-run by default and previews the per-item verdicts;\n" ++ "--apply performs the re-run and requires --yes under --json or a\n" ++ "non-TTY stdin. A frozen vault refuses. NOTHING here deletes a letter:\n" ++ "a recovered letter is retained, and removing it stays an operator's\n" ++ "hand action on the named file.\n","extract-signals":"usage: o2b brain extract-signals <session-ref> [--vault <vault>] [--agent <name>]\n" +" [--payload <json> | --payload-file <path>] [--json]\n" +@@ -1317,6 +1346,19 @@ export const VERB_HELP: Record<string, string> = {" older than 180 days with no recent\n" +" evidence to `_lifecycle: draft`.\n" +"Requires --yes in non-interactive mode (--json or non-TTY).\n",+ validate:+ "usage: o2b brain validate --paths <path> [--paths <path>...] [--strict] [--vault <path>] [--json]\n" ++ " o2b brain validate --dirty [--strict] [--vault <path>] [--json]\n" ++ "The standalone validation gate for hook-less writers. Runs the exact\n" ++ "write-receipt page lint over exactly one caller-named page set -\n" ++ "--paths (vault-relative, repeatable, one flag per page) or --dirty\n" ++ "(every git-dirty Markdown note, modified, added and untracked) - and\n" ++ "nothing else, so it is safe inside any gate. The exit code is the\n" ++ "product, byte-for-byte the doctor contract: an error finding exits 1,\n" ++ "warnings exit 2 under --strict, a named page the lint could not read\n" ++ "exits 1, clean exits 0. Report-only: the fixes stay with `brain doctor\n" ++ "--repair --apply` and `brain lint --consolidate --apply`, which every\n" ++ "finding's next_command names.\n",actions:"usage: o2b brain actions [--top-n <n>] [--vault <path>] [--json]\n" +"Ranked maintenance action list. Aggregates page-dedup, lint\n" +diff --git a/src/cli/brain/verbs/bank-export.ts b/src/cli/brain/verbs/bank-export.tsindex a8a77d94..b12e7f14 100644--- a/src/cli/brain/verbs/bank-export.ts+++ b/src/cli/brain/verbs/bank-export.ts@@ -1,5 +1,9 @@import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";-import { exportBankBundle } from "../../../core/brain/portability/bundle.ts";+import {+ exportBankBundleDetailed,+ type BankBundleExportOptions,+} from "../../../core/brain/portability/bundle.ts";+import { preferenceDenialNotice, type PreferenceDenial } from "../../../core/brain/export.ts";import {isPromptDerivedPage,omittedPageReferenceMatcher,@@ -29,10 +33,25 @@ function referenceOmissionNotice(dropped: number): string {}/**- * `o2b brain bank-export [--out <file>] [--include-prompt-derived]` -- * serialise a whole-vault bank bundle (preferences + page graph + page- * contracts + sources dashboard) to a schema-versioned JSON. Prints to- * stdout, or writes to `--out <file>`. Read-only on the vault.+ * The stderr line naming the reserved preferences a `--include-reserved`+ * run carried into the backup, in the `EGRESS_CONTENT_CLASS_INCLUDE_NOTICE`+ * shape: counted, each row named with the key that denied it, the flag+ * spelled, and the one-line account of what the override changed.+ */+function reservedInclusionNotice(denied: ReadonlyArray<PreferenceDenial>): string {+ const list = denied.map((d) => `${d.id} (${d.denied_by})`).join(", ");+ return (+ `note: ${denied.length} reserved preference(s) INCLUDED by override (--include-reserved): ` ++ `${list}; this personal backup carries material the shared lanes leave out\n`+ );+}++/**+ * `o2b brain bank-export [--out <file>] [--include-prompt-derived]+ * [--include-reserved]` - serialise a whole-vault bank bundle+ * (preferences + page graph + page contracts + sources dashboard) to a+ * schema-versioned JSON. Prints to stdout, or writes to `--out <file>`.+ * Read-only on the vault.** Every byte goes through the shared egress guard first (registry entry* `brain-bank-export`). The guard runs over the bundle TREE and the JSON@@ -53,22 +72,44 @@ function referenceOmissionNotice(dropped: number): string {* the policy kept, so those targets drop from the bundle (counted on* stderr). Everything else about the kept records, their remaining* targets included, stays exactly as the exporters derived it.+ *+ * A preference the privacy deny markers reserve (`visibility: private`,+ * or an informal marker saying the same thing) is left out of the+ * preferences section before the guard runs, and the bundle's+ * `preferences_omitted` report is disclosed on stderr in the same notice+ * shape, beside whatever the class policy did: the page override carries+ * the marked pages back in and says so, and the denial is named on that+ * run exactly as on the default run - a bundle shared with another+ * reader is a shared lane, and no page flag carries a reserved rule.+ * `--include-reserved` is the ONE override for the reservation itself,+ * and it exists for the documented purpose of this verb: the one-file+ * backup of the operator's own vault. A reservation is a statement about+ * shared readers; the operator's own restore copy is not one, so the+ * flag carries the reserved rows into the section whole and the run+ * prints the inclusion notice where the denial notice would have been -+ * a backup that silently lost a rule would fail exactly when it is used.*/export async function cmdBrainBankExport(argv: string[]): Promise<number> {const { flags } = parse(argv, {vault: { type: "string" },out: { type: "string" },"include-prompt-derived": { type: "boolean" },+ "include-reserved": { type: "boolean" },});const { vault } = brainVerbContext(flags);const classPolicy = { contentClass: { include: flags["include-prompt-derived"] === true } };+ const includeReserved = flags["include-reserved"] === true;+ const bundleOpts: BankBundleExportOptions = { includeReserved };let json: string;let redacted: boolean;let omitted: ReadonlyArray<string> = [];+ let preferenceOmissions: ReadonlyArray<PreferenceDenial> = [];+ let reservedCarried: ReadonlyArray<PreferenceDenial> = [];let droppedReferences = 0;try {- const bundle = exportBankBundle(vault);+ const { bundle, reserved } = exportBankBundleDetailed(vault, bundleOpts);+ reservedCarried = includeReserved ? reserved : [];const nodeSplit = egressContentClassSplit(bundle.graph.nodes, classPolicy, {name: (node) => node.path,isPromptDerived: (node) => isPromptDerivedPage(vault, node.path),@@ -107,6 +148,20 @@ export async function cmdBrainBankExport(argv: string[]): Promise<number> {pages: keptPages,});if (verdict.outcome !== EGRESS_OUTCOME.released) return fail(verdict.detail);+ // Absent-when-empty: the bundle carries the field only when a+ // reservation held a row back. Read from the RELEASED payload, so the+ // notice names each denied id in the same scrubbed form the export+ // carries - a hand-edited id whose credential the guard stripped+ // reaches stderr scrubbed, never raw.+ preferenceOmissions = verdict.payload.preferences_omitted ?? [];+ // The carried rows' names for the inclusion notice go through the+ // same boundary: the ids ride the bundle scrubbed, and the notice+ // spells them the way the bundle does.+ if (reservedCarried.length > 0) {+ const reservedVerdict = redactForEgress("brain-bank-export", reservedCarried);+ if (reservedVerdict.outcome !== EGRESS_OUTCOME.released) return fail(reservedVerdict.detail);+ reservedCarried = reservedVerdict.payload;+ }json = JSON.stringify(verdict.payload, null, 2) + "\n";redacted = verdict.redacted;} catch (exc) {@@ -123,6 +178,15 @@ export async function cmdBrainBankExport(argv: string[]): Promise<number> {} catch (exc) {return fail(`bank-export failed to write output: ${(exc as Error).message ?? exc}`);}+ // The reservation notice sits above the class-policy arm: whichever+ // way the reservation was answered - withheld and named, or carried in+ // under --include-reserved and named - an operator overriding the page+ // policy is told about it too.+ if (reservedCarried.length > 0) {+ process.stderr.write(reservedInclusionNotice(reservedCarried));+ } else if (preferenceOmissions.length > 0) {+ process.stderr.write(preferenceDenialNotice(preferenceOmissions));+ }if (flags["include-prompt-derived"] === true) {process.stderr.write(EGRESS_CONTENT_CLASS_INCLUDE_NOTICE);} else {diff --git a/src/cli/brain/verbs/context-receipts.ts b/src/cli/brain/verbs/context-receipts.tsindex f1f670db..c88a525b 100644--- a/src/cli/brain/verbs/context-receipts.ts+++ b/src/cli/brain/verbs/context-receipts.ts@@ -2,7 +2,9 @@ import {getContextReceipt,isContextReceiptTrigger,listContextReceipts,+ lookupReceiptReplyPresence,summarizeContextReceipt,+ type ReceiptReplyPresenceJoin,} from "../../../core/brain/context-receipts.ts";import { CliError, brainVerbContext, parse } from "../helpers.ts";@@ -39,7 +41,10 @@ function listReceipts(argv: string[]): number {: {}),...(limit !== undefined ? { limit } : {}),});- const summaries = receipts.map(summarizeContextReceipt);+ // Arrow, not point-free: summarizeContextReceipt's second parameter is+ // the optional reply-presence join, which a point-free map would feed+ // each row's array index into.+ const summaries = receipts.map((receipt) => summarizeContextReceipt(receipt));if (flags["json"]) {process.stdout.write(@@ -67,13 +72,21 @@ function showReceipt(argv: string[]): number {const vault = brainVerbContext(flags).vault;const receipt = getContextReceipt(vault, id);if (receipt === null) throw new CliError(`brain context-receipts show: receipt not found: ${id}`);+ // The receipt's session reply-presence join (t_f8510c55): the per-note+ // verdicts of the session's latest reply_presence record, or the named+ // unjoined outcome - a receipt whose session checked no turn, or that+ // names no session at all, says so instead of reading as silently+ // absent. Both output shapes carry it; the list stays a summary.+ const replyPresence = lookupReceiptReplyPresence(vault, receipt);if (flags["json"]) {- process.stdout.write(JSON.stringify(receipt, null, 2) + "\n");+ process.stdout.write(+ JSON.stringify({ ...receipt, reply_presence: replyPresence }, null, 2) + "\n",+ );return 0;}- const summary = summarizeContextReceipt(receipt);+ const summary = summarizeContextReceipt(receipt, replyPresence);process.stdout.write(`id: ${summary.id}\n`);process.stdout.write(`created_at: ${summary.created_at}\n`);process.stdout.write(`trigger: ${summary.trigger ?? "unknown"}\n`);@@ -86,9 +99,34 @@ function showReceipt(argv: string[]): number {const { level, action, escalate } = summary.adequacy;process.stdout.write(`adequacy: ${level} -> ${action}${escalate ? " (escalate)" : ""}\n`);}+ if (summary.reply_presence) printReplyPresence(summary.reply_presence);return 0;}+/** Render the reply-presence join; the unjoined outcome names why, never a blank. */+function printReplyPresence(join: ReceiptReplyPresenceJoin): void {+ if (join.joined) {+ const { presence } = join;+ const checked = presence.checked === null ? "" : `, checked=${presence.checked}`;+ process.stdout.write(+ `reply_presence: joined (record ${presence.record_id} @ ${presence.created_at}${checked})\n`,+ );+ for (const note of presence.per_note) {+ const range =+ note.start_line !== undefined && note.end_line !== undefined+ ? `#L${note.start_line}-L${note.end_line}`+ : "";+ process.stdout.write(` ${note.path}${range}: ${note.verdict}\n`);+ }+ return;+ }+ const why =+ join.session_id !== undefined+ ? `no reply_presence record for session ${join.session_id}`+ : "receipt names no session";+ process.stdout.write(`reply_presence: unjoined (${why})\n`);+}+function parsePositiveInteger(value: string | undefined, label: string): number | undefined {if (value === undefined) return undefined;if (!/^[0-9]+$/.test(value)) {diff --git a/src/cli/brain/verbs/dead-letters.ts b/src/cli/brain/verbs/dead-letters.tsnew file mode 100644index 00000000..f90a841b--- /dev/null+++ b/src/cli/brain/verbs/dead-letters.ts@@ -0,0 +1,504 @@+/**+ * `o2b brain dead-letters <list|show|recover>` - the dead-letter surface+ * (one-command recovery, t_50794f57, task C3).+ *+ * A dead letter is the durable record of a multi-artifact write that+ * failed part way (`src/core/brain/dead-letter.ts`). Until now it was a+ * fact without an exit: the file sat in+ * `<vault>/.open-second-brain/dead-letters/` and every reader worked out+ * alone what to do. This verb is the exit. `list` (the default) renders+ * every letter with its classification and the exact copy-paste command+ * that resolves it; `show <id>` prints one letter in full; `recover <id>`+ * re-runs a schema-2 letter's frozen payload through the extraction+ * commit at CURRENT vault state - the capture boundary, the dedup index+ * and the staging lane are re-derived at call time, so already-written+ * items dedup away, an item the session re-delivered by re-extracting is+ * left out (its frozen wording is stale), and nothing stale is ever+ * replayed.+ *+ * The frozen payload is handled per surface: `show --json` carries it+ * (the freeze redacts the free-text fields, and an operator inspecting+ * one letter locally may need the items); `list --json` carries only+ * `has_payload`, because the listing is the surface agents and cron logs+ * read in bulk.+ *+ * The consent ladder is the house one for a write that has a preview:+ * recover is dry-run by default, and `--apply` requires `--yes` under+ * `--json` or a non-TTY stdin (the `brain lint --apply` /+ * `brain doctor --repair --apply` rule). The record id is itself the pin+ * - no second confirmation phrase, exactly as `brain writes revert+ * --apply <digest>`.+ *+ * RETENTION is preserved: nothing here deletes a letter. A successful+ * recovery reports success and names the file the operator may delete BY+ * HAND once the payload is reconciled - the letter is the only surviving+ * evidence of the partial write, and no tool sweeps it.+ *+ * Exit codes: 0 on success (a listing is a report, whatever it says);+ * 1 on an operational failure - a refused apply, a non-recoverable+ * letter asked to recover, a frozen vault, a letter the store refuses to+ * read (corrupt JSON, an unknown schema_version); 2 on usage errors,+ * including a named-but-unknown record id and a `--dry-run` beside an+ * `--apply`.+ */++import { existsSync } from "node:fs";++import {+ type DeadLetterRecord,+ DeadLetterError,+ deadLetterPath,+ listDeadLetters,+ readDeadLetter,+} from "../../../core/brain/dead-letter.ts";+import {+ DEAD_LETTER_ITEM_VERDICT,+ type DeadLetterRecoveryItemVerdict,+ DeadLetterRecoveryError,+ applyRecovery,+ classifyDeadLetter,+ planRecovery,+} from "../../../core/brain/dead-letter-recovery.ts";+import { VaultFrozenError } from "../../../core/brain/freeze-marker.ts";+import { assertVaultIdentityForWrite } from "../../../core/brain/vault-identity.ts";+import {+ brainVerbContext,+ fail,+ ok,+ okJson,+ parse,+ resolveBrainAgent,+ usageError,+} from "../helpers.ts";++const USAGE =+ "usage: o2b brain dead-letters [list] [--vault <path>] [--json]\n" ++ " o2b brain dead-letters show <id> [--vault <path>] [--json]\n" ++ " o2b brain dead-letters recover <id> [--dry-run | --apply] [--yes] [--agent <name>]\n" ++ " [--vault <path>] [--json]";++/** The three subcommand names, for the usage error. */+const SUBCOMMANDS = "list | show <id> | recover <id>";++export async function cmdBrainDeadLetters(argv: string[]): Promise<number> {+ const first = argv[0];+ // The bare verb IS the listing: a first word that is a flag (`--vault`,+ // `--json`) is the list invocation, not a subcommand. A first word that+ // is neither a known subcommand nor a flag is a usage error rather than+ // a surprise listing of the vault.+ const known = first === "list" || first === "show" || first === "recover";+ const rest = known ? argv.slice(1) : argv;+ if (!known && first !== undefined && !first.startsWith("-")) {+ return usageError(`brain dead-letters requires a subcommand: ${SUBCOMMANDS}`);+ }+ switch (first) {+ case "show":+ return deadLettersShow(rest);+ case "recover":+ return deadLettersRecover(rest);+ default:+ return deadLettersList(rest);+ }+}++// ----- Shared rendering -----------------------------------------------------++/** The classification and exit of one letter, read against current vault state. */+interface RowView {+ readonly record: DeadLetterRecord;+ readonly category: string;+ readonly reason: string;+ readonly command: string | null;+}++function rowView(vault: string, record: DeadLetterRecord): RowView {+ const c = classifyDeadLetter(vault, record);+ return {+ record,+ category: c.category,+ reason: c.reason,+ command: c.command,+ };+}++/**+ * One row's JSON. The frozen payload rides only when `includePayload` is+ * set: `list --json` is the machine-read bulk surface - agents and cron+ * logs read it - so the payload never rides on a listing, not even+ * redacted (`has_payload` still says the letter carries one). `show+ * --json` keeps it: an operator inspecting ONE letter locally may need+ * the frozen items - they are the only record of what the failed commit+ * was writing - and the freeze redacts the free-text fields at write+ * time, so what show prints is the redacted form for every letter this+ * build recorded.+ */+function rowJson(+ view: RowView,+ opts: { readonly includePayload: boolean },+): Record<string, unknown> {+ const r = view.record;+ return {+ id: r.id,+ schema_version: r.schema_version,+ lane: r.lane,+ step: r.step,+ reference: r.reference,+ target: r.target,+ attempted: r.attempted,+ found: r.found,+ missing: [...r.missing],+ ...(opts.includePayload && r.payload !== undefined ? { payload: r.payload } : {}),+ has_payload: r.payload !== undefined,+ outcome: r.outcome,+ first_error: r.first_error,+ recorded_at: r.recorded_at,+ category: view.category,+ reason: view.reason,+ command: view.command,+ };+}++// ----- list ------------------------------------------------------------------++function deadLettersList(argv: string[]): number {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const { vault } = brainVerbContext(flags);+ const asJson = flags["json"] === true;++ // A letter on disk this build cannot read is a hard error by the+ // store's own contract (`listDeadLetters` refuses rather than skips) -+ // a listing that under-reports is the failure this surface exists to+ // prevent. Refused like `show` and `recover` refuse the same fault:+ // a typed exit 1, never an uncaught crash.+ let views: ReturnType<typeof rowView>[];+ try {+ views = listDeadLetters(vault).map((record) => rowView(vault, record));+ } catch (err) {+ if (err instanceof DeadLetterError) return refused(err.message, asJson);+ throw err;+ }++ if (asJson) {+ okJson({+ ok: true,+ total: views.length,+ letters: views.map((v) => rowJson(v, { includePayload: false })),+ });+ return 0;+ }+ if (views.length === 0) {+ ok("no dead letters in this vault");+ return 0;+ }+ for (const view of views) {+ const r = view.record;+ ok(`${r.id} [${r.lane}] ${view.category}`);+ ok(+ ` session ${r.reference} -> ${r.target}, attempted ${r.attempted}, ` ++ `found ${r.found}, missing ${r.missing.length}`,+ );+ if (r.missing.length > 0) ok(` missing: ${r.missing.join(", ")}`);+ ok(` reason: ${view.reason}`);+ if (view.command !== null) ok(` next: ${view.command}`);+ }+ return 0;+}++// ----- show ------------------------------------------------------------------++function deadLettersShow(argv: string[]): number {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ if (positional.length < 1) {+ return usageError(`brain dead-letters show requires an <id> argument\n${USAGE}`);+ }+ const { vault } = brainVerbContext(flags);+ const asJson = flags["json"] === true;+ const id = positional[0]!;++ let record: DeadLetterRecord | null;+ try {+ record = readDeadLetterQuietly(vault, id);+ } catch (err) {+ // The store refused to read the letter (corrupt JSON, an unknown+ // schema_version): the named error at exit 1, never the unknown-id+ // usage shape at exit 2 - a letter this build cannot read exists,+ // and saying otherwise under-reports it.+ if (err instanceof DeadLetterError) return refused(err.message, asJson);+ throw err;+ }+ if (record === null) {+ return unknownId(id);+ }+ const view = rowView(vault, record);++ if (asJson) {+ okJson({ ok: true, letter: rowJson(view, { includePayload: true }) });+ return 0;+ }+ const r = view.record;+ ok(`${r.id} [${r.lane}] ${view.category}`);+ ok(` schema: ${r.schema_version}${r.payload !== undefined ? " (payload frozen)" : ""}`);+ ok(` step: ${r.step}`);+ ok(` session: ${r.reference}`);+ ok(` target: ${r.target}`);+ ok(` attempted: ${r.attempted}, found: ${r.found}, missing: ${r.missing.length}`);+ for (const key of r.missing) ok(` missing: ${key}`);+ if (r.payload !== undefined) {+ const items = r.payload["items"];+ if (Array.isArray(items)) {+ for (const item of items) {+ const topic = (item as { topic?: unknown })["topic"];+ if (typeof topic === "string") ok(` payload item: ${topic}`);+ }+ }+ }+ ok(` outcome: ${r.outcome}`);+ ok(` first error: ${r.first_error}`);+ ok(` recorded: ${r.recorded_at}`);+ ok(` reason: ${view.reason}`);+ if (view.command !== null) ok(` next: ${view.command}`);+ return 0;+}++// ----- recover ---------------------------------------------------------------++function deadLettersRecover(argv: string[]): number {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ agent: { type: "string" },+ "dry-run": { type: "boolean" },+ apply: { type: "boolean" },+ yes: { type: "boolean" },+ json: { type: "boolean" },+ });+ if (positional.length < 1) {+ return usageError(`brain dead-letters recover requires an <id> argument\n${USAGE}`);+ }+ const asJson = flags["json"] === true;+ const apply = flags["apply"] === true;+ // The two flags name opposite modes - an explicit `--dry-run` beside an+ // explicit `--apply` is a caller mistake, refused as a usage error+ // rather than resolved in favor of whichever the verb felt like: a+ // write that ignored the caller's dry-run request would be exactly the+ // dishonesty this verb exists to prevent.+ if (flags["dry-run"] === true && apply) {+ return usageError(+ "brain dead-letters recover: --dry-run and --apply are mutually exclusive " ++ "(dry-run is the default; drop one of the two flags)",+ );+ }+ // Dry-run is the default; --apply is the write. The headless consent+ // rule is the `brain lint --apply` one: no prompts under --json or a+ // non-TTY stdin, so --yes is the only consent that can be given there.+ if (apply && flags["yes"] !== true && (asJson || !process.stdin.isTTY)) {+ const message =+ "brain dead-letters recover --apply requires --yes in non-interactive mode " ++ "(dry-run is the default; --apply re-runs the recorded payload)";+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+ const { config, vault } = brainVerbContext(flags);+ const id = positional[0]!;++ let record: DeadLetterRecord | null;+ try {+ record = readDeadLetterQuietly(vault, id);+ } catch (err) {+ // The store refused to read the letter: the named error at exit 1,+ // never the unknown-id usage shape - same contract as `show`.+ if (err instanceof DeadLetterError) return refused(err.message, asJson);+ throw err;+ }+ if (record === null) {+ return unknownId(id);+ }++ try {+ if (!apply) {+ const plan = planRecovery(vault, record);+ if (asJson) {+ okJson({+ ok: true,+ id: record.id,+ mode: "dry-run",+ category: plan.classification.category,+ reason: plan.classification.reason,+ items: plan.items.map((i) => ({+ topic: i.topic,+ verdict: i.verdict,+ ...(i.reason !== undefined ? { reason: i.reason } : {}),+ })),+ });+ } else {+ ok(`dry-run recovery plan for ${record.id} (${plan.classification.category})`);+ ok(` reason: ${plan.classification.reason}`);+ for (const i of plan.items) {+ ok(+ ` ${i.topic}: ${verdictText(i.verdict)}${i.reason !== undefined ? ` (${i.reason})` : ""}`,+ );+ }+ ok("nothing written; re-run with --apply --yes to write");+ }+ return 0;+ }++ // The apply is a content write: the same vault guards every content+ // writer passes - the freeze and the vault identity - refuse here+ // FIRST, before anything is written (the freeze names `o2b brain+ // unfreeze` as its exit).+ assertVaultIdentityForWrite(vault);+ const res = applyRecovery(vault, record, {+ agent: resolveBrainAgent(flags, config),+ now: new Date(),+ });+ const letterPath = deadLetterPath(vault, record.id);+ // The module's own promise: never report success over a re-run that+ // delivered nothing. The classifier refuses the states it can see+ // (every undelivered item gate-refused, every missing item already+ // delivered); an apply that still comes back with zero writes and+ // zero staging - the vault changing between the classification and+ // the commit is the shape this catches - is refused here with the+ // accounting named, instead of printed as a green `wrote 0+ // signal(s)`.+ if (res.written.length + res.staged === 0) {+ const refusedItems = res.rejected.map((r) => `${r.topic}: ${r.reason}`).join("; ");+ const message =+ `nothing was delivered while recovering ${record.id}: wrote 0 signal(s) and staged 0 ` ++ `(deduped ${res.deduped}, durability-rejected ${res.durabilityRejected}` ++ (refusedItems !== "" ? `; ${refusedItems}` : "") ++ `); the letter is retained at ${letterPath}`;+ return refused(message, asJson);+ }+ if (asJson) {+ okJson({+ ok: true,+ id: record.id,+ mode: "apply",+ written: res.written.map((w) => ({ id: w.id, path: w.path, topic: w.topic })),+ staged: res.staged,+ deduped: res.deduped,+ durability_rejected: res.durabilityRejected,+ rejected: res.rejected.map((r) => ({ topic: r.topic, reason: r.reason })),+ letter_retained: true,+ letter_path: letterPath,+ // The commit result's contract: the failure rides here by name,+ // absent when the mining record landed.+ ...(res.miningLedgerFailure !== undefined+ ? { mining_ledger_failure: res.miningLedgerFailure }+ : {}),+ });+ } else {+ ok(+ `recovered ${record.id}: wrote ${res.written.length} signal(s), ` ++ `deduped ${res.deduped}, durability-rejected ${res.durabilityRejected}` ++ (res.staged > 0 ? `, staged ${res.staged} for approval` : ""),+ );+ for (const r of res.rejected) ok(` rejected: ${r.topic} (${r.reason})`);+ if (res.miningLedgerFailure !== undefined) {+ ok(`mining ledger not updated: ${res.miningLedgerFailure}`);+ }+ ok(+ `the dead letter is retained at ${letterPath}; ` ++ "delete it by hand once the payload is reconciled",+ );+ }+ return 0;+ } catch (err) {+ if (err instanceof VaultFrozenError) {+ return refused(err.message, asJson);+ }+ if (err instanceof DeadLetterRecoveryError) {+ return refused(err.message, asJson);+ }+ const message = `brain dead-letters recover failed: ${(err as Error).message ?? String(err)}`;+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+ }+}++/**+ * The dry-run verdict text, in the operator's words, enumerated per known+ * verdict: the table's exhaustive key type makes a verdict joining+ * `DEAD_LETTER_ITEM_VERDICT` a compile error until it is given its own+ * words here, so a future verdict can never silently render as another+ * verdict's - "quarantined" reading as "refused" would tell the operator+ * the wrong thing.+ */+const VERDICT_TEXT: Readonly<Record<DeadLetterRecoveryItemVerdict, string>> = Object.freeze({+ [DEAD_LETTER_ITEM_VERDICT.write]: "will write",+ [DEAD_LETTER_ITEM_VERDICT.staged]: "will stage for approval",+ [DEAD_LETTER_ITEM_VERDICT.dedup]: "already on disk (dedup)",+ [DEAD_LETTER_ITEM_VERDICT.refused]: "refused",+});++/**+ * The text for one verdict, refusing an unknown one by name. Unreachable+ * through the typed plan in this build; the named refusal is the guard+ * for a verdict that reaches this surface unrendered.+ */+export function verdictText(verdict: string): string {+ const text = VERDICT_TEXT[verdict as DeadLetterRecoveryItemVerdict];+ if (text === undefined) {+ throw new Error(`dead-letters: unknown recovery item verdict ${JSON.stringify(verdict)}`);+ }+ return text;+}++/** An operational refusal: the message on the error channel, exit 1. */+function refused(message: string, asJson: boolean): number {+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+}++// ----- Shared refusal paths --------------------------------------------------++/**+ * The unknown-id refusal. The id was NAMED by the caller, so this is a+ * usage error (exit 2) rather than an empty report - a silent no-op would+ * read as "nothing to do" for a letter the caller misquoted. A usage+ * error is plain text on stderr in both modes: the `{ ok: false }`+ * envelope is reserved for operational refusals (exit 1).+ */+function unknownId(id: string): number {+ return usageError(`brain dead-letters: no dead letter with id ${JSON.stringify(id)}`);+}++/**+ * Read one letter for the `show`/`recover` reads, mapping a malformed id+ * to the unknown-id refusal shape: `deadLetterPath` throws on an id that+ * does not match the `<lane>-<digest>` shape, and a malformed id is one+ * nothing was ever written under.+ *+ * EVERY other store refusal propagates: a corrupt file or an unknown+ * `schema_version` is a hard error by the store's own contract+ * (`dead-letter.ts`: reading refuses rather than skips), and a caller+ * hearing "no dead letter with id" for an unreadable record would be+ * told the partial write does not exist - the under-report this surface+ * exists to prevent. The store's error reaches the operator at exit 1+ * through the shared refusal path each subcommand renders it with.+ */+function readDeadLetterQuietly(vault: string, id: string): DeadLetterRecord | null {+ let path: string;+ try {+ path = deadLetterPath(vault, id);+ } catch {+ return null;+ }+ if (!existsSync(path)) return null;+ return readDeadLetter(vault, id);+}diff --git a/src/cli/brain/verbs/explorer.ts b/src/cli/brain/verbs/explorer.tsindex d9359e4c..49c4318e 100644--- a/src/cli/brain/verbs/explorer.ts+++ b/src/cli/brain/verbs/explorer.ts@@ -3,11 +3,13 @@ import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";import {buildLiveServer,collectExplorerData,+ collectExplorerDenials,renderExportedHtml,type ExplorerGraph,type ExplorerParseFailure,type LiveServerHandle,} from "../../../core/brain/explorer.ts";+import { preferenceDenialNotice, type PreferenceDenial } from "../../../core/brain/export.ts";import {EGRESS_OUTCOME,EGRESS_REDACTION_NOTICE,@@ -67,18 +69,41 @@ export async function cmdBrainExplorer(argv: string[]): Promise<number> {return fail(`${exportPath} exists; pass --force to overwrite`);const collected = collectOrRefuse(vault);if (typeof collected === "number") return collected;+ // The shared lanes' denial judgment, applied to the explorer's own+ // node kinds: a preference or retired file the privacy deny markers+ // reserve is withheld from the file - the export is handed to another+ // reader, and the live view (the operator's own) keeps every node.+ const denials = collectExplorerDenials(vault);+ const reserved = new Set(denials.map((d) => d.id));+ const shared: ExplorerGraph =+ reserved.size > 0+ ? { ...collected, nodes: collected.nodes.filter((node) => !reserved.has(node.id)) }+ : collected;// Registry entry `brain-explorer-export`. The scan runs over the graph// TREE and the template substitution happens afterwards, so redaction// can never disturb the document's own quoting.- const verdict = redactForEgress("brain-explorer-export", collected);+ const verdict = redactForEgress("brain-explorer-export", shared);if (verdict.outcome !== EGRESS_OUTCOME.released) return fail(verdict.detail);+ // The denial names ride the same guard as the llms-txt lane's+ // omission list: the notice names each denied id in the scrubbed form+ // the boundary released, never a raw hand-edited frontmatter value.+ let noticeDenials: ReadonlyArray<PreferenceDenial> = denials;+ if (denials.length > 0) {+ const denialVerdict = redactForEgress("brain-explorer-export", denials);+ if (denialVerdict.outcome !== EGRESS_OUTCOME.released) return fail(denialVerdict.detail);+ noticeDenials = denialVerdict.payload;+ }const html = renderExportedHtml(verdict.payload);try {atomicWriteFileSync(exportPath, html);} catch (err) {return fail(`failed to write ${exportPath}: ${(err as Error).message ?? err}`);}+ // The count answers for what was written: the withheld nodes are not+ // in the file, so they are not in the number either - what stayed out+ // is named on stderr beside the notice.ok(`exported ${verdict.payload.nodes.length} nodes to ${exportPath}`);+ if (noticeDenials.length > 0) process.stderr.write(preferenceDenialNotice(noticeDenials));if (verdict.redacted) process.stderr.write(EGRESS_REDACTION_NOTICE);return 0;}diff --git a/src/cli/brain/verbs/export.ts b/src/cli/brain/verbs/export.tsindex 79605bdf..5a1675a5 100644--- a/src/cli/brain/verbs/export.ts+++ b/src/cli/brain/verbs/export.ts@@ -7,9 +7,11 @@ import {EXPORT_FORMAT,EXPORT_FORMATS,exportPreferencesJson,- exportPreferencesLlmsTxt,+ exportPreferencesLlmsTxtDetailed,isExportFormat,+ preferenceDenialNotice,type ExportFormat,+ type PreferenceDenial,} from "../../../core/brain/export.ts";import {streamTranscriptConversations,@@ -68,14 +70,29 @@ const EGRESS_SITE = "brain-export";* or streams it to stdout rather than ever holding it.*/type FormatOutcome =- | { readonly kind: "body"; readonly body: string; readonly redacted: boolean }+ | {+ readonly kind: "body";+ readonly body: string;+ readonly redacted: boolean;+ /**+ * The preferences the privacy deny markers kept out of this+ * document, named for the stderr disclosure. Empty when the vault+ * holds no reservation - the json envelope's own `omitted` field+ * is the machine-readable half of the same report.+ */+ readonly omitted: ReadonlyArray<PreferenceDenial>;+ }| { readonly kind: "spooled"; readonly spool: string; readonly redacted: boolean }| { readonly kind: "usage"; readonly detail: string }| { readonly kind: "refused"; readonly detail: string };/** Lift an egress verdict over already-composed bytes into an outcome. */-function released(body: string, redacted: boolean): FormatOutcome {- return { kind: "body", body, redacted };+function released(+ body: string,+ redacted: boolean,+ omitted: ReadonlyArray<PreferenceDenial> = [],+): FormatOutcome {+ return { kind: "body", body, redacted, omitted };}async function exportJson(flags: BrainVerbFlags): Promise<FormatOutcome> {@@ -84,16 +101,34 @@ async function exportJson(flags: BrainVerbFlags): Promise<FormatOutcome> {if (verdict.outcome !== EGRESS_OUTCOME.released) {return { kind: "refused", detail: verdict.detail };}- return released(JSON.stringify(verdict.payload) + "\n", verdict.redacted);+ // Absent-when-empty: the envelope carries the field only when a+ // reservation held a row back.+ return released(+ JSON.stringify(verdict.payload) + "\n",+ verdict.redacted,+ verdict.payload.omitted ?? [],+ );}async function exportLlmsTxt(flags: BrainVerbFlags): Promise<FormatOutcome> {const { vault } = brainVerbContext(flags);- const verdict = redactForEgress(EGRESS_SITE, exportPreferencesLlmsTxt(vault));+ const detail = exportPreferencesLlmsTxtDetailed(vault);+ const verdict = redactForEgress(EGRESS_SITE, detail.text);if (verdict.outcome !== EGRESS_OUTCOME.released) {return { kind: "refused", detail: verdict.detail };}- return released(verdict.payload, verdict.redacted);+ // The omission list rides the same guard as the document: the notice+ // names each denied id in the scrubbed form the boundary released,+ // never the raw frontmatter value.+ const omittedVerdict = redactForEgress(EGRESS_SITE, detail.omitted);+ if (omittedVerdict.outcome !== EGRESS_OUTCOME.released) {+ return { kind: "refused", detail: omittedVerdict.detail };+ }+ return released(+ verdict.payload,+ verdict.redacted || omittedVerdict.redacted,+ omittedVerdict.payload,+ );}/** `--since` / `--until` as instants, or the operator's error. */@@ -418,6 +453,12 @@ export async function cmdBrainExport(argv: string[]): Promise<number> {outcome.kind === "spooled"? deliverSpool(outcome.spool, outPath): deliverBody(outcome.body, outPath);+ // The omission is disclosed on stderr only, after the document is+ // delivered: the json bytes carry the machine-readable half, and the+ // notice is the prose half for the human reading the terminal.+ if (code === 0 && outcome.kind === "body" && outcome.omitted.length > 0) {+ process.stderr.write(preferenceDenialNotice(outcome.omitted));+ }if (code === 0 && outcome.redacted) process.stderr.write(EGRESS_REDACTION_NOTICE);return code;}diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 720d7c7a..c2956c5e 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -102,6 +102,7 @@ export { cmdBrainTrigger } from "./trigger.ts";export { cmdBrainDeepSynthesis } from "./deep-synthesis.ts";export { cmdBrainDiarize } from "./diarize.ts";export { cmdBrainExtractSignals } from "./extract-signals.ts";+export { cmdBrainDeadLetters } from "./dead-letters.ts";export { cmdBrainDesignNote } from "./design-note.ts";export { cmdBrainIdeas } from "./ideas.ts";export { cmdBrainEntity } from "./entity.ts";@@ -141,6 +142,7 @@ export {cmdBrainSessionGrep,} from "./session-recall.ts";export { cmdBrainLint } from "./lint.ts";+export { cmdBrainValidate } from "./validate.ts";export { cmdBrainActions } from "./actions.ts";export { cmdBrainSummary } from "./summary.ts";export { cmdBrainUnlinked } from "./unlinked.ts";diff --git a/src/cli/brain/verbs/note-lifecycle.ts b/src/cli/brain/verbs/note-lifecycle.tsindex 6dca0f2f..265f906e 100644--- a/src/cli/brain/verbs/note-lifecycle.ts+++ b/src/cli/brain/verbs/note-lifecycle.ts@@ -1,11 +1,15 @@/*** `o2b brain note-lifecycle <action> <path> [<to>]` - rename, move,- * archive and delete for note FILES (B2).+ * archive and delete for note FILES (B2), plus the folder actions+ * `move-folder` and `rename-folder` (t_9571a47f).*- * CLI mirror of the `brain_note_lifecycle` MCP tool; both delegate to- * `core/brain/notes/lifecycle.ts`, so the path envelope, the+ * CLI mirror of the `brain_note_lifecycle` MCP tool. The file actions+ * delegate to `core/brain/notes/lifecycle.ts`; the folder actions+ * delegate to `core/brain/notes/folder-lifecycle.ts`, the module that+ * runs them - the vocabulary is one constant, but the machinery is two+ * modules, and the surface owns the dispatch. The path envelope, the* confirmation ladder, the count guard and the recoverability verdict- * cannot come to mean two different things on two surfaces.+ * therefore cannot come to mean two different things on two surfaces.** Distinct from `o2b brain lifecycle`, which is the BELIEF lifecycle and* moves no bytes. The two verbs sit beside each other on purpose rather@@ -22,14 +26,28 @@* mentions it in prose is reported, never deleted. The receipt then* prints two lists rather than a count: what will go, and what is* reported and stays.+ *+ * A folder action moves MARKDOWN ONLY - the move set is the same note+ * population every lifecycle surface addresses - and the folder receipt+ * says what that honestly costs: attachments and other non-Notes files+ * are named in `left_behind`, and a moved note's relative Markdown links+ * or images whose target stayed behind are named in+ * `dangling_relative_links` (rendered on the human receipt beside the+ * residue, with the "only Markdown moves" statement in the line).*/import { defaultConfigPath } from "../../../core/config.ts";+import {+ folderLifecycle,+ isFolderLifecycleAction,+ type FolderLifecycleResult,+} from "../../../core/brain/notes/folder-lifecycle.ts";import {isNoteLifecycleAction,noteLifecycle,NOTE_LIFECYCLE_ACTIONS,type NoteLifecycleResult,+ type NoteReferenceReport,} from "../../../core/brain/notes/lifecycle.ts";import { normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";@@ -40,6 +58,40 @@ function usageError(message: string): number {return USAGE_ERROR_EXIT;}+/**+ * The reference report, identical on both lifecycle machines - the folder+ * result carries the same {@link NoteReferenceReport} the file result+ * does, so the projection is written once.+ */+function renderReferences(refs: NoteReferenceReport): Record<string, unknown> {+ return {+ files_scanned: refs.filesScanned,+ inbound_files: [...refs.inboundFiles],+ files_rewritten: refs.filesRewritten,+ rewritten_spellings: refs.rewrittenSpellings.map((s) => ({+ from: s.from,+ to: s.to,+ })),+ rewrite_failures: refs.rewriteFailures.map((f) => ({+ path: f.path,+ reason: f.reason,+ })),+ basename: refs.basename,+ index: {+ state: refs.index.state,+ last_indexed_at: refs.index.lastIndexedAt,+ next_command: refs.index.nextCommand,+ },+ // `claimed` says a detached refresh run is IN FLIGHT, never that it+ // has landed; every other value names why nothing was started, and+ // `refresh_reason` spells that reason - the freshen machinery's own+ // skip token, or the error it raised - so `not_claimed` is never+ // the whole answer a caller receives.+ refresh: refs.refresh,+ refresh_reason: refs.refreshReason,+ };+}+/** The receipt, snake_cased exactly as the MCP tool renders it. */function renderJson(res: NoteLifecycleResult): Record<string, unknown> {return {@@ -54,32 +106,7 @@ function renderJson(res: NoteLifecycleResult): Record<string, unknown> {},snapshot:res.snapshot === null ? null : { run_id: res.snapshot.runId, path: res.snapshot.path },- references: {- files_scanned: res.references.filesScanned,- inbound_files: [...res.references.inboundFiles],- files_rewritten: res.references.filesRewritten,- rewritten_spellings: res.references.rewrittenSpellings.map((s) => ({- from: s.from,- to: s.to,- })),- rewrite_failures: res.references.rewriteFailures.map((f) => ({- path: f.path,- reason: f.reason,- })),- basename: res.references.basename,- index: {- state: res.references.index.state,- last_indexed_at: res.references.index.lastIndexedAt,- next_command: res.references.index.nextCommand,- },- // `claimed` says a detached refresh run is IN FLIGHT, never that it- // has landed; every other value names why nothing was started, and- // `refresh_reason` spells that reason - the freshen machinery's own- // skip token, or the error it raised - so `not_claimed` is never- // the whole answer a caller receives.- refresh: res.references.refresh,- refresh_reason: res.references.refreshReason,- },+ references: renderReferences(res.references),cascade:res.cascade === null? null@@ -91,6 +118,44 @@ function renderJson(res: NoteLifecycleResult): Record<string, unknown> {};}+/** The folder receipt, snake_cased exactly as the MCP tool renders it. */+function renderFolderJson(res: FolderLifecycleResult): Record<string, unknown> {+ return {+ action: res.action,+ from: res.from,+ to: res.to,+ applied: res.applied,+ // The report style the folder module answers in: the list of what+ // relocated, and the per-file list of what did not and why.+ moved: res.moved.map((m) => ({ from: m.from, to: m.to })),+ move_failures: res.moveFailures.map((f) => ({ path: f.path, reason: f.reason })),+ // Absent-when-empty: a move that emptied its source folder carried+ // nothing through, so the key's presence is the signal.+ ...(res.leftBehind.length > 0 ? { left_behind: [...res.leftBehind] } : {}),+ // Absent-when-empty: the relative Markdown links and images the move+ // left pointing at nothing, named per note and target - a folder move+ // is a MARKDOWN move, and without this a `files_rewritten: 0` would+ // read as "nothing broke" while every relative embed dangled.+ ...(res.danglingRelativeLinks.length > 0+ ? {+ dangling_relative_links: res.danglingRelativeLinks.map((l) => ({+ note: l.note,+ target: l.target,+ })),+ }+ : {}),+ recoverability: {+ state: res.recoverability.state,+ coverage: [...res.recoverability.coverage],+ blockers: [...res.recoverability.blockers],+ },+ // Always null on this surface: a relocation destroys nothing, so no+ // recovery point is taken (the rewrite's risk is the verdict's).+ snapshot: null,+ references: renderReferences(res.references),+ };+}+/*** The human line. It names the index state and the command that fixes it* on every run, because the operator reading a terminal is exactly the@@ -143,6 +208,64 @@ function renderText(res: NoteLifecycleResult): string {);}+/**+ * The folder receipt's human line, in the same shape the file receipt+ * uses - the shared evidence tail rendered identically, with the move+ * report in the folder module's own style: the moved list printed IN+ * FULL (a dry run's preview IS this list, so an empty set is printed as+ * a measurement, never omitted) and a mid-set failure named per file,+ * never counted.+ */+function renderFolderText(res: FolderLifecycleResult): string {+ const mode = res.applied ? res.action : `${res.action} (plan)`;+ const refs = res.references;+ const moved =+ ` moved (${res.moved.length}):\n` ++ (res.moved.length === 0+ ? " (none)\n"+ : res.moved.map((m) => ` ${m.from} -> ${m.to}\n`).join(""));+ // A half-applied move is the one outcome an operator must not scroll+ // past, so it gets its own line naming every file that kept its old+ // path - not a count, because the remedy is per file.+ const split =+ res.moveFailures.length === 0+ ? ""+ : ` NOT moved (still at their old paths):\n` ++ res.moveFailures.map((f) => ` ${f.path}: ${f.reason}\n`).join("");+ // Non-Markdown residue is not a failure and not a count - it is named,+ // in place, so a receipt that reads clean really is clean.+ const residue =+ res.leftBehind.length === 0+ ? ""+ : ` left behind (still in ${res.from}):\n` ++ res.leftBehind.map((p) => ` ${p}\n`).join("");+ // A relative embed the move broke is named in full, not counted - and+ // the line says what a folder move IS, so the residue reads as the+ // settled cost of a Markdown-only move rather than as an omission.+ const dangling =+ res.danglingRelativeLinks.length === 0+ ? ""+ : ` relative links now dangling (only Markdown moves; the target stayed behind):\n` ++ res.danglingRelativeLinks.map((l) => ` ${l.note}: ${l.target}\n`).join("");+ return (+ `${mode}: ${res.from} -> ${res.to}\n` ++ moved ++ split ++ residue ++ dangling ++ ` inbound references: ${refs.inboundFiles.length} file(s) of ${refs.filesScanned} scanned, ` ++ `${refs.filesRewritten} rewritten (basename: ${refs.basename})\n` ++ ` recoverability: ${res.recoverability.state}` ++ (res.recoverability.blockers.length > 0 ? ` (${res.recoverability.blockers.join(", ")})` : "") ++ "\n" ++ ` search index: ${refs.index.state}` ++ (refs.index.lastIndexedAt === null ? "" : ` since ${refs.index.lastIndexedAt}`) ++ `; refresh: ${refs.refresh}` ++ (refs.refreshReason === null ? "" : ` (${refs.refreshReason})`) ++ `; next: ${refs.index.nextCommand}`+ );+}+export async function cmdBrainNoteLifecycle(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {vault: { type: "string" },@@ -177,6 +300,36 @@ export async function cmdBrainNoteLifecycle(argv: string[]): Promise<number> {const vault = resolveBrainVault(flags["vault"] as string | undefined, config);try {+ // The surface owns the dispatch: one vocabulary, two machines. A+ // folder action sent to the file module would be refused+ // `wrong_action` - the action exists and the caller named it+ // correctly, so it runs where it lives.+ if (isFolderLifecycleAction(action)) {+ // Refused rather than dropped, the file surface's own rule for a+ // flag its action cannot honour: a folder action is never a+ // delete, so neither flag has anything to extend.+ if (flags["confirm"] !== undefined || flags["delete-linked"] !== undefined) {+ return usageError(+ `brain note-lifecycle ${action} takes neither --confirm nor --delete-linked: ` ++ "a folder action is never a delete",+ );+ }+ const res = await folderLifecycle(vault, {+ action,+ path,+ ...(to !== undefined ? { to } : {}),+ apply: flags["apply"] === true,+ expect: expectCount,+ strict: flags["strict"] === true,+ // The post-write refresh resolves through the config file this+ // invocation already resolved the vault from, the same rule the+ // file arm below reads.+ refreshConfigPath: config,+ });+ if (flags["json"] === true) okJson(renderFolderJson(res));+ else ok(renderFolderText(res));+ return 0;+ }const res = await noteLifecycle(vault, {action,path,diff --git a/src/cli/brain/verbs/validate.ts b/src/cli/brain/verbs/validate.tsnew file mode 100644index 00000000..9b69f3ef--- /dev/null+++ b/src/cli/brain/verbs/validate.ts@@ -0,0 +1,198 @@+/**+ * `o2b brain validate --paths <p>... | --dirty` - the standalone+ * validation gate (t_dc782fd5, task C4).+ *+ * An agent that patches vault files outside a hook or a tool call has+ * had no way to block its own commit: `brain lint` always exits 0 and+ * `brain doctor` is a whole-vault invariant pass that cannot be pointed+ * at a subset. This verb is the gate. It runs the EXACT write-receipt+ * page-lint vocabulary over a caller-named page set - the same+ * `lintWrittenPages` pass a note-write receipt carries, plus nothing+ * new - and maps findings onto doctor's exit contract, so both gates+ * share one document:+ *+ * - an `error` finding blocks: exit 1;+ * - warnings block only under `--strict`: exit 2;+ * - a page the caller NAMED that the lint could not read (skipped as+ * `page-unreadable` or `page-lint-failed`) is itself blocking: a+ * gate that could not read what it was pointed at may not report+ * clean. An `page-over-byte-cap` skip is reported and non-blocking+ * - the content was measured, it is just too big to read whole;+ * - clean: exit 0.+ *+ * The verb is read-only and non-interactive by construction: no prompts,+ * therefore no `--yes`, and no fix modes - report-only in v1, with each+ * finding's existing `next_command` pointing at the established fixers+ * (`brain doctor --repair --apply`, `brain lint --consolidate --apply`).+ * A third fix vocabulary is the failure mode the card warns about.+ *+ * The documented split from doctor: doctor is the whole-vault structural+ * invariant pass (config, ids, logs, drift, store integrity) with repair+ * modes; validate is per-page authored-content lint over a named subset,+ * no vault walk beyond those pages, with the exit code as the product.+ */++import {+ PAGE_LINT_SKIP_REASON,+ lintWrittenPages,+ type PageLintReport,+} from "../../../core/brain/page-lint.ts";+import { READ_ALL_REFS } from "../../../core/brain/near-duplicate.ts";+import {+ VaultDirtyError,+ listDirtyMarkdownPaths,+ vaultRelativeOrNull,+} from "../../../core/brain/vault-dirty.ts";+import { brainVerbContext, ok, okJson, parse, usageError } from "../helpers.ts";++const USAGE =+ "usage: o2b brain validate --paths <path> [--paths <path>...] [--strict] [--vault <path>] [--json]\n" ++ " o2b brain validate --dirty [--strict] [--vault <path>] [--json]\n" ++ "\n" ++ "Exactly one of --paths / --dirty: an explicit vault-relative page set, or\n" ++ "every git-dirty Markdown note under the vault. --paths is repeatable, one\n" ++ "flag per page. Errors exit 1; warnings exit 2 under --strict; a named page\n" ++ "the lint could not read exits 1; clean exits 0. Report-only - the fixers\n" ++ "stay `brain doctor --repair --apply` and `brain lint --consolidate --apply`,\n" ++ "which the findings' next_command name.";++const SELECTION_RULE = "brain validate needs exactly one of --paths / --dirty";++/** Whether the report means "blocked", under the strictness in force. */+function blockingSkips(report: PageLintReport): ReadonlyArray<string> {+ return report.skipped+ .filter(+ (s) =>+ s.reason === PAGE_LINT_SKIP_REASON.unreadable ||+ s.reason === PAGE_LINT_SKIP_REASON.lintFailed,+ )+ .map((s) => s.page);+}++export async function cmdBrainValidate(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ paths: { type: "string-array" },+ dirty: { type: "boolean" },+ strict: { type: "boolean" },+ vault: { type: "string" },+ json: { type: "boolean" },+ });+ const asJson = flags["json"] === true;+ const strict = flags["strict"] === true;+ // The schema declares `paths` a string-array; the flags record's value+ // union is wider, so the read narrows it the way every sibling verb does.+ const paths = flags["paths"] as string[] | undefined;+ const dirty = flags["dirty"] === true;+ if (paths !== undefined && paths.length > 0 && dirty) {+ return usageError(`${SELECTION_RULE}, never both\n\n${USAGE}`);+ }+ if ((paths === undefined || paths.length === 0) && !dirty) {+ return usageError(+ `${SELECTION_RULE} (whole-vault validation stays brain doctor's job)\n\n${USAGE}`,+ );+ }+ if (positional.length > 0) {+ return usageError(+ `brain validate takes no positional arguments (got ${JSON.stringify(positional[0])})`,+ );+ }+ const { vault } = brainVerbContext(flags);++ let selection: "paths" | "dirty";+ let pages: ReadonlyArray<string>;+ if (dirty) {+ selection = "dirty";+ try {+ pages = listDirtyMarkdownPaths(vault);+ } catch (err) {+ if (err instanceof VaultDirtyError) return usageError(err.message);+ throw err;+ }+ } else {+ selection = "paths";+ const named: string[] = [];+ for (const raw of paths ?? []) {+ const rel = vaultRelativeOrNull(vault, raw);+ if (rel === null) {+ return usageError(+ `brain validate --paths: ${JSON.stringify(raw)} resolves outside the vault`,+ );+ }+ named.push(rel);+ }+ pages = named;+ }++ // Operator reach: the gate is run by the operator or an agent with the+ // operator's rights, so every vault page is readable - the same+ // `READ_ALL_REFS` the doctor's own lint callers pass.+ const report = lintWrittenPages(vault, pages, { readable: READ_ALL_REFS });++ const errors = report.findings.filter((f) => f.severity === "error");+ const warnings = report.findings.filter((f) => f.severity === "warning");+ const unread = blockingSkips(report);+ const gate =+ report.unavailable !== undefined ||+ errors.length > 0 ||+ unread.length > 0 ||+ (strict && warnings.length > 0);++ // Errors, unreadable named pages and a lint that could not run at all+ // are exit 1; only the strict-warnings block reads exit 2, matching+ // the doctor contract's one meaning for each code.+ const exit = !gate+ ? 0+ : errors.length > 0 || unread.length > 0 || report.unavailable !== undefined+ ? 1+ : 2;++ if (asJson) {+ // The PageLintReport field names verbatim - the shape a write+ // receipt carries - plus the gate's own verdict. No advisory-rail+ // lines under --json.+ okJson({+ ok: !gate,+ selection,+ strict,+ selected: pages.length,+ total: report.total,+ returned: report.returned,+ truncated: report.truncated,+ findings: report.findings,+ skipped: report.skipped,+ ...(report.unavailable !== undefined ? { unavailable: report.unavailable } : {}),+ });+ return exit;+ }++ ok(`validate: ${pages.length} page(s) selected (${selection}${strict ? ", strict" : ""})`);+ for (const p of pages) ok(` linted ${p}`);+ if (report.unavailable !== undefined) {+ ok(`the lint could not run: ${report.unavailable.code} (${report.unavailable.message})`);+ return 1;+ }+ for (const f of report.findings) {+ ok(` ${f.severity} ${f.page} ${f.code}: ${f.message}`);+ if (f.next_command !== undefined) ok(` next: ${f.next_command}`);+ }+ for (const s of report.skipped) {+ ok(` skipped ${s.page} (${s.reason}: ${s.detail})`);+ }+ if (errors.length > 0 || unread.length > 0) {+ ok(+ `blocked: ${errors.length} error(s)` ++ (unread.length > 0 ? `, ${unread.length} unreadable page(s)` : ""),+ );+ return 1;+ }+ if (strict && warnings.length > 0) {+ ok(`blocked under --strict: ${warnings.length} warning(s)`);+ return 2;+ }+ ok(+ warnings.length > 0+ ? `ok with ${warnings.length} warning(s) (re-run with --strict to block on them)`+ : "ok: nothing to say",+ );+ return 0;+}diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex d5178015..888e184c 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -660,7 +660,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({]),command("note-lifecycle",- "Note FILES: rename, move, archive or delete one, rewriting inbound wikilinks",+ "Note FILES or whole FOLDERS: rename, move, archive or delete a file, move-folder or rename-folder a folder, rewriting inbound wikilinks",[flag("vault", "string"),flag("config", "string"),@@ -761,6 +761,29 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("payload-file", "string"),],),+ command(+ "dead-letters",+ "Dead extraction writes: list with each row's recovery exit, show, recover (dry-run; --apply --yes to write)",+ [],+ [+ command("list", "Every dead letter with its classification and recovery command", [+ flag("vault", "string"),+ flag("json", "boolean"),+ ]),+ command("show", "One dead letter in full detail", [+ flag("vault", "string"),+ flag("json", "boolean"),+ ]),+ command("recover", "Re-run a letter's frozen payload at current vault state", [+ flag("vault", "string"),+ flag("agent", "string"),+ flag("dry-run", "boolean"),+ flag("apply", "boolean"),+ flag("yes", "boolean"),+ flag("json", "boolean"),+ ]),+ ],+ ),command("okf-export", "Write a portable Open Knowledge Format bundle"),command("okf-import",@@ -870,6 +893,17 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("apply", "boolean"),flag("yes", "boolean"),]),+ command(+ "validate",+ "Standalone validation gate over --paths or git-dirty notes; errors exit 1, --strict warnings exit 2",+ [+ flag("paths", "string-array"),+ flag("dirty", "boolean"),+ flag("strict", "boolean"),+ flag("vault", "string"),+ flag("json", "boolean"),+ ],+ ),command("actions","Ranked maintenance action list over dedup, lint, and footprint findings",diff --git a/src/cli/main.ts b/src/cli/main.tsindex 9c65f65f..e7bb8caf 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -29,7 +29,12 @@ import { ensureVaultCurrent } from "../core/maintenance/ensure-current.ts";import { checkSelfHealUpgrade } from "../core/maintenance/self-heal-upgrade-state.ts";import { doctor } from "../core/doctor.ts";import { checkHermesResolverParity } from "../core/doctor-hermes-parity.ts";-import { runReadinessProbes, type ReadinessReport } from "../core/doctor-readiness.ts";+import {+ runReadinessProbes,+ READINESS_STATUS,+ type ReadinessReport,+ type ReadinessStatus,+} from "../core/doctor-readiness.ts";import {runDoctorSelftest,selftestJsonPayload,@@ -408,6 +413,14 @@ async function cmdDoctor(argv: string[]): Promise<number> {return failed > 0 ? DOCTOR_EXIT.failed : DOCTOR_EXIT.probeIncomplete;}}++ /** The terminal tag for one readiness status - probe lines and row lines alike. */+ const READINESS_TAG: Record<ReadinessStatus, string> = {+ [READINESS_STATUS.pass]: "PASS",+ [READINESS_STATUS.fail]: "FAIL",+ [READINESS_STATUS.skipped]: "SKIP",+ [READINESS_STATUS.unknown]: "UNKNOWN",+ };const exitCode = doctorExitCode(failed, readiness);if (flags["json"]) {@@ -432,6 +445,19 @@ async function cmdDoctor(argv: string[]): Promise<number> {status: p.status,detail: p.detail,duration_ms: p.durationMs,+ // `client_versions`' per-target rows - the only probe that+ // sets them (t_8e49ec96). Absent on every other probe, so+ // the payload shape of the existing probes is unchanged.+ ...(p.rows !== undefined+ ? {+ rows: p.rows.map((row) => ({+ target: row.target,+ status: row.status,+ version: row.version,+ detail: row.detail,+ })),+ }+ : {}),})),// 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@@ -472,15 +498,20 @@ async function cmdDoctor(argv: string[]): Promise<number> {// one direction. Only the new member gets a new tag - the three that// already existed keep their exact spelling, so a reader sees a// byte-identical line for every outcome it already knew.- const tag =- p.status === "pass"- ? "PASS"- : p.status === "fail"- ? "FAIL"- : p.status === "skipped"- ? "SKIP"- : "UNKNOWN";+ const tag = READINESS_TAG[p.status];process.stdout.write(`[${tag}] ${p.name}: ${p.detail}\n`);+ // The per-target rows a probe reports (today, `client_versions`'):+ // one indented line each, so an operator reading the terminal sees+ // WHICH client answered and with what. The probe's own detail is+ // the census only, so this is where each client's answer is named.+ for (const row of p.rows ?? []) {+ process.stdout.write(+ ` ${READINESS_TAG[row.status]} ${row.target}` ++ (row.version !== null ? `: ${row.version}` : "") ++ (row.version === null && row.detail ? ` (${row.detail})` : "") ++ `\n`,+ );+ }}}return exitCode;diff --git a/src/core/brain/answer-quotes/check.ts b/src/core/brain/answer-quotes/check.tsindex 2d292ffb..22def308 100644--- a/src/core/brain/answer-quotes/check.ts+++ b/src/core/brain/answer-quotes/check.ts@@ -54,6 +54,14 @@ export const ANSWER_QUOTE_VERDICT = Object.freeze({noteUnavailable: "note-unavailable",/** The evidence bytes are not valid UTF-8 text. */notText: "not-text",+ /**+ * Per-note presence only (reply-presence receipts, t_f8510c55): no+ * reply span was ever checked against this note - it was injected into+ * context and no quoted span of the answer was measured against it.+ * Never a span verdict: every span gets one of the five above, so a+ * consumer reading a per-span outcome never sees this member.+ */+ absent: "absent",} as const);/** Closed union over {@link ANSWER_QUOTE_VERDICT}. */diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.tsindex 3791593b..b9e6a7bd 100644--- a/src/core/brain/context-pack.ts+++ b/src/core/brain/context-pack.ts@@ -282,10 +282,66 @@ export interface ContextPackEntityFactsReport {*/export const CONTEXT_PACK_ENTITY_FACTS_MAX_ENTITIES = 3;+/**+ * Score-aware tail trim (t_cb6a5558): how many of the pack's delivered+ * items are immune to the trim. The head of the delivery is what the+ * tier gate already vouched for; only the tail past these items competes+ * on query-term overlap. A named constant, not a knob.+ */+export const CONTEXT_PACK_TAIL_TRIM_KEEP = 3;++/**+ * Score-aware tail trim (t_cb6a5558): a tail item whose query-term+ * coverage - the fraction of the query's tokens it carries - is at+ * least this fraction of the top delivered item's coverage restates+ * the question's terms nearly as fully as the top hit and stays+ * deliverable. A named constant, not a knob.+ */+export const TAIL_TRIM_KEEP_FRACTION = 0.8;++/** The skip reason a whole dropped tail item carries ({@link ContextPackSkipped.reason}). */+const TAIL_TRIM_SKIP_REASON = "tail-trim";++/**+ * One candidate the unified walker budgeted but could not fit, kept+ * (only under the tail-trim flag) so the rescue can offer it the freed+ * budget in priority order. `body`/`trimmed`/`tokens` are the+ * post-char-budget values the walker would have emitted.+ */+interface TailTrimRescueCandidate {+ readonly candidate: Candidate;+ readonly body: string;+ readonly trimmed: boolean;+ readonly tokens: number;+}++/**+ * What the score-aware tail trim (t_cb6a5558) did to the delivered+ * tail, counted whole items and tokens. Present ONLY when the caller+ * opted in via {@link ContextPackOptions.tailTrim} AND a query was+ * present to score against - the same conditional shape as `semantic`,+ * `packing` and `entityFacts`.+ */+export interface ContextPackTailTrimReport {+ /** Tail items dropped whole; each also carries a `"tail-trim"` skip entry. */+ readonly dropped: number;+ /** Tail items kept because their query-term coverage nearly matched the top hit's. */+ readonly keptByQueryTerms: number;+ /** Former `over-budget` candidates re-admitted under the freed budget. */+ readonly rescued: number;+ /** Tokens the trim freed, net of the budget the rescue re-spent. */+ readonly tokensSaved: number;+}+export interface ContextPackSkipped {readonly id: string;readonly tokens: number;- readonly reason: "over-budget" | "filter-miss" | "guard-blocked" | "over-char-budget";+ readonly reason:+ | "over-budget"+ | "filter-miss"+ | "guard-blocked"+ | "over-char-budget"+ | "tail-trim";}/**@@ -364,6 +420,12 @@ export interface ContextPackReport {* {@link ContextPackEntityFactsReport}.*/readonly entityFacts?: ContextPackEntityFactsReport;+ /**+ * Present only when the caller opted in via+ * {@link ContextPackOptions.tailTrim} and a query scored the tail;+ * see {@link ContextPackTailTrimReport}.+ */+ readonly tailTrim?: ContextPackTailTrimReport;}/**@@ -529,6 +591,22 @@ export interface ContextPackOptions {* `entity_facts_context_pack` config key.*/readonly entityFacts?: boolean;+ /**+ * Score-aware tail trim for delivered evidence (t_cb6a5558). When+ * true AND a query is present, the pack scores every delivered item's+ * query-term coverage - the fraction of the query's tokens the item+ * carries, in every query mode - keeps its top+ * {@link CONTEXT_PACK_TAIL_TRIM_KEEP} delivered items, keeps any tail+ * item whose coverage is at least+ * {@link TAIL_TRIM_KEEP_FRACTION} of the top delivered item's (it+ * restates the question's terms), drops the rest whole with+ * `"tail-trim"` skip entries, and offers the freed budget back to+ * `over-budget` candidates in priority order. The report gains a+ * conditional `tailTrim` member. Omitted/false keeps the pack+ * byte-identical - the trim never runs without the flag. Callers+ * gate this on the `tail_trim_context_pack` config key.+ */+ readonly tailTrim?: boolean;/*** Which candidate pages the caller may see, asked with each page's* ABSOLUTE path. Applied to the collected candidates before ranking,@@ -952,7 +1030,10 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac// (the facts lane, the distilled layer) and retired pages (the pages// lane) - and let the caller name the claim order. The whole branch// runs ONLY when the policy is named; an omitted option never reaches- // it, which is what keeps the unified pack byte-identical.+ // it, which is what keeps the unified pack byte-identical. Scope note+ // (t_cb6a5558): the score-aware tail trim applies to the unified path+ // only in v1 - the policy's lane allocations are untouched and its+ // reports never carry the `tailTrim` member.if (opts.packingPolicy !== undefined) {const policy = opts.packingPolicy;const factsCandidates = candidates.filter((c) => c.source === "preferences");@@ -1190,6 +1271,32 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac);}+ // Score-aware tail trim (t_cb6a5558): active only when the caller+ // opted in AND the query carries at least one token to score against.+ // A tokenless query scores every candidate 0 and the trim could not+ // discriminate, so it does not run and no report member appears.+ const trimQueryTokens =+ opts.tailTrim === true && opts.query !== undefined ? tokenise(opts.query) : null;+ const tailTrimActive = trimQueryTokens !== null && trimQueryTokens.size > 0;+ // Per-candidate restatement scores for the trim: query-term coverage+ // in EVERY mode. The ranked comparator's jaccard kernel is not+ // reusable here - its union grows with the page's own vocabulary, so+ // a long body that carries every query term scores a fraction of the+ // page that is only the query, and the trim would keep the short+ // ones rather than the restating ones. Coverage's denominator is the+ // query alone, which is the keep rule's own measure; the scores are+ // computed here, under the flag only, so the off-path work does not+ // change.+ const tailTrimScoreById = new Map<string, number>();+ if (tailTrimActive) {+ for (const c of candidates) {+ tailTrimScoreById.set(+ c.id,+ queryTermCoverage(trimQueryTokens, tokenise(`${c.topic} ${c.principle} ${c.body}`)),+ );+ }+ }+// Per-memory character cap (v0.20.0): trim oversized bodies in priority// order via the shared budget primitive before the token budget runs,// so one huge page cannot starve the rest. A trimmed body is re-tokenised@@ -1202,8 +1309,11 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac},);- const items: ContextPackItem[] = [];- const skipped: ContextPackSkipped[] = [];+ // Reassigned only by the tail trim (t_cb6a5558); the flag-off path+ // never touches them again after the walk.+ let items: ContextPackItem[] = [];+ let skipped: ContextPackSkipped[] = [];+ const tailTrimRescue: TailTrimRescueCandidate[] = [];let used = 0;for (const { item: c, text: body, trimmed } of budgeted.kept) {if (query !== null) {@@ -1216,6 +1326,9 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPacconst tokens = trimmed ? estimateTokens(body) : c.tokens;if (used + tokens > opts.maxTokens) {skipped.push({ id: c.id, tokens, reason: "over-budget" });+ if (tailTrimActive) {+ tailTrimRescue.push({ candidate: c, body, trimmed, tokens });+ }continue;}items.push(toContextPackItem(c, body, trimmed, tokens, densityRanking, densityScoreById));@@ -1265,6 +1378,27 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac}}+ // Score-aware tail trim (t_cb6a5558): runs once the delivered set is+ // complete (attention item included, at the head), before the total+ // char ceiling so that ceiling stays the final word on the emitted set.+ let tailTrim: TailTrimCounters | null = null;+ if (tailTrimActive) {+ const trimmed = applyTailTrim(+ items,+ used,+ skipped,+ tailTrimRescue,+ tailTrimScoreById,+ opts.maxTokens,+ densityRanking,+ densityScoreById,+ );+ items = [...trimmed.items];+ used = trimmed.used;+ skipped = [...trimmed.skipped];+ tailTrim = trimmed.counters;+ }+// Total recall character cap (v0.20.0): a second ceiling over the// token-budgeted set. Applied via the shared primitive on the emitted// items only (so query-missed pages never count), dropping the@@ -1305,6 +1439,7 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPacstartedAtMs,ownerScopeWarnings,withheldIds,+ tailTrim === null ? null : tailTrimReportOf(tailTrim, new Set(keptItems.map((i) => i.id))),);}}@@ -1325,6 +1460,7 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPacstartedAtMs,ownerScopeWarnings,withheldIds,+ tailTrim === null ? null : tailTrimReportOf(tailTrim, new Set(finalItems.map((i) => i.id))),);}@@ -1362,6 +1498,167 @@ function semanticRelevanceFor(opts: ContextPackOptions): ReadonlyMap<string, numreturn opts.semanticRelevance;}+/**+ * Query-term coverage: the fraction of the query's tokens the document+ * carries - |q ∩ d| / |q| - the measure the trim's keep rule and its+ * `kept_by_query_terms` counter name ("restates the question's terms+ * nearly as fully"). The denominator is the query alone, so a long+ * body that carries every query term scores 1 where the ranked+ * comparator's jaccard kernel (|q ∩ d| / |q ∪ d|) scores it a fraction+ * of the page that is only the query. A tokenless query covers+ * nothing.+ */+function queryTermCoverage(+ queryTokens: ReadonlySet<string>,+ docTokens: ReadonlySet<string>,+): number {+ if (queryTokens.size === 0) return 0;+ let hits = 0;+ for (const token of queryTokens) if (docTokens.has(token)) hits += 1;+ return hits / queryTokens.size;+}++/**+ * The score-aware tail trim (t_cb6a5558), applied once to the unified+ * walk's delivered set. The first {@link CONTEXT_PACK_TAIL_TRIM_KEEP}+ * items are immune - position, not score, shields the head, so the+ * synthesized attention item (always unshifted first) is never scored,+ * dropped or reordered. Every later item whose query-term coverage is+ * at least {@link TAIL_TRIM_KEEP_FRACTION} of the top delivered item's+ * is kept; the rest drop WHOLE - never partially re-cut - each becoming+ * a {@link TAIL_TRIM_SKIP_REASON} skip. The freed budget is then+ * offered to `over-budget` candidates in walk (priority) order: one+ * that clears the same bar is re-admitted as a normal item - its+ * `over-budget` skip is retracted, since it was delivered - and one+ * that does not clear the bar, or that does not fit inside the budget+ * the trim freed, keeps its skip - the rescue re-spends what the trim+ * freed, never the slack the walk happened to leave under `maxTokens`.+ * Returns the trimmed item list in delivery order (head, kept tail,+ * rescued), the tokens now spent (`used`), and the raw counters the+ * report is computed from - so a later ceiling that cuts the trim's+ * own output can recount it against what actually shipped.+ */+function applyTailTrim(+ items: ReadonlyArray<ContextPackItem>,+ used: number,+ skipped: ReadonlyArray<ContextPackSkipped>,+ rescueCandidates: ReadonlyArray<TailTrimRescueCandidate>,+ scoreById: ReadonlyMap<string, number>,+ maxTokens: number,+ densityRanking: boolean,+ densityScoreById: ReadonlyMap<string, number>,+): {+ readonly items: ReadonlyArray<ContextPackItem>;+ readonly used: number;+ readonly skipped: ReadonlyArray<ContextPackSkipped>;+ readonly counters: TailTrimCounters;+} {+ const keepCount = Math.min(CONTEXT_PACK_TAIL_TRIM_KEEP, items.length);+ const head = items.slice(0, keepCount);+ const tail = items.slice(keepCount);+ let topScore = 0;+ for (const item of items) topScore = Math.max(topScore, scoreById.get(item.id) ?? 0);+ const keepBar = topScore * TAIL_TRIM_KEEP_FRACTION;+ const keptTail: ContextPackItem[] = [];+ const dropped: ContextPackItem[] = [];+ for (const item of tail) {+ if ((scoreById.get(item.id) ?? 0) >= keepBar) keptTail.push(item);+ else dropped.push(item);+ }+ let keptUsed = 0;+ for (const item of head) keptUsed += item.tokens;+ for (const item of keptTail) keptUsed += item.tokens;+ const freedTokens = used - keptUsed;+ const rescuedItems: ContextPackItem[] = [];+ const rescuedIds = new Set<string>();+ let rescuedTokens = 0;+ for (const entry of rescueCandidates) {+ if ((scoreById.get(entry.candidate.id) ?? 0) < keepBar) continue;+ // The freed budget is the rescue's whole allowance: the trim dropped+ // these tokens, and re-admission may spend them and no more. (This+ // also keeps the maxTokens bound, which every kept item already fits+ // and the freed tokens never exceed.)+ if (rescuedTokens + entry.tokens > freedTokens) continue;+ rescuedItems.push(+ toContextPackItem(+ entry.candidate,+ entry.body,+ entry.trimmed,+ entry.tokens,+ densityRanking,+ densityScoreById,+ ),+ );+ rescuedIds.add(entry.candidate.id);+ rescuedTokens += entry.tokens;+ }+ return {+ items: [...head, ...keptTail, ...rescuedItems],+ used: keptUsed + rescuedTokens,+ skipped: [+ ...skipped.filter((s) => !rescuedIds.has(s.id)),+ ...dropped.map((d): ContextPackSkipped => ({+ id: d.id,+ tokens: d.tokens,+ reason: TAIL_TRIM_SKIP_REASON,+ })),+ ],+ counters: Object.freeze({+ dropped: dropped.length,+ freedTokens,+ keptTailTokens: new Map(keptTail.map((item) => [item.id, item.tokens])),+ rescuedTokens: new Map(rescuedItems.map((item) => [item.id, item.tokens])),+ }),+ };+}++/**+ * What one lane's trim delivered, in ids and tokens rather than finished+ * counts: a ceiling that runs after the trim can cut the trim's own+ * rescued or kept-tail items, and the report must then describe what+ * actually shipped, not what the trim alone decided.+ */+interface TailTrimCounters {+ /** Tail items the trim dropped whole; never reduced by a later ceiling. */+ readonly dropped: number;+ /** Tokens the trim freed. */+ readonly freedTokens: number;+ /** Kept-tail items by id, with their token cost. */+ readonly keptTailTokens: ReadonlyMap<string, number>;+ /** Rescued items by id, with the tokens re-admitting each cost. */+ readonly rescuedTokens: ReadonlyMap<string, number>;+}++/**+ * The trim report over the set that actually ships: kept-tail and+ * rescued counters count only ids still present in `keptIds`, and+ * `tokensSaved` nets the re-spend of the rescued survivors against the+ * freed tokens - never negative, since the rescue's whole allowance is+ * the freed budget.+ */+function tailTrimReportOf(+ trim: TailTrimCounters,+ keptIds: ReadonlySet<string>,+): ContextPackTailTrimReport {+ let keptByQueryTerms = 0;+ for (const id of trim.keptTailTokens.keys()) {+ if (keptIds.has(id)) keptByQueryTerms += 1;+ }+ let rescued = 0;+ let reSpent = 0;+ for (const [id, tokens] of trim.rescuedTokens) {+ if (!keptIds.has(id)) continue;+ rescued += 1;+ reSpent += tokens;+ }+ return Object.freeze({+ dropped: trim.dropped,+ keptByQueryTerms,+ rescued,+ tokensSaved: trim.freedTokens - reSpent,+ });+}+/*** The conditional `entityFacts` rollup (dated commitments, t_43b0a379).* Entities: canonical scope only (`entityStatusInScope` - a quarantined@@ -1427,8 +1724,23 @@ function finalizeContextPackReport(* reported, but without the tension id, which embeds both subject ids.*/withheldIds: ReadonlySet<string> = new Set(),+ /**+ * The score-aware tail trim's counters (t_cb6a5558) when the trim ran+ * in the passing path. Attached before the receipt and telemetry are+ * emitted so the counters ride both; null on every path that did not+ * trim (the packing-policy branch, the zero-budget short-circuit, an+ * absent option or a tokenless query), keeping those reports+ * byte-identical.+ */+ tailTrim: ContextPackTailTrimReport | null = null,): ContextPackReport {let enriched = report;+ // Conditional tail-trim counters (t_cb6a5558). Attached first so the+ // receipt budget and the telemetry metadata below read them off the+ // enriched report; absent on every path that did not trim.+ if (tailTrim !== null) {+ enriched = { ...enriched, tailTrim: Object.freeze(tailTrim) };+ }// Conditional entity-facts rollup (dated commitments, t_43b0a379).// Attached in the one funnel every return path passes through, so the// zero-budget pack, the char-budget-degraded packs and the@@ -1489,7 +1801,7 @@ function finalizeContextPackReport(evidenceRefs: item.evidenceRefs,})),finalText: report.items.map((item) => item.body).join("\n\n"),- budget: contextPackBudgetMetadata(opts, report),+ budget: contextPackBudgetMetadata(opts, enriched),...(opts.recallAdequacy ? { adequacy: opts.recallAdequacy } : {}),...(opts.recallAdequacy && opts.decisionAnswerable? { decisionAnswerable: opts.decisionAnswerable }@@ -1512,7 +1824,7 @@ function finalizeContextPackReport(gaps: contextPackGaps(report),metadata: {...(telemetryOptions.metadata ?? {}),- ...contextPackBudgetMetadata(opts, report),+ ...contextPackBudgetMetadata(opts, enriched),skipped_count: report.skipped.length,lanes: opts.includeLanes === true,...(enriched.receiptId ? { receipt_id: enriched.receiptId } : {}),@@ -1580,6 +1892,17 @@ function contextPackBudgetMetadata(// PACKING_POLICIES vocabulary - which names nothing sensitive - and// an unnamed caller's records never grow the key....(opts.packingPolicy !== undefined ? { packing_policy: opts.packingPolicy } : {}),+ // The trim counters ride along only when the trim ran (t_cb6a5558):+ // a pack that never trimmed keeps its receipt and telemetry metadata+ // byte-identical.+ ...(report.tailTrim !== undefined+ ? {+ tail_trim_dropped: report.tailTrim.dropped,+ tail_trim_kept_by_query_terms: report.tailTrim.keptByQueryTerms,+ tail_trim_rescued: report.tailTrim.rescued,+ tail_trim_tokens_saved: report.tailTrim.tokensSaved,+ }+ : {}),};}diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.tsindex 37ad4b12..34274a82 100644--- a/src/core/brain/context-receipts.ts+++ b/src/core/brain/context-receipts.ts@@ -1,12 +1,18 @@import { sha256Hex } from "../integrity/digest.ts";+import {+ ANSWER_QUOTE_VERDICT,+ isAnswerQuoteVerdict,+ mergeAnswerQuoteVerdicts,+} from "./answer-quotes/check.ts";import {appendContinuityRecord,isCanonicalUtcTimestamp,listContinuityRecords,} from "./continuity/store.ts";-import type { ContinuityRecord } from "./continuity/types.ts";+import { CONTINUITY_SESSION_ID_KEY, type ContinuityRecord } from "./continuity/types.ts";import type { RecallAdequacyVerdict } from "./recall-adequacy.ts";+import type { ReachView } from "./reach-view.ts";/*** What produced the injected context a receipt accounts for.@@ -118,6 +124,14 @@ export interface ContextReceiptSummary {readonly action: string;readonly escalate: boolean;};+ /**+ * The receipt's session reply-presence join (t_f8510c55), present ONLY+ * when the caller handed a {@link lookupReceiptReplyPresence} result in.+ * List summaries stay summaries and omit it; a show path passes the+ * lookup in, and the member then names either the joined per-note+ * verdicts or the unjoined outcome - never a silent absence.+ */+ readonly reply_presence?: ReceiptReplyPresenceJoin;}export function emitContextReceipt(@@ -464,7 +478,321 @@ export function getContextReceipt(vault: string, id: string): ContinuityRecord |);}-export function summarizeContextReceipt(record: ContinuityRecord): ContextReceiptSummary {+// ----- reply-presence join (t_f8510c55) ------------------------------------++/**+ * One injected note's presence verdict, as the answer-quote-check hook+ * wrote it. The verdict string is the quote-check vocabulary (`verified`,+ * `not-in-note`, `source-truncated`, `note-unavailable`, `not-text`,+ * plus the per-note-only `absent`); the reader passes it through+ * verbatim, so a verdict member a newer hook writes still reads here+ * without a reader release.+ */+export interface ReceiptReplyPresenceNote {+ readonly path: string;+ readonly start_line?: number;+ readonly end_line?: number;+ readonly verdict: string;+}++/**+ * The per-note presence verdicts one receipt's session produced, joined+ * from the session's `reply_presence` records. Identifiers and verdicts+ * only - the records never carried answer text, and none is invented+ * here.+ */+export interface ReceiptReplyPresence {+ /**+ * Continuity id of the NEWEST `reply_presence` record the join folded.+ * The verdicts are the fold's, not that record's alone: every readable+ * session record written at or after the receipt contributed.+ */+ readonly record_id: string;+ /** When that record was written - the last turn the fold drew from. */+ readonly created_at: string;+ /**+ * How many reply spans the folded records measured in sum; `null` when+ * none of them carried a readable count.+ */+ readonly checked: number | null;+ /**+ * One row per note THIS receipt injected, first-seen order across the+ * folded turns kept. The hook's record covers the session's whole+ * injection ledger; the join covers the receipt, so a row for a note+ * the receipt never injected is not this receipt's history to report.+ * A note the receipt injected that no folded record carried has no row:+ * the join reports what was measured, never an inferred verdict.+ */+ readonly per_note: ReadonlyArray<ReceiptReplyPresenceNote>;+ /**+ * How many folded note rows for THIS receipt's own notes were WITHHELD+ * below the caller's reach, by the same {@link isPathReadableAtReach}+ * verdict every surface resolves a path with - summed across the folded+ * records. Present only when rows were dropped, so a join that+ * withheld nothing stays byte-identical - and a truncated join can+ * never read as a session that checked fewer notes.+ */+ readonly withheld?: number;+ /**+ * Hash binding the verdicts to the exact answer text checked - carried+ * only when the fold drew from ONE record. A fold over several records+ * answers across several answers, and no single answer hash binds it.+ */+ readonly source_hash?: string;+}++/**+ * The outcome of joining a receipt to its session's `reply_presence`+ * record. `joined` carries the verdicts; `unjoined` is the HONEST+ * absence: the receipt names a session no presence record answers, or+ * names no session at all. A missing join is never rendered as an+ * inferred one - there is no time-window fallback - and the unjoined+ * outcome names the key that did not match so a reader can tell a+ * keyless receipt from an unchecked session.+ */+export type ReceiptReplyPresenceJoin =+ | { readonly joined: true; readonly presence: ReceiptReplyPresence }+ | { readonly joined: false; readonly reason: "unjoined"; readonly session_id?: string };++/**+ * Join a context receipt to its session's reply-presence records by exact+ * {@link CONTINUITY_SESSION_ID_KEY} match (t_f8510c55).+ *+ * The receipt's own creation draws the fold window: EVERY readable+ * `reply_presence` record of the session written at or after+ * `createdAt` folds into the join, chronologically, with `verified`+ * winning across turns. The window is the honesty guarantee on both+ * sides. The Stop hook writes a record on every checked turn - including+ * turns that quote nothing, where every note reads `absent` - so joining+ * only the session's newest record would answer a receipt whose note was+ * verified in the next turn with a later turn's absence; and a record+ * written before the receipt describes turns this receipt's injections+ * did not exist for, so no earlier record may answer it either. A+ * receipt with no readable record at or after its own creation reads+ * `unjoined` - the HONEST absence, never an inferred join - whether no+ * record exists, none matches the window, or every in-window record's+ * payload is unreadable. A record whose payload cannot be read is+ * skipped per record (never reported as the join, never a reason to+ * orphan readable records behind it); a record whose written time cannot+ * be read claims no place in the window. The join names itself+ * (`record_id`, `created_at` - the newest record folded), and earlier+ * turns remain in the ledger for the continuity reader.+ *+ * `per_note` is restricted to the receipt's own injected notes: the+ * hook's record covers the session's whole ledger, and a row for a note+ * the receipt never carried is not this receipt's history to report.+ *+ * A receipt without a session key is unjoined before the ledger is read:+ * there is nothing to match on, and inventing a window would answer a+ * question the receipt never asked.+ *+ * `view` is the caller's reach view ({@link reachView}); every folded+ * note row whose path it hides is DROPPED from `per_note` and counted in+ * `withheld`, so a caller below local reach reads neither the path, the+ * line range nor the verdict of a page reserved against it - the same+ * shaping the receipt record itself undergoes. Absent (the CLI, which+ * runs at local reach by construction) withholds nothing.+ */+export function lookupReceiptReplyPresence(+ vault: string,+ record: ContinuityRecord,+ view?: ReachView,+): ReceiptReplyPresenceJoin {+ const sessionId = record.payload[CONTINUITY_SESSION_ID_KEY];+ if (typeof sessionId !== "string" || sessionId.length === 0) {+ return Object.freeze({ joined: false as const, reason: "unjoined" });+ }+ // A receipt whose creation cannot be read can establish no window at+ // all: no record can prove it was written at or after the receipt, so+ // nothing may claim to answer it.+ const createdAtMs = Date.parse(record.createdAt);+ if (Number.isNaN(createdAtMs)) {+ return Object.freeze({+ joined: false as const,+ reason: "unjoined" as const,+ session_id: sessionId,+ });+ }+ const injectedPaths = receiptInjectedPaths(record);+ // Exact session match, as before; then the window - at or after the+ // receipt, readable, chronological. Append order breaks same-instant+ // ties, matching the store's read order.+ const store = listContinuityRecords(vault, { kind: "reply_presence" });+ const turns: PresenceTurn[] = [];+ for (let i = 0; i < store.length; i++) {+ const sibling = store[i]!;+ if (sibling.payload[CONTINUITY_SESSION_ID_KEY] !== sessionId) continue;+ const writtenMs = Date.parse(sibling.createdAt);+ if (Number.isNaN(writtenMs) || writtenMs < createdAtMs) continue;+ const turn = readablePresenceTurn(sibling, writtenMs, i, injectedPaths, view);+ if (turn !== null) turns.push(turn);+ }+ if (turns.length === 0) {+ // No sibling at all, none at or after the receipt, or none in the+ // window whose payload reads: either way the honest answer is the+ // named absence, keyed on the session that did not produce a+ // readable record for this receipt.+ return Object.freeze({+ joined: false as const,+ reason: "unjoined" as const,+ session_id: sessionId,+ });+ }+ const folded = turns.toSorted(+ (a, b) => a.writtenMs - b.writtenMs || a.appendIndex - b.appendIndex,+ );+ const newest = folded[folded.length - 1]!;+ const rowsByPath = new Map<string, ReceiptReplyPresenceNote[]>();+ let withheld = 0;+ let checked: number | null = null;+ for (const turn of folded) {+ if (typeof turn.checked === "number") checked = (checked ?? 0) + turn.checked;+ withheld += turn.withheld;+ for (const row of turn.rows) {+ const rows = rowsByPath.get(row.path);+ if (rows === undefined) rowsByPath.set(row.path, [row]);+ else rows.push(row);+ }+ }+ const perNote = [...rowsByPath.values()].map((rows) => foldNoteRows(rows));+ return Object.freeze({+ joined: true as const,+ presence: Object.freeze({+ record_id: newest.record.id,+ created_at: newest.record.createdAt,+ checked,+ per_note: Object.freeze(perNote),+ ...(withheld > 0 ? { withheld } : {}),+ ...(folded.length === 1 && folded[0]!.sourceHash !== undefined+ ? { source_hash: folded[0]!.sourceHash }+ : {}),+ }),+ });+}++/**+ * The vault-relative note paths THIS receipt injected: the `path` members+ * of its recorded items. Items without a path (the operator-rule blocks,+ * the bodies keyed by id alone) offer nothing the presence rows could+ * match, and a receipt whose items cannot be read injects nothing this+ * join can report on.+ */+function receiptInjectedPaths(record: ContinuityRecord): ReadonlySet<string> {+ const paths = new Set<string>();+ const stored = record.payload["items"];+ if (!Array.isArray(stored)) return paths;+ for (const raw of stored) {+ if (raw === null || typeof raw !== "object") continue;+ const path = (raw as Record<string, unknown>)["path"];+ if (typeof path === "string" && path.length > 0) paths.add(path);+ }+ return paths;+}++/**+ * One readable in-window `reply_presence` record, shaped for the fold:+ * its rows restricted to the receipt's own injected notes, each visible+ * row kept and each reach-hidden row counted. `null` when the payload+ * cannot be read at all (no `per_note` array) - the per-record+ * unreadable skip the walk-back named, here meaning the record simply+ * contributes no turn.+ */+function readablePresenceTurn(+ record: ContinuityRecord,+ writtenMs: number,+ appendIndex: number,+ injectedPaths: ReadonlySet<string>,+ view?: ReachView,+): PresenceTurn | null {+ const stored = record.payload["per_note"];+ if (!Array.isArray(stored)) return null;+ const visible = view?.visible ?? (() => true);+ const rows: ReceiptReplyPresenceNote[] = [];+ let withheld = 0;+ for (const raw of stored) {+ if (raw === null || typeof raw !== "object") continue;+ const note = raw as Record<string, unknown>;+ const path = note["path"];+ const verdict = note["verdict"];+ if (typeof path !== "string" || path.length === 0) continue;+ if (typeof verdict !== "string" || verdict.length === 0) continue;+ // The receipt scopes the join: a row for a note this receipt never+ // injected is dropped before the reach verdict runs, so the join+ // resolves no visibility it will not use.+ if (!injectedPaths.has(path)) continue;+ // The reach verdict runs on the row's path BEFORE anything from it is+ // kept, and a hidden row counts: reporting the drop is what keeps a+ // filtered join honest instead of reading as a smaller check.+ if (!visible(path)) {+ withheld += 1;+ continue;+ }+ rows.push({+ path,+ verdict,+ ...(typeof note["start_line"] === "number" ? { start_line: note["start_line"] } : {}),+ ...(typeof note["end_line"] === "number" ? { end_line: note["end_line"] } : {}),+ });+ }+ const checked = record.payload["checked"];+ const sourceHash = record.payload["source_hash"];+ return {+ record,+ writtenMs,+ appendIndex,+ checked: typeof checked === "number" ? checked : null,+ rows,+ withheld,+ ...(typeof sourceHash === "string" && sourceHash.length > 0 ? { sourceHash } : {}),+ };+}++/** Sort and fold input: one readable in-window record's contribution. */+interface PresenceTurn {+ readonly record: ContinuityRecord;+ /** The record's written time, the fold's primary sort key. */+ readonly writtenMs: number;+ /** Store append position, the same-instant tiebreak. */+ readonly appendIndex: number;+ readonly checked: number | null;+ readonly rows: ReadonlyArray<ReceiptReplyPresenceNote>;+ readonly withheld: number;+ readonly sourceHash?: string;+}++/**+ * Fold one injected note's rows across the folded turns, oldest first. A+ * hit anywhere in the receipt's lifetime wins - a later turn's absence+ * never erases an earlier verification, and the newest verifying row+ * carries the line range the hit was found against. Otherwise the check+ * module's own merge ladder runs over the MEASURED misses: `absent` is+ * no turn's measurement, and it neither upgrades nor downgrades a miss+ * another turn recorded. A note whose every row is `absent` - or whose+ * verdicts a newer hook wrote and this reader cannot place - reads its+ * newest row verbatim: the join passes verdict strings through, it does+ * not interpret what it does not know.+ */+function foldNoteRows(rows: ReadonlyArray<ReceiptReplyPresenceNote>): ReceiptReplyPresenceNote {+ if (rows.length === 1) return rows[0]!;+ const verified = rows.filter((row) => row.verdict === ANSWER_QUOTE_VERDICT.verified);+ if (verified.length > 0) return verified[verified.length - 1]!;+ const measured = rows.flatMap((row) =>+ row.verdict !== ANSWER_QUOTE_VERDICT.absent && isAnswerQuoteVerdict(row.verdict)+ ? [row.verdict]+ : [],+ );+ if (measured.length > 0) {+ const merged = mergeAnswerQuoteVerdicts(measured);+ const carrier = [...rows].reverse().find((row) => row.verdict === merged);+ return carrier ?? rows[rows.length - 1]!;+ }+ return rows[rows.length - 1]!;+}++export function summarizeContextReceipt(+ record: ContinuityRecord,+ replyPresence?: ReceiptReplyPresenceJoin,+): ContextReceiptSummary {const payload = record.payload;return {id: record.id,@@ -478,6 +806,7 @@ export function summarizeContextReceipt(record: ContinuityRecord): ContextReceipprivate: record.private,redacted: record.redacted,...adequacySummary(payload["adequacy"]),+ ...(replyPresence !== undefined ? { reply_presence: replyPresence } : {}),};}diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.tsindex 50fdda10..5665a20e 100644--- a/src/core/brain/continuity/types.ts+++ b/src/core/brain/continuity/types.ts@@ -95,6 +95,18 @@ export type ContinuityRecordKind =* can audit what any mark claimed.*/| "decision_model_eval_grade"+ /**+ * One checked turn's reply-presence verdicts (t_f8510c55), written by+ * the answer-quote-check Stop hook: per injected note, whether at+ * least one quoted span of the turn's reply verified against it+ * (`verified`), the strongest miss verdict when spans were checked and+ * all missed, or `absent` when no span was ever measured against it -+ * the row this kind exists to surface (rendered into context, never+ * surfaced in the answer). Joined to the session's `context_receipt`+ * records by `session_id` on read; identifiers and verdicts only,+ * never answer text.+ */+ | "reply_presence"/*** One mined entity mention from a session turn (recall-quality wave,* Lane B): one record per (family, key, sessionRef), where family is a@@ -158,6 +170,7 @@ export const CONTINUITY_RECORD_KINDS: ReadonlyArray<ContinuityRecordKind> = Obje"decision_model_call","decision_model_extract_commit","decision_model_eval_grade",+ "reply_presence","session_entity_mention","receipt_compaction",]);diff --git a/src/core/brain/dead-letter-recovery.ts b/src/core/brain/dead-letter-recovery.tsnew file mode 100644index 00000000..af5128d1--- /dev/null+++ b/src/core/brain/dead-letter-recovery.ts@@ -0,0 +1,739 @@+/**+ * One-command recovery for dead extraction writes (t_50794f57).+ *+ * A dead letter used to be a fact without an exit: the record named what+ * failed and what it was writing, and every reader - operator or agent -+ * had to work out alone what to do next. This module is the exit. It+ * reads a letter against the vault's CURRENT state and answers one of+ * five questions, each with its exact copy-paste command where one+ * exists:+ *+ * - {@link DEAD_LETTER_RECOVERY_CATEGORY.recover} - the letter carries+ * its frozen schema-2 payload, the session is still+ * capture-classified, and at least one missing item is still not on+ * disk: re-run the recorded payload.+ * - {@link DEAD_LETTER_RECOVERY_CATEGORY.pending} - the session's+ * landed items sit staged in the write-approval queue: the exit is+ * the queue, not a re-run.+ * - {@link DEAD_LETTER_RECOVERY_CATEGORY.reExtract} - nothing to+ * re-run (a payload-less v1 letter, a payload that no longer passes+ * the lane's own validation): mine the session again.+ * - {@link DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable} - an unknown+ * lane, a session the import ledger does not know, or a session the+ * capture boundary now refuses: no command, the reason is the+ * answer.+ * - {@link DEAD_LETTER_RECOVERY_CATEGORY.resolved} - every missing key+ * now exists on disk: nothing to do. This fifth state exists because+ * the retention rule keeps reconciled letters on disk forever, and a+ * reconciled row must not read as still-broken.+ *+ * ## Re-admission means re-run at current state, never at a recorded+ * revision+ *+ * The extraction-signal lane carries no revision counter - its+ * concurrency story is the content-derived dedup hash plus atomic+ * per-file writes - so {@link applyRecovery} hands the recorded payload+ * straight back to `commitExtractedSignals`, which re-derives the+ * capture boundary, the dedup index and the staging lane at call time.+ * Already-written items dedup away; an item the session re-delivered by+ * mining again (the `re-extract` route, whose reworded text can never+ * match the frozen hash) is left out of the re-run entirely; nothing+ * stale is ever replayed.+ *+ * ## Nothing here deletes a letter+ *+ * The retention rule stands: no tool removes a dead letter. Recovery+ * writes signals, never record files; a reconciled letter is an+ * operator's hand-deletion decision on a named file, exactly as before.+ */++import { readFileSync } from "node:fs";++import { buildCaptureBoundary } from "./capture-boundary.ts";+import { buildDedupIndex, computeDedupHash } from "./dedup-hash.ts";+import { type DeadLetterPayload, type DeadLetterRecord, isDeadLetterLane } from "./dead-letter.ts";+import {+ commitExtractedSignals,+ type CommitExtractedSignalsResult,+ type ExtractedSignalItem,+} from "./extract-signals.ts";+import { classifyDurability, resolveDurabilityDenylist } from "./gates/durability.ts";+import { listPending, resolveWriteApprovalEnabled } from "./pending.ts";+import { assertResponseCheck } from "./response-checks.ts";+import {+ EXTRACTED_SIGNALS_SHAPE,+ EXTRACTED_SIGNALS_SURFACE,+ assertResponseShape,+} from "./response-shape.ts";+import { listSessionRawTurns } from "./session-recall.ts";+import { parseFrontmatterText } from "../vault.ts";++// ----- Vocabulary -----------------------------------------------------------++/** The five honest states a dead letter can be in, named once. */+export const DEAD_LETTER_RECOVERY_CATEGORY = Object.freeze({+ recover: "recover",+ pending: "pending",+ reExtract: "re-extract",+ notRecoverable: "not_recoverable",+ resolved: "resolved",+} as const);++export type DeadLetterRecoveryCategory =+ (typeof DEAD_LETTER_RECOVERY_CATEGORY)[keyof typeof DEAD_LETTER_RECOVERY_CATEGORY];++/** What one recorded payload item will do when the recovery re-runs it. */+export const DEAD_LETTER_ITEM_VERDICT = Object.freeze({+ /** The item writes fresh. */+ write: "write",+ /** The item writes, into the write-approval queue. */+ staged: "staged",+ /** The item is already on disk; the commit's dedup recognizes it. */+ dedup: "dedup",+ /** The item fails the durability gate; the commit refuses it by name. */+ refused: "refused",+} as const);++export type DeadLetterRecoveryItemVerdict =+ (typeof DEAD_LETTER_ITEM_VERDICT)[keyof typeof DEAD_LETTER_ITEM_VERDICT];++/** One classification: the state, why, and the command that resolves it. */+export interface DeadLetterClassification {+ readonly category: DeadLetterRecoveryCategory;+ /** Why this letter is in this state, for the row rendering. */+ readonly reason: string;+ /**+ * The exact copy-paste command, or `null` when no command resolves the+ * state - `not_recoverable` and `resolved` rows carry their reason+ * instead of inventing an exit.+ */+ readonly command: string | null;+}++/** One payload item's forecast for the dry run. */+export interface DeadLetterRecoveryItemPlan {+ readonly topic: string;+ readonly verdict: DeadLetterRecoveryItemVerdict;+ /** The durability gate's refusal, for a {@link DEAD_LETTER_ITEM_VERDICT.refused} item. */+ readonly reason?: string;+}++/** The dry-run view of one recoverable letter: its state plus per-item verdicts. */+export interface DeadLetterRecoveryPlan {+ readonly classification: DeadLetterClassification;+ readonly items: ReadonlyArray<DeadLetterRecoveryItemPlan>;+}++/** A recovery was asked for a letter that cannot carry one. */+export class DeadLetterRecoveryError extends Error {+ readonly category: DeadLetterRecoveryCategory;+ constructor(message: string, category: DeadLetterRecoveryCategory) {+ super(message);+ this.name = "DeadLetterRecoveryError";+ this.category = category;+ }+}++/**+ * The classification's copy-paste command, appended to a refusal that+ * names the classification: the operator (or agent) holding the error+ * alone gets the same exit the listing would have rendered, instead of+ * having to re-derive it. Null for the states that carry no command.+ */+function nextCommandSuffix(command: string | null): string {+ return command !== null ? ` (next: ${command})` : "";+}++// ----- Command spelling -----------------------------------------------------++/**+ * The copy-paste command shapes, composed from the verb spellings their+ * surfaces own. The recovery command is the HEADLESS spelling -+ * dry-run-default verbs refuse `--apply` without `--yes` under `--json`+ * or a non-TTY stdin, and a copy-paste command must work in exactly+ * those contexts.+ */+const RECOVER_COMMAND_PREFIX = "o2b brain dead-letters recover";+const PENDING_APPLY_COMMAND = "o2b brain pending apply";+const EXTRACT_SIGNALS_COMMAND = "o2b brain extract-signals";++// ----- Payload identity -----------------------------------------------------++/**+ * The extraction lane's payload, validated with the SAME gates the commit+ * applies, or `null` when the letter carries nothing this build may+ * re-run. A payload that fails the shape or the semantic checks cannot be+ * re-committed verbatim - handing it to the commit would only re-refuse+ * it - so the classifier reads that state as `re-extract` rather than as+ * `recover`.+ */+function recoverablePayload(record: DeadLetterRecord): {+ readonly items: ReadonlyArray<ExtractedSignalItem>;+} | null {+ const payload: DeadLetterPayload | undefined = record.payload;+ if (payload === undefined) return null;+ const items = payload["items"];+ if (!Array.isArray(items) || items.length === 0) return null;+ try {+ assertResponseShape(EXTRACTED_SIGNALS_SURFACE, EXTRACTED_SIGNALS_SHAPE, payload);+ assertResponseCheck(EXTRACTED_SIGNALS_SURFACE, payload);+ } catch {+ return null;+ }+ return { items: (payload as { items: ReadonlyArray<ExtractedSignalItem> }).items };+}++/** The `items[<index>]:<topic>` key the commit names every unwritten item by. */+const MISSING_KEY_RE = /^items\[(\d+)\]:(.+)$/;++/**+ * Why one missing key did not resolve - the cause the refusal names, so+ * an operator is pointed at the actual problem instead of one refusal+ * that assumes why.+ */+interface UnresolvedMissingKey {+ readonly key: string;+ readonly why: string;+}++/**+ * Resolve the letter's `missing` keys against the frozen payload - the+ * ONLY items a recovery plans or re-runs. Each key must parse, name an+ * index the payload carries, name that item's own topic, and name it+ * ONCE: a key that fails any rung is a letter this build cannot recover+ * faithfully (hand-edited, truncated, or written by a future format) -+ * a repeated key is the same hand-edit shape, and counting its item+ * twice could read a half-delivered letter resolved or hand the commit+ * the same item twice - and guessing would replay the wrong item, or+ * nothing at all, silently. `null` means every key resolved; otherwise+ * the first key that failed is named WITH its own cause.+ */+function resolveMissingItems(+ missing: ReadonlyArray<string>,+ items: ReadonlyArray<ExtractedSignalItem>,+): { items: ReadonlyArray<ExtractedSignalItem>; unresolved: UnresolvedMissingKey | null } {+ const resolved: ExtractedSignalItem[] = [];+ const seen = new Set<number>();+ for (const key of missing) {+ const match = MISSING_KEY_RE.exec(key);+ if (match === null) {+ return {+ items: resolved,+ unresolved: { key, why: "is not an items[<index>]:<topic> key" },+ };+ }+ const index = Number(match[1]);+ const item = items[index];+ if (item === undefined) {+ return {+ items: resolved,+ unresolved: { key, why: "names no item the frozen payload carries" },+ };+ }+ if (item.topic !== match[2]) {+ return {+ items: resolved,+ unresolved: { key, why: "does not name that item's own topic" },+ };+ }+ if (seen.has(index)) {+ return {+ items: resolved,+ unresolved: { key, why: "repeats an earlier key's item" },+ };+ }+ seen.add(index);+ resolved.push(item);+ }+ return { items: resolved, unresolved: null };+}++/**+ * The dedup hash one recorded item will dedup against, composed exactly+ * as `commitExtractedSignals` composes it - the same fields, the same+ * scope trim - so the classifier's forecast and the commit's decision+ * cannot disagree.+ *+ * A schema-2 item frozen by the extractor carries `dedup_hash`: the hash+ * of the RAW text, stored at freeze time beside the REDACTED fields (the+ * letter is redacted at rest, so recomputing over its fields would hash+ * the placeholder text and never match what the original delivery wrote+ * into the dedup index). The stored hash IS the original delivery+ * identity; the recomputation is the fallback for letters frozen by an+ * older build, whose fields are the raw ones.+ */+const FROZEN_DEDUP_HASH_KEY = "dedup_hash";++function itemDedupHash(item: ExtractedSignalItem): string {+ const frozen = item as unknown as { readonly [FROZEN_DEDUP_HASH_KEY]?: unknown };+ const stored = frozen[FROZEN_DEDUP_HASH_KEY];+ if (typeof stored === "string" && stored.length > 0) return stored;+ const scope = item.scope?.trim();+ return computeDedupHash({+ topic: item.topic,+ signal: item.signal,+ principle: item.principle,+ ...(scope ? { scope } : {}),+ });+}++/**+ * The inbox topics a payload-less (schema-1) letter can be re-measured+ * against, with how many of the session's OWN signal pages carry each:+ * the pages the dedup index walks whose `session_ref` names this+ * letter's session. A signal from another session confirms nothing+ * about what THIS session's commit delivered, and counting it would+ * read a real partial write as resolved. A page that carries no+ * readable topic confirms nothing either.+ */+function inboxSignalTopicCounts(+ dedup: ReturnType<typeof buildDedupIndex>,+ sessionRef: string,+): ReadonlyMap<string, number> {+ const counts = new Map<string, number>();+ for (const entry of dedup.values()) {+ try {+ const meta = parseFrontmatterText(readFileSync(entry.path, "utf8"))[0];+ if (meta["session_ref"] !== sessionRef) continue;+ const topic = meta["topic"];+ if (typeof topic === "string") counts.set(topic, (counts.get(topic) ?? 0) + 1);+ } catch {+ // A signal page that cannot be read cannot confirm a topic. That+ // is the conservative direction: the row stays actionable.+ }+ }+ return counts;+}++/**+ * One page on disk answers ONE missing key: the keys are consumed+ * against the page counts, so two keys naming one topic - two payload+ * items on one subject, or a hand-edit - are satisfied only by two+ * pages, never twice by the same one.+ */+function countDeliveredByTopic(+ missing: ReadonlyArray<string>,+ topicCounts: ReadonlyMap<string, number>,+): number {+ const remaining = new Map(topicCounts);+ let delivered = 0;+ for (const key of missing) {+ const match = MISSING_KEY_RE.exec(key);+ if (match === null) continue;+ const topic = match[2] ?? "";+ const left = remaining.get(topic) ?? 0;+ if (left > 0) {+ remaining.set(topic, left - 1);+ delivered += 1;+ }+ }+ return delivered;+}++/**+ * How a payload letter's resolved missing items stand against the vault's+ * current state, in key order. An item is DELIVERED when its dedup hash+ * is on disk (the exact identity - the frozen raw-text hash for a redacted+ * letter) or - the rule a v1 letter always used, now extended to v2 -+ * when this session already holds a signal page on the item's topic: the+ * `re-extract` route rewords the principle, so the exact hash never+ * matches and the topic is the evidence the content was delivered after+ * all. Counting a topic-delivered item undelivered made the apply replay+ * the stale wording as a second signal on the same session and topic.+ *+ * The buckets separate what each consumer needs:+ * - `reExtracted` - delivered by topic alone. The re-run must never hand+ * these back to the commit (the commit's dedup is hash-only; it would+ * write the duplicate the topic measure just ruled out), so the plan+ * and the apply leave them out.+ * - `undelivered` - no delivery evidence at all. These are what a+ * recovery would write, and what the durability gate is measured over.+ */+interface DeliveryMeasure {+ readonly delivered: number;+ readonly reExtracted: ReadonlyArray<ExtractedSignalItem>;+ readonly undelivered: ReadonlyArray<ExtractedSignalItem>;+}++function measureDelivery(+ dedup: ReturnType<typeof buildDedupIndex>,+ topicCounts: ReadonlyMap<string, number>,+ items: ReadonlyArray<ExtractedSignalItem>,+): DeliveryMeasure {+ const remaining = new Map(topicCounts);+ const reExtracted: ExtractedSignalItem[] = [];+ const undelivered: ExtractedSignalItem[] = [];+ let delivered = 0;+ for (const item of items) {+ if (dedup.has(itemDedupHash(item))) {+ delivered += 1;+ continue;+ }+ const left = remaining.get(item.topic) ?? 0;+ if (left > 0) {+ remaining.set(item.topic, left - 1);+ delivered += 1;+ reExtracted.push(item);+ continue;+ }+ undelivered.push(item);+ }+ return Object.freeze({+ delivered,+ reExtracted: Object.freeze(reExtracted),+ undelivered: Object.freeze(undelivered),+ });+}++// ----- Classification -------------------------------------------------------++/**+ * Classify one dead letter against the vault's current state. Total: the+ * five categories cover every letter this build can read, and the checks+ * run in the order the states are decided in - a fully delivered row is+ * `resolved` whatever else changed, a refused or unknown session is+ * `not_recoverable` whatever the payload promises, and only a live+ * session with undelivered items and a re-runnable payload is+ * `recover`.+ */+export function classifyDeadLetter(+ vault: string,+ record: DeadLetterRecord,+): DeadLetterClassification {+ if (!isDeadLetterLane(record.lane)) {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ reason:+ `dead-letter lane ${JSON.stringify(record.lane)} is unknown to this build; the lane ` ++ "union is closed on purpose",+ command: null,+ });+ }++ // A repeated missing key is a hand-edit on either schema: the commit's+ // own report builder refuses duplicates, and counting a repeated key+ // against the key count - by topic on a v1 letter as much as by item on+ // a v2 one - could read a half-delivered letter resolved or hand the+ // re-run the same item twice. The record does not vouch for itself.+ // The keys compare in CANONICAL form - parsed index plus topic - so a+ // zero-padded respelling of the same key does not slip past an exact+ // string match; a key that parses no further compares as written.+ const canonicalKeys = record.missing.map((key) => {+ const match = MISSING_KEY_RE.exec(key);+ return match === null ? key : `items[${Number(match[1])}]:${match[2]}`;+ });+ const repeatKey = record.missing.find((_, index) => {+ const canonical = canonicalKeys[index];+ return canonical !== undefined && canonicalKeys.indexOf(canonical) !== index;+ });+ if (repeatKey !== undefined) {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ reason:+ `missing key ${JSON.stringify(repeatKey)} repeats an earlier key; the record may be ` ++ "hand-edited or from a different build",+ command: null,+ });+ }++ // The resolved re-measure needs no session state: it answers whether+ // the letter's subject - its missing items - exists on disk, which is+ // true even if the session has since been ignored or forgotten.+ const payload = recoverablePayload(record);+ const dedup = buildDedupIndex(vault);+ const resolvedMissing =+ payload !== null ? resolveMissingItems(record.missing, payload.items) : null;+ if (payload !== null && resolvedMissing !== null && resolvedMissing.unresolved !== null) {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ reason:+ `missing key ${JSON.stringify(resolvedMissing.unresolved.key)} ${resolvedMissing.unresolved.why}; ` ++ "the record may be hand-edited or from a different build",+ command: null,+ });+ }+ // The session's own topic pages, computed once: a v1 letter measures+ // its keys against them, and a v2 item falls back to them when its+ // exact hash is absent (the re-extract route rewords the principle).+ const topicCounts = inboxSignalTopicCounts(dedup, record.reference);+ let delivered: number;+ let undelivered: ReadonlyArray<ExtractedSignalItem> = Object.freeze([]);+ if (payload !== null && resolvedMissing !== null) {+ const measure = measureDelivery(dedup, topicCounts, resolvedMissing.items);+ delivered = measure.delivered;+ undelivered = measure.undelivered;+ } else {+ delivered = countDeliveredByTopic(record.missing, topicCounts);+ }+ if (record.missing.length > 0 && delivered === record.missing.length) {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.resolved,+ reason: `all ${record.missing.length} missing item(s) are now on disk`,+ command: null,+ });+ }++ const boundary = buildCaptureBoundary(vault);+ const decision = boundary.sessionDecision(record.reference);+ if (decision !== "capture") {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ reason:+ `session ${record.reference} is classified '${decision}' by the capture boundary; ` ++ "it may not produce signals",+ command: null,+ });+ }+ if (listSessionRawTurns(vault, record.reference).length === 0) {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ reason:+ `session ${record.reference} has no imported turns; the import ledger does not know it. ` ++ "Import it first with 'o2b brain import-session --recall'",+ command: null,+ });+ }++ const staged = listPending(vault).filter(+ (entry) => entry.signal.session_ref === record.reference,+ );+ if (staged.length > 0 && staged[0] !== undefined) {+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.pending,+ reason:+ `${staged.length} staged signal(s) for this session sit in the write-approval queue; ` ++ "review the queue instead of re-running the payload",+ command: `${PENDING_APPLY_COMMAND} ${staged[0].id}`,+ });+ }++ if (payload !== null) {+ // An item the durability gate refuses never reaches disk, so the+ // dedup index can never show it delivered: a letter whose EVERY+ // undelivered item is refused would read `recover` forever, and each+ // apply would report success over zero writes - the exact dishonesty+ // the module refuses. The same gate, over the same items, is run here+ // so the state is named before a command promises a re-run.+ if (undelivered.length > 0) {+ const denylist = resolveDurabilityDenylist();+ const refusals = undelivered+ .map((item) => classifyDurability(item.principle, { denylist }))+ .filter((verdict) => !verdict.durable);+ if (refusals.length === undelivered.length) {+ const reasons = [+ ...new Set(+ refusals.flatMap((verdict) => (verdict.reason !== null ? [verdict.reason] : [])),+ ),+ ].join("; ");+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ reason:+ `all ${undelivered.length} undelivered missing item(s) are refused by the durability ` ++ `gate (${reasons}); the payload cannot be re-run until the gate accepts them`,+ command: null,+ });+ }+ }+ const reRunnable = record.missing.length - delivered;+ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.recover,+ reason:+ `${reRunnable} of ${record.missing.length} missing item(s) are not yet on disk; ` ++ "the frozen payload can be re-run at current vault state",+ command: `${RECOVER_COMMAND_PREFIX} ${record.id} --apply --yes`,+ });+ }++ return Object.freeze({+ category: DEAD_LETTER_RECOVERY_CATEGORY.reExtract,+ reason: "the letter carries no frozen payload to re-run; mine the session again",+ command: `${EXTRACT_SIGNALS_COMMAND} ${record.reference}`,+ });+}++// ----- Plan and apply -------------------------------------------------------++/**+ * The resolved missing items behind a plan or an apply, in key order. The+ * classifier has already refused any letter whose keys do not resolve, so+ * on this path the resolution cannot fail; the throw is an invariant+ * check for a caller that skipped the classification, not a second code+ * path - one refusal, shared, so the two surfaces cannot drift.+ */+function resolvedMissingItemsOrThrow(+ record: DeadLetterRecord,+ items: ReadonlyArray<ExtractedSignalItem>,+): ReadonlyArray<ExtractedSignalItem> {+ const resolved = resolveMissingItems(record.missing, items);+ if (resolved.unresolved !== null) {+ throw new DeadLetterRecoveryError(+ `dead letter ${record.id} cannot name its missing items: missing key ` ++ `${JSON.stringify(resolved.unresolved.key)} ${resolved.unresolved.why}`,+ DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable,+ );+ }+ return resolved.items;+}++/**+ * What a recovery hands back to the commit: the resolved missing items+ * MINUS the ones the topic measure found delivered by a re-extract. An+ * item whose exact hash is absent but whose topic this session already+ * holds was delivered with reworded text; replaying the frozen wording+ * would write a second signal on the same session and topic, because the+ * commit's dedup is hash-only and cannot see the delivery the topic+ * measure just ruled out. Items whose exact hash IS on disk stay in: the+ * commit dedups them by the same hash, which is how a delivered item is+ * accounted without being rewritten.+ */+function replayItems(+ dedup: ReturnType<typeof buildDedupIndex>,+ record: DeadLetterRecord,+ items: ReadonlyArray<ExtractedSignalItem>,+): ReadonlyArray<ExtractedSignalItem> {+ const measure = measureDelivery(dedup, inboxSignalTopicCounts(dedup, record.reference), items);+ const reExtracted = new Set(measure.reExtracted);+ return items.filter((item) => !reExtracted.has(item));+}++/** Test and caller seams for {@link planRecovery}, mirroring the commit's own options. */+export interface PlanRecoveryOptions {+ /** Pre-compiled durability denylist; resolved from config when omitted. */+ readonly durabilityDenylist?: ReadonlyArray<RegExp>;+ /** Write-approval toggle; resolved from config when omitted. */+ readonly writeApprovalEnabled?: boolean;+}++/**+ * The dry-run forecast: the letter's classification plus one verdict per+ * recorded payload item, computed with the same gates in the same order+ * the commit applies them - dedup, then the durability gate, then the+ * staging lane. A forecast is a reading of current state, not a promise:+ * the apply re-derives every gate at call time.+ */+export function planRecovery(+ vault: string,+ record: DeadLetterRecord,+ opts: PlanRecoveryOptions = {},+): DeadLetterRecoveryPlan {+ const classification = classifyDeadLetter(vault, record);+ if (classification.category !== DEAD_LETTER_RECOVERY_CATEGORY.recover) {+ // Worded without assuming why: a resolved or not_recoverable v2+ // letter still carries its frozen payload, so "carries no payload"+ // would be false exactly where the classification is the point.+ throw new DeadLetterRecoveryError(+ `dead letter ${record.id} cannot be planned as a payload re-run: classified ` ++ `'${classification.category}' (${classification.reason})` ++ nextCommandSuffix(classification.command),+ classification.category,+ );+ }+ const payload = recoverablePayload(record);+ if (payload === null) {+ throw new DeadLetterRecoveryError(+ `dead letter ${record.id} classified recover but carries no readable payload`,+ DEAD_LETTER_RECOVERY_CATEGORY.recover,+ );+ }+ const dedup = buildDedupIndex(vault);+ const denylist = opts.durabilityDenylist ?? resolveDurabilityDenylist();+ const staged = opts.writeApprovalEnabled ?? resolveWriteApprovalEnabled();+ // The plan previews exactly what the apply would re-run: the MISSING+ // items the commit would not recognise as already delivered. The items+ // that landed before the failure are not recovery's input - replaying+ // them would resurrect any one an operator removed afterwards (a+ // deleted signal, a rejected queue row the dedup index never walked) -+ // and an item the session re-delivered by re-extracting is left out+ // too, or its stale wording would be the second signal on that topic.+ // A missing key that names no payload item is a letter this build+ // cannot recover faithfully, and the classifier has already refused it+ // above.+ const replay = replayItems(dedup, record, resolvedMissingItemsOrThrow(record, payload.items));+ return Object.freeze({+ classification,+ items: Object.freeze(+ replay.map((item) => {+ if (dedup.has(itemDedupHash(item))) {+ return Object.freeze({ topic: item.topic, verdict: DEAD_LETTER_ITEM_VERDICT.dedup });+ }+ const verdict = classifyDurability(item.principle, { denylist });+ if (!verdict.durable) {+ return Object.freeze({+ topic: item.topic,+ verdict: DEAD_LETTER_ITEM_VERDICT.refused,+ ...(verdict.reason !== null ? { reason: verdict.reason } : {}),+ });+ }+ return Object.freeze({+ topic: item.topic,+ verdict: staged ? DEAD_LETTER_ITEM_VERDICT.staged : DEAD_LETTER_ITEM_VERDICT.write,+ });+ }),+ ),+ });+}++export interface ApplyRecoveryOptions {+ /** Acting agent name for the re-run commit. */+ readonly agent: string;+ readonly now: Date;+ /** Write-approval toggle; resolved from config when omitted. */+ readonly writeApprovalEnabled?: boolean;+}++/**+ * Re-run a letter's frozen payload through the extraction commit, at+ * CURRENT vault state. Refuses by name when the letter is not classified+ * `recover` - a v1 letter, a staged row or a resolved row is not this+ * verb's input - and never touches the letter itself: the retention rule+ * keeps every record on disk.+ */+export function applyRecovery(+ vault: string,+ record: DeadLetterRecord,+ opts: ApplyRecoveryOptions,+): CommitExtractedSignalsResult {+ const classification = classifyDeadLetter(vault, record);+ if (classification.category !== DEAD_LETTER_RECOVERY_CATEGORY.recover) {+ throw new DeadLetterRecoveryError(+ `dead letter ${record.id} cannot be recovered by re-running a payload: classified ` ++ `'${classification.category}' (${classification.reason})` ++ nextCommandSuffix(classification.command),+ classification.category,+ );+ }+ const payload = recoverablePayload(record);+ if (payload === null) {+ throw new DeadLetterRecoveryError(+ `dead letter ${record.id} classified recover but carries no readable payload`,+ DEAD_LETTER_RECOVERY_CATEGORY.recover,+ );+ }+ // The re-run commits exactly the MISSING items the commit would not+ // recognise as already delivered, never the whole payload: the items+ // that landed before the failure are not recovery's input, and+ // replaying them would resurrect any one an operator removed+ // afterwards - a deleted signal, or a rejected queue row, neither of+ // which the dedup index walks. An item the session re-delivered by+ // re-extracting is left out as well: its frozen wording is stale, and+ // the commit's hash-only dedup would land it as a second signal on the+ // same topic. "Nothing stale is replayed" is the module's own promise -+ // and so is never reporting success over a re-run that would write+ // nothing: the classifier has already refused any letter whose missing+ // keys do not resolve, and the shared refusal keeps that true on this+ // path too.+ const dedup = buildDedupIndex(vault);+ const replay = replayItems(dedup, record, resolvedMissingItemsOrThrow(record, payload.items));+ return commitExtractedSignals(+ vault,+ record.reference,+ { items: replay },+ {+ agent: opts.agent,+ now: opts.now,+ ...(opts.writeApprovalEnabled !== undefined+ ? { writeApprovalEnabled: opts.writeApprovalEnabled }+ : {}),+ },+ );+}diff --git a/src/core/brain/dead-letter.ts b/src/core/brain/dead-letter.tsindex 370e2bb0..d4ac8fb7 100644--- a/src/core/brain/dead-letter.ts+++ b/src/core/brain/dead-letter.ts@@ -28,6 +28,17 @@* first real error, so an operator reading the file knows which payload* to re-run and why the run stopped.*+ * Since schema 2 it also carries the payload itself, frozen at failure+ * time: the producer's validated payload, recorded so recovery can re-run+ * the exact write that failed part way without a second model call. The+ * freeze may redact free-text fields and keep each item's original dedup+ * hash beside it (the extraction lane does: the letter lives forever and+ * the dead-letters surfaces print it) - the identity a re-run dedups+ * against survives, the raw text does not. A v1 letter names the payload+ * but does not carry it, and still parses - it is the recovery layer's+ * business what that means, not this module's (see+ * `dead-letter-recovery.ts`).+ ** ## Where it lives, and why nothing here deletes it** Under `<vault>/.open-second-brain/dead-letters/`, the machine-artifact@@ -69,8 +80,41 @@ import { DERIVED_STORE_DIR } from "./path-constants.ts";import { isoSecond } from "./time.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";-/** Only schema version currently understood. Unknown versions are refused. */-export const DEAD_LETTER_SCHEMA_VERSION = 1 as const;+/**+ * Only schema version currently WRITTEN. Parsing is strict per version+ * over {@link PARSED_DEAD_LETTER_SCHEMA_VERSIONS}: schema 2 freezes the+ * failing commit's validated payload into the record (one-command+ * recovery, t_50794f57), schema 1 letters keep parsing - payload-less,+ * exactly as their writer left them - and anything else is refused, so a+ * version this build does not understand can never be read as one it+ * does.+ */+export const DEAD_LETTER_SCHEMA_VERSION = 2 as const;++/**+ * Every schema version this build parses. A list rather than a range+ * check: accepting a version is a decision per version, and the type+ * below is derived from it so a parser branch and the record type cannot+ * drift apart.+ */+export const PARSED_DEAD_LETTER_SCHEMA_VERSIONS = Object.freeze([+ 1,+ DEAD_LETTER_SCHEMA_VERSION,+] as const);++/** A schema version a record on disk may carry. */+export type DeadLetterSchemaVersion = (typeof PARSED_DEAD_LETTER_SCHEMA_VERSIONS)[number];++/**+ * Whether `value` is a schema version this build parses. The reader's+ * version gate: the guard is the list itself, so a version the constant+ * admits parses the day it lands and the gate cannot drift behind the+ * type; what each accepted version carries is still a decision per+ * version, made by the parser's own branches.+ */+function isParsedDeadLetterSchemaVersion(value: unknown): value is DeadLetterSchemaVersion {+ return (PARSED_DEAD_LETTER_SCHEMA_VERSIONS as ReadonlyArray<unknown>).includes(value);+}/** Subdirectory under the machine-artifact root holding one JSON per record. */const DEAD_LETTER_DIR = "dead-letters";@@ -89,6 +133,20 @@ const ID_RE = new RegExp(`^[a-z][a-z0-9-]*-[0-9a-f]{${ID_DIGEST_CHARS}}$`);*/export type DeadLetterLane = "extract-signals";+/**+ * The lane union at runtime, for readers of records from disk: a record's+ * `lane` field is a string from JSON, and a lane this build does not know+ * has to be nameable as such rather than silently treated as one it does.+ * A new member joining {@link DeadLetterLane} is added here in the same+ * edit.+ */+export const DEAD_LETTER_LANES: ReadonlyArray<DeadLetterLane> = Object.freeze(["extract-signals"]);++/** Whether `value` names a lane this build commits multi-artifact writes in. */+export function isDeadLetterLane(value: string): value is DeadLetterLane {+ return (DEAD_LETTER_LANES as ReadonlyArray<string>).includes(value);+}+/** Which payload, from which lane, the unwritten items belonged to. */export interface DeadLetterEnvelopeIdentity {readonly lane: DeadLetterLane;@@ -100,9 +158,23 @@ export interface DeadLetterEnvelopeIdentity {readonly target: string;}+/**+ * The frozen payload a schema-2 record carries: the producer's validated+ * payload as the lane froze it, so recovery can re-run the exact write+ * that failed part way without a second model call. The shape is the+ * lane's own - this module never looks inside it, so a future lane may+ * freeze a different envelope here without this file learning its+ * fields. A lane whose payload carries free text redacts it at freeze+ * time and keeps the pre-redaction dedup identity beside it; recovery+ * reads whatever shape the lane froze.+ */+export interface DeadLetterPayload {+ readonly [key: string]: unknown;+}+/** One persisted dead letter. */export interface DeadLetterRecord {- readonly schema_version: typeof DEAD_LETTER_SCHEMA_VERSION;+ readonly schema_version: DeadLetterSchemaVersion;readonly id: string;readonly lane: DeadLetterLane;readonly step: string;@@ -114,6 +186,14 @@ export interface DeadLetterRecord {readonly found: number;/** Keys naming every artifact that did NOT reach disk. */readonly missing: ReadonlyArray<string>;+ /**+ * The validated payload this commit was writing, frozen at failure+ * time. Present only on schema-2 records whose producer recorded it:+ * the field is optional because a v2 record from a lane that freezes+ * nothing is still a well-formed record, and the recovery layer - not+ * this module - decides what its absence means.+ */+ readonly payload?: DeadLetterPayload;readonly outcome: ReconciliationOutcome;/** Message of the first real error, verbatim. */readonly first_error: string;@@ -125,6 +205,13 @@ export interface RecordDeadLetterInput {readonly report: ReconciliationReport;/** The error that stopped the commit; anything throwable. */readonly firstError: unknown;+ /**+ * The validated payload to freeze into the record. A multi-artifact+ * lane that can be recovered by re-running its payload passes it here;+ * the id is derived over it, so two failures differing only in what+ * they tried to write are distinct records.+ */+ readonly payload?: DeadLetterPayload;readonly now: Date;}@@ -169,7 +256,7 @@ export function deadLetterPath(vault: string, id: string): string {* write for two writers to race on.*/export function recordDeadLetter(vault: string, input: RecordDeadLetterInput): DeadLetterRecord {- const { envelope, report, firstError, now } = input;+ const { envelope, report, firstError, payload, now } = input;requireContent("step", envelope.step);requireContent("reference", envelope.reference);requireContent("target", envelope.target);@@ -193,6 +280,7 @@ export function recordDeadLetter(vault: string, input: RecordDeadLetterInput): Dattempted: report.attempted,found: report.found,missing: Object.freeze([...report.missing]),+ ...(payload !== undefined ? { payload } : {}),outcome: deriveReconciliationOutcome(report),first_error: message,};@@ -273,12 +361,30 @@ function parseRecord(path: string): DeadLetterRecord {throw new DeadLetterError(`dead letter is not an object: ${path}`);}const obj = parsed as Record<string, unknown>;- if (obj["schema_version"] !== DEAD_LETTER_SCHEMA_VERSION) {+ const version = obj["schema_version"];+ if (!isParsedDeadLetterSchemaVersion(version)) {throw new DeadLetterError(- `dead letter schema_version ${String(obj["schema_version"])} not supported ` +- `(expected ${DEAD_LETTER_SCHEMA_VERSION}): ${path}`,+ `dead letter schema_version ${String(version)} not supported ` ++ `(this build parses ${PARSED_DEAD_LETTER_SCHEMA_VERSIONS.join(" and ")}): ${path}`,);}+ // Strict per version: a v1 record never carried a payload, so one that+ // claims it is not a v1 record and is refused rather than silently+ // promoted; a v2 record may carry the frozen payload, and when it does+ // the payload must be an object - the lane's own envelope - never a+ // bare list, a string or null.+ let payload: DeadLetterPayload | undefined;+ if (version === 1) {+ if (obj["payload"] !== undefined) {+ throw new DeadLetterError(`dead letter schema_version 1 must not carry a payload: ${path}`);+ }+ } else if (obj["payload"] !== undefined) {+ const raw = obj["payload"];+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {+ throw new DeadLetterError(`dead letter payload is not an object: ${path}`);+ }+ payload = Object.freeze({ ...(raw as object) });+ }const missing = obj["missing"];if (!Array.isArray(missing) || missing.some((key) => typeof key !== "string")) {throw new DeadLetterError(`dead letter has no readable missing key list: ${path}`);@@ -288,7 +394,7 @@ function parseRecord(path: string): DeadLetterRecord {throw new DeadLetterError(`dead letter carries an unknown outcome: ${path}`);}return Object.freeze({- schema_version: DEAD_LETTER_SCHEMA_VERSION,+ schema_version: version,id: requireString(obj, "id", path),lane: requireString(obj, "lane", path) as DeadLetterLane,step: requireString(obj, "step", path),@@ -297,6 +403,7 @@ function parseRecord(path: string): DeadLetterRecord {attempted: requireNumber(obj, "attempted", path),found: requireNumber(obj, "found", path),missing: Object.freeze([...(missing as ReadonlyArray<string>)]),+ ...(payload !== undefined ? { payload } : {}),outcome,first_error: requireString(obj, "first_error", path),recorded_at: requireString(obj, "recorded_at", path),@@ -315,6 +422,7 @@ function serialize(record: DeadLetterRecord): Record<string, unknown> {attempted: record.attempted,found: record.found,missing: [...record.missing],+ ...(record.payload !== undefined ? { payload: record.payload } : {}),outcome: record.outcome,first_error: record.first_error,recorded_at: record.recorded_at,diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.tsindex fa042344..b112978d 100644--- a/src/core/brain/destructive-sites.ts+++ b/src/core/brain/destructive-sites.ts@@ -114,6 +114,15 @@ const UNARCHIVED_EXCLUDED: RecoverabilityFacts = Object.freeze({blastRadius: Object.freeze({ snapshotExcludedEntries: true }),});+/**+ * No archive behind it, and no bytes reachable at all: the call removes+ * a directory entry that is empty by construction the moment it runs.+ */+const EMPTY_SHELL_ONLY: RecoverabilityFacts = Object.freeze({+ recoveryPoint: false,+ blastRadius: Object.freeze({}),+});+/*** Every destructive site under `src/core/brain/` that is not routed* through the destructive gate, with the argument for why the removal@@ -494,6 +503,20 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati"and whose Brain-resident half the archive therefore does hold.",},+ "src/core/brain/notes/folder-lifecycle.ts": {+ calls: ["rmdirSync", "unlinkSync"],+ recovery: EMPTY_SHELL_ONLY,+ reason:+ "prunes the moved folder's own emptied directories after every file of the move set " ++ "has relocated: `rmdirSync` refuses a non-empty directory, so a folder whose " ++ "subtree still holds a failed file - or any file this surface does not address - " ++ "keeps it, which is exactly where the report says the bytes are. The one " ++ "`unlinkSync` drops a destination name a mid-set fault linked after the source " ++ "name's own drop had already failed: the source name still holds that inode, so " ++ "the bytes outlive the removal and the failure report's kept-path claim stays " ++ "true. No file bytes are ever reached: both removals take names, never bytes.",+ },+// --- Outside the vault entirely --------------------------------------"src/core/brain/portability/pointer.ts": {calls: ["rmSync"],diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 71224dbb..74af4412 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -289,6 +289,19 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain claims",autoRepairable: false,},+ {+ // The dead-letter exit (t_50794f57). Spelled as a literal for the+ // same reason `undated-quantity` above is: importing the code from+ // `extract-signals.ts` would close an import cycle (the extractor+ // sits inside this module's import graph). The producer and this+ // entry are kept in step by the surface test, which resolves THIS+ // code through `resolveNextStep` against the command the write+ // error's message names.+ code: "extract-signals-dead-letter",+ issueClass: "a partial extraction write left a dead letter on disk",+ nextCommand: "o2b brain dead-letters",+ autoRepairable: false,+ },{// Issue #149. The detector has existed since the hygiene lints// shipped; what it never had was an exit. Recording real use isdiff --git a/src/core/brain/doctor/session-identity-check.ts b/src/core/brain/doctor/session-identity-check.tsindex 8fad0989..c36a23ce 100644--- a/src/core/brain/doctor/session-identity-check.ts+++ b/src/core/brain/doctor/session-identity-check.ts@@ -71,6 +71,10 @@ export const SESSION_IDENTITY_SITE = "brain.doctor.sessionIdentity";* `sessionId`, stamped into every payload).* - `decision_model_extract_commit` - `extract-signals-prefilter.ts`* (stamped from the commit result's required session id).+ * - `reply_presence` - `hooks/answer-quote-check.ts` (the Stop hook+ * appends the record only when the host names a session, and stamps+ * the key on every payload it appends, so a record never exists+ * without one).** The writer-shape census that keeps this list honest over the full* `ContinuityRecordKind` population lives in the check's test file.@@ -79,6 +83,7 @@ export const SESSION_IDENTITY_CHECKED_KINDS: ReadonlyArray<ContinuityRecordKind>"decision_model_extract_commit","post_compact_audit","pre_compact_extract",+ "reply_presence","session_summary_digest","session_summary_node","session_turn",diff --git a/src/core/brain/explorer.ts b/src/core/brain/explorer.tsindex f4ba87a5..88a01409 100644--- a/src/core/brain/explorer.ts+++ b/src/core/brain/explorer.ts@@ -21,6 +21,12 @@* ({@link ExplorerParseFailure}), never dropped. This surface both* displays the graph and exports it, and a graph silently missing a rule* is indistinguishable from a vault that never had one.+ *+ * The privacy deny markers reserve a node without refusing it: the+ * collector keeps every parsed node and+ * {@link collectExplorerDenials} reports which ones a SHARED output+ * must withhold - the live view is the operator's own, the export is+ * not, so the narrowing lives with the caller that writes bytes outward.*/import { existsSync, readFileSync, readdirSync } from "node:fs";@@ -28,8 +34,10 @@ import { basename, dirname, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";import { buildBacklinkIndex, type BacklinkIndex } from "./backlinks.ts";+import { deniedReservationKey, PREFERENCE_DENY_REASON, type PreferenceDenial } from "./export.ts";import { brainDirs } from "./paths.ts";import { parsePreference, parseRetired } from "./preference.ts";+import { parseFrontmatter } from "../vault.ts";import {BRAIN_PREFERENCE_STATUS,type BrainConfidence,@@ -38,6 +46,8 @@ import {} from "./types.ts";import { collectExplorerConsole } from "./explorer-console.ts";import { buildOperatorSnapshot } from "./operator-snapshot.ts";+import { redactRawOutput } from "../redactor.ts";+import { sortedDistinctLiterals } from "../secret-ref.ts";export const EXPLORER_SCHEMA_VERSION = 1 as const;@@ -105,6 +115,55 @@ export interface CollectExplorerDataOptions {readonly now?: Date;}+/**+ * The nodes the privacy deny markers reserve, as the shared lanes'+ * denial report: one list over BOTH node kinds, preference and retired,+ * each named with its id and the frontmatter key that denied it.+ *+ * The same judgment the preference exporters make, read from the+ * frontmatter of every `pref-*.md` under `Brain/preferences/` and every+ * `ret-*.md` under `Brain/retired/`. It is a report beside the+ * collector, not a filter inside it: {@link collectExplorerData} keeps+ * every parsed node, because the live server is the operator's own view+ * and a silently smaller graph there is the exact lie the parse-failure+ * refusal exists to prevent. A caller that writes bytes for another+ * reader narrows at its own seam and names what it left out.+ *+ * A file the parsers would refuse appears in+ * {@link ExplorerGraph.parse_failures}, and every export caller refuses+ * on that before reading this list - so a file with no readable+ * frontmatter id can never match a node and is skipped here rather than+ * guessed at.+ */+export function collectExplorerDenials(vault: string): ReadonlyArray<PreferenceDenial> {+ const dirs = brainDirs(vault);+ const denied: PreferenceDenial[] = [];+ const scan = (dir: string, prefix: string): void => {+ if (!existsSync(dir)) return;+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith(prefix)) continue;+ const path = join(dir, entry.name);+ // `parseFrontmatter` cannot throw; a file it cannot read yields an+ // empty map, which denies nothing - and the parse-failure refusal+ // has already stopped the export before this list is read.+ const [meta] = parseFrontmatter(path);+ const key = deniedReservationKey(meta);+ if (key === null) continue;+ const id = meta["id"];+ if (typeof id !== "string") continue;+ denied.push({ id, reason: PREFERENCE_DENY_REASON, denied_by: key });+ }+ };+ scan(dirs.preferences, "pref-");+ scan(dirs.retired, "ret-");+ // Sorted like the shared collectors' denial lists: the report rides+ // byte-deterministic surfaces (the stderr notice), and the explorer's+ // own output ordering is stable by id.+ denied.sort((a, b) => a.id.localeCompare(b.id));+ return denied;+}+export function collectExplorerData(vault: string,opts: CollectExplorerDataOptions = {},@@ -476,7 +535,25 @@ export function buildLiveServer(if (url.pathname === "/status.json") {try {const snapshot = await buildOperatorSnapshot(vault, snapshotOptions);- return jsonResponse(JSON.stringify(snapshot));+ // The explorer serves browsers, so the store group answers the+ // way the MCP surface answers below local reach: the writer+ // lock PATH is withheld - it is a resolved host path the index+ // may keep outside the vault - while every state field stays,+ // and `state_files.search_index` still answers presence.+ const store = { ...snapshot.store, writerLockPath: null };+ // The probe's failure reason can embed the same resolved host+ // path this field withholds (proper-lockfile's fs errors carry+ // it verbatim), so the path - in both its spellings - is+ // scrubbed from the reason too: the browser surface answers+ // below local reach for the whole store group, not for one+ // field of it.+ if (store.writerLockReason !== null && snapshot.store.writerLockPath !== null) {+ const index = snapshot.store.writerLockPath;+ store.writerLockReason = redactRawOutput(store.writerLockReason, {+ literals: sortedDistinctLiterals([index, `${index}.lock`]),+ });+ }+ return jsonResponse(JSON.stringify({ ...snapshot, store }));} catch (err) {return errorResponse("/status.json", err);}diff --git a/src/core/brain/export.ts b/src/core/brain/export.tsindex 4cf818e0..ae38a099 100644--- a/src/core/brain/export.ts+++ b/src/core/brain/export.ts@@ -4,6 +4,12 @@* (`confirmed | unconfirmed | quarantine`) are included; retired* and signal artifacts are deliberately excluded.*+ * A preference the privacy deny markers reserve (`visibility: private`,+ * or an informal `access` / `confidentiality` / `sensitivity` marker) is+ * still collected and reported - in {@link PreferenceCollection.denied} -+ * but the shared lanes built on this module leave it out and name the+ * omission; there is no flag that carries a reserved rule through.+ ** llms-txt follows the [llmstxt.org](https://llmstxt.org) shape;* empty status sections are omitted so a single-status vault* renders one H2 rather than three.@@ -20,16 +26,73 @@ import { existsSync, readdirSync } from "node:fs";import { join, relative } from "node:path";import { toPosix } from "../path-safety.ts";+import type { FrontmatterMap } from "../types.ts";import { hostPathFreeReason } from "./host-path-free.ts";import { parsePreference } from "./preference.ts";import { brainDirs } from "./paths.ts";import { vaultDisplayName } from "./templates.ts";import { isoSecond } from "./time.ts";import { BRAIN_PREFERENCE_STATUS, type BrainPreference } from "./types.ts";+import {+ hasPrivacyDenyMarker,+ PRIVACY_DENY_MARKER_VALUES,+ PRIVACY_MARKER_KEYS,+} from "../graph/privacy-markers.ts";+import { REMOTE_DENY_VISIBILITY_TOKEN, normToken, pageVisibility } from "../graph/visibility.ts";import { parseFrontmatter } from "../vault.ts";export const BRAIN_EXPORT_SCHEMA_VERSION = 1 as const;+/**+ * Why the collector denied a preference from the shared lanes. One value+ * today, matching `pageBlockReason`'s vocabulary in+ * `portability/knowledge-pack.ts`: a deny here is a visibility+ * reservation - the reserved token declared under `visibility:`, or an+ * informal privacy marker saying the same thing - and never a content+ * class, which this lane does not read.+ */+export const PREFERENCE_DENY_REASON = "visibility" as const;++/**+ * The frontmatter key whose value denied a shared lane a preference.+ *+ * `visibility` names the reserved token's own key; the other three are the+ * informal marker keys of {@link PRIVACY_MARKER_KEYS} (kept in sync by+ * construction - the runtime list below is built from that constant, and a+ * key added there flows into the denial vocabulary with it).+ */+export type PreferenceDenyKey = "visibility" | "access" | "confidentiality" | "sensitivity";++/** The denial keys, in the order the docs list them. */+export const PREFERENCE_DENY_KEYS: ReadonlyArray<PreferenceDenyKey> = Object.freeze([+ "visibility",+ ...PRIVACY_MARKER_KEYS,+]) as ReadonlyArray<PreferenceDenyKey>;++/** One preference a shared lane leaves out, named the way the rows name them. */+export interface PreferenceDenial {+ /** The denied row's id (`pref-<slug>`), as it appears in `rows`. */+ readonly id: string;+ /**+ * The reason CLASS, always the reserved-token class: a deny here is a+ * visibility reservation, never a content class. Kept verbatim so the+ * machine readers of the json envelope's `omitted`, the bundle's+ * `preferences_omitted` and the knowledge pack's `blocked` list keep+ * their vocabulary; the key below is the specific half.+ */+ readonly reason: typeof PREFERENCE_DENY_REASON;+ /**+ * The frontmatter key whose value made the denial, named `denied_by`+ * rather than `key` because the egress guard redacts every value under+ * a field name containing "key" - a denial report must survive its own+ * boundary. `visibility` when the reserved token under `visibility:`+ * denied, or the informal marker key (`access` / `confidentiality` /+ * `sensitivity`) that said the same thing. Canonical lower-case+ * spelling, whatever case the file used.+ */+ readonly denied_by: PreferenceDenyKey;+}+/** How many unreadable files the error names before it stops listing. */const MAX_NAMED_PARSE_FAILURES = 10;@@ -166,19 +229,74 @@ export interface ExportedPreferencesJson {readonly generated_at: string;readonly vault_basename: string;readonly preferences: ReadonlyArray<ExportedPreferenceRow>;+ /**+ * The preferences the privacy deny markers kept out of this export,+ * each named with its id and reason. Absent when empty, so a vault+ * with no reservation serialises byte-identically to the field-less+ * envelope and the schema stays 1 - an additive field, per the module's+ * own versioning rule. There is no override: the field reports what a+ * shared lane must never carry, so no flag fills it back in.+ */+ readonly omitted?: ReadonlyArray<PreferenceDenial>;}/**- * Every row the walk produced, and every file it could not read.+ * Every row the walk produced, every file it could not read, and every+ * row the privacy deny markers keep out of the SHARED lanes.*- * The pair, never one of them: a caller holding this has been told both- * how much it got and how much it missed, which is the property- * {@link collectExportRows}' refusal enforces for callers that cannot use- * a partial answer.+ * The triple, never one of them alone: a caller holding this has been+ * told how much it got, how much it missed, and what it must not carry.+ * `rows` stays complete on purpose - the import-side topic maps+ * (`preference-restore.ts`, `knowledge-pack.ts`) read the DESTINATION+ * vault to learn which topics existing rules claim, and a marker on a+ * rule does not unmake the rule - so denial is a report beside the rows,+ * not a filter inside the collector. The shared lanes filter at their+ * own composition seam and name what they leave out.*/export interface PreferenceCollection {readonly rows: ReadonlyArray<ExportedPreferenceRow>;readonly failures: ReadonlyArray<PreferenceParseFailure>;+ readonly denied: ReadonlyArray<PreferenceDenial>;+}++/**+ * Which frontmatter key, if any, denies this preference a shared lane?+ *+ * The same judgment `pageBlockReason` makes for pages in the knowledge+ * pack, read once here from the frontmatter map the collector already+ * parsed: a `visibility:` declaration carrying the reserved token, or an+ * informal privacy marker (`access: private` and its siblings) saying+ * what the reserved token says. A preference that declares only a+ * caller-scope token is a shared decision, not a reservation, and is+ * carried. The answer is the KEY that spoke, not just the fact of a+ * denial, so the stderr notice can name what the docs promise - the+ * reservation key that denied the row.+ */+export function deniedReservationKey(meta: FrontmatterMap): PreferenceDenyKey | null {+ if (pageVisibility(meta).includes(REMOTE_DENY_VISIBILITY_TOKEN)) return "visibility";+ if (!hasPrivacyDenyMarker(meta)) return null;+ // `hasPrivacyDenyMarker` just said some informal marker denies; name the+ // key that carries the deny value. The value reading mirrors the marker+ // module's own (a string, or an array of strings, normalised the same+ // way) - that reader is not exported there, and this module needs it+ // once, to answer WHICH key spoke rather than only whether one did.+ for (const key of Object.keys(meta)) {+ const canonical = PRIVACY_MARKER_KEYS.find((k) => normToken(k) === normToken(key));+ if (canonical === undefined) continue;+ const raw = meta[key];+ const values =+ typeof raw === "string"+ ? [raw]+ : Array.isArray(raw)+ ? raw.filter((v): v is string => typeof v === "string")+ : [];+ if (values.some((v) => PRIVACY_DENY_MARKER_VALUES.includes(normToken(v)))) {+ return canonical as PreferenceDenyKey;+ }+ }+ // Unreachable: `hasPrivacyDenyMarker` was true, so one of the marker+ // keys above carries a deny value and the loop already returned it.+ return null;}/**@@ -218,12 +336,17 @@ export function collectExportRows(vault: string): ReadonlyArray<ExportedPreferen* The directory LISTING failure still raises: it is a permission or* filesystem fault over the whole directory, not a per-file parse, and no* partial answer exists to give.+ *+ * A row the privacy deny markers reserve is reported in `denied` while+ * still parsed whole into `rows`; see {@link PreferenceCollection} for+ * why the split lives beside the rows and not inside them.*/export function collectPreferenceRows(vault: string): PreferenceCollection {const dir = brainDirs(vault).preferences;- if (!existsSync(dir)) return { rows: [], failures: [] };+ if (!existsSync(dir)) return { rows: [], failures: [], denied: [] };const rows: ExportedPreferenceRow[] = [];const failures: PreferenceParseFailure[] = [];+ const denied: PreferenceDenial[] = [];let entries: ReadonlyArray<string>;try {entries = readdirSync(dir);@@ -264,18 +387,31 @@ export function collectPreferenceRows(vault: string): PreferenceCollection {// consumer wants when sharing or system-prompt-injecting the// rule. A read failure here is the same defect as a frontmatter// one: the row would go out missing what the agent wrote.+ // The frontmatter map is already in hand at this line, so the+ // deny judgment reads it here rather than paying a second read.let body = "";+ let meta: FrontmatterMap = {};try {- const [, parsedBody] = parseFrontmatter(abs);+ const [parsedMeta, parsedBody] = parseFrontmatter(abs);+ meta = parsedMeta;body = parsedBody;} catch (err) {record(err);continue;}+ const denyKey = deniedReservationKey(meta);+ if (denyKey !== null) {+ denied.push({ id: pref.id, reason: PREFERENCE_DENY_REASON, denied_by: denyKey });+ }rows.push(toRow(pref, body));}rows.sort((a, b) => a.id.localeCompare(b.id));- return { rows, failures };+ // The denial list sorts like the rows: it rides the json envelope's+ // `omitted`, the bank bundle's `preferences_omitted` and the stderr+ // notice, and a byte-deterministic export cannot leave it in+ // readdir order.+ denied.sort((a, b) => a.id.localeCompare(b.id));+ return { rows, failures, denied };}function toRow(p: BrainPreference, body: string): ExportedPreferenceRow {@@ -305,12 +441,66 @@ function toRow(p: BrainPreference, body: string): ExportedPreferenceRow {});}+/**+ * The denying detail path beside {@link collectExportRows}: the same+ * walk, the same parse-failure refusal, and the denial list handed back+ * with `rows` still complete. For a caller that must see every row to+ * answer - the knowledge pack's selector resolution, which reports a+ * reserved rule as a named block rather than an unmatched selector.+ */+export function collectExportRowsWithDenials(vault: string): {+ readonly rows: ReadonlyArray<ExportedPreferenceRow>;+ readonly denied: ReadonlyArray<PreferenceDenial>;+} {+ const { rows, failures, denied } = collectPreferenceRows(vault);+ if (failures.length > 0) throw new PreferenceParseError(failures);+ return { rows, denied };+}++/**+ * The composition seam for everything handed to another reader - the+ * json envelope, the llms-txt document, the bank bundle: the denying+ * walk with `rows` narrowed to what a shared lane may carry. The+ * collector keeps `rows` complete for the import topic maps; the shared+ * lanes narrow here, where the omission is at hand to be named.+ */+export function collectSharedExportRows(vault: string): {+ readonly rows: ReadonlyArray<ExportedPreferenceRow>;+ readonly denied: ReadonlyArray<PreferenceDenial>;+} {+ const { rows, denied } = collectExportRowsWithDenials(vault);+ const reserved = new Set(denied.map((d) => d.id));+ return { rows: rows.filter((row) => !reserved.has(row.id)), denied };+}++/**+ * The stderr note naming the preferences a shared lane left out on a+ * visibility reservation, in the `contentClassOmissionNotice` shape:+ * counted, each item named with the reservation key that denied it, and a+ * remedy. The remedy names the reservation itself rather than an export+ * flag - a reserved rule never rides a shared lane, so the only way to+ * share it is to clear the reservation on the file, and the keys listed+ * are the ones this module reads.+ */+export function preferenceDenialNotice(denied: ReadonlyArray<PreferenceDenial>): string {+ const list = denied.map((d) => `${d.id} (${d.denied_by})`).join(", ");+ return (+ `note: ${denied.length} preference(s) left out on a visibility reservation: ${list}; ` ++ "no export flag carries them - clear the reservation " ++ "(visibility / access / confidentiality / sensitivity) on the preference file to share it\n"+ );+}+export function exportPreferencesJson(vault: string): ExportedPreferencesJson {+ const { rows, denied } = collectSharedExportRows(vault);return Object.freeze({schema: BRAIN_EXPORT_SCHEMA_VERSION,generated_at: isoSecond(),vault_basename: vaultDisplayName(vault),- preferences: collectExportRows(vault),+ preferences: rows,+ // Absent-when-empty keeps a reservation-free vault's bytes exactly+ // what they always were.+ ...(denied.length > 0 ? { omitted: denied } : {}),});}@@ -326,15 +516,26 @@ const LLMS_TXT_SECTION_LABEL: Readonly<Record<BrainPreference["status"], string>[BRAIN_PREFERENCE_STATUS.quarantine]: "Quarantine",};+/** The llms-txt document beside the omissions its privacy policy made. */+export interface LlmsTxtExport {+ readonly text: string;+ readonly omitted: ReadonlyArray<PreferenceDenial>;+}+/*** Render the export as an [llmstxt.org](https://llmstxt.org) markdown* file: H1 title, blockquote summary, then an H2 per non-empty* status. Each preference becomes one bullet line of the form* `- <id> (topic: <topic>[, scope: <scope>]): <principle>`. Status* sections without any rows are omitted entirely.+ *+ * Reserved preferences (see {@link PreferenceCollection.denied}) appear+ * in neither the sections nor the bullets; the detailed variant returns+ * the omissions beside the text so a caller can name them, the same+ * additive report the json envelope carries.*/-export function exportPreferencesLlmsTxt(vault: string): string {- const rows = collectExportRows(vault);+export function exportPreferencesLlmsTxtDetailed(vault: string): LlmsTxtExport {+ const { rows, denied } = collectSharedExportRows(vault);const name = vaultDisplayName(vault);const lines: string[] = [`# ${name} — Brain preferences`,@@ -355,5 +556,17 @@ export function exportPreferencesLlmsTxt(vault: string): string {}lines.push("");}- return lines.join("\n");+ return { text: lines.join("\n"), omitted: denied };+}++/**+ * The stable string signature, kept for the SDK façade and every+ * existing reader: the detailed variant's text, unchanged in shape and+ * byte-for-byte identical when nothing is denied. The string variant+ * carries no denial report - visibility-reserved rows are left out+ * silently - so a caller that must name what stayed out uses+ * {@link exportPreferencesLlmsTxtDetailed}.+ */+export function exportPreferencesLlmsTxt(vault: string): string {+ return exportPreferencesLlmsTxtDetailed(vault).text;}diff --git a/src/core/brain/extract-signals.ts b/src/core/brain/extract-signals.tsindex ace41faf..b8e427b0 100644--- a/src/core/brain/extract-signals.ts+++ b/src/core/brain/extract-signals.ts@@ -48,13 +48,19 @@import { posix } from "node:path";+import { redactRawOutput } from "../redactor.ts";import { buildReconciliationReport, type ReconciliationReport } from "../reconciliation-report.ts";import {buildCaptureBoundary,type CaptureBoundary,type SessionCaptureDecision,} from "./capture-boundary.ts";-import { tryRecordDeadLetter, type DeadLetterLane, type DeadLetterOutcome } from "./dead-letter.ts";+import {+ tryRecordDeadLetter,+ type DeadLetterLane,+ type DeadLetterOutcome,+ type DeadLetterPayload,+} from "./dead-letter.ts";import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";import { classifyDurability, resolveDurabilityDenylist } from "./gates/durability.ts";import { buildNeedsLlmStep, type NeedsLlmStep } from "./llm-step.ts";@@ -198,7 +204,9 @@ export class ExtractSignalsWriteError extends Error {/** The dead-letter half of the message above, either way it went. */function describeDeadLetter(outcome: DeadLetterOutcome): string {return outcome.recorded- ? `a dead letter recording this is at ${outcome.path} (${outcome.id})`+ ? `a dead letter recording this is at ${outcome.path} (${outcome.id}); ` ++ "'o2b brain dead-letters' classifies it and names the recovery exit " ++ "(diagnostic code extract-signals-dead-letter)": `NO dead letter could be recorded for it (${outcome.reason})`;}@@ -644,6 +652,48 @@ function transcriptLabel(turn: MinedTurn): string {// ----- Phase two: what the caller mined ------------------------------------+/**+ * The payload as it is FROZEN into a dead letter. The letter sits in+ * `.open-second-brain/dead-letters/` forever (the retention rule deletes+ * nothing) and the dead-letters surfaces print it, so each item's+ * free-text fields - `principle` and `scope` - are redacted here exactly+ * as `writeSignal` redacts them before disk; the letter is never the one+ * place the raw text survives.+ *+ * What redaction must not cost is the delivery identity: the dedup hash+ * a re-run would have been recognised by is computed over the RAW text,+ * so the raw text's hash is frozen beside each item (`dedup_hash`, the+ * same field name the delivered pages carry). Recovery prefers it, and a+ * later delivery of the real content still reads as delivered.+ *+ * The fields are enumerated rather than spread so a field added to+ * {@link ExtractedSignalItem} later cannot ride into the letter+ * unredacted: freezing it becomes a decision, not an accident.+ */+function frozenDeadLetterPayload(items: ReadonlyArray<ExtractedSignalItem>): DeadLetterPayload {+ return {+ items: items.map((item) => {+ const scope = item.scope?.trim();+ return {+ topic: item.topic,+ signal: item.signal,+ principle: redactRawOutput(item.principle),+ confidence: item.confidence,+ ...(scope !== undefined && scope !== "" ? { scope: redactRawOutput(scope) } : {}),+ ...(typeof item.source_turn === "string" && item.source_turn.trim() !== ""+ ? { source_turn: item.source_turn }+ : {}),+ dedup_hash: computeDedupHash({+ topic: item.topic,+ signal: item.signal,+ principle: item.principle,+ ...(scope !== undefined && scope !== "" ? { scope } : {}),+ }),+ };+ }),+ };+}+/** A plan's surveyed-turns hash: a SHA-256 digest in lowercase hex. */const SURVEYED_TURNS_HASH_RE = /^[0-9a-f]{64}$/;@@ -770,6 +820,15 @@ export function commitExtractedSignals(},report: reconciliation,firstError: err,+ // Schema 2 freezes the validated payload - the SAME payload the+ // error message tells the caller to re-run - so recovery can+ // re-commit it without a second model call. The items already+ // written ride along on purpose: a re-run lets the dedup index+ // recognize them, exactly as the message says. The freeze+ // redacts the free-text fields and keeps each item's raw dedup+ // hash, so the letter never becomes the one unredacted copy of+ // the payload and recovery still matches the original identity.+ payload: frozenDeadLetterPayload(items),now: opts.now,}),});diff --git a/src/core/brain/notes/folder-lifecycle.ts b/src/core/brain/notes/folder-lifecycle.tsnew file mode 100644index 00000000..e1443342--- /dev/null+++ b/src/core/brain/notes/folder-lifecycle.ts@@ -0,0 +1,1412 @@+/**+ * Folder-level note lifecycle: `move-folder` and `rename-folder`+ * (t_9571a47f).+ *+ * The note-file lifecycle (`./lifecycle.ts`) is defined per FILE: re-+ * organizing a vault by folder means moving notes one at a time through a+ * surface that refuses any directory change, which is how inbound+ * path-spelled wikilinks break by hand. This module moves a whole folder+ * in one call on the SAME terms the file surface set: the same path+ * envelope minus the `.md` rung, the same link-assert-unlink relocation,+ * the same count guard, the same dry-run default, and the same settled+ * partial-failure doctrine - a mid-set failure is NAMED, never rolled+ * back.+ *+ * ## The envelope has one rung less, and nothing else+ *+ * `resolveNoteTarget` requires a `.md` suffix, which a folder cannot+ * carry; every other rung is mirrored here rung for rung: vault-relative+ * (no absolute path), separators this host reads the way the caller wrote+ * them, no `..` traversal, not the `Brain/` machinery root (on the+ * spelled and the realpath alike, case-insensitively), vault-scope+ * checks, the operator's write binding, inside the vault. The SOURCE must+ * additionally stat as a directory - `source_missing`, the refusal a+ * path with no folder gets - and the vault root is refused as a subject.+ *+ * ## Why one rewrite pass is genuinely complete here+ *+ * A folder move never changes a basename. The bare `[[Name]]` spelling+ * resolved by carrier count before the move and resolves by the same+ * carrier count after it - the carriers moved, the count did not - so+ * `decideBasename`'s whole question does not arise and the bare-name+ * repair pass the file surface needs has nothing to do. Only PATH-spelled+ * links (`[[Projects/Old/a]]`, `[[Projects/Old/a.md]]`) break, and ONE+ * `retargetWikilinks` call over all pairs - minimal spellings computed+ * against the post-move population - fixes them, including links inside+ * the moved folder, because the pass matches text rather than live paths.+ *+ * ## Nothing here is atomic, and the report says where it split+ *+ * The move set is the vault's MARKDOWN, the same population every+ * lifecycle surface addresses (`retargetWikilinks`'s own walk produces+ * it): other files are not notes, are not moved, and are not this+ * operation's business. A folder whose subtree holds them reports the+ * Markdown relocations honestly in `moved` and leaves the rest standing+ * - the prune at the end removes only what the moves genuinely emptied.+ * And the set is judged by REAL LOCATION, never by the spelling the walk+ * happened to reach a file through: the walk lists a note under whichever+ * alias of its directory won the walk, so a move set built from spellings+ * would relocate another folder's notes through a symlinked directory+ * inside the source, or read as an empty applied success when an alias+ * elsewhere was walked first. Membership - and the spelling every move+ * pair and rewrite pair carries - is decided by where a file really+ * lives: inside the source's real path, under the source's real name. A+ * symlinked directory inside the source therefore relocates none of the+ * foreign notes it reaches (the link is the named residue), a symlinked+ * note is left standing rather than hard-linking its target, and a+ * source reached through an alias is moved, reported and pruned under+ * the name its bytes actually answer to.+ *+ * Relative Markdown links and images are NOT wikilinks and get no+ * rewrite - the pass repairs `[[path]]` spellings only, and a relative+ * `` depends on the note's directory, which the move+ * changed. When a moved note's relative target stayed behind, the+ * receipt names the pair in `danglingRelativeLinks` instead of letting+ * `files_rewritten: 0` read as "nothing broke".+ *+ * Occupancy is eliminated up front: every destination file path, and the+ * destination folder itself, is checked (with the dev/ino case-only+ * exemption) BEFORE the first rename, and an occupied destination refuses+ * naming every collision with nothing moved. What the pre-flight cannot+ * eliminate is a mid-set I/O fault, and rolling one back would mean+ * unlinking already-moved destination names - new destructive behavior+ * the snapshot gate does not cover. So the set continues and the result+ * reports the split point exactly: `moved` is what relocated,+ * `moveFailures` is what did not and why, and EVERYTHING downstream - the+ * rewrite pairs, the spellings reported - is computed from the+ * successfully moved set only. A file that failed to move keeps its old+ * path, its inbound links stay correct, and no pair of theirs enters the+ * pass. Relocations are byte-preserving and destroy nothing, so - as on+ * the file surface - no destructive snapshot is taken for a move.+ */++import {+ existsSync,+ lstatSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ rmdirSync,+ statSync,+ unlinkSync,+ type Dirent,+ type Stats,+} from "node:fs";+import { dirname, join, posix, sep, win32 } from "node:path";++import { checkWriteBinding } from "../../write-binding/index.ts";+import { ensureInsideVault, realVaultRelative, toPosix } from "../../path-safety.ts";+import { pathCovers } from "../../vault-scope/defaults.ts";+import { assertExpectedCount } from "../count-guard.ts";+import { classifyRecoverability, type RecoverabilityVerdict } from "../gates/recoverability.ts";+import { minimalSpellingFor } from "../link-graph/minimal-spelling.ts";+import { retargetWikilinks } from "../page-dedup.ts";+import { BRAIN_LOG_REL, BRAIN_CONFIG_FILE, BRAIN_ROOT_REL, isUnderBrainRoot } from "../paths.ts";+import { BrainConfigError } from "../policy.ts";+import { requireNextStep } from "../next-step.ts";+import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import {+ inspectPath,+ resolveVaultScope,+ type InspectResult,+ type VaultScope,+} from "../../vault-scope/index.ts";+import {+ BASENAME_REWRITE,+ INDEX_REFRESH,+ namesSameEntry,+ NOTE_LIFECYCLE_ACTION,+ NoteLifecycleError,+ readIndexEvidence,+ relocateFileBytes,+ type IndexEvidence,+ type IndexRefresh,+ type NoteLifecycleAction,+ type NoteReferenceReport,+} from "./lifecycle.ts";+// The claim itself is NOT re-exported by `./lifecycle.ts` (only the+// vocabulary and the evidence read are, for reporters): sibling writers+// import it from the module that owns it, exactly as the create and+// content-update writers do.+import { claimPostWriteRefresh } from "./index-refresh.ts";+import { CreateNoteError, NOTE_CONFIG_INVALID_CODE } from "./create-note.ts";++// ----- What a caller may ask for --------------------------------------------++/**+ * The folder actions, spelled by the ONE lifecycle vocabulary+ * (`NOTE_LIFECYCLE_ACTION`) so the CLI guard, the MCP enum and the+ * manifest cannot drift apart. The file actions refuse a folder subject+ * (their envelope requires `.md`), and this surface refuses the file+ * actions by name: `delete` and `archive` are decisions about a FILE, and+ * running them over a directory would invent new destructive behavior+ * this module does not own.+ */+export const FOLDER_LIFECYCLE_ACTION = Object.freeze({+ /** Move a whole folder under a destination parent. */+ moveFolder: NOTE_LIFECYCLE_ACTION.moveFolder,+ /** Rename a whole folder within its parent. */+ renameFolder: NOTE_LIFECYCLE_ACTION.renameFolder,+} as const);++/** Closed union over {@link FOLDER_LIFECYCLE_ACTION}. */+export type FolderLifecycleAction =+ (typeof FOLDER_LIFECYCLE_ACTION)[keyof typeof FOLDER_LIFECYCLE_ACTION];++/** Membership list. */+export const FOLDER_LIFECYCLE_ACTIONS: ReadonlyArray<FolderLifecycleAction> = Object.freeze(+ Object.values(FOLDER_LIFECYCLE_ACTION),+);++/**+ * `unknown` rather than `string`: the value arrives as an untyped MCP+ * argument or a raw CLI positional, exactly like+ * {@link isNoteLifecycleAction}, whose census probing this guard shares.+ */+export function isFolderLifecycleAction(value: unknown): value is FolderLifecycleAction {+ return (+ typeof value === "string" && (FOLDER_LIFECYCLE_ACTIONS as ReadonlyArray<string>).includes(value)+ );+}++// ----- Inputs, results, refusals --------------------------------------------++export interface FolderLifecycleInput {+ /** `move-folder` or `rename-folder`; every other action is refused. */+ readonly action: NoteLifecycleAction;+ /** Vault-relative path of the subject folder. */+ readonly path: string;+ /**+ * `move-folder`: the vault-relative destination DIRECTORY (the folder+ * lands under it, keeping its name). `rename-folder`: the new single-+ * segment name, under the same parent. Required for both.+ */+ readonly to?: string;+ /** False (the default) walks, counts and writes nothing. */+ readonly apply?: boolean;+ /** `--expect N`: assert the inbound-reference count before any write. */+ readonly expect?: number | null;+ /** `--strict`: refuse a mutation carrying no `--expect` guard. */+ readonly strict?: boolean;+ /** Injected clock, forwarded to the recovery claim so a run stays reproducible. */+ readonly now?: Date;+ /**+ * May the caller read the vault file at this vault-relative path? One+ * they may not is reported as a vault without it would be - absent+ * from `inboundFiles`, `filesScanned` and `rewriteFailures` - the same+ * rule the file surface's `readable` documents. The reach judges the+ * MOVE SET as well: a folder holding any note the caller may not read+ * is refused exactly as a missing folder, so neither the plan nor the+ * apply can name, count or relocate a page past the caller's reach. A+ * folder with no Markdown at all has no page to judge and moves.+ * Absent, every file counts (the CLI, which reads the vault directly).+ */+ readonly readable?: (rel: string) => boolean;+ /** Test seam: replaces the detached spawn of the post-write index refresh. */+ readonly refreshSpawn?: (argv: string[]) => void;+ /**+ * Test seam: the byte relocation itself, defaulting to the shared+ * {@link relocateFileBytes}. A stand-in produces faults the host cannot+ * schedule deterministically - a foreign file appearing at a destination+ * name the pre-flight had cleared, the exact race the occupied-name+ * guard exists for.+ */+ readonly relocate?: typeof relocateFileBytes;+ /**+ * The config file the post-write refresh resolves the search config+ * through - the caller's `--config` (or the MCP server's config path).+ */+ readonly refreshConfigPath?: string;+}++/** One file that relocated. */+export interface FolderMovedPath {+ /** Vault-relative path the file was at. */+ readonly from: string;+ /** Vault-relative path it is at now. */+ readonly to: string;+}++/** One file the set could not relocate, with the filesystem's reason. */+export interface FolderMoveFailure {+ /** Vault-relative path the file KEEPS - it never moved. */+ readonly path: string;+ /** The filesystem's own message, never a re-description of it. */+ readonly reason: string;+}++/** One relative link or image in a moved note whose target stayed behind. */+export interface FolderDanglingLink {+ /**+ * The moved note, spelled at its NEW path - where the broken spelling+ * now lives.+ */+ readonly note: string;+ /** The relative target, spelled exactly as the note spells it. */+ readonly target: string;+}++export interface FolderLifecycleResult {+ readonly action: FolderLifecycleAction;+ /** Vault-relative path the folder was at. */+ readonly from: string;+ /** Vault-relative path it is at now. */+ readonly to: string;+ /** False when this was a plan-only run. */+ readonly applied: boolean;+ /**+ * Every file that relocated, sorted by its old path. A plan-only run+ * relocates nothing and reports the PLANNED set here - the preview the+ * apply would carry out - so an empty list always means an empty move+ * set, never an unapplied one; {@link FolderLifecycleResult.applied}+ * carries that distinction.+ */+ readonly moved: ReadonlyArray<FolderMovedPath>;+ /**+ * Every file that did not relocate, with why. Non-empty means the+ * operation is HALF-APPLIED: the rewrite pairs were computed from+ * {@link FolderLifecycleResult.moved} only, so each failure's inbound+ * links still name the path its bytes are actually at. Never rolled+ * back - see the module header for why that is the better half-state.+ */+ readonly moveFailures: ReadonlyArray<FolderMoveFailure>;+ /**+ * What stayed in the source folder after the prune, from a readdir of+ * it once the prune had done its best. The move set is the vault's+ * MARKDOWN, so a subtree that also holds anything else - an image+ * beside the notes, a file the moves could not relocate - keeps its+ * source folder, and without this field the result would read as if+ * the folder went with its notes. Empty (and absent on the rendered+ * surfaces) means nothing was left behind: the folder itself is gone.+ * A plan-only run relocates nothing, so it leaves nothing behind+ * either.+ */+ readonly leftBehind: ReadonlyArray<string>;+ /**+ * The moved notes' RELATIVE Markdown links and images that no longer+ * resolve: targets the move did not carry (the set is the vault's+ * MARKDOWN) and that stayed behind in the source folder. The rewrite+ * pass repairs `[[path]]` spellings only, so without this field a+ * `files_rewritten: 0` would read as "nothing broke" while every moved+ * note's relative embed pointed at nothing. A target that moved with+ * its note still resolves and is not named; a vault-absolute or scheme+ * spelling never depended on the note's directory; a link that was+ * already dangling is not this operation's doing. A plan reports the+ * same judgment for its planned set. Empty (and absent on the rendered+ * surfaces) when nothing dangles.+ */+ readonly danglingRelativeLinks: ReadonlyArray<FolderDanglingLink>;+ /** What the recovery point (if any) is worth for THIS operation. */+ readonly recoverability: RecoverabilityVerdict;+ /**+ * Always `null`, kept for shape parity with the file result: a+ * relocation destroys nothing, so no recovery point is taken for a+ * move. The REWRITE's risk is what {@link FolderLifecycleResult.recoverability}+ * grades, exactly as on the file surface.+ */+ readonly snapshot: null;+ /** What happened to inbound references, and on what evidence. */+ readonly references: NoteReferenceReport;+}++// ----- The folder envelope: resolveNoteTarget minus the `.md` rung ----------++/** The separator that is structure on Windows and a filename character elsewhere. */+const FOLDER_WINDOWS_SEP = win32.sep;++/** Registry code for a vault whose Brain config does not load. */+const FOLDER_CONFIG_INVALID_EXIT = requireNextStep(NOTE_CONFIG_INVALID_CODE).nextCommand;++/** Vault-relative spelling of the config file every refusal here names. */+const BRAIN_CONFIG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_CONFIG_FILE);++/**+ * Translate a Brain config failure into this surface's typed refusal -+ * the same composition `resolveNoteTarget` uses, so a malformed config+ * reads the same on whichever surface reaches it first.+ */+function withConfigFault<T>(read: () => T): T {+ try {+ return read();+ } catch (err) {+ if (err instanceof BrainConfigError) {+ throw new CreateNoteError(+ "config_invalid",+ `${BRAIN_CONFIG_REL}: ${err.message}; ${FOLDER_CONFIG_INVALID_EXIT}`,+ );+ }+ throw err;+ }+}++/**+ * Refuse a caller-named path whose separators this host does not read the+ * way the caller wrote them - the same refusal `resolveNoteTarget` makes,+ * for the same reason: normalising `\` would silently reinterpret the+ * caller's string into a path it did not send.+ */+function assertHostPathSeparators(path: string): void {+ if (FOLDER_WINDOWS_SEP === sep) return;+ if (!path.includes(FOLDER_WINDOWS_SEP)) return;+ throw new CreateNoteError(+ "invalid_path",+ `folder path must use '${posix.sep}' to separate segments; on this host ` ++ `'${FOLDER_WINDOWS_SEP}' is an ordinary filename character, so the path would not ` ++ `mean what it looks like: ${path}`,+ );+}++/** The refusal sentence for a path vault scope rejects - `create-note.ts`'s wording. */+function scopeRefusal(scope: VaultScope, inspected: InspectResult): string {+ if (inspected.reason === "not-included") {+ return `path is outside vault.include_paths (${(scope.includePaths ?? []).join(", ")})`;+ }+ return `path is excluded by vault.ignore_paths (${inspected.rule?.raw ?? "rule"})`;+}++/**+ * A folder path resolved through the shared write safety envelope: the+ * exact ladder {@link resolveNoteTarget} runs, minus the `.md` rung a+ * folder cannot pass. Both the source folder and the destination folder+ * go through it, so a destination cannot reach somewhere a note could not+ * live.+ *+ * `allowVaultRoot` relaxes exactly one rung, for exactly one caller: the+ * destination DIRECTORY of a `move-folder` may be the vault root, because+ * a folder may land at the top level - while the root itself stays+ * refused as a SUBJECT (a subject is what moves; the root is what+ * everything moves within).+ */+function resolveFolderTarget(+ vault: string,+ path: string,+ opts: { readonly allowVaultRoot?: boolean } = {},+): { relPath: string; abs: string } {+ if (path.startsWith(posix.sep) || path.startsWith(FOLDER_WINDOWS_SEP)) {+ throw new CreateNoteError("invalid_path", `folder path must be vault-relative: ${path}`);+ }+ assertHostPathSeparators(path);++ const scope = withConfigFault(() => resolveVaultScope(vault));+ let inspected;+ try {+ inspected = inspectPath(path, scope, vault);+ } catch (err) {+ throw new CreateNoteError("invalid_path", err instanceof Error ? err.message : String(err));+ }+ const relPath = inspected.relPath;+ // The vault root (`""`, or a spelling `inspectPath` normalises to it)+ // is the whole vault: moving or renaming it is not a folder operation,+ // and pretending otherwise would report a move of every note in the+ // vault under one `moved` count.+ if (relPath === "" && opts.allowVaultRoot !== true) {+ throw new CreateNoteError(+ "invalid_path",+ `the vault root is not a folder subject: ${path === "" ? "(empty path)" : path}`,+ );+ }+ if (relPath === "") {+ // Reachable only with `allowVaultRoot`: the destination directory IS+ // the vault, inside it by definition, with no realpath or binding+ // rung of its own left to run - every file that lands beneath it+ // resolves through a full pass of its own.+ return { relPath: "", abs: ensureInsideVault(vault, vault) };+ }++ if (isUnderBrainRoot(relPath)) {+ throw new CreateNoteError(+ "excluded",+ `the Brain machinery root is not writable via the folder lifecycle: ${relPath}`,+ );+ }+ let landsAt: string | null;+ try {+ landsAt = realVaultRelative(vault, relPath);+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code ?? "unknown";+ throw new CreateNoteError(+ "invalid_path",+ `folder path cannot be resolved (${code}): ${relPath}`,+ );+ }+ if (landsAt === null) {+ throw new CreateNoteError(+ "outside_vault",+ `folder path resolves outside the vault: ${relPath}`,+ );+ }+ if (isUnderBrainRoot(landsAt)) {+ throw new CreateNoteError(+ "excluded",+ `the Brain machinery root is not writable via the folder lifecycle: ${relPath} resolves to ${landsAt}`,+ );+ }+ if (inspected.excluded) {+ throw new CreateNoteError("excluded", `${scopeRefusal(scope, inspected)}: ${relPath}`);+ }+ const refusal = withConfigFault(() => checkWriteBinding(vault, relPath));+ if (refusal !== null) {+ throw new CreateNoteError("write_binding", refusal.message);+ }+ let abs: string;+ try {+ abs = ensureInsideVault(join(vault, relPath), vault);+ } catch (err) {+ throw new CreateNoteError("outside_vault", err instanceof Error ? err.message : String(err));+ }+ // The folder envelope speaks POSIX: every judgment below compares or+ // slices relPath against real locations and walk spellings, which are+ // POSIX spellings on every platform. `inspectPath` joins its segments+ // with the platform separator, so without this rung a Windows relPath+ // carries backslashes and the spelled guards (`startsWith(`${rel}/`)`)+ // silently stop matching - the destination-inside-source refusal never+ // fires and the move nests the folder into itself on a case-folding+ // host.+ return { relPath: toPosix(relPath), abs };+}++// ----- Path helpers (folder-shaped) -----------------------------------------++/** `Projects/Old` -> `Old`. */+function folderBasename(relPath: string): string {+ return relPath.split(posix.sep).at(-1) ?? relPath;+}++/** `Projects/Old` -> `Projects`, and `Old` -> `""`. */+function folderParent(relPath: string): string {+ const cut = relPath.lastIndexOf(posix.sep);+ return cut < 0 ? "" : relPath.slice(0, cut);+}++/** The `.md` suffix, matched case-insensitively. */+const MARKDOWN_SUFFIX = ".md";++/** `Projects/Old/a.md` -> `Projects/Old/a`. */+function withoutSuffix(relPath: string): string {+ return relPath.toLowerCase().endsWith(MARKDOWN_SUFFIX)+ ? relPath.slice(0, -MARKDOWN_SUFFIX.length)+ : relPath;+}++/** `statSync`, or `null` when the path is not there or cannot be read. */+function statOrNull(target: string): Stats | null {+ try {+ return statSync(target);+ } catch {+ return null;+ }+}++/**+ * `lstatSync`, or `null` when the NAME is not there or cannot be read.+ * Unlike `statSync`/`existsSync` this judges the name itself, so a+ * symlink whose target is gone - a name this call created and then+ * reported as failed - still counts as present and can be dropped.+ */+function lstatOrNull(target: string): Stats | null {+ try {+ return lstatSync(target);+ } catch {+ return null;+ }+}++/**+ * The spelling the disk answers to: `relPath`'s real vault-relative+ * location, or the caller's spelling when that does not resolve (the+ * vault root, or a path whose deepest existing ancestor already carries+ * the answer). Every path this module JUDGES, MOVES or REPORTS goes+ * through it, so a symlink alias cannot make one folder look like two:+ * the review's H2/M15 faults were both spelling comparisons where one+ * side was an alias.+ */+function realSpelling(vault: string, relPath: string): string {+ return realVaultRelative(vault, relPath) ?? relPath;+}++/**+ * Whether the folder's REAL subtree holds any Markdown file: a plain+ * readdir that never follows a symlinked entry, because a link's name is+ * not a Markdown file of this subtree - its target's real location is+ * somewhere else (or nowhere) and is judged there. This is the disk's+ * own answer for the empty-move-set refusal, independent of what the+ * vault walk happened to list.+ */+function subtreeHoldsMarkdown(vault: string, fromRel: string): boolean {+ const stack: string[] = [join(vault, fromRel)];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ let entries: Dirent[];+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (entry.isSymbolicLink()) continue;+ if (entry.isDirectory()) {+ stack.push(join(dir, entry.name));+ continue;+ }+ if (entry.isFile() && entry.name.toLowerCase().endsWith(MARKDOWN_SUFFIX)) return true;+ }+ }+ return false;+}++/** `readdirSync`, or `null` when the directory cannot be read. */+function readdirOrNull(target: string): string[] | null {+ try {+ return readdirSync(target);+ } catch {+ return null;+ }+}++/**+ * Subtrees the rewrite pass READS and REPORTS but never rewrites - the+ * file surface's one entry, shared for the same reason: `Brain/log` is an+ * append-only record of what an agent said at an instant, and repairing+ * testimony changes what it says was said.+ */+const APPEND_ONLY_REL: ReadonlyArray<string> = Object.freeze([BRAIN_LOG_REL]);++/** The walk root the reference scan and the move-set planning share: the whole vault. */+const VAULT_ROOT_REL = "";++/** Where one planned file goes, with the dev/ino answer for its destination name. */+interface PlannedMove {+ readonly fromRel: string;+ readonly toRel: string;+ readonly fromAbs: string;+ readonly toAbs: string;+ /** The case-only folder rename: destination name IS the source entry. */+ readonly sameEntry: boolean;+}++// ----- Destination resolution -----------------------------------------------++/**+ * Resolve the destination FOLDER this action implies, through the same+ * envelope as the source, and refuse the caller mistakes the file+ * surface's rename/move split exists to catch - at folder granularity:+ * `move-folder` must change the folder's parent, `rename-folder` must+ * keep it.+ *+ * Both judgments run on REAL paths, never on spellings. The source+ * arrives already normalized to the name its bytes answer to; the+ * destination directory is normalized here before anything is decided,+ * because a symlink alias spells a path outside the source while naming+ * the source itself (or something inside it) - the inside-source guard+ * comparing spellings let such a destination fold the folder into+ * itself, and a case-folded spelling slipped past the same way. The+ * landing path is reported in its real spelling too, so the receipt+ * names where the bytes actually went.+ *+ * The rename-intent heuristic for `move-folder` - a destination in the+ * source's own parent is the spelling of a RENAME - applies ONLY when+ * the named destination directory does not exist: an existing sibling+ * directory is a real move target (moving `Projects/Old` under an+ * existing `Projects/Archive`), and refusing it pointed at+ * `rename-folder`, which refuses the cross-parent move right back. A+ * sibling that is not there is exactly the caller mistake the heuristic+ * exists for, so it is refused by name. The heuristic exempts the top+ * level: a rename there spells a single segment, so `Old` under+ * `Archive` can only ever mean the move it asked for, and refusing it+ * would leave every top-level folder unmovable into a sibling+ * top-level directory.+ */+function resolveFolderDestination(+ vault: string,+ input: FolderLifecycleInput,+ source: { relPath: string; abs: string },+): { relPath: string; abs: string } {+ if (input.to === undefined) {+ throw new NoteLifecycleError(+ "destination_required",+ `${input.action} requires a destination ('to')`,+ );+ }+ const action = input.action;+ if (action === FOLDER_LIFECYCLE_ACTION.renameFolder) {+ if (input.to.includes(posix.sep) || input.to.includes(FOLDER_WINDOWS_SEP)) {+ // Refused as the caller mistake it is - a rename spelled across+ // parents - not normalised into the move it did not ask for.+ throw new NoteLifecycleError(+ "wrong_action",+ `rename-folder keeps the folder in ${folderParent(source.relPath) || "the vault root"}; ` ++ `'${input.to}' crosses parents - use move-folder`,+ );+ }+ }+ /** The landing folder, judged and reported in its real spelling. */+ const landing = (folder: { relPath: string; abs: string }): { relPath: string; abs: string } => {+ const real = realSpelling(vault, folder.relPath);+ return real === folder.relPath+ ? folder+ : { relPath: real, abs: ensureInsideVault(join(vault, real), vault) };+ };+ if (action === FOLDER_LIFECYCLE_ACTION.moveFolder) {+ const destinationDirectory = resolveFolderTarget(vault, input.to, { allowVaultRoot: true });+ const destinationReal = realSpelling(vault, destinationDirectory.relPath);+ // A destination directory inside the source's own subtree nests the+ // tree inside itself: every planned path stays a strict descendant of+ // the source, so the file-surface refusals (same path, same parent)+ // all pass while the operation folds the folder into its own+ // descendant. Refused on the destination DIRECTORY the caller named -+ // the computed landing path is necessarily deeper still - and judged+ // by real path on both sides, which is what an alias (or a case+ // fold) cannot talk its way past.+ if (destinationReal === source.relPath || destinationReal.startsWith(`${source.relPath}/`)) {+ throw new NoteLifecycleError(+ "destination_inside_source",+ `${action} destination ${destinationDirectory.relPath} sits inside the source folder ` ++ `${source.relPath} (it resolves on disk to ${destinationReal}); the folder would ` ++ "nest inside itself",+ );+ }+ // Spelling-independent rung: walk the destination chain up to the+ // vault root and refuse when any existing entry IS the source's own+ // directory entry. A file-identity compare is what a case fold, a+ // Unicode normalization form or an alias cannot talk past - the+ // spelled rungs above judge spellings, and a host that answers a+ // spelled path from a differently spelled real entry can slip a+ // mismatch past every one of them.+ const sourceEntry = statOrNull(source.abs);+ if (sourceEntry !== null && sourceEntry.ino !== 0) {+ let cursor = destinationDirectory.abs;+ for (;;) {+ const entry = statOrNull(cursor);+ if (entry !== null && entry.ino === sourceEntry.ino && entry.dev === sourceEntry.dev) {+ throw new NoteLifecycleError(+ "destination_inside_source",+ `${action} destination ${destinationDirectory.relPath} is the source folder ` ++ `${source.relPath} (same directory entry on this host); the folder would ` ++ "nest inside itself",+ );+ }+ const parent = dirname(cursor);+ if (parent === cursor || parent === vault || parent.length < vault.length) break;+ cursor = parent;+ }+ }+ const destination = landing(+ resolveFolderTarget(+ vault,+ posix.join(destinationDirectory.relPath, folderBasename(source.relPath)),+ ),+ );+ if (destination.relPath === source.relPath) {+ throw new NoteLifecycleError(+ "destination_unchanged",+ `${action} destination is the source folder: ${source.relPath}`,+ );+ }+ if (+ statOrNull(destinationDirectory.abs) === null &&+ folderParent(source.relPath) !== "" &&+ folderParent(destinationReal) === folderParent(source.relPath)+ ) {+ throw new NoteLifecycleError(+ "wrong_action",+ `move-folder changes the folder's parent; ${destinationDirectory.relPath} sits in ` ++ `${folderParent(source.relPath) || "the vault root"}, where ${source.relPath} lives - ` ++ `use rename-folder`,+ );+ }+ return destination;+ }+ const destination = landing(+ resolveFolderTarget(vault, posix.join(folderParent(source.relPath), input.to)),+ );+ if (destination.relPath === source.relPath) {+ throw new NoteLifecycleError(+ "destination_unchanged",+ `${action} destination is the source folder: ${source.relPath}`,+ );+ }+ return destination;+}++// ----- Occupancy pre-flight --------------------------------------------------++/**+ * Check EVERY destination before the first rename and refuse naming every+ * collision. Within-set collisions are impossible (the relative structure+ * is preserved), so the only collisions are with pre-existing files and+ * directories at the destination - and finding them all before anything+ * moves is the closest thing to atomicity this operation honestly has.+ * The check runs on the PLAN, so a zero-file move set is covered too: an+ * empty folder whose destination path is taken by a FILE refuses exactly+ * like a full one.+ *+ * A destination folder that exists is an occupancy unless it is EMPTY+ * (the files land into it) or is the same directory entry as the SOURCE+ * folder (the case-only folder rename). A destination FILE path is an+ * occupancy unless it names the same entry as its source file - the+ * case-only rename's per-file face.+ */+function assertDestinationsFree(+ planned: ReadonlyArray<PlannedMove>,+ sourceAbs: string,+ destination: { relPath: string; abs: string },+): void {+ const collisions: string[] = [];+ const destinationStat = statOrNull(destination.abs);+ if (destinationStat !== null && !destinationStat.isDirectory()) {+ collisions.push(destination.relPath);+ } else if (destinationStat !== null && !namesSameEntry(sourceAbs, destination.abs)) {+ // An unreadable destination directory states nothing about emptiness,+ // so it is an occupancy too - a move into it cannot be verified free,+ // and a refusal names the directory rather than guessing.+ const entries = readdirOrNull(destination.abs);+ if (entries === null) collisions.push(`${destination.relPath} (could not be read)`);+ else if (entries.length > 0) collisions.push(`${destination.relPath} (not empty)`);+ }+ for (const move of planned) {+ const destinationStat = statOrNull(move.toAbs);+ if (destinationStat === null) continue;+ if (namesSameEntry(move.fromAbs, move.toAbs)) continue;+ collisions.push(move.toRel);+ }+ if (collisions.length > 0) {+ throw new NoteLifecycleError(+ "destination_occupied",+ `destinations already exist and nothing was moved: ${collisions.join(", ")}`,+ );+ }+}++// ----- What a Markdown-only move leaves dangling -----------------------------++/** Inline Markdown link/image target: `[text](target)`, ``. */+const MARKDOWN_LINK_TARGET_RE = /\[[^\]]*\]\(\s*<?([^)<>]+?)>?\s*\)/g;++/**+ * The URI-scheme shape (`https:`, `obsidian:`, `mailto:`) that is an+ * address rather than a path - the same judgment `path-safety.ts`'s+ * unexported `URI_SCHEME_RE` makes for wikilink targets.+ */+const URI_SCHEME_TEST = /^[a-z][a-z0-9+.-]*:/i;++/**+ * Which of the moved notes' RELATIVE Markdown links and images now point+ * at nothing. The judgment is made for each target exactly as the note+ * spells it, against the OLD directory the link was written to resolve+ * from and the NEW one the note now lives at: the link dangles only when+ * the target sat where the old spelling resolved to (it was never this+ * operation's business otherwise) and sits nowhere where the new one+ * does. A target that moved with the folder still resolves; a+ * vault-absolute (`/pic.png`) or scheme spelling never depended on the+ * note's directory; an in-page `#anchor` names the note itself; a link+ * that was already dangling names no fault of the move. Each distinct+ * note-and-target pair is named once, sorted by note then target.+ */+function danglingRelativeLinks(+ vault: string,+ moves: ReadonlyArray<{+ readonly from: string;+ readonly to: string;+ /** Where the note's bytes are right now - the old path on a plan, the new one on an apply. */+ readonly bytesAbs: string;+ }>,+ /**+ * PLAN only: the move-set's own promise that a Markdown target sitting+ * inside the source will be at the new location once the move runs.+ * An apply needs no promise - the relocation has already happened and+ * the disk is the whole truth - but a plan that judged by the current+ * disk would name EVERY relative target dangling, because nothing has+ * landed yet.+ */+ willLand?: (oldRel: string) => boolean,+): FolderDanglingLink[] {+ const seen = new Set<string>();+ const out: FolderDanglingLink[] = [];+ for (const move of moves) {+ let body: string;+ try {+ body = readFileSync(move.bytesAbs, "utf8");+ } catch {+ // A note that cannot be read states nothing about its links; the+ // per-file machinery has already named it if the move failed.+ continue;+ }+ for (const match of body.matchAll(MARKDOWN_LINK_TARGET_RE)) {+ const raw = match[1]!;+ if (raw === "" || raw.startsWith("#") || raw.startsWith("/") || URI_SCHEME_TEST.test(raw)) {+ continue;+ }+ const target = (() => {+ try {+ return decodeURIComponent(raw);+ } catch {+ return raw;+ }+ })();+ const hash = target.indexOf("#");+ const pathPart = hash < 0 ? target : target.slice(0, hash);+ if (pathPart === "") continue;+ const oldRel = posix.normalize(posix.join(posix.dirname(move.from), pathPart));+ const newRel = posix.normalize(posix.join(posix.dirname(move.to), pathPart));+ if (oldRel.startsWith("..") || newRel.startsWith("..")) continue;+ const stayed = existsSync(join(vault, oldRel));+ const landed = existsSync(join(vault, newRel)) || (willLand?.(oldRel) ?? false);+ if (stayed && !landed) {+ const key = `${move.to}\u0000${raw}`;+ if (!seen.has(key)) {+ seen.add(key);+ out.push({ note: move.to, target: raw });+ }+ }+ }+ }+ return out.toSorted((a, b) =>+ a.note === b.note ? (a.target < b.target ? -1 : 1) : a.note < b.note ? -1 : 1,+ );+}++// ----- The operation ----------------------------------------------------------++/**+ * Run one folder lifecycle operation. Ordering is load-bearing, as on the+ * file surface: the envelope judges both folders before anything is read;+ * the walk establishes the move set and the blast radius before the count+ * guard runs; the occupancy pre-flight runs before the first rename; the+ * rewrite runs once, over the successfully moved set's pairs; and the+ * index evidence is read at the END, with the refresh claim trailing it.+ */+export async function folderLifecycle(+ vault: string,+ input: FolderLifecycleInput,+): Promise<FolderLifecycleResult> {+ const apply = input.apply === true;+ // Vault-identity write guard (context-integrity-gates, Unit J) - on the+ // planning path too, exactly as the file surface asserts it: a plan+ // names real vault paths, and computing one against a vault this+ // process was not pointed at is already the confusion the guard exists+ // to refuse.+ assertVaultIdentityForWrite(vault);++ if (!isFolderLifecycleAction(input.action)) {+ throw new NoteLifecycleError(+ "wrong_action",+ `the folder lifecycle runs ${FOLDER_LIFECYCLE_ACTIONS.join(" | ")}; ` ++ `'${input.action}' is a note-file action and refuses a folder subject`,+ );+ }+ const action = input.action;+ const source = resolveFolderTarget(vault, input.path);+ const sourceStat = statOrNull(source.abs);+ if (sourceStat === null || !sourceStat.isDirectory()) {+ throw new NoteLifecycleError("source_missing", `no note folder at ${source.relPath}`);+ }+ // The source is judged, moved and reported under its REAL spelling.+ // Every judgment below compares or slices it against walk spellings+ // and real locations, so an alias-spelled source would plan a move of+ // names the disk does not answer to. The envelope has already vetted+ // the real location - it refuses a path whose realpath leaves the+ // vault or lands under `Brain/` - so this only makes the name honest.+ const sourceRel = realSpelling(vault, source.relPath);+ const sourceFolder =+ sourceRel === source.relPath+ ? source+ : { relPath: sourceRel, abs: ensureInsideVault(join(vault, sourceRel), vault) };+ // Pass one: walk the whole vault once. This is the move set's source,+ // the post-move population the minimal spellings are computed against,+ // and the filesScanned denominator - one walk, so no two of those can+ // see different vaults.+ const walk = retargetWikilinks(vault, [], { root: VAULT_ROOT_REL, apply: false });+ const vaultFiles = walk.files;+ // The move set is the walked files whose REAL LOCATION is inside the+ // source's real path, carried under that real spelling. The walk lists+ // a file under whichever alias of its directory won the walk (it skips+ // a directory whose realpath was already visited), so membership - and+ // the spelling every move pair and rewrite pair carries - must be+ // decided by where a file really lives: a symlinked directory inside+ // the source puts ANOTHER folder's notes under the source's spelling,+ // and an alias elsewhere puts the source's own notes under a foreign+ // one. The walk dedupes directories by realpath, so each file is+ // listed under exactly one spelling and the set cannot hold a file+ // twice. (The realpath read is memoized per spelling; the judgment is+ // order-independent, so either alias order plans the same move.)+ const realCache = new Map<string, string>();+ const realOf = (rel: string): string => {+ const cached = realCache.get(rel);+ if (cached !== undefined) return cached;+ const real = realSpelling(vault, rel);+ realCache.set(rel, real);+ return real;+ };+ const movingReal = new Set<string>();+ for (const rel of vaultFiles) {+ const real = realOf(rel);+ if (real === sourceRel || real.startsWith(`${sourceRel}/`)) movingReal.add(real);+ }+ const movingSet = [...movingReal].toSorted();+ // The caller's reach judges the MOVE SET, and it judges BEFORE the+ // destination is resolved: one note under the folder that the caller+ // may not read refuses the WHOLE operation as a missing folder, on+ // every later error path too - a denied folder that answers a+ // destination mistake with `wrong_action` while a truly missing one+ // answers `source_missing` would be an existence oracle. Skipping the+ // denied files would still leak them - through the occupancy+ // pre-flight, the rewrite pairs and the residue report - and moving+ // them would relocate pages the caller cannot read, so the refusal+ // reads exactly as the file surface's missing-note one. (A folder is+ // not itself a page, so its notes are what the reach predicate can+ // judge.)+ if (movingSet.some((rel) => input.readable?.(rel) === false)) {+ throw new NoteLifecycleError("source_missing", `no note folder at ${source.relPath}`);+ }+ const reported = (rel: string): boolean => input.readable?.(rel) ?? true;+ const destination = resolveFolderDestination(vault, input, sourceFolder);+ // A destination that IS the source's directory entry - the case-only+ // folder rename on a host that folds case - cannot be performed by+ // re-homing the folder's files: the entry keeps its spelling, the+ // prune cannot remove it, and the receipt would name a move that+ // never happened. Refused before anything is planned, on the plan+ // too: a dry run that previews a move it cannot perform is a lie.+ if (namesSameEntry(sourceFolder.abs, destination.abs)) {+ throw new NoteLifecycleError(+ "destination_unchanged",+ `${action} destination ${destination.relPath} is the source folder's own directory ` ++ "entry on this host (a case-only spelling); moving the folder's files cannot " ++ "re-case the entry - rename the directory itself",+ );+ }+ // An empty move set over a folder the disk says is non-empty is not a+ // quiet success waiting to happen when the spelling is the fault: a+ // path whose case (or Unicode normalization form) differs from the+ // vault's real names stats fine on a case-insensitive host and yet+ // matches no walked file, and the operation would report applied:true+ // with an empty `moved` over notes that are really there. The same+ // empty applied success is what a symlinked entry inside the source+ // used to produce from the other direction: the walk holds spellings+ // that fold under the path, but each names a file whose real location+ // is elsewhere. Both shapes are recognisable and refused, naming the+ // suspicion. A folder the walk has NOTHING under, whatever it holds on+ // disk, is simply not a Markdown subject: an attachments-only or+ // empty-subtree folder moves an empty set, keeps its contents, and the+ // residue report says so - unless the disk holds Markdown under the+ // source that NO walked spelling accounts for (out of the caller's+ // vault scope, or a directory the walk could not read), which is the+ // third shape of the same lie and refused too. A directory this+ // process cannot read states nothing about emptiness either, so it+ // does not refuse here - the per-file machinery names the fault if the+ // move really is attempted.+ const sourceEntries = readdirOrNull(sourceFolder.abs);+ if (movingSet.length === 0 && sourceEntries !== null && sourceEntries.length > 0) {+ const fold = (rel: string): string => `${rel.normalize("NFC").toLowerCase()}/`;+ const foldedSource = fold(sourceRel);+ if (vaultFiles.some((rel) => fold(rel).startsWith(foldedSource))) {+ throw new NoteLifecycleError(+ "move_set_empty",+ `no Markdown moves from ${sourceRel} but the folder is not empty on disk: the walk saw ` ++ `${vaultFiles.length} Markdown file(s) spelled under the path, and none of them ` ++ "really lives inside it - each is reached through a symlink whose target the move " ++ "does not follow, or sits under a different casing or character normalization of " ++ "the path - check the folder's own names against the vault's",+ );+ }+ if (subtreeHoldsMarkdown(vault, sourceRel)) {+ throw new NoteLifecycleError(+ "move_set_empty",+ `no Markdown moves from ${sourceRel} but the folder is not empty on disk: it holds ` ++ "Markdown that no walked spelling accounts for - excluded by vault scope, or a " ++ "directory the walk could not read - and moving none of it is refused rather than " ++ "reported as an empty success",+ );+ }+ }+ const planned: PlannedMove[] = movingSet.map((fromRel) => {+ const toRel = `${destination.relPath}${fromRel.slice(sourceRel.length)}`;+ const fromAbs = ensureInsideVault(join(vault, fromRel), vault);+ const toAbs = ensureInsideVault(join(vault, toRel), vault);+ return { fromRel, toRel, fromAbs, toAbs, sameEntry: namesSameEntry(fromAbs, toAbs) };+ });++ // The occupancy gate runs on the plan too: a dry run that reports a+ // move it cannot perform would preview a lie.+ assertDestinationsFree(planned, sourceFolder.abs, destination);++ // The post-move population: every walked file that is not moving - by+ // real location, so a foreign note that merely sat under the source's+ // alias spelling stays in the population the minimal spellings are+ // disambiguated against - plus every destination. The folder analogue+ // of the file surface's postRelocationPopulation, derived from the+ // same walked list.+ const newRels = new Set(planned.map((move) => move.toRel));+ const postPopulation = [+ ...vaultFiles.filter((rel) => !movingReal.has(realOf(rel))),+ ...newRels,+ ].toSorted();++ // One pair set, no bare basename rung: a folder move never changes a+ // basename, so the bare `[[Name]]` spellings keep resolving and+ // bareNameRepairs has nothing to do. Each old spelling collapses onto+ // the minimal spelling of the destination, as on the file surface.+ const pairsFor = (moves: ReadonlyArray<PlannedMove>): { from: string; to: string }[] =>+ moves.flatMap((move) => {+ const to = minimalSpellingFor(move.toRel, postPopulation);+ return [+ { from: move.fromRel, to },+ { from: withoutSuffix(move.fromRel), to },+ ];+ });+ const plannedPairs = pairsFor(planned);++ const probe = retargetWikilinks(+ vault,+ plannedPairs.map((pair) => ({ from: pair.from })),+ { root: VAULT_ROOT_REL, apply: false },+ );+ const inboundFiles = probe.matched.filter(reported);+ const filesScanned = vaultFiles.filter(reported).length;++ assertExpectedCount({+ matched: inboundFiles.length,+ expect: input.expect ?? null,+ strict: input.strict === true,+ willMutate: apply,+ matchList: inboundFiles,+ });++ let moved: FolderMovedPath[] = apply+ ? []+ : // A plan-only run relocates nothing, so an empty `moved` would read+ // as "nothing to do" - the plan IS the preview, and it reports the+ // full set the apply would relocate (recon 1.3: a dry run reports+ // the full planned set and writes nothing).+ planned.map((move) => ({ from: move.fromRel, to: move.toRel }));+ let moveFailures: FolderMoveFailure[] = [];+ // Nothing has been left behind until something has been moved.+ let leftBehind: ReadonlyArray<string> = [];+ let rewritten: ReadonlyArray<string> = [];+ let rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }> = [];+ let appliedPairs: ReadonlyArray<{ readonly from: string; readonly to: string }> = [];++ if (apply) {+ // The destination folder exists before the first relocation, so a+ // zero-file move set still lands somewhere when the SOURCE folder+ // was itself empty (the pre-flight has already approved or refused+ // this exact path). A folder that KEEPS entries - the attachments-+ // only case - creates nothing: its destination directory would hold+ // no file and no folder, just residue this operation invented.+ const destinationExisted = statOrNull(destination.abs) !== null;+ // The deepest ancestor of the destination that is already on disk+ // ("." when that is the vault root): the directories this apply+ // invents all sit strictly below it, and the cleanup of an invented+ // chain stops AT it - before removing anything. A directory that was+ // already here is not this operation's to remove, empty or not.+ let existingAncestor = ".";+ if (!destinationExisted) {+ let probe = dirname(destination.relPath);+ while (probe !== ".") {+ if (statOrNull(ensureInsideVault(join(vault, probe), vault)) !== null) {+ existingAncestor = probe;+ break;+ }+ const parentRel = dirname(probe);+ if (parentRel === probe) break;+ probe = parentRel;+ }+ }+ if (planned.length > 0 || sourceEntries === null || sourceEntries.length === 0) {+ mkdirSync(destination.abs, { recursive: true });+ }+ // The directories below the destination that are already on disk+ // before the first relocation - a failed move's branch the vault+ // already had, empty or not, is the vault's own and never this+ // cleanup's to remove. Recorded now, before any of it can change.+ const preExistingBranchDirs = new Set<string>();+ for (const move of planned) {+ let dir = dirname(move.toRel);+ while (dir !== destination.relPath && dir !== ".") {+ if (statOrNull(ensureInsideVault(join(vault, dir), vault)) !== null) {+ preExistingBranchDirs.add(dir);+ }+ const parentRel = dirname(dir);+ if (parentRel === dir) break;+ dir = parentRel;+ }+ }+ // The destination spellings the per-file machinery created for moves+ // that then failed: the invented subtree the cleanup below offers+ // back to the filesystem.+ const failedDestinations: string[] = [];+ // The moves run in sorted order and the set continues past a failure:+ // by the time one file cannot relocate, others already have, and+ // undoing them would unlink destination names - new destructive+ // behavior no gate covers. The report names the split instead.+ for (const move of planned) {+ try {+ (input.relocate ?? relocateFileBytes)(move.fromAbs, move.toAbs, move.toRel, move.sameEntry);+ moved.push({ from: move.fromRel, to: move.toRel });+ } catch (err) {+ let reason = err instanceof Error ? err.message : String(err);+ failedDestinations.push(move.toRel);+ // A fault AFTER the destination name was created - a linked name+ // (same inode) or a cross-device copy the fallback wrote - leaves+ // bytes at `toRel` while the report is about to say this path+ // "never moved". The source name still holds the original bytes+ // whenever it exists, so the extra destination name is dropped+ // before the failure is reported; if even that fails, the+ // failure says so. The name is judged with LSTAT, not+ // `existsSync`: a name that dangles - a link whose target the+ // new depth cannot see - is still a name this call created, and+ // following the link would see nothing and leave it standing.+ // A source that no longer exists means the unlink SUCCEEDED and+ // a later step threw - the file moved, and the destination name+ // is the only copy, so it stays. And a destination this call+ // never created is never this operation's to drop: the+ // pre-flight cleared the name, so `destination_occupied` means a+ // foreign file appeared there between the check and the link,+ // and unlinking it would delete bytes this operation did not+ // write.+ const occupied = err instanceof NoteLifecycleError && err.code === "destination_occupied";+ if (!move.sameEntry && !occupied && lstatOrNull(move.toAbs) !== null) {+ if (existsSync(move.fromAbs)) {+ try {+ unlinkSync(move.toAbs);+ } catch (cleanup) {+ reason +=+ `; the destination name ${move.toRel} was written before the fault and ` ++ `could not be dropped either (${cleanup instanceof Error ? cleanup.message : String(cleanup)})`;+ }+ } else {+ reason += `; the destination name ${move.toRel} holds the moved bytes`;+ }+ }+ moveFailures.push({ path: move.fromRel, reason });+ }+ }+ // The directories the per-file machinery invented for FAILED moves+ // never stay behind: each failed move's own destination spelling+ // names its branch, offered to rmdirSync deepest-first, each only+ // while genuinely empty - so a moved file's branch, a foreign name or+ // a name that could not be dropped keeps its branch standing - and a+ // branch that was already here is spared by name. When NOTHING moved,+ // the destination folder and the chain the recursive mkdir invented+ // above it go too, up to - never including - the ancestor that was+ // already here; with a partial set they hold real moves, so the walk+ // stops at the destination folder. A destination that existed before,+ // or one an empty-source move deliberately created, is not this+ // cleanup's business.+ if (failedDestinations.length > 0) {+ const doomed = new Set<string>();+ if (moved.length === 0 && !destinationExisted) {+ doomed.add(destination.relPath);+ let up = dirname(destination.relPath);+ while (up !== "." && up !== existingAncestor) {+ doomed.add(up);+ const parentRel = dirname(up);+ if (parentRel === up) break;+ up = parentRel;+ }+ }+ for (const toRel of failedDestinations) {+ let dir = dirname(toRel);+ while (dir !== destination.relPath && dir !== ".") {+ doomed.add(dir);+ const parentRel = dirname(dir);+ if (parentRel === dir) break;+ dir = parentRel;+ }+ }+ const deepestFirst = [...doomed]+ .filter((rel) => !preExistingBranchDirs.has(rel))+ .toSorted((a, b) => b.length - a.length);+ for (const rel of deepestFirst) {+ try {+ rmdirSync(ensureInsideVault(join(vault, rel), vault));+ } catch {+ // Not empty (a foreign name, or a name that could not be+ // dropped) or not removable: what stands, stands, and the+ // report already names where every file is.+ }+ }+ }+ // The folders the moves emptied go with their files: every ancestor+ // of a successfully moved file, up to and including the subject, is+ // offered to rmdirSync deepest-first, and only genuinely empty ones+ // go - so a failed file's parent stays exactly where the report says+ // its bytes are, and directories the move never touched (empty+ // siblings, a subtree that held no Markdown) are not this operation's+ // to delete.+ pruneEmptiedFolders(vault, sourceRel, moved);+ // An EMPTY folder's move is the directory entry itself: nothing was+ // relocated, so the prune has no moved file whose ancestors name the+ // subject, and the entry is dropped by hand - but only while the disk+ // still says the source is empty, and never when the source keeps+ // entries it was never going to move (the attachments-only case).+ if (planned.length === 0 && (readdirOrNull(sourceFolder.abs) ?? []).length === 0) {+ try {+ rmdirSync(sourceFolder.abs);+ } catch {+ // The entry is not removable (or re-appeared between the read and+ // the removal): the residue report names what stayed.+ }+ }+ // Whatever the prune could not remove is exactly what stayed - a+ // non-Markdown file beside the notes, a symlinked entry whose real+ // location is outside the source, or a failed file's folder - and+ // the report names it rather than reading as if the source folder+ // went with its notes.+ leftBehind = (readdirOrNull(sourceFolder.abs) ?? []).toSorted();+ // ONE rewrite pass over the SUCCESSFULLY moved set's pairs, under the+ // destination. A failed file's pairs are excluded, which is the+ // correct outcome: its inbound links still resolve to where its+ // bytes actually are.+ const movedPlanned = planned.filter((move) =>+ moved.some((entry) => entry.from === move.fromRel),+ );+ appliedPairs = pairsFor(movedPlanned);+ const pass = retargetWikilinks(vault, appliedPairs, {+ root: VAULT_ROOT_REL,+ apply: true,+ neverRewrite: APPEND_ONLY_REL,+ });+ rewritten = pass.rewritten.filter(reported);+ rewriteFailures = pass.failed+ .filter((failure) => reported(failure.path))+ .map((failure) => ({ path: failure.path, reason: failure.reason }))+ .toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ }++ // The MOVE destroys nothing; the REWRITE overwrites hand-authored prose+ // in place, so the blast radius is declared from the files this call+ // actually rewrote - the file surface's reading, region for region.+ const recoverability = classifyRecoverability({+ recoveryPoint: false,+ blastRadius: {+ ...(rewritten.some((rel) => pathCovers(BRAIN_ROOT_REL, rel)) ? { brainTopLevel: true } : {}),+ ...(rewritten.some((rel) => !pathCovers(BRAIN_ROOT_REL, rel))+ ? { outsideBrainRoot: true }+ : {}),+ },+ });++ const index: IndexEvidence = await readIndexEvidence(vault, apply, input.refreshConfigPath);+ // The refresh claim trails the evidence read on purpose: the evidence+ // must describe the index as this call left it, and the claim starts a+ // DETACHED run that will not have landed by any instant this call can+ // observe. A plan-only run claims nothing and refused nothing.+ let refresh: IndexRefresh;+ let refreshReason: string | null;+ if (apply) {+ const claim = await claimPostWriteRefresh(+ vault,+ index,+ input.refreshSpawn,+ input.now,+ input.refreshConfigPath,+ );+ refresh = claim.refresh;+ refreshReason = claim.refreshReason;+ } else {+ refresh = INDEX_REFRESH.notClaimed;+ refreshReason = null;+ }++ // The relative-link judgment (M17) reads the moved notes' bytes once,+ // from where they now are: the planned set on a plan (the notes have+ // not moved - the plan is the preview), the SUCCESSFULLY moved set on+ // an apply - a failed file never moved, so its relative links still+ // resolve and name no fault.+ const linkMoves = (+ apply+ ? moved.map((m) => ({+ from: m.from,+ to: m.to,+ bytesAbs: ensureInsideVault(join(vault, m.to), vault),+ }))+ : planned.map((m) => ({ from: m.fromRel, to: m.toRel, bytesAbs: m.fromAbs }))+ ).toSorted((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : 0));+ const dangling = danglingRelativeLinks(+ vault,+ linkMoves,+ apply+ ? undefined+ : // The plan's promise: a target whose real location is inside the+ // source's real path is IN the move set and will be at the new+ // location once the move runs.+ (oldRel: string) => movingReal.has(realSpelling(vault, oldRel)),+ );++ return Object.freeze({+ action,+ from: sourceRel,+ to: destination.relPath,+ applied: apply,+ moved: Object.freeze(+ moved.toSorted((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : 0)),+ ),+ moveFailures: Object.freeze(+ moveFailures.toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)),+ ),+ leftBehind: Object.freeze([...leftBehind]),+ danglingRelativeLinks: Object.freeze(dangling),+ recoverability,+ snapshot: null,+ references: Object.freeze({+ filesScanned,+ inboundFiles: Object.freeze([...inboundFiles]),+ filesRewritten: rewritten.length,+ rewrittenSpellings: Object.freeze([...(apply ? appliedPairs : plannedPairs)]),+ rewriteFailures: Object.freeze([...rewriteFailures]),+ basename: BASENAME_REWRITE.notNeeded,+ index,+ refresh,+ refreshReason,+ }),+ });+}++/**+ * Remove the directories the moves genuinely emptied, deepest first.+ * `rmdirSync` removes only an empty directory, so a folder whose subtree+ * still holds a failed file - or any file this surface does not address -+ * keeps it, which is exactly where the report says the bytes are. The+ * candidate set is derived from the MOVED FILES' ancestor chains up to+ * the subject - never from a walk of the subject's subtree - so a+ * symlinked directory anywhere under the source is neither followed nor+ * removed, and directories the move never touched (empty siblings, a+ * no-Markdown subtree) are not this operation's to delete. The folders+ * ABOVE the subject are not its business either, and an emptied+ * `Projects/` left behind reads as the ordinary residue a file move+ * leaves too.+ */+function pruneEmptiedFolders(+ vault: string,+ fromRel: string,+ moved: ReadonlyArray<FolderMovedPath>,+): void {+ const candidates = new Set<string>();+ for (const file of moved) {+ let dir = dirname(file.from);+ // Walk the ancestor chain in VAULT-RELATIVE spellings - the move+ // report's own paths, never names resolved through the filesystem -+ // and stop at the subject itself. The walk is bounded to fail closed:+ // a moved path outside the subject (a different spelling, a future+ // caller) can never send the walk below the vault root, where+ // `dirname` stops changing and the loop would never end.+ candidates.add(dir);+ while (dir !== fromRel) {+ const parent = dirname(dir);+ if (parent === dir || parent === ".") break;+ dir = parent;+ candidates.add(dir);+ }+ }+ const deepestFirst = [...candidates]+ .filter((rel) => rel === fromRel || rel.startsWith(`${fromRel}/`))+ .toSorted((a, b) => b.length - a.length);+ for (const rel of deepestFirst) {+ try {+ rmdirSync(ensureInsideVault(join(vault, rel), vault));+ } catch {+ // The directory is not empty (or not removable): the residue+ // stands, and the report already names where every file is.+ }+ }+}diff --git a/src/core/brain/notes/lifecycle.ts b/src/core/brain/notes/lifecycle.tsindex bcd5e8c3..9603dcc3 100644--- a/src/core/brain/notes/lifecycle.ts+++ b/src/core/brain/notes/lifecycle.ts@@ -172,12 +172,16 @@ import { resolveNoteTarget, type ResolvedNoteTarget } from "./create-note.ts";// ----- What a caller may ask for --------------------------------------------/**- * The four operations. `rename` and `move` are one relocation under the+ * The six operations. `rename` and `move` are one relocation under the* hood and are kept apart at the surface deliberately: a caller that* meant to change a note's NAME and accidentally changed its FOLDER has* made a mistake no path check would catch, because both spellings are* perfectly legal destinations. Declaring which one was intended lets the- * other be refused.+ * other be refused. The folder actions (`move-folder`, `rename-folder`)+ * split the same way at folder granularity - see+ * `./folder-lifecycle.ts`, the module that runs them - so a caller that+ * meant to rename a folder and accidentally moved it across parents is+ * caught by the same discipline instead of by the consequences.*/export const NOTE_LIFECYCLE_ACTION = Object.freeze({/** Change the filename, keeping the note in its directory. */@@ -188,6 +192,17 @@ export const NOTE_LIFECYCLE_ACTION = Object.freeze({archive: "archive",/** Remove the note. The one operation here that destroys bytes. */delete: "delete",+ /**+ * Move a whole folder under a destination parent. A file action+ * (`rename`/`move`/`archive`/`delete`) refuses a folder subject, and+ * this action runs in `./folder-lifecycle.ts`.+ */+ moveFolder: "move-folder",+ /**+ * Rename a whole folder within its parent. Split from `move-folder`+ * for the same reason `rename` is split from `move`.+ */+ renameFolder: "rename-folder",} as const);/** Closed union over {@link NOTE_LIFECYCLE_ACTION}. */@@ -393,6 +408,10 @@ export type NoteLifecycleErrorCode =| "destination_occupied"/** Source and destination are the same path. */| "destination_unchanged"+ /** A move whose destination directory sits inside the source subtree. */+ | "destination_inside_source"+ /** The move set is empty while the source folder is not. */+ | "move_set_empty"/** A `rename` that changes the directory, or a `move` that does not. */| "wrong_action"/** A delete reached the mutating path without an explicit confirmation. */@@ -702,8 +721,12 @@ function statOrNull(target: string): Stats | null {* front of it rather than by a `process.platform` string, and the branch* is reachable on Linux too, where a hardlinked destination has exactly* this shape.+ *+ * Exported for the folder lifecycle, whose occupancy pre-flight asks the+ * same question of the destination FOLDER and of every destination FILE+ * in a case-only folder rename.*/-function namesSameEntry(a: string, b: string): boolean {+export function namesSameEntry(a: string, b: string): boolean {const left = bigintStatOrNull(a);const right = bigintStatOrNull(b);if (left === null || right === null) return false;@@ -785,30 +808,45 @@ function relocateBytes(destination: ResolvedNoteTarget,sameEntry: boolean,): void {- mkdirSync(dirname(destination.abs), { recursive: true });+ relocateFileBytes(source.abs, destination.abs, destination.relPath, sameEntry);+}++/**+ * The byte relocation itself, on absolute paths - the exact machinery+ * {@link relocateBytes} runs, shared with the folder lifecycle, which+ * relocates whole sets of files that never went through+ * {@link resolveNoteTarget} (a folder path has no `.md` rung to pass).+ * One implementation, so the byte-preservation and refuse-to-overwrite+ * guarantees cannot come to mean two things on the two surfaces.+ */+export function relocateFileBytes(+ fromAbs: string,+ toAbs: string,+ label: string,+ sameEntry: boolean,+): void {+ mkdirSync(dirname(toAbs), { recursive: true });if (sameEntry) {- const staged = `${destination.abs}.${process.pid}.${Date.now()}.relocating`;- linkOneName(source.abs, staged, destination.relPath);+ const staged = `${toAbs}.${process.pid}.${Date.now()}.relocating`;+ linkOneName(fromAbs, staged, label);// Destroys nothing: `staged` is a second name for this very inode,// so the bytes outlive the name being dropped here. Declared for the// destructive-site census, which reads sites and not files.- unlinkSync(source.abs);- renameWithRetry(staged, destination.abs);+ unlinkSync(fromAbs);+ renameWithRetry(staged, toAbs);} else {- linkOneName(source.abs, destination.abs, destination.relPath);- if (!existsSync(destination.abs)) {- throw new Error(- `noteLifecycle: write of ${destination.relPath} reported success but the file is absent`,- );+ linkOneName(fromAbs, toAbs, label);+ if (!existsSync(toAbs)) {+ throw new Error(`noteLifecycle: write of ${label} reported success but the file is absent`);}// Destroys nothing: the assertion above has just confirmed the same// bytes are reachable at the destination, so this drops a name and// not a file. Declared for the destructive-site census.- unlinkSync(source.abs);+ unlinkSync(fromAbs);}- if (!existsSync(destination.abs)) {+ if (!existsSync(toAbs)) {throw new Error(- `noteLifecycle: relocation of ${destination.relPath} reported success but the file is absent`,+ `noteLifecycle: relocation of ${label} reported success but the file is absent`,);}}@@ -837,6 +875,23 @@ export async function noteLifecycle(assertVaultIdentityForWrite(vault);const action = input.action;+ if (+ action === NOTE_LIFECYCLE_ACTION.moveFolder ||+ action === NOTE_LIFECYCLE_ACTION.renameFolder+ ) {+ // Refused rather than dispatched, the mirror of the folder surface's+ // refusal of the file actions: the vocabulary is ONE constant (the+ // CLI guard, the MCP enum and the manifest read it together), but the+ // machinery is two modules, and a folder action that fell through to+ // the file envelope would report a one-file result for a many-file+ // operation. The caller that owns the dispatch - the verb surface,+ // the MCP tool - sends folder actions to `./folder-lifecycle.ts`.+ throw new NoteLifecycleError(+ "wrong_action",+ `the note-file lifecycle runs rename | move | archive | delete; ` ++ `'${action}' is a folder action and runs in the folder lifecycle`,+ );+ }const source = resolveNoteTarget(vault, input.path);// `isFile`, not merely `exists`: a DIRECTORY named `Notes.md` is a// perfectly legal thing for a vault to contain, and checking existencediff --git a/src/core/brain/operator-snapshot.ts b/src/core/brain/operator-snapshot.tsindex 054694e1..438eb571 100644--- a/src/core/brain/operator-snapshot.ts+++ b/src/core/brain/operator-snapshot.ts@@ -19,6 +19,7 @@ import { existsSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";import { resolveSearchConfig } from "../search/index.ts";+import { isWriterLockHeld } from "../search/store/writer-lock.ts";import { FREEZE_NEXT_COMMAND, readFreezeMarker, type FreezeMarker } from "./freeze-marker.ts";import { runDoctor } from "./doctor.ts";import { resolveSignal } from "./diagnostics.ts";@@ -54,6 +55,82 @@ export interface SnapshotCounts {readonly inbox: number;}+/**+ * The three honest answers about the search writer lock. `unknown` is+ * "I could not find out" - a stat that failed, a config that would not+ * resolve - and is deliberately NOT a spelling of `free`: a caller that+ * treats the second as the first has been told something untrue (the same+ * rule `isWriterLockHeld` itself states).+ */+export const WRITER_LOCK_STATE = Object.freeze({+ /** A live writer holds the lock right now. */+ held: "held",+ /** No live holder at the instant of the read. */+ free: "free",+ /** The state could not be measured; `writerLockReason` says what stopped it. */+ unknown: "unknown",+} as const);++/** Closed union over {@link WRITER_LOCK_STATE}. */+export type WriterLockState = (typeof WRITER_LOCK_STATE)[keyof typeof WRITER_LOCK_STATE];++/**+ * What this surface states about the memory store (t_cfe2ce5d).+ *+ * Scoped v1 to the SEARCH writer lock - the one `isWriterLockHeld`+ * answers. The scattered brain-lane `.lock` files stay with the doctor's+ * stale-lock probe; this group must not be read as covering both lock+ * families.+ *+ * `writerLockOwner` is `null` ALWAYS in v1, and that is a measurement+ * rather than a gap: the lock is a bare `proper-lockfile` directory whose+ * only metadata is its mtime, refreshed by a heartbeat. It answers "is+ * someone alive holding this"; it cannot answer "who". Naming a holder is+ * a deferred acquire-side change (stamping identity inside the lock+ * directory), not a field this snapshot can honestly fill today.+ *+ * A held lock is a live writer, not a fault: it is reported, never folded+ * into `healthy` or `problems` - the `frozen` precedent. Crash residue is+ * the doctor's `stale-lock` uncertain finding, which owns the "is this+ * holder actually dead" question.+ */+export interface SnapshotStore {+ /** Three-state answer about the search writer lock, fail-soft. */+ readonly writerLock: WriterLockState;+ /** Set when `unknown`: what stopped the measurement, errno included. */+ readonly writerLockReason: string | null;+ /**+ * Age of the lock directory's mtime when `held`, in milliseconds, from+ * the snapshot clock; `null` when free, unknown, or unmeasurable. The+ * heartbeat refreshes the mtime, so this is a lower bound on how long+ * the holder has been alive, never an upper bound.+ */+ readonly writerLockAgeMs: number | null;+ /** `null` in v1 - the lock record carries no identity. See above. */+ readonly writerLockOwner: string | null;+ /**+ * The lock path (the resolved search index path) at LOCAL reach;+ * `null` elsewhere. The path is a resolved host path that may sit+ * outside the vault, so the MCP surface withholds it below local reach+ * exactly the way `stateFiles.searchIndex` answers presence without it.+ */+ readonly writerLockPath: string | null;+ /**+ * This snapshot never writes and never takes the lock. The consequence+ * is rendered beside the flag, SCOPED TO WHAT THE LOCK GATES: while+ * `writerLock` is `held`, an index write THIS caller attempted - `o2b+ * search index` / reindex - would refuse with `INDEX_LOCKED` after its+ * retries. This is the search writer lock, and it gates index writers+ * only: vault and memory writes serialize on the brain lane's own lock+ * files, not on this one, so the rendered line says they are not gated+ * rather than implying a refusal this lock cannot cause.+ */+ readonly thisCaller: typeof THIS_CALLER_READ_ONLY;+}++/** The one value `thisCaller` can honestly take: this surface writes nothing. */+export const THIS_CALLER_READ_ONLY = "read-only";+export interface OperatorSnapshot {readonly counts: SnapshotCounts;/** stale preferences + signals + log files. */@@ -92,6 +169,13 @@ export interface OperatorSnapshot {* self-heal leaves a pending upgrade behind and nothing else says so.*/readonly selfHealUpgradeFailure: SelfHealUpgradeFailure | null;+ /**+ * What this snapshot can honestly state about the memory store: the+ * search writer lock's three-state answer, its age, the absence of any+ * owner identity on the lock record, and this caller's own read-only+ * standing. See {@link SnapshotStore}.+ */+ readonly store: SnapshotStore;}export interface BuildOperatorSnapshotOptions {@@ -113,6 +197,14 @@ export interface BuildOperatorSnapshotOptions {* read. A local caller passes nothing.*/readonly keepFinding?: (finding: HygieneFinding) => boolean;+ /**+ * Whether the search writer lock is held at this index path. Injected+ * only by tests - the product asks `isWriterLockHeld`, and a throw from+ * it reads `unknown` rather than `free`, exactly as that module's+ * contract requires. Named after `MigrationPlanInput.writerLockHeldAt`,+ * so the two seams read as one pattern.+ */+ readonly writerLockHeldAt?: (dbPath: string) => boolean;}/**@@ -143,6 +235,9 @@ export async function buildOperatorSnapshot(problem("state-file", "Brain config `_brain.yaml` is missing");}+ // --- Store ownership (t_cfe2ce5d) ---+ const store = readStoreGroup(searchDbPath, now, opts.writerLockHeldAt);+// --- Automatic upgrade ---const selfHealUpgradeFailure = readSelfHealUpgradeFailure(vault);if (selfHealUpgradeFailure !== null) {@@ -243,9 +338,84 @@ export async function buildOperatorSnapshot(healthy: problems.length === 0,frozen: readFreezeMarker(vault),selfHealUpgradeFailure,+ store,});}+/**+ * Ask the search writer lock its three-state answer, wrapped fail-soft+ * exactly like the migration preflight's `writerLockRefusal`: a probe+ * that throws reads `unknown` with the errno in the reason, because+ * "I could not find out" is not "the lock is free". An index path that+ * never resolved is the same honest state - the lock could not be probed+ * at all - so it reads `unknown` too, with the reason naming that.+ */+function readStoreGroup(+ dbPath: string | null,+ now: Date,+ probe: ((dbPath: string) => boolean) | undefined,+): SnapshotStore {+ if (dbPath === null) {+ return Object.freeze({+ writerLock: WRITER_LOCK_STATE.unknown,+ writerLockReason: "the search index path could not be resolved, so the lock was not probed",+ writerLockAgeMs: null,+ writerLockOwner: null,+ writerLockPath: null,+ thisCaller: THIS_CALLER_READ_ONLY,+ });+ }+ let held: boolean;+ try {+ held = (probe ?? isWriterLockHeld)(dbPath);+ } catch (error) {+ const err = error as NodeJS.ErrnoException;+ return Object.freeze({+ writerLock: WRITER_LOCK_STATE.unknown,+ writerLockReason: `the writer lock state could not be determined (${err.code ?? "unknown error"}): ${err.message}`,+ writerLockAgeMs: null,+ writerLockOwner: null,+ writerLockPath: dbPath,+ thisCaller: THIS_CALLER_READ_ONLY,+ });+ }+ return Object.freeze({+ writerLock: held ? WRITER_LOCK_STATE.held : WRITER_LOCK_STATE.free,+ writerLockReason: null,+ writerLockAgeMs: held ? lockAgeMs(dbPath, now) : null,+ writerLockOwner: null,+ writerLockPath: dbPath,+ thisCaller: THIS_CALLER_READ_ONLY,+ });+}++/**+ * The held lock's mtime age against the snapshot clock, or `null` when the+ * stat fails - a best-effort measurement beside a state that is already+ * known, never a second chance to claim a state that is not.+ */+function lockAgeMs(dbPath: string, now: Date): number | null {+ try {+ return Math.max(0, Math.round(now.getTime() - statSync(writerLockDir(dbPath)).mtimeMs));+ } catch {+ return null;+ }+}++/**+ * The lock directory `proper-lockfile` creates for an index path: a bare+ * `${dbPath}.lock` directory whose only metadata is its mtime (`getLockFile`+ * in `proper-lockfile/lib/lockfile.js`; `writer-lock.ts` takes it with+ * `mkdir`). Spelled here because the age reads that directory's mtime, and+ * the state probe (`isWriterLockHeld`) asks the same path behind the same+ * library.+ */+const WRITER_LOCK_SUFFIX = ".lock";++function writerLockDir(dbPath: string): string {+ return `${dbPath}${WRITER_LOCK_SUFFIX}`;+}+/*** Render the snapshot as compact operator-readable text. A healthy vault* prints a single all-clear line plus the summary; otherwise each problem@@ -279,6 +449,14 @@ export function renderOperatorSnapshot(snap: OperatorSnapshot): string {`(${snap.frozen.reason === "" ? "no reason given" : snap.frozen.reason}); ` +`lift with \`${FREEZE_NEXT_COMMAND}\``,);+ // Printed on BOTH branches, like the frozen line: the state an operator+ // most needs stated is the one where nothing is writing, and "no line"+ // would be indistinguishable from a renderer that forgot to ask. A held+ // lock names the refusal an INDEX write would hit - scoped to what the+ // lock gates, since vault and memory writes serialize elsewhere - so+ // the agent reading this before writing does not learn it from the+ // write failing.+ out.push(` ${renderStoreLine(snap.store)}`);if (!snap.healthy) {out.push("");@@ -310,3 +488,37 @@ function countMarkdown(dir: string): number {return 0;}}++/** Age suffix for the held-lock line; absent when the mtime was unreadable. */+function heldForSuffix(ageMs: number | null): string {+ return ageMs === null ? "" : ` for ${ageMs}ms`;+}++/**+ * The one store line, rendered for every state the group can hold. The+ * owner's absence is stated when the lock is held - the lock record+ * carries no identity, and silence would read as a renderer that forgot+ * to ask who - and the held line names the concrete refusal an index+ * writer hits (`INDEX_LOCKED`, the search lane's typed contention+ * error), scoped to what the search writer lock gates: vault and memory+ * writes serialize on the brain lane's own lock files and are not gated+ * by this lock, so the line says so rather than implying a refusal the+ * lock cannot cause.+ */+function renderStoreLine(store: SnapshotStore): string {+ const caller = `this caller ${store.thisCaller}`;+ switch (store.writerLock) {+ case WRITER_LOCK_STATE.free:+ return `store: writer lock free; ${caller}`;+ case WRITER_LOCK_STATE.held:+ return (+ `store: writer lock held${heldForSuffix(store.writerLockAgeMs)} ` ++ "(owner: unknown, the lock record carries no identity; " ++ "an index write (o2b search index / reindex) would refuse with INDEX_LOCKED; " ++ "vault and memory writes are not gated by this lock); " ++ caller+ );+ case WRITER_LOCK_STATE.unknown:+ return `store: writer lock state unknown (${store.writerLockReason ?? "reason unavailable"}); ${caller}`;+ }+}diff --git a/src/core/brain/portability/bundle.ts b/src/core/brain/portability/bundle.tsindex ee57c2fa..6f75b69c 100644--- a/src/core/brain/portability/bundle.ts+++ b/src/core/brain/portability/bundle.ts@@ -3,11 +3,16 @@* Unit A).** `exportBankBundle` composes the existing exporters - preferences- * (`collectExportRows`), the page link-graph (`exportVaultGraph`), the+ * (`collectSharedExportRows`, the shared lanes' denying detail of+ * `collectExportRows`), the page link-graph (`exportVaultGraph`), the* page interchange contract (`projectPageContracts`), and the read-only* sources dashboard (`aggregateSources`) - into one schema-versioned* envelope for backup, cross-instance migration, or downstream-tool- * ingest. It forks no serialisation path; it only assembles.+ * ingest. It forks no serialisation path; it only assembles. Reserved+ * preference rows stay out of the shared composition and are named;+ * `includeReserved` is the personal-backup override that carries them+ * into the operator's own copy, where a reservation about shared+ * readers does not bind.** `importBankBundle` reconstructs the two sections that round-trip: the* page graph, delegated to `importVaultGraph` under a conflict mode, and@@ -41,7 +46,12 @@* nodes through `graph.rejected[]`.*/-import { collectExportRows, type ExportedPreferenceRow } from "../export.ts";+import {+ collectExportRowsWithDenials,+ collectSharedExportRows,+ type ExportedPreferenceRow,+ type PreferenceDenial,+} from "../export.ts";import { isoSecond } from "../time.ts";import { vaultDisplayName } from "../templates.ts";import {@@ -63,6 +73,17 @@ export interface BankBundle {readonly generated_at: string;readonly vault_basename: string;readonly preferences: ReadonlyArray<ExportedPreferenceRow>;+ /**+ * The preferences the privacy deny markers kept out of this bundle,+ * each named with its id, the reason class and the key that denied it.+ * Absent when empty, so a vault with no reservation serialises with+ * exactly the keys it always carried (the schema stays "1" - additive,+ * the module's own versioning rule). Absent under+ * `includeReserved` too, for the same reason in reverse: nothing was+ * withheld, so there is nothing to report. The bank-export verb turns+ * the field into its stderr omission notice.+ */+ readonly preferences_omitted?: ReadonlyArray<PreferenceDenial>;readonly graph: VaultGraph;readonly pages: ReadonlyArray<PageContract>;readonly sources: SourcesReport;@@ -72,16 +93,73 @@ export interface BankBundle {* Export a whole-vault bank bundle. The content sections are* deterministic (each underlying exporter sorts); only `generated_at`* varies between runs. Pure and read-only on the vault.+ *+ * Preference rows the privacy deny markers reserve are left out of the+ * preferences section and named in `preferences_omitted` - the same+ * report the json preference export carries, so no two exporters+ * disagree about the same directory. `opts.includeReserved` is the+ * personal-backup override: the operator's own copy of their own vault,+ * where a reservation about shared readers does not bind, so the+ * reserved rows ride the section whole and the report is absent because+ * nothing was withheld.+ */+export function exportBankBundle(vault: string, opts: BankBundleExportOptions = {}): BankBundle {+ return exportBankBundleDetailed(vault, opts).bundle;+}++/** Options for {@link exportBankBundle}, stated beside the report. */+export interface BankBundleExportOptions {+ /**+ * Carry the reserved preference rows into the bundle's preferences+ * section. The personal-backup override, spelled+ * `--include-reserved` on the verb: a reservation is a statement about+ * shared readers, and a bundle the operator keeps for restore is not+ * one. Default (false): reserved rows stay out and are named in+ * `preferences_omitted`.+ */+ readonly includeReserved?: boolean;+}++/**+ * The bundle beside the reservation report, whatever the override+ * decided: `reserved` names the preferences the privacy deny markers+ * hold, on an override run (where they rode the section IN and the run+ * must say so) exactly as on a default run (where they stayed out and+ * the report rides the bundle).*/-export function exportBankBundle(vault: string): BankBundle {+export interface BankBundleExport {+ readonly bundle: BankBundle;+ readonly reserved: ReadonlyArray<PreferenceDenial>;+}++/**+ * The one-walk composition behind {@link exportBankBundle}: callers that+ * must say on stderr what the reservation did - in either direction -+ * read `reserved` here instead of walking the directory a second time.+ */+export function exportBankBundleDetailed(+ vault: string,+ opts: BankBundleExportOptions = {},+): BankBundleExport {+ const includeReserved = opts.includeReserved === true;+ const { rows, denied } = includeReserved+ ? collectExportRowsWithDenials(vault)+ : collectSharedExportRows(vault);return {- schema: BANK_BUNDLE_SCHEMA_VERSION,- generated_at: isoSecond(),- vault_basename: vaultDisplayName(vault),- preferences: collectExportRows(vault),- graph: exportVaultGraph(vault),- pages: projectPageContracts(vault),- sources: aggregateSources(vault),+ bundle: {+ schema: BANK_BUNDLE_SCHEMA_VERSION,+ generated_at: isoSecond(),+ vault_basename: vaultDisplayName(vault),+ preferences: rows,+ // Absent-when-empty keeps a reservation-free vault's bytes exactly+ // what they always were; absent under the override because nothing+ // was withheld.+ ...(denied.length > 0 && !includeReserved ? { preferences_omitted: denied } : {}),+ graph: exportVaultGraph(vault),+ pages: projectPageContracts(vault),+ sources: aggregateSources(vault),+ },+ reserved: denied,};}diff --git a/src/core/brain/portability/knowledge-pack.ts b/src/core/brain/portability/knowledge-pack.tsindex add5e29e..e6a16fed 100644--- a/src/core/brain/portability/knowledge-pack.ts+++ b/src/core/brain/portability/knowledge-pack.ts@@ -56,7 +56,12 @@ import {} from "../../redactor.ts";import { appendContinuitySourceInvalidation } from "../continuity/store.ts";import { topicKey } from "../dream-plan.ts";-import { collectExportRows, collectPreferenceRows, type ExportedPreferenceRow } from "../export.ts";+import {+ collectExportRowsWithDenials,+ collectPreferenceRows,+ PREFERENCE_DENY_REASON,+ type ExportedPreferenceRow,+} from "../export.ts";import type { RecoverabilityVerdict } from "../gates/recoverability.ts";import { classifyRecoverability } from "../gates/recoverability.ts";import {@@ -331,11 +336,25 @@ export function selectKnowledgePack(const blocked: KnowledgePackBlocked[] = [];const warnings: KnowledgePackWarning[] = [];+ // The complete rows, so a selector naming a reserved rule is MATCHED+ // and reported as a named block - never "matched nothing".+ const { rows: exportRows, denied } = collectExportRowsWithDenials(vault);+ const deniedById = new Map(denied.map((d) => [d.id, d] as const));+const preferences: ExportedPreferenceRow[] = [];- for (const row of collectExportRows(vault)) {+ for (const row of exportRows) {const hits = parsed.filter((sel) => prefMatches(sel, row));if (hits.length === 0) continue;for (const sel of hits) matched.add(sel.raw);+ // A reserved preference cannot ride redacted - the pack carries+ // preference rows with the body dropped but the principle line+ // verbatim - so this is drop-and-name, under the same reason+ // `pageBlockReason` records for pages, and ahead of the owner check+ // with the page reason precedence (visibility > owner).+ if (deniedById.has(row.id)) {+ blocked.push({ kind: "preference", id: row.id, reason: PREFERENCE_DENY_REASON });+ continue;+ }if (preferenceOwner(vault, row.id) !== null) {blocked.push({ kind: "preference", id: row.id, reason: "owner" });continue;diff --git a/src/core/brain/receipts/types.ts b/src/core/brain/receipts/types.tsindex a7ef5727..aae1c15e 100644--- a/src/core/brain/receipts/types.ts+++ b/src/core/brain/receipts/types.ts@@ -189,6 +189,11 @@ export const FOLDABLE_CONTINUITY_KINDS: ReadonlyArray<ContinuityRecordKind> = Ob* cutoff would collapse a skill's usage to its last window and* reorder the offers (its payload carries `agent`, not `agent_id`, so* the clip-key rule never protected it either).+ * - `reply_presence` - the per-turn reply-presence verdicts (t_f8510c55)+ * the context-receipt read surface joins by `session_id`; a fold+ * would sever the receipt-to-presence join for every record past the+ * cutoff, turning "checked and verified/missed" into an+ * `unjoined` read.*/export const KEPT_CONTINUITY_KINDS: ReadonlyArray<ContinuityRecordKind> = Object.freeze(["source_invalidation",@@ -207,6 +212,7 @@ export const KEPT_CONTINUITY_KINDS: ReadonlyArray<ContinuityRecordKind> = Object"negative_recall","receipt_compaction","skill_invoked",+ "reply_presence",]);/** One shard selected for compaction, as a scan reported it. */diff --git a/src/core/brain/sdk.ts b/src/core/brain/sdk.tsindex 8e6a0353..3eacb774 100644--- a/src/core/brain/sdk.ts+++ b/src/core/brain/sdk.ts@@ -17,8 +17,12 @@import type { CreateNoteInput, CreateNoteResult } from "./notes/create-note.ts";import { createNote } from "./notes/create-note.ts";-import type { ExportedPreferencesJson } from "./export.ts";-import { exportPreferencesJson, exportPreferencesLlmsTxt } from "./export.ts";+import type { ExportedPreferencesJson, LlmsTxtExport } from "./export.ts";+import {+ exportPreferencesJson,+ exportPreferencesLlmsTxt,+ exportPreferencesLlmsTxtDetailed,+} from "./export.ts";import {type BankBundle,type BankImportResult,@@ -75,7 +79,19 @@ export interface BrainSdk {// Preference export.exportPreferencesJson(): ExportedPreferencesJson;+ /**+ * The stable string signature, kept for every existing caller.+ *+ * @deprecated the string carries no denial report - a preference the+ * privacy deny markers reserve leaves the text silently, so a caller+ * cannot name what stayed out. Use+ * {@link BrainSdk.exportPreferencesLlmsTxtDetailed}, which returns the+ * same text beside the omission report; the CLI surface (which names+ * every omission on stderr) is the model.+ */exportPreferencesLlmsTxt(): string;+ /** The llms-txt document beside the omissions its privacy policy made. */+ exportPreferencesLlmsTxtDetailed(): LlmsTxtExport;// Open Knowledge Format bundle export/import (Unit C).buildOkfBundle(): OkfBundle;@@ -109,6 +125,7 @@ export function createBrain(vault: string): BrainSdk {exportPreferencesJson: () => exportPreferencesJson(vault),exportPreferencesLlmsTxt: () => exportPreferencesLlmsTxt(vault),+ exportPreferencesLlmsTxtDetailed: () => exportPreferencesLlmsTxtDetailed(vault),buildOkfBundle: () => buildOkfBundle(vault),writeOkfBundle: (dir, bundle, opts) => writeOkfBundle(dir, bundle, opts ?? {}),diff --git a/src/core/brain/vault-dirty.ts b/src/core/brain/vault-dirty.tsnew file mode 100644index 00000000..a94a710b--- /dev/null+++ b/src/core/brain/vault-dirty.ts@@ -0,0 +1,201 @@+/**+ * The git-dirty page set for `o2b brain validate --dirty` (t_dc782fd5,+ * task C4): every Markdown note under the vault that git reports as+ * modified, added or untracked.+ *+ * The one git subprocess in the module follows the `git/reader.ts`+ * precedent (`execFileSync("git", ["-C", repo], ...)`, quiet stderr,+ * bounded buffer). Unlike the reader, this module is NOT fail-soft: a+ * gate that silently reported "clean" for a vault whose dirtiness it+ * could not measure would be the exact failure the verb exists to+ * prevent, so a vault that is not a git worktree, a vault its enclosing+ * repository ignores (inside a worktree, `git status` omits ignored+ * files - dirt under such a vault can never be seen), or a git that+ * cannot answer is a named {@link VaultDirtyError}, and the verb refuses+ * with exit 2 rather than passing.+ *+ * Deleted entries are excluded by name: a deleted path cannot be linted,+ * and the gate's subject is the page content a caller is about to+ * commit, not the deletion bookkeeping around it. Untracked directories+ * are expanded with `-uall` - an agent-created new note is exactly the+ * population this gate targets, and plain `--porcelain` would otherwise+ * collapse it into a bare directory row. `-z` NUL-terminated output is+ * parsed instead of line-oriented, so filenames with spaces, quotes and+ * non-ASCII arrive verbatim (git skips its quotePath C-style quoting in+ * this mode), and a rename arrives as its destination followed by the+ * origin in the next NUL field - two adjacent fields rather than an+ * `old -> new` spelling that a filename could forge - of which the gate+ * lints the destination. The listing is bounded by a `.` pathspec and+ * every path is rebased from the repository root onto the vault, so a+ * vault nested inside a larger repository lints exactly its own dirt.+ */++import { execFileSync } from "node:child_process";+import { isAbsolute, relative, resolve, sep } from "node:path";++/** The refusal for a vault whose dirtiness git cannot measure. */+export class VaultDirtyError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "VaultDirtyError";+ }+}++/** The condition behind the refusal, stated so the remedy names the other selector. */+const NOT_A_WORKTREE_MESSAGE =+ "the vault is not inside a git worktree, so --dirty has nothing to measure; " ++ "name pages explicitly with --paths instead";++/**+ * The second unmeasurable condition: a vault its enclosing repository+ * IGNORES. `rev-parse --is-inside-work-tree` answers `true` inside an+ * ignored directory and `git status` omits ignored files, so without the+ * check-ignore guard such a vault read as permanently clean - the exact+ * state the module's contract refuses to report. The remedy is the other+ * selector, by name.+ */+const IGNORED_VAULT_MESSAGE =+ "the vault directory is ignored by its enclosing git repository, so git cannot " ++ "measure its dirty state; name pages explicitly with --paths instead";++/** The first line of an error's message: git output is multi-line. */+function firstLine(err: unknown): string {+ const message = err instanceof Error ? err.message : String(err);+ return message.split("\n")[0] ?? message;+}++/**+ * Every git-dirty Markdown path under `vault`, vault-relative with POSIX+ * separators: modified, added (staged), renamed and untracked. Deleted+ * paths are never returned. Order is git's own (sorted by path).+ */+export function listDirtyMarkdownPaths(vault: string): ReadonlyArray<string> {+ // The worktree check is its own call, not an inference from an empty+ // status: an empty status in a non-worktree is indistinguishable from+ // a clean one, and the refusal must name the condition rather than+ // read as a clean pass.+ try {+ const inside = execFileSync(+ "git",+ ["-C", resolve(vault), "rev-parse", "--is-inside-work-tree"],+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 },+ ).trim();+ if (inside !== "true") throw new Error(`git answered ${JSON.stringify(inside)}`);+ } catch (err) {+ throw new VaultDirtyError(`${NOT_A_WORKTREE_MESSAGE} (${firstLine(err)})`);+ }++ // Inside a worktree is not yet measurable: a vault that sits in a+ // directory the repository's exclude rules IGNORE passes the check+ // above while `git status` silently omits every file under it - the+ // gate would read permanently clean for dirt it can never see. Ask git+ // directly whether the vault root itself is ignored. `check-ignore -q`+ // exits 0 when the path IS ignored and 1 when it is not; any other+ // exit (or an execution failure) is a git that could not answer, which+ // refuses rather than passes, like every git call in this module.+ let ignored: boolean;+ try {+ execFileSync("git", ["-C", resolve(vault), "check-ignore", "-q", "."], {+ stdio: ["ignore", "ignore", "ignore"],+ });+ ignored = true;+ } catch (err) {+ const status = (err as NodeJS.ErrnoException & { status?: number | null }).status;+ if (status !== 1) {+ throw new VaultDirtyError(+ `${NOT_A_WORKTREE_MESSAGE} (git check-ignore failed: ${firstLine(err)})`,+ );+ }+ ignored = false;+ }+ if (ignored) throw new VaultDirtyError(IGNORED_VAULT_MESSAGE);++ let out: string;+ try {+ // The pathspec bounds the listing to the vault: git answers for the+ // whole repository otherwise, and a vault nested inside a larger+ // repo would inherit its neighbours' dirtiness.+ out = execFileSync(+ "git",+ ["-C", resolve(vault), "status", "--porcelain", "-uall", "-z", "--", "."],+ {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ maxBuffer: 64 * 1024 * 1024,+ },+ );+ } catch (err) {+ throw new VaultDirtyError(`${NOT_A_WORKTREE_MESSAGE} (git status failed: ${firstLine(err)})`);+ }++ // Porcelain paths are relative to the repository ROOT, not to the `-C`+ // directory, so the vault's own prefix is stripped from every path+ // before it is used - a no-op when the vault IS the repo root.+ let prefix: string;+ try {+ prefix = execFileSync("git", ["-C", resolve(vault), "rev-parse", "--show-prefix"], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ // Only the trailing newline goes: a leading space is a real+ // character of a top-level directory's name.+ }).replace(/\r?\n$/, "");+ } catch (err) {+ throw new VaultDirtyError(+ `${NOT_A_WORKTREE_MESSAGE} (git show-prefix failed: ${firstLine(err)})`,+ );+ }++ /** Repo-root-relative porcelain path to a vault-relative one, or `null` outside the vault. */+ const inVault = (repoPath: string): string | null => {+ if (prefix === "") return repoPath;+ return repoPath.startsWith(prefix) ? repoPath.slice(prefix.length) : null;+ };++ const dirty: string[] = [];+ const entries = out.split("\0").filter((e) => e.length > 0);+ for (let i = 0; i < entries.length; i++) {+ const entry = entries[i]!;+ const xy = entry.slice(0, 2);+ // In `-z` output a rename or copy entry carries a SECOND NUL field -+ // the origin path - and git orders it AFTER the destination ("the+ // field order is reversed", git-status docs): THIS field's path is+ // the destination, the spelling a commit would contain, and the+ // origin field is consumed here and names nothing to lint.+ if (xy.includes("R") || xy.includes("C")) {+ i++; // consume the origin field+ // The destination can be deleted from the worktree just like a+ // plain entry (a staged rename whose destination was then removed+ // reports `RD`): no file on disk, nothing to lint.+ if (xy[1] === "D") continue;+ const destination = inVault(entry.slice(3));+ if (destination !== null && destination.endsWith(".md")) dirty.push(destination);+ continue;+ }+ const rel = inVault(entry.slice(3));+ if (rel === null) continue; // outside the vault: not this gate's subject+ if (rel.endsWith("/") || !rel.endsWith(".md")) continue; // a directory row, or not a note+ if (xy[0] === "D" || xy[1] === "D") continue; // deleted in the index or the worktree: nothing on disk to lint+ dirty.push(rel);+ }+ return dirty;+}++/**+ * The vault-relative spelling of a `--paths` argument, or `null` when it+ * resolves outside the vault, so the caller refuses by name without+ * inventing its own boundary arithmetic. Mirrors the derivation+ * `lintPagesWithContext` applies to every page it names (`vaultRelative`+ * over `resolve(vault, page)`), so the refusal and the report can never+ * disagree about where the boundary sits.+ */+export function vaultRelativeOrNull(vault: string, page: string): string | null {+ const rel = relative(resolve(vault), resolve(vault, page));+ // A real parent-directory segment is the escape; a name that merely+ // begins with two dots (`..draft.md`) is an ordinary vault-relative+ // name and is kept.+ if (rel === "" || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;+ return rel+ .split(/[\\/]/)+ .filter((p) => p.length > 0)+ .join("/");+}diff --git a/src/core/config.ts b/src/core/config.tsindex c26eceb7..cd3cc9a4 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -872,6 +872,23 @@ export function resolveEntityFactsContextPack(configPath?: string): boolean {);}+/**+ * Context-pack score-aware tail-trim gate (delivered-evidence trim,+ * t_cb6a5558). Default OFF: brain_context_pack never trims delivered+ * items after the tier/budget walk unless `tail_trim_context_pack:+ * "true"` (or the env override), keeping the default pack+ * byte-identical. When on, the pack drops the low-scoring tail past its+ * top delivered items and reports the trim in a conditional `tailTrim`+ * report member.+ */+export function resolveTailTrimContextPack(configPath?: string): boolean {+ return resolveConfigFlag(+ "OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK",+ "tail_trim_context_pack",+ configPath,+ );+}+/*** Counterparty-brief hook gate (dated commitments, t_43b0a379). Default* OFF: the UserPromptSubmit hook exits without output unlessdiff --git a/src/core/doctor-readiness.ts b/src/core/doctor-readiness.tsindex 54b9324c..971de553 100644--- a/src/core/doctor-readiness.ts+++ b/src/core/doctor-readiness.ts@@ -64,6 +64,12 @@* reported with the `o2b install <target> --apply` recovery line, never* rewritten.*+ * The `client_versions` probe (t_8e49ec96) slots beside it and reads the+ * SAME manifest: one fail-soft, read-only, async version ask per recorded+ * client, graded pass/unknown/skipped and never `fail`, because a version+ * row never proves a surface broken. Its rows travel on the verdict's+ * optional `rows` member, which no other probe sets.+ ** The `writeback_contract` probe (t_7c01bb39) is check-only in the same* way: it audits whether the workspace agent-instruction file(s) carry* the same-turn atomic-fact memory write gate. The contract itself - the@@ -132,6 +138,7 @@ export const READINESS_PROBE = {runtimeAdapterWiring: "runtime_adapter_wiring",installedRuntimes: "installed_runtimes",registeredCommands: "registered_commands",+ clientVersions: "client_versions",writebackContract: "writeback_contract",decisionModel: "decision_model",} as const;@@ -303,6 +310,27 @@ export function isReadinessStatus(value: unknown): value is ReadinessStatus {export interface ReadinessVerdict {readonly status: ReadinessStatus;readonly detail: string;+ /**+ * Per-target machine rows, set ONLY by the `client_versions` probe+ * (t_8e49ec96). Absent on every other probe. Additive and safe: the+ * readiness JSON exists only under `--readiness`, so no byte-identical+ * output contract is stressed, and `readiness_summary` is untouched -+ * a fully-unknown version probe keeps the exit at+ * `DOCTOR_EXIT.probeIncomplete`, never a `fail`.+ */+ readonly rows?: ReadonlyArray<ReadinessVersionRow>;+}++/** One client's answer inside a `client_versions` verdict. */+export interface ReadinessVersionRow {+ /** The install-manifest target the row was asked about. */+ readonly target: string;+ /** pass (answered), unknown (no usable answer), skipped (nothing to ask). */+ readonly status: ReadinessStatus;+ /** The client's own first stdout line when it answered; `null` otherwise. */+ readonly version: string | null;+ /** Why the row graded as it did, never empty. */+ readonly detail: string;}/** A completed probe: its verdict plus the name and wall-clock duration. */@@ -335,6 +363,16 @@ export interface ReadinessOptions {readonly env?: Readonly<Record<string, string | undefined>>;/** Per-check timeout budget; defaults to {@link DEFAULT_READINESS_TIMEOUT_MS}. */readonly perCheckTimeoutMs?: number;+ /**+ * Ask one client binary its version. Injected only by tests, which+ * cannot install clients; the product spawns `argv` asynchronously+ * (see {@link probeClientVersions} for why async). A throw reads+ * `unknown`, never `fail` - the same contract+ * {@link isWriterLockHeld}-style probes observe.+ */+ readonly clientVersionRunner?: (+ argv: ReadonlyArray<string>,+ ) => Promise<{ readonly exitCode: number; readonly stdout: string }>;}// ----- Timeout wrapper ------------------------------------------------------@@ -1086,6 +1124,381 @@ function probeRegisteredEntries(return { target, status: worst, detail: summaries.join("; ") };}+// ----- client_versions (t_8e49ec96) -----------------------------------------++/**+ * The version command asked of each install target's client, and the one+ * target with no client binary of its own.+ *+ * A client INSTALLED but never registered through Open Second Brain is out+ * of scope by construction: detection comes from the install manifest,+ * exactly like `registered_commands`, so the probe asks only the clients+ * this tool recorded.+ *+ * Binary names are pinned to each adapter's own spawn precedent+ * (`copilot-cli.ts` spawns `copilot --version`; `codex.ts` resolves `codex`+ * via `Bun.which`; `gemini-cli.ts`'s notes name `gemini`) and to each+ * client's documented CLI. `generic` writes a user-named config and has no+ * client binary of its own, so it is skipped by name rather than probed.+ * A correction to a row is a one-line follow-up in this table's own module.+ */+const CLIENT_VERSION_COMMANDS: Readonly<Record<string, ReadonlyArray<string> | null>> =+ Object.freeze({+ aider: ["aider", "--version"],+ codex: ["codex", "--version"],+ "copilot-cli": ["copilot", "--version"],+ cursor: ["cursor", "--version"],+ "gemini-cli": ["gemini", "--version"],+ grok: ["grok", "--version"],+ kiro: ["kiro", "--version"],+ opencode: ["opencode", "--version"],+ pi: ["pi", "--version"],+ generic: null,+ });++/**+ * Clients format their version freely ("codex-cli 0.9.0", "GitHub Copilot+ * CLI 1.0.5"), so the raw line is the value and nothing is parsed - but a+ * runaway first line must not carry a readiness payload, so it is capped.+ */+const CLIENT_VERSION_MAX_LENGTH = 200;++/**+ * The product runner: an ASYNC spawn, not `spawnSync`.+ *+ * `probeInstalledRuntimes`' docblock records the cost of the synchronous+ * kind: it blocks the event loop, so the timeout timer that is meant to+ * cut a hung probe off cannot fire behind it. This probe's version ask is+ * exactly the kind of subprocess a hung binary would wedge, so it runs on+ * the promise machinery the per-probe budget already covers. Read-only and+ * fail-soft: the child inherits the environment and writes nothing.+ *+ * The ask carries a child-level budget of its own (defaulting to the+ * per-probe budget, {@link DEFAULT_READINESS_TIMEOUT_MS}): the probe-level+ * wrapper can only abandon the promise it awaits, so a hung `--version`+ * child would otherwise survive the cut as an orphan. The child's exit is+ * raced against the timer here, and the child itself is killed when the+ * timer wins - SIGTERM first, then SIGKILL after a short grace+ * ({@link CLIENT_KILL_GRACE_MS}), because a client that traps or ignores+ * TERM would otherwise outlive doctor together with everything it+ * spawned. stderr is ignored, not piped: nothing observes it, and a pipe+ * a chatty child fills unread would block the child on write.+ *+ * stdout is drained INCREMENTALLY, never as one await of EOF: a client+ * whose `--version` forks a background helper that inherits stdout (an+ * update checker, a daemon) prints its version and exits 0 while the+ * helper keeps the pipe open, so an EOF-await would time out an ask that+ * was actually answered. The drain settles at the first newline - the+ * only thing the grader reads - or at EOF, or, once the child has+ * exited, at a short bounded window ({@link STDOUT_DRAIN_WINDOW_MS})+ * over whatever stdout has already buffered.+ */+export async function spawnClientVersion(+ argv: ReadonlyArray<string>,+ timeoutMs: number = DEFAULT_READINESS_TIMEOUT_MS,+): Promise<{ exitCode: number; stdout: string }> {+ const child = Bun.spawn({ cmd: [...argv], stdout: "pipe", stderr: "ignore" });+ let exited = false;+ void child.exited.then(() => {+ exited = true;+ });+ let timer: ReturnType<typeof setTimeout> | undefined;+ const budget = new Promise<never>((_, reject) => {+ timer = setTimeout(() => {+ try {+ child.kill();+ } catch {+ /* already gone */+ }+ // SIGTERM can be trapped or ignored, and the escalation must+ // outlive this function - the budget rejects now, the grace timer+ // keeps its appointment regardless. A child that answered in+ // between is already reaped and is left alone.+ setTimeout(() => {+ if (!exited) {+ try {+ child.kill("SIGKILL");+ } catch {+ /* already gone */+ }+ }+ }, CLIENT_KILL_GRACE_MS);+ reject(new ReadinessTimeoutError(`client version ${argv[0]}`, timeoutMs));+ }, timeoutMs);+ });+ try {+ return await Promise.race([+ (async () => {+ // The drain starts immediately so a child writing past the pipe+ // buffer is consumed rather than wedged on write, but the ask+ // settles on the child's EXIT, not on the pipe closing.+ const drained = drainVersionStdout(child.stdout, child.exited);+ const exitCode = await child.exited;+ const stdout = await drained;+ return { exitCode, stdout };+ })(),+ budget,+ ]);+ } finally {+ clearTimeout(timer);+ }+}++/**+ * How long the drain keeps reading past the child's exit before+ * returning what stdout has buffered: a helper holding the pipe can keep+ * EOF from ever arriving, and the buffered bytes are already there - the+ * window is the bound that turns them into an answer instead of a+ * timeout. Long enough to be a rounding error on a real spawn, short+ * enough to never matter against the ask's budget.+ */+const STDOUT_DRAIN_WINDOW_MS = 250;++/** The gap between the budget's SIGTERM and its SIGKILL follow-up. */+const CLIENT_KILL_GRACE_MS = 250;++/**+ * Read the child's stdout incrementally, settling at the first newline+ * (the version is graded from the raw first line and nothing beyond it),+ * at EOF, or - once `exited` resolves - at the bounded window, returning+ * whatever has buffered by then. A read that rejects (the stream erroring+ * while a helper still holds the pipe) returns what buffered too, never+ * rejects the ask.+ */+async function drainVersionStdout(+ stream: ReadableStream<Uint8Array>,+ exited: Promise<unknown>,+): Promise<string> {+ const reader = stream.getReader();+ const decoder = new TextDecoder();+ let text = "";+ // Armed once per ask: the window opens when the child exits, not when+ // the drain starts, so a child that answers late is not penalized.+ const windowCloses: Promise<null> = exited+ .then(+ () => Bun.sleep(STDOUT_DRAIN_WINDOW_MS),+ () => Bun.sleep(STDOUT_DRAIN_WINDOW_MS),+ )+ .then(() => null);+ for (;;) {+ const read = reader.read().then(+ (chunk) => ({ chunk }),+ () => null,+ );+ const settled = await Promise.race([read, windowCloses]);+ if (settled === null) return text;+ if (settled.chunk.done || settled.chunk.value === undefined) return text;+ text += decoder.decode(settled.chunk.value, { stream: true });+ if (text.includes("\n")) return text;+ }+}++/**+ * The ask's own budget, derived from the probe's: the normal ask keeps a+ * fifth of the probe budget in reserve (the 80% share), floored at 50 ms+ * so a real spawn never answers against nothing. The floor is capped at+ * the probe budget minus a margin, less whatever the probe already+ * spent, so the ask's timer expires strictly BEFORE the probe-level+ * wrapper's - which was armed first and expires at a fixed point - even+ * though each ask's timer is armed later, one spawn at a time. The+ * wrapper can then only ever fire on a child that ignored its own+ * (earlier) budget, and the verdict that carries the rows wins the race.+ * Under the floor the ask dies the margin before the wrapper, so the+ * verdict still carries its rows, each naming its own timeout; a+ * degenerate budget clamps at zero instead of going negative, and the+ * row says timed out after 0ms - a measurement that had no budget, never+ * a negative one.+ */+export function clientAskBudgetMs(probeBudgetMs: number, elapsedMs: number = 0): number {+ return Math.max(+ 0,+ Math.min(+ probeBudgetMs - CLIENT_ASK_MARGIN_MS - Math.max(0, elapsedMs),+ Math.max(50, Math.floor(probeBudgetMs * 0.8)),+ ),+ );+}++/** First stdout line, trimmed and length-capped - the raw line, never parsed. */+function firstVersionLine(stdout: string): string | null {+ const line = stdout.split("\n")[0]?.trim() ?? "";+ if (line === "") return null;+ return line.length > CLIENT_VERSION_MAX_LENGTH ? line.slice(0, CLIENT_VERSION_MAX_LENGTH) : line;+}++/**+ * One manifest target's version answer, graded pass/unknown/skipped and+ * never `fail`: "the client answered with a version" is the only measured+ * fact here, and no version row proves a surface broken - resolvability+ * itself is `registered_commands`' finding, and a client this doctor's+ * PATH cannot see may still resolve for the host that spawns it. An+ * unanswered row therefore points at that probe's finding rather than+ * raising this one's own alarm.+ */+async function clientVersionRow(+ target: string,+ runner: (argv: ReadonlyArray<string>) => Promise<{ exitCode: number; stdout: string }>,+): Promise<ReadinessVersionRow> {+ const argv = CLIENT_VERSION_COMMANDS[target];+ if (argv === undefined) {+ // Loud, never silent: a manifest target the table does not know is a+ // table that lags the adapter registry, and the row names the fix.+ return {+ target,+ status: READINESS_STATUS.unknown,+ version: null,+ detail: `no version command is known for target '${target}' - extend CLIENT_VERSION_COMMANDS`,+ };+ }+ if (argv === null) {+ return {+ target,+ status: READINESS_STATUS.skipped,+ version: null,+ detail: "no client binary of its own (it writes a user-named config) - nothing to ask",+ };+ }+ let answered: { exitCode: number; stdout: string };+ try {+ answered = await runner(argv);+ } catch (err) {+ const code = (err as NodeJS.ErrnoException)?.code;+ const pointer = "resolvability is 'registered_commands' finding, so this row is not a fail";+ return {+ target,+ status: READINESS_STATUS.unknown,+ version: null,+ detail:+ code === "ENOENT"+ ? `${argv[0]} is not on the doctor's PATH (ENOENT; the host may still resolve it); ${pointer}`+ : `the version ask failed (${code ?? "unknown error"}): ${flattenReason((err as Error).message)}; ${pointer}`,+ };+ }+ if (answered.exitCode !== 0) {+ return {+ target,+ status: READINESS_STATUS.unknown,+ version: null,+ detail: `${argv[0]} exited ${answered.exitCode} with no version; ${argv.join(" ")} did not answer`,+ };+ }+ const version = firstVersionLine(answered.stdout);+ if (version === null) {+ return {+ target,+ status: READINESS_STATUS.unknown,+ version: null,+ detail: `${argv[0]} answered with no version output; ${argv.join(" ")} exited 0 but printed nothing`,+ };+ }+ return {+ target,+ status: READINESS_STATUS.pass,+ version,+ detail: `${argv.join(" ")} answered: ${version}`,+ };+}++/**+ * The wall-clock headroom the ask's own timer keeps below the probe-level+ * wrapper's fixed expiry: timers carry millisecond precision and the+ * asks' timers are armed one spawn after another, so the margin - not a+ * one-millisecond subtraction - is what keeps every ask's expiry strictly+ * earlier than the wrapper's.+ */+const CLIENT_ASK_MARGIN_MS = 5;++/**+ * Which version of each detected agent client answered (t_8e49ec96).+ *+ * Slot beside `registered_commands` and read the SAME detection source -+ * the install manifest - because "which clients are here" is a question+ * that must not grow two answers. Read-only, fail-soft, and graded+ * pass/unknown/skipped with no `fail`: a version row never proves a+ * surface broken, so a fully-unknown probe keeps the doctor exit at+ * `DOCTOR_EXIT.probeIncomplete` (6), never 1.+ *+ * There is deliberately no minimum-version table in v1: no `minVersion`+ * column, no config surface. Adding one is a design decision (what a+ * below-minimum row should DO to the exit code) to settle when a consumer+ * exists, not a column to ship half-decided.+ */+export async function probeClientVersions(opts: ReadinessOptions): Promise<ReadinessVerdict> {+ // The probe's own start, before anything is read: the wrapper's timer+ // was armed just before this call, so every ask's budget is measured+ // against this instant - the manifest read and the earlier spawns spend+ // the asks' shared share, never the wrapper's margin.+ const startedAtMs = Date.now();+ let manifest;+ try {+ manifest = readManifest(opts.vault);+ } catch (err) {+ return {+ status: READINESS_STATUS.unknown,+ detail:+ "install manifest could not be read, so no client version could be asked: " ++ flattenReason((err as Error).message),+ };+ }+ const installs = Object.values(manifest.installs);+ if (installs.length === 0) {+ return {+ status: READINESS_STATUS.skipped,+ detail: "install manifest records no installs; no client version to ask",+ };+ }+ // The asks run TOGETHER, and each child's own budget stays below the+ // probe's, so a verdict that carries the rows always wins the race+ // against the probe-level cutoff. Sequential asks could spend the+ // whole probe budget on the first slow client - the cutoff would then+ // replace every answered row with a bare timeout while the loop kept+ // spawning children nobody awaited any more.+ const probeBudgetMs = opts.perCheckTimeoutMs ?? DEFAULT_READINESS_TIMEOUT_MS;+ // Each ask's budget is read at ask time against the probe's own start,+ // so the manifest read and the time spawning the earlier children took+ // come off the later asks' share, never off the wrapper's margin. A+ // budget with nothing left spawns nothing: a child started only to be+ // killed on a zero timer would race its own first tick.+ const ask =+ opts.clientVersionRunner ??+ ((argv: ReadonlyArray<string>) => {+ const budgetMs = clientAskBudgetMs(probeBudgetMs, Date.now() - startedAtMs);+ return budgetMs <= 0+ ? Promise.reject(new ReadinessTimeoutError(`client version ${argv[0]}`, 0))+ : spawnClientVersion(argv, budgetMs);+ });+ // Promise.all preserves the manifest's order, whichever ask settles first.+ const rows: ReadinessVersionRow[] = await Promise.all(+ installs.map((entry) => clientVersionRow(entry.target, ask)),+ );+ const counts = countByStatus(rows.map((row) => row.status));+ // The rows carry every client's own answer on every surface that reads+ // this verdict - the human renderer prints one line per row, and the+ // JSON report carries the rows array - so the detail stays the census+ // and never repeats what the rows already say.+ const census = `(${counts.pass} pass, ${counts.unknown} unknown, ${counts.skipped} skipped)`;+ const base = { rows: Object.freeze(rows) };+ if (counts.unknown > 0) {+ return {+ ...base,+ status: READINESS_STATUS.unknown,+ detail: `could not read ${counts.unknown} client version(s) ${census} - each row names its own`,+ };+ }+ if (counts.skipped > 0) {+ return {+ ...base,+ status: READINESS_STATUS.skipped,+ detail: `nothing to ask of ${counts.skipped} of ${rows.length} target(s) ${census}`,+ };+ }+ return {+ ...base,+ status: READINESS_STATUS.pass,+ detail: `${counts.pass} client version(s) answered ${census}`,+ };+}+function extractRegisteredCommands(raw: string): CommandExtraction {const fromJson = extractFromJsonConfig(raw);if (fromJson !== null) return fromJson;@@ -1390,6 +1803,7 @@ export const DEFAULT_PROBES: ReadonlyArray<NamedProbe> = [{ name: READINESS_PROBE.runtimeAdapterWiring, fn: probeRuntimeAdapterWiring },{ name: READINESS_PROBE.installedRuntimes, fn: probeInstalledRuntimes },{ name: READINESS_PROBE.registeredCommands, fn: probeRegisteredCommands },+ { name: READINESS_PROBE.clientVersions, fn: probeClientVersions },{ name: READINESS_PROBE.writebackContract, fn: probeWritebackContract },{ name: READINESS_PROBE.decisionModel, fn: probeDecisionModel },];diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.tsindex 5121bb8a..048167a7 100644--- a/src/core/search/visibility-surface-registry.ts+++ b/src/core/search/visibility-surface-registry.ts@@ -556,7 +556,13 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>"is left, and summary folds without the rule items, so a degraded injection that kept " +"only the rules counts as an empty receipt. A measured injection receipt whose every item " +"was a rule block (isRuleOnlyInjection) is withheld whole: list and summary exclude it " +- "before their limit and fold bound, and show answers it as an unknown id.",+ "before their limit and fold bound, and show answers it as an unknown id. The show " ++ "payload also carries the session's reply-presence join (lookupReceiptReplyPresence, " ++ "context-receipts.ts), and that join runs at the caller's reach: a per-note row naming a " ++ "path the caller's reach view cannot read is withheld from per_note and counted in " ++ "withheld - absent when nothing was withheld - so a reserved page's path, line range and " ++ "verdict never reach a caller the page withheld itself from, and a filtered join cannot " ++ "read as a session that checked fewer notes.",},{surface: "brain_event_trace",diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.tsindex 1ee06054..9140fe28 100644--- a/src/mcp/brain/health-tools.ts+++ b/src/mcp/brain/health-tools.ts@@ -29,6 +29,7 @@ import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import type { DoctorIssue } from "../../core/brain/types.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceBool, coerceFormat } from "../coerce.ts";+import { redactErrorForCaller } from "../error-redaction.ts";import { vaultRelativeSafe } from "./shared.ts";import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";import { findingRefs } from "./hygiene-tools.ts";@@ -396,7 +397,42 @@ async function toolBrainStatus(? {}: { keepFinding: (finding) => findingView.row(...findingRefs(ctx.vault, finding)) }),});- return { format, ...snapshot };+ // Below local reach the lock PATH is withheld while every state field+ // stays: the path is a resolved host path (the index may live outside+ // the vault), and `state_files.search_index` already answers presence+ // without it - the same split the collect errors above make between a+ // local message and a closed one. The refusal REASON goes through the+ // same split: a probe that threw embeds the stat'd host path in its+ // message (proper-lockfile's fs errors carry it verbatim), so below+ // local reach the message is redacted the way every error leaving the+ // process is (server.ts's `redactedErrorMessage`, which the core+ // snapshot layer cannot import) - the errno keeps, the path becomes a+ // placeholder.+ const local = contextReach(ctx) === TRANSPORT_REACH.local;+ const store = local+ ? snapshot.store+ : {+ ...snapshot.store,+ writerLockPath: null,+ ...(snapshot.store.writerLockReason !== null+ ? {+ writerLockReason: redactErrorForCaller(+ snapshot.store.writerLockReason,+ ctx.vault,+ contextReach(ctx),+ // The resolved index path may sit outside every root the+ // redactor knows (a custom index location) - the fs error+ // embeds its `.lock` spelling verbatim, and the path is+ // already resolved here, so it goes to the scrubber as a+ // literal beside the roots.+ snapshot.store.writerLockPath !== null+ ? [snapshot.store.writerLockPath, `${snapshot.store.writerLockPath}.lock`]+ : [],+ ),+ }+ : {}),+ };+ return { format, ...snapshot, store };}// ----- Serializers ---------------------------------------------------------diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.tsindex 0e49c426..32fffbba 100644--- a/src/mcp/brain/lifecycle-file-tools.ts+++ b/src/mcp/brain/lifecycle-file-tools.ts@@ -1,19 +1,22 @@/**- * Note-FILE lifecycle MCP tool: `brain_note_lifecycle` (B2).+ * Note lifecycle MCP tool: `brain_note_lifecycle` (B2, t_9571a47f).*- * One tool dispatching on `action` - rename, move, archive, delete - in- * the shape `brain_lifecycle` established. The sibling name is- * deliberate and so is the separation: `brain_lifecycle` is the BELIEF- * lifecycle (tombstone, supersede, temporal-replace), which marks a- * memory's status in frontmatter and never moves a byte. This one moves- * and removes files. Merging them would put "mark this claim superseded"- * and "delete this file" behind one `action` key, where a mistyped value- * is the difference between an annotation and a deletion.+ * One tool dispatching on `action` - rename, move, archive, delete for a+ * note FILE, move-folder and rename-folder for a whole FOLDER - in the+ * shape `brain_lifecycle` established. The sibling name is deliberate and+ * so is the separation: `brain_lifecycle` is the BELIEF lifecycle+ * (tombstone, supersede, temporal-replace), which marks a memory's status+ * in frontmatter and never moves a byte. This one moves and removes+ * files. Merging them would put "mark this claim superseded" and "delete+ * this file" behind one `action` key, where a mistyped value is the+ * difference between an annotation and a deletion.*- * The handler coerces arguments and renders the result; every guard -- * the nine-step path envelope on BOTH paths, the confirmation ladder, the- * count guard, the recovery point and its verdict - lives in- * `core/brain/notes/lifecycle.ts`, so the CLI verb beside it cannot drift+ * The handler coerces arguments, owns the dispatch and renders the+ * result; every guard - the path envelope on BOTH paths, the+ * confirmation ladder, the count guard, the recovery point and its+ * verdict - lives in the core (`notes/lifecycle.ts` for the file+ * actions, `notes/folder-lifecycle.ts` for the folder ones, which is+ * where a folder action runs), so the CLI verb beside it cannot drift* into a different set of rules.** Refusals carry their typed `code` in `data` rather than only in prose,@@ -28,7 +31,13 @@ import {NOTE_LIFECYCLE_ACTIONS,isNoteLifecycleAction,type NoteLifecycleResult,+ type NoteReferenceReport,} from "../../core/brain/notes/lifecycle.ts";+import {+ folderLifecycle,+ isFolderLifecycleAction,+ type FolderLifecycleResult,+} from "../../core/brain/notes/folder-lifecycle.ts";import {DANGLING_SCAN_DEFAULT_LIMIT,listDanglingTargets,@@ -54,6 +63,45 @@ import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";const TOOL = "brain_note_lifecycle";+/**+ * The reference report, identical on both lifecycle machines - the folder+ * result carries the same {@link NoteReferenceReport} the file result+ * does, so the projection is written once.+ */+function renderReferences(refs: NoteReferenceReport): Record<string, unknown> {+ return {+ files_scanned: refs.filesScanned,+ inbound_files: [...refs.inboundFiles],+ files_rewritten: refs.filesRewritten,+ rewritten_spellings: refs.rewrittenSpellings.map((s) => ({+ from: s.from,+ to: s.to,+ })),+ // Non-empty means the operation is half-applied: the note is at+ // `to` and these files still name `from`. Rendered on every+ // response, empty included, so a caller reading the field is+ // reading an answer rather than guessing from its absence.+ rewrite_failures: refs.rewriteFailures.map((f) => ({+ path: f.path,+ reason: f.reason,+ })),+ basename: refs.basename,+ index: {+ state: refs.index.state,+ last_indexed_at: refs.index.lastIndexedAt,+ next_command: refs.index.nextCommand,+ },+ // `claimed` says a detached refresh run is IN FLIGHT, never that it+ // has landed; every other value names why nothing was started, and+ // `refresh_reason` spells that reason - the freshen machinery's own+ // skip token, or the error it raised - so `not_claimed` is never+ // the whole answer a caller receives. Read from THIS call's own+ // decision, never from state another vault could have written.+ refresh: refs.refresh,+ refresh_reason: refs.refreshReason,+ };+}+/** Project the frozen core result into the tool's snake_cased response. */function renderResult(res: NoteLifecycleResult): Record<string, unknown> {return {@@ -68,37 +116,7 @@ function renderResult(res: NoteLifecycleResult): Record<string, unknown> {},snapshot:res.snapshot === null ? null : { run_id: res.snapshot.runId, path: res.snapshot.path },- references: {- files_scanned: res.references.filesScanned,- inbound_files: [...res.references.inboundFiles],- files_rewritten: res.references.filesRewritten,- rewritten_spellings: res.references.rewrittenSpellings.map((s) => ({- from: s.from,- to: s.to,- })),- // Non-empty means the operation is half-applied: the note is at- // `to` and these files still name `from`. Rendered on every- // response, empty included, so a caller reading the field is- // reading an answer rather than guessing from its absence.- rewrite_failures: res.references.rewriteFailures.map((f) => ({- path: f.path,- reason: f.reason,- })),- basename: res.references.basename,- index: {- state: res.references.index.state,- last_indexed_at: res.references.index.lastIndexedAt,- next_command: res.references.index.nextCommand,- },- // `claimed` says a detached refresh run is IN FLIGHT, never that it- // has landed; every other value names why nothing was started, and- // `refresh_reason` spells that reason - the freshen machinery's own- // skip token, or the error it raised - so `not_claimed` is never- // the whole answer a caller receives. Read from THIS call's own- // decision, never from state another vault could have written.- refresh: res.references.refresh,- refresh_reason: res.references.refreshReason,- },+ references: renderReferences(res.references),// `null` when no cascade was asked for, which is a different answer// from a cascade that found nothing. Rendered on every response so a// caller reads the distinction rather than inferring it from an@@ -114,6 +132,47 @@ function renderResult(res: NoteLifecycleResult): Record<string, unknown> {};}+/**+ * Project the folder result into the same snake_cased response shape,+ * with the move report in the folder module's own style: the list of+ * what relocated, and the per-file list of what did not and why.+ */+function renderFolderResult(res: FolderLifecycleResult): Record<string, unknown> {+ return {+ action: res.action,+ from: res.from,+ to: res.to,+ applied: res.applied,+ moved: res.moved.map((m) => ({ from: m.from, to: m.to })),+ move_failures: res.moveFailures.map((f) => ({ path: f.path, reason: f.reason })),+ // Absent-when-empty: a move that emptied its source folder carried+ // nothing through, so the key's presence is the signal.+ ...(res.leftBehind.length > 0 ? { left_behind: [...res.leftBehind] } : {}),+ // Absent-when-empty: the moved notes' relative Markdown links and+ // images whose target stayed behind, named per note and target. The+ // wikilink pass repairs [[path]] spellings only, so without this a+ // files_rewritten: 0 would read as "nothing broke" while every+ // relative embed in the moved notes pointed at nothing.+ ...(res.danglingRelativeLinks.length > 0+ ? {+ dangling_relative_links: res.danglingRelativeLinks.map((l) => ({+ note: l.note,+ target: l.target,+ })),+ }+ : {}),+ recoverability: {+ state: res.recoverability.state,+ coverage: [...res.recoverability.coverage],+ blockers: [...res.recoverability.blockers],+ },+ // Always null on this surface: a relocation destroys nothing, so no+ // recovery point is taken (the rewrite's risk is the verdict's).+ snapshot: null,+ references: renderReferences(res.references),+ };+}+async function toolBrainNoteLifecycle(ctx: ServerContext,args: Record<string, unknown>,@@ -135,6 +194,39 @@ async function toolBrainNoteLifecycle(const { expect, strict } = readCountGuardArgs(args);try {+ // The surface owns the dispatch: one vocabulary, two machines. A+ // folder action sent to the file module would be refused+ // `wrong_action` - the action exists and the caller named it+ // correctly, so it runs where it lives.+ if (isFolderLifecycleAction(action)) {+ // Refused rather than dropped, the file surface's own rule for a+ // flag whose action cannot honour it: a folder action is never a+ // delete, so neither flag has anything to extend - honouring them+ // silently would tell a caller that asked for a cascade that it+ // got one.+ if (confirm !== undefined || deleteLinked !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `${TOOL}: ${action} takes neither confirm nor delete_linked: a folder action is never a delete`,+ { code: "cascade_forbidden" },+ );+ }+ const res = await folderLifecycle(ctx.vault, {+ action,+ path,+ ...(to !== undefined ? { to } : {}),+ ...(apply !== undefined ? { apply } : {}),+ expect,+ strict,+ // A folder holding a note the caller may not read at its reach+ // is refused exactly as a missing one - the folder lifecycle+ // judges its move set by the same predicate the file surface+ // judges its subject by.+ readable: readableAtContextReach(ctx),+ ...(ctx.configPath !== null ? { refreshConfigPath: ctx.configPath } : {}),+ });+ return renderFolderResult(res);+ }const res = await noteLifecycle(ctx.vault, {action,path,@@ -381,7 +473,7 @@ export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze{name: TOOL,description:- "Note-file lifecycle: rename, move, archive (displaces the note under Archive/), delete. Dry-run unless apply; delete needs confirm. Rewrites inbound [[wikilinks]] to the minimal spelling that still resolves; applied writes claim a detached index refresh (references.refresh: claimed, not landed).",+ "Note lifecycle: rename, move, archive, delete take a note file; move-folder/rename-folder run the folder lifecycle. Dry-run unless apply; delete needs confirm. Rewrites inbound [[wikilinks]] minimally so they still resolve; applied writes claim the detached refresh (claimed, not landed).",inputSchema: {type: "object",properties: {@@ -393,12 +485,12 @@ export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freezepath: {type: "string",description:- "Vault-relative path of the note; must end in .md and stay inside the vault.",+ "Vault-relative path of the subject: a note file (must end in .md) for the file actions, a folder for move-folder/rename-folder; stays inside the vault.",},to: {type: "string",description:- "rename/move: vault-relative destination. Forbidden for archive (it picks its own) and delete.",+ "rename/move: vault-relative destination. move-folder: the DIRECTORY the folder lands in; rename-folder: the new single-segment name. Forbidden for archive and delete.",},apply: {type: "boolean",diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex 97249230..bdae296d 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -17,6 +17,7 @@ import {resolveRecallAdequacyThresholds,resolveRecallGateTelemetry,resolveSearchFocusContextPack,+ resolveTailTrimContextPack,} from "../../core/config.ts";import { resolveSearchConfig } from "../../core/search/index.ts";import { SearchError } from "../../core/search/search-error.ts";@@ -55,6 +56,7 @@ import {getContextReceipt,isContextReceiptTrigger,listContextReceipts,+ lookupReceiptReplyPresence,RECEIPT_ITEM_ACTIVE_BODY,RECEIPT_ITEM_LESSONS_BODY,RECEIPT_ITEM_SCOPED_RULES,@@ -453,6 +455,10 @@ async function toolBrainContextPack(// entity_facts_context_pack config key (default off) so the default// tool output carries no entity_facts key.const entityFacts = resolveEntityFactsContextPack(ctx.configPath ?? undefined);+ // Tail-trim wiring (t_cb6a5558): gated on the tail_trim_context_pack+ // config key (default off) so the default tool output carries no+ // tail_trim key and no trim ever runs.+ const tailTrim = resolveTailTrimContextPack(ctx.configPath ?? undefined);const agentScope = coerceAgentScope(ctx, args, true);// Root closure (t_sec_pack_reach): the pack reads page bodies by path,// outside the three read roots, so the reserved-token rule is asked per@@ -501,6 +507,7 @@ async function toolBrainContextPack(...(agentScope !== undefined ? { agentScope } : {}),...(densityRanking ? { densityRanking: true } : {}),...(entityFacts ? { entityFacts: true } : {}),+ ...(tailTrim ? { tailTrim: true } : {}),...(sessionFocus !== null ? { sessionFocus } : {}),...(query ? { query } : {}),...(queryMode !== null ? { queryMode } : {}),@@ -611,6 +618,19 @@ async function toolBrainContextPack(},}: {}),+ // The trim block appears only when the config key resolved on AND+ // the pack actually trimmed - the same conditional shape as+ // `entity_facts` above. Fields project to the tool's wire casing.+ ...(report.tailTrim+ ? {+ tail_trim: {+ dropped: report.tailTrim.dropped,+ kept_by_query_terms: report.tailTrim.keptByQueryTerms,+ rescued: report.tailTrim.rescued,+ tokens_saved: report.tailTrim.tokensSaved,+ },+ }+ : {}),...(adequacy !== undefined? {adequacy: {@@ -664,9 +684,13 @@ async function toolBrainContextReceipts(...(sessionId !== undefined ? { sessionId } : {}),...(local ? {} : { exclude: isRuleOnlyInjection }),});+ // The join is show-only: summarizeContextReceipt's second parameter+ // is the presence join, so the summaries are mapped through an arrow+ // - a point-free `.map(summarizeContextReceipt)` would hand every+ // row's ARRAY INDEX to that parameter.const summaries = receipts.map((receipt) => receiptAtReach(receipt, local))- .map(summarizeContextReceipt);+ .map((receipt) => summarizeContextReceipt(receipt));const page = pageSlice(summaries, offset, limit ?? Math.max(summaries.length, 1));return {vault_path: vaultPathField(ctx),@@ -697,6 +721,21 @@ async function toolBrainContextReceipts(payload: receipt.payload,private: receipt.private,redacted: receipt.redacted,+ // The receipt's session reply-presence join (t_f8510c55): the+ // per-note verdicts of the session's latest reply_presence record,+ // or the named unjoined outcome - a receipt whose session checked+ // no turn, or that names no session at all, says so instead of+ // reading as silently absent. The lookup runs on the reach-adjusted+ // record, so a payload redacted below local reach joins only on+ // what it still carries - and through the caller's reach view, so+ // a note row naming a page reserved below local reach drops from+ // `per_note` (counted in `withheld`) instead of disclosing its+ // path, range and verdict to a caller the page withheld itself from.+ reply_presence: lookupReceiptReplyPresence(+ ctx.vault,+ receipt,+ reachView(ctx.vault, contextReach(ctx)),+ ),};}diff --git a/src/mcp/tool-error-codes.ts b/src/mcp/tool-error-codes.tsindex b8c33414..d426b29d 100644--- a/src/mcp/tool-error-codes.ts+++ b/src/mcp/tool-error-codes.ts@@ -211,6 +211,8 @@ const NOTE_LIFECYCLE_CODES = exhaustiveMembers<NoteLifecycleErrorCode>()(["destination_forbidden","destination_occupied","destination_unchanged",+ "destination_inside_source",+ "move_set_empty","wrong_action","not_confirmed","already_archived",diff --git a/tests/cli/brain-bank-export.test.ts b/tests/cli/brain-bank-export.test.tsnew file mode 100644index 00000000..6e2cc69d--- /dev/null+++ b/tests/cli/brain-bank-export.test.ts@@ -0,0 +1,172 @@+/**+ * CLI tests for `o2b brain bank-export`'s stderr notice surface.+ *+ * The bundle body's content-class behaviour (the default split, the+ * `--include-prompt-derived` override, the dropped structured references)+ * is pinned in `tests/core/content-class-egress.test.ts`, and the+ * preference denial's default-run notice in+ * `tests/cli/export-redaction.test.ts`. This file pins the notices of a+ * run where BOTH policies fire at once - the one combination each of+ * those suites leaves unexercised: the preference denial is UNCONDITIONAL+ * (no flag carries a reserved rule), so its notice must ride the+ * override run too, not only the default arm's.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";+import {+ CONTENT_CLASS,+ CONTENT_CLASS_FIELD,+} from "../../src/core/brain/provenance/content-class.ts";+import { EGRESS_CONTENT_CLASS_INCLUDE_NOTICE } from "../../src/core/egress/guard.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-bank-export-"));+ vault = join(tmp, "vault");+ config = join(tmp, "config.yaml");+});+afterEach(() => rmSync(tmp, { recursive: true, force: true }));++const ENV = (): { env: Record<string, string> } => ({+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+});++async function bootstrap(): Promise<void> {+ expect((await runCli(["init", "--vault", vault, "--name", "T"], ENV())).returncode).toBe(0);+ expect((await runCli(["brain", "init", "--vault", vault], ENV())).returncode).toBe(0);+ writeFileSync(+ join(vault, "Operator Page.md"),+ "---\ntitle: Operator Page\n---\n\nWritten by the operator.\n",+ "utf8",+ );+ writeFileSync(+ join(vault, "Agent Page.md"),+ `---\ntitle: Agent Page\n${CONTENT_CLASS_FIELD}: ${CONTENT_CLASS.promptDerived}\n---\n\nSynthesised from a prompt.\n`,+ "utf8",+ );+}++async function seedPreference(slug: string, principle: string): Promise<void> {+ const r = await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ slug,+ "--signal",+ "positive",+ "--principle",+ principle,+ "--scope",+ "writing",+ "--force-confirmed",+ "--agent",+ "claude",+ ],+ ENV(),+ );+ expect(r.returncode).toBe(0);+}++/** Hand-add an informal privacy marker, the way an operator does. */+function stampPrefMarker(slug: string, line: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+}++describe("brain bank-export notices", () => {+ test("the preference denial is named beside the --include-prompt-derived notice", async () => {+ // The reserved preference is withheld before the guard runs and no+ // flag carries a reserved rule, so the override changes nothing about+ // the denial - the notice that names the reserved row must ride the+ // override run exactly as it rides the default run, or the operator+ // who carries the marked pages back in drops the reserved rule+ // silently.+ await bootstrap();+ await seedPreference("reserved", "principle reserved");+ stampPrefMarker("reserved", "access: private");++ const r = await runCli(+ ["brain", "bank-export", "--vault", vault, "--include-prompt-derived"],+ ENV(),+ );+ expect(r.returncode).toBe(0);+ expect(r.stderr).toContain(EGRESS_CONTENT_CLASS_INCLUDE_NOTICE);+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("left out");+ // stderr only: the bundle names the omission as data, not prose.+ expect(r.stdout).not.toContain("left out");+ const bundle = JSON.parse(r.stdout) as {+ preferences: ReadonlyArray<{ id: string }>;+ preferences_omitted?: ReadonlyArray<{+ id: string;+ reason: string;+ denied_by: string;+ }>;+ };+ expect(bundle.preferences.map((p) => p.id)).toEqual([]);+ expect(bundle.preferences_omitted).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "access" },+ ]);+ });++ test("the default run still leaves the reserved row out of the preferences section", async () => {+ await bootstrap();+ await seedPreference("open", "principle open");+ await seedPreference("reserved", "principle reserved");+ stampPrefMarker("reserved", "access: private");++ const r = await runCli(["brain", "bank-export", "--vault", vault], ENV());+ expect(r.returncode).toBe(0);+ const bundle = JSON.parse(r.stdout) as {+ preferences: ReadonlyArray<{ id: string }>;+ preferences_omitted?: ReadonlyArray<{ id: string }>;+ };+ expect(bundle.preferences.map((p) => p.id)).toEqual(["pref-open"]);+ expect(bundle.preferences_omitted?.map((d) => d.id)).toEqual(["pref-reserved"]);+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("left out");+ });++ test("--include-reserved carries the reserved row into the backup and names the inclusion", async () => {+ // The bundle is documented as the one-file backup: the operator's own+ // copy of their own vault. A reservation is a statement about SHARED+ // readers, not about the operator, so the flag carries the reserved+ // rows back in and the run says so - the mirror of+ // --include-prompt-derived - and the denial notice is silent because+ // nothing was denied.+ await bootstrap();+ await seedPreference("open", "principle open");+ await seedPreference("reserved", "principle reserved");+ stampPrefMarker("reserved", "access: private");++ const r = await runCli(["brain", "bank-export", "--vault", vault, "--include-reserved"], ENV());+ expect(r.returncode).toBe(0);+ const bundle = JSON.parse(r.stdout) as {+ preferences: ReadonlyArray<{ id: string; principle: string }>;+ preferences_omitted?: ReadonlyArray<{ id: string }>;+ };+ expect(bundle.preferences.map((p) => p.id)).toEqual(["pref-open", "pref-reserved"]);+ expect(bundle.preferences[1]!.principle).toBe("principle reserved");+ // Nothing was withheld, so no omission report rides the bundle.+ expect("preferences_omitted" in bundle).toBe(false);+ // The run names the inclusion and the flag that caused it.+ expect(r.stderr).toContain("--include-reserved");+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("INCLUDED");+ // The preference denial is silent - nothing was withheld. The class+ // policy's own omission notice may still fire (the bootstrapped+ // prompt-derived page), so the assertion names the denial's phrase.+ expect(r.stderr).not.toContain("visibility reservation");+ });+});diff --git a/tests/cli/brain-context-receipts.test.ts b/tests/cli/brain-context-receipts.test.tsindex f56f3818..cceb4362 100644--- a/tests/cli/brain-context-receipts.test.ts+++ b/tests/cli/brain-context-receipts.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";import { runCli } from "../helpers/run-cli.ts";let vault: string;@@ -68,3 +69,116 @@ test("brain context-receipts lists and shows prompt receipt records", async () =tokens: 4,});});++test("brain context-receipts show joins the session's reply_presence and names unjoined honestly", async () => {+ const joined = emitContextReceipt(vault, {+ options: {+ host: "cli-test",+ trigger: "session_inject",+ createdAt: "2026-05-20T14:00:00.000Z",+ sessionId: "session-cli-present",+ },+ finalText: "eager layer",+ items: [{ id: "pref-alpha", path: "Brain/preferences/pref-alpha.md" }],+ });+ const lonely = emitContextReceipt(vault, {+ options: {+ host: "cli-test",+ trigger: "session_inject",+ createdAt: "2026-05-20T14:05:00.000Z",+ sessionId: "session-cli-absent",+ },+ finalText: "eager layer",+ items: [{ id: "pref-bravo", path: "Brain/preferences/pref-bravo.md" }],+ });+ const presence = appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-20T14:10:00.000Z",+ payload: {+ session_id: "session-cli-present",+ checked: 1,+ per_note: [+ {+ path: "Brain/preferences/pref-alpha.md",+ start_line: 2,+ end_line: 4,+ verdict: "verified",+ },+ ],+ },+ });++ // The joined show names the sibling record and carries its per-note verdicts.+ const showJoined = await runCli([+ "brain",+ "context-receipts",+ "show",+ joined.id,+ "--vault",+ vault,+ "--json",+ ]);+ expect(showJoined.returncode).toBe(0);+ expect(JSON.parse(showJoined.stdout)["reply_presence"]).toEqual({+ joined: true,+ presence: {+ record_id: presence.id,+ created_at: "2026-05-20T14:10:00.000Z",+ checked: 1,+ per_note: [+ {+ path: "Brain/preferences/pref-alpha.md",+ start_line: 2,+ end_line: 4,+ verdict: "verified",+ },+ ],+ },+ });++ // No reply_presence record for this receipt's session: the outcome is+ // NAMED on the response, never a silent absence.+ const showLonely = await runCli([+ "brain",+ "context-receipts",+ "show",+ lonely.id,+ "--vault",+ vault,+ "--json",+ ]);+ expect(showLonely.returncode).toBe(0);+ expect(JSON.parse(showLonely.stdout)["reply_presence"]).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-cli-absent",+ });++ // The text show prints the verdicts, and the unjoined absence says why.+ const textJoined = await runCli([+ "brain",+ "context-receipts",+ "show",+ joined.id,+ "--vault",+ vault,+ ]);+ expect(textJoined.returncode).toBe(0);+ expect(textJoined.stdout).toContain(+ `reply_presence: joined (record ${presence.id} @ 2026-05-20T14:10:00.000Z, checked=1)`,+ );+ expect(textJoined.stdout).toContain(" Brain/preferences/pref-alpha.md#L2-L4: verified\n");++ const textLonely = await runCli([+ "brain",+ "context-receipts",+ "show",+ lonely.id,+ "--vault",+ vault,+ ]);+ expect(textLonely.returncode).toBe(0);+ expect(textLonely.stdout).toContain(+ "reply_presence: unjoined (no reply_presence record for session session-cli-absent)\n",+ );+});diff --git a/tests/cli/brain-dead-letters.test.ts b/tests/cli/brain-dead-letters.test.tsnew file mode 100644index 00000000..32a28afd--- /dev/null+++ b/tests/cli/brain-dead-letters.test.ts@@ -0,0 +1,746 @@+/**+ * `o2b brain dead-letters` CLI surface (one-command recovery,+ * t_50794f57, task C3). Claims pinned here:+ *+ * 1. `list` (the default) renders every letter with its classification+ * and the exact copy-paste recovery command, and exits 0 - a listing+ * is a report, never a failure. An empty vault says so and exits 0.+ * 2. `show <id>` prints one letter in full detail; an unknown id is a+ * typed usage error (exit 2), never a silent no-op.+ * 3. `recover <id>` is dry-run by default and previews the per-item+ * verdicts; `--apply` performs the re-run.+ * 4. `--apply` without `--yes` under `--json` or a non-TTY stdin refuses+ * typed, writes nothing, and names the consent rule.+ * 5. A frozen vault refuses the apply by name (exit 1) and points at+ * `o2b brain unfreeze`.+ * 6. Nothing ever deletes the letter: after a successful recovery the+ * record is still on disk, and the verb says the removal is the+ * operator's hand action.+ * 7. The verb is wired: the router dispatches it, the manifest carries+ * it (so the derived help surfaces list it), and the write error's+ * diagnostic entry resolves to the verb.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import {+ deadLetterDir,+ deadLetterPath,+ listDeadLetters,+ recordDeadLetter,+ type DeadLetterEnvelopeIdentity,+} from "../../src/core/brain/dead-letter.ts";+import { DEAD_LETTER_ITEM_VERDICT } from "../../src/core/brain/dead-letter-recovery.ts";+import { verdictText } from "../../src/cli/brain/verbs/dead-letters.ts";+import { resolveNextStep } from "../../src/core/brain/next-step.ts";+import { freezeVault } from "../../src/core/brain/freeze.ts";+import { resetFreezeMarkerCache } from "../../src/core/brain/freeze-marker.ts";+import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";+import { importSessionRecall } from "../../src/core/brain/session-recall.ts";+import {+ commitExtractedSignals,+ type ExtractedSignalItem,+} from "../../src/core/brain/extract-signals.ts";+import { buildReconciliationReport } from "../../src/core/reconciliation-report.ts";+import { sessionMiningLedgerPath } from "../../src/core/brain/session-mining-ledger.ts";+import { runCli } from "../helpers/run-cli.ts";++const NOW = new Date("2026-08-23T10:15:00Z");+const SESSION = "sess-cli-recover";+const AGENT = "tester";++let tmp: string;+let vault: string;+let configPath: string;++function item(overrides: Partial<ExtractedSignalItem> = {}): ExtractedSignalItem {+ return {+ topic: "release-notes-style",+ signal: "positive",+ principle: "Name the release theme in the heading, never the ticket id.",+ confidence: 0.9,+ ...overrides,+ };+}++const ENVELOPE: DeadLetterEnvelopeIdentity = Object.freeze({+ lane: "extract-signals",+ step: "extract-signals",+ reference: SESSION,+ target: "Brain/inbox",+});++/** A schema-2 letter over `items` naming `missingKeys`, as the commit writes it. */+function v2Letter(+ items: ReadonlyArray<ExtractedSignalItem>,+ missingKeys: ReadonlyArray<string>,+): ReturnType<typeof recordDeadLetter> {+ return recordDeadLetter(vault, {+ envelope: ENVELOPE,+ report: buildReconciliationReport({+ attempted: items.length,+ found: items.length - missingKeys.length,+ missing: missingKeys,+ }),+ firstError: "EIO: i/o error",+ now: NOW,+ payload: { items: [...items] },+ });+}++function run(args: ReadonlyArray<string>) {+ return runCli(["brain", "dead-letters", ...args, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+}++/** Corrupt the session mining ledger the way a truncated write leaves it. */+function corruptMiningLedger(): void {+ mkdirSync(dirname(sessionMiningLedgerPath(vault)), { recursive: true });+ writeFileSync(sessionMiningLedgerPath(vault), "{ truncated");+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-dead-letters-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\n`);+ importSessionRecall(vault, {+ sessionId: SESSION,+ turns: [+ {+ turnId: "t1",+ timestamp: "2026-08-22T09:01:00Z",+ role: "user",+ text: "Always name the release theme in the heading.",+ },+ ],+ createdAt: "2026-08-22T10:00:00Z",+ });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ resetFreezeMarkerCache();+ resetVaultIdentityPins();+});++describe("dead-letters list", () => {+ test("an empty vault is a clean, zero-exit report", async () => {+ const r = await run([]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("no dead letters");+ });++ test("the default renders the classification and the exact recovery command per row", async () => {+ const letter = v2Letter([item(), item({ topic: "module-names" })], ["items[1]:module-names"]);+ const r = await run([]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain(letter.id);+ expect(r.stdout).toContain("recover");+ expect(r.stdout).toContain(`o2b brain dead-letters recover ${letter.id} --apply --yes`);+ expect(r.stdout).toContain(SESSION);+ expect(r.stdout).toContain("items[1]:module-names");+ });++ test("a resolved row renders no command and names why", async () => {+ const items = [item(), item({ topic: "module-names" })];+ commitExtractedSignals(vault, SESSION, { items }, { agent: AGENT, now: NOW });+ v2Letter(items, ["items[0]:release-notes-style", "items[1]:module-names"]);+ const r = await run([]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("resolved");+ expect(r.stdout).toContain("now on disk");+ expect(r.stdout).not.toContain("--apply");+ });++ test("--json carries the per-row category, reason and command", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ ok: boolean;+ total: number;+ letters: Array<{+ id: string;+ lane: string;+ reference: string;+ missing: string[];+ category: string;+ reason: string;+ command: string | null;+ }>;+ };+ expect(payload.ok).toBe(true);+ expect(payload.total).toBe(1);+ const row = payload.letters[0]!;+ expect(row.id).toBe(letter.id);+ expect(row.lane).toBe("extract-signals");+ expect(row.reference).toBe(SESSION);+ expect(row.missing).toEqual(["items[0]:release-notes-style"]);+ expect(row.category).toBe("recover");+ expect(row.command).toBe(`o2b brain dead-letters recover ${letter.id} --apply --yes`);+ });++ test("a non-recoverable row is still exit 0 - a listing reports, it does not fail", async () => {+ v2Letter([item()], ["items[0]:release-notes-style"]);+ // A second letter for a session the ledger does not know.+ recordDeadLetter(vault, {+ envelope: { ...ENVELOPE, reference: "sess-nowhere" },+ report: buildReconciliationReport({ attempted: 1, found: 0, missing: ["items[0]:x"] }),+ firstError: "disk full",+ now: NOW,+ payload: { items: [item({ topic: "x" })] },+ });+ const r = await run([]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("not_recoverable");+ expect(r.stdout).toContain("sess-nowhere");+ });++ test("list --json carries has_payload but never the payload itself", async () => {+ // The listing is the machine-read bulk surface - agents and cron logs+ // read it - so the frozen items never ride on it, not even redacted.+ // `show` is the one-letter inspection surface and keeps them.+ expect(() =>+ commitExtractedSignals(+ vault,+ SESSION,+ {+ items: [+ {+ topic: "release-notes-style",+ signal: "positive",+ principle: "Use token password=hunter2secret when scraping.",+ confidence: 0.9,+ },+ // A colon is not a legal slug character: the write refuses and+ // the commit records the letter, frozen payload and all.+ {+ topic: "module:names",+ signal: "positive",+ principle: "Never abbreviate a module name.",+ confidence: 0.9,+ },+ ],+ },+ { agent: AGENT, now: NOW },+ ),+ ).toThrow(/failed to write extracted signal/);+ expect(listDeadLetters(vault)).toHaveLength(1);+ const r = await run(["--json"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).not.toContain("hunter2secret");+ const payload = JSON.parse(r.stdout) as {+ letters: Array<Record<string, unknown> & { has_payload: boolean }>;+ };+ const row = payload.letters[0]!;+ expect(row["payload"]).toBeUndefined();+ expect(row.has_payload).toBe(true);+ });++ test("show --json keeps the frozen payload for the one-letter inspection, redacted as frozen", async () => {+ expect(() =>+ commitExtractedSignals(+ vault,+ SESSION,+ {+ items: [+ {+ topic: "release-notes-style",+ signal: "positive",+ principle: "Use token password=hunter2secret when scraping.",+ confidence: 0.9,+ },+ {+ topic: "module:names",+ signal: "positive",+ principle: "Never abbreviate a module name.",+ confidence: 0.9,+ },+ ],+ },+ { agent: AGENT, now: NOW },+ ),+ ).toThrow(/failed to write extracted signal/);+ const letter = listDeadLetters(vault)[0]!;+ const r = await run(["show", letter.id, "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ letter: { payload?: { items: Array<Record<string, unknown>> } };+ };+ // An operator inspecting ONE letter locally may need the frozen items+ // - they are the only record of what the failed commit was writing -+ // and the freeze redacts the free text already.+ expect(payload.letter.payload).toBeDefined();+ expect(JSON.stringify(payload.letter.payload)).not.toContain("hunter2secret");+ expect(payload.letter.payload?.items[0]?.["dedup_hash"]).toBeTypeOf("string");+ });+});++describe("dead-letters show", () => {+ test("one letter renders in full detail, missing keys named", async () => {+ const letter = v2Letter([item(), item({ topic: "module-names" })], ["items[1]:module-names"]);+ const r = await run(["show", letter.id]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain(letter.id);+ expect(r.stdout).toContain("items[1]:module-names");+ expect(r.stdout).toContain("EIO: i/o error");+ expect(r.stdout).toContain("module-names");+ });++ test("show --json carries the frozen payload's items", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["show", letter.id, "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ ok: boolean;+ letter: { id: string; payload?: { items: Array<{ topic: string }> } };+ };+ expect(payload.ok).toBe(true);+ expect(payload.letter.id).toBe(letter.id);+ expect(payload.letter.payload?.items[0]?.topic).toBe("release-notes-style");+ });++ test("an unknown id is a typed usage error, not a silent no-op", async () => {+ const r = await run(["show", "extract-signals-0123456789ab"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("extract-signals-0123456789ab");+ });++ test("an unknown id under --json stays a plain-text usage error on stderr", async () => {+ // Usage errors are exit 2 plain text on stderr in BOTH modes; the+ // { ok: false } envelope is reserved for operational refusals (exit+ // 1), so a misquoted id must not mint one on stdout.+ for (const subcommand of ["show", "recover"] as const) {+ const r = await run([subcommand, "extract-signals-0123456789ab", "--json"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("no dead letter with id");+ expect(r.stdout).toBe("");+ }+ });++ test("a missing id argument is a usage error", async () => {+ const r = await run(["show"]);+ expect(r.returncode).toBe(2);+ });++ test("a malformed id reads as unknown too - nothing was ever written under it", async () => {+ const r = await run(["show", "garbage"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("no dead letter with id");+ });+});++describe("a letter the store refuses to parse is exit 1, never unknown-id", () => {+ // A letter whose bytes this build cannot read is a hard error by the+ // store's own contract (`dead-letter.ts`: reading refuses rather than+ // skips) - a surface that turned it into "no dead letter with id" would+ // under-report the exact failure the store exists to prevent.+ const CORRUPT_ID = "extract-signals-001122334455";+ const UNKNOWN_VERSION_ID = "extract-signals-ff0011223344";++ function writeCorruptLetter(): void {+ mkdirSync(deadLetterDir(vault), { recursive: true });+ writeFileSync(deadLetterPath(vault, CORRUPT_ID), "{ not json");+ }++ function writeUnknownVersionLetter(): void {+ mkdirSync(deadLetterDir(vault), { recursive: true });+ writeFileSync(+ deadLetterPath(vault, UNKNOWN_VERSION_ID),+ `${JSON.stringify(+ {+ schema_version: 99,+ id: UNKNOWN_VERSION_ID,+ lane: "extract-signals",+ step: "extract-signals",+ reference: SESSION,+ target: "Brain/inbox",+ attempted: 1,+ found: 0,+ missing: ["items[0]:x"],+ outcome: "partial",+ first_error: "disk full",+ recorded_at: "2026-08-23T10:15:00Z",+ },+ null,+ 2,+ )}\n`,+ );+ }++ test("show names the store's corrupt-JSON error at exit 1", async () => {+ writeCorruptLetter();+ const r = await run(["show", CORRUPT_ID]);+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("corrupt");+ expect(r.stderr).not.toContain("no dead letter with id");+ });++ test("show --json refuses typed at exit 1", async () => {+ writeCorruptLetter();+ const r = await run(["show", CORRUPT_ID, "--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("corrupt");+ });++ test("list names the store's refusal at exit 1 instead of crashing", async () => {+ writeCorruptLetter();+ const r = await run([]);+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("corrupt");+ // A typed refusal, never an uncaught stack: the listing under-reports+ // nothing and the operator gets the same sentence show gives. The+ // frame shape is matched, not the substring "at " - a refusal+ // sentence that happens to contain " at " is not a stack trace.+ expect(r.stderr).not.toMatch(/^\s+at\s/m);+ });++ test("list --json refuses typed at exit 1", async () => {+ writeUnknownVersionLetter();+ const r = await run(["--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("schema_version");+ expect(payload.message).toContain("parses 1 and 2");+ });++ test("show names an unsupported schema_version at exit 1", async () => {+ writeUnknownVersionLetter();+ const r = await run(["show", UNKNOWN_VERSION_ID]);+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("schema_version");+ expect(r.stderr).not.toContain("no dead letter with id");+ });++ test("recover names the store's refusal at exit 1 and writes nothing", async () => {+ writeCorruptLetter();+ const r = await run(["recover", CORRUPT_ID, "--apply", "--yes"]);+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("corrupt");+ expect(existsSync(join(vault, "Brain", "inbox"))).toBe(false);+ });+});++describe("dead-letters recover", () => {+ test("dry-run is the default and previews the per-item verdicts, writing nothing", async () => {+ commitExtractedSignals(vault, SESSION, { items: [item()] }, { agent: AGENT, now: NOW });+ const letter = v2Letter(+ [item(), item({ topic: "module-names" })],+ ["items[0]:release-notes-style", "items[1]:module-names"],+ );+ const r = await run(["recover", letter.id]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("dry-run");+ expect(r.stdout).toContain("release-notes-style");+ expect(r.stdout).toContain("module-names");+ expect(r.stdout).toMatch(/dedup|already on disk/);+ expect(r.stdout).toContain("--apply");+ // Nothing was written.+ expect(listDeadLetters(vault).length).toBe(1);+ expect(r.stdout).not.toContain("wrote");+ });++ test("recover --json dry-run labels the mode and lists the verdicts", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["recover", letter.id, "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ ok: boolean;+ id: string;+ mode: string;+ items: Array<{ topic: string; verdict: string }>;+ };+ expect(payload.ok).toBe(true);+ expect(payload.id).toBe(letter.id);+ expect(payload.mode).toBe("dry-run");+ expect(payload.items).toEqual([{ topic: "release-notes-style", verdict: "write" }]);+ });++ test("--apply without --yes under --json refuses typed and writes nothing", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["recover", letter.id, "--apply", "--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("--yes");+ expect(listDeadLetters(vault).length).toBe(1);+ });++ test("--apply without --yes in plain non-TTY mode refuses too", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["recover", letter.id, "--apply"]);+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("--yes");+ });++ test("--dry-run and --apply together refuse as a usage error and write nothing", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["recover", letter.id, "--dry-run", "--apply", "--yes"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--dry-run");+ expect(r.stderr).toContain("--apply");+ // The refusal precedes every write: the letter's item never reached+ // the inbox, and no new letter was recorded either.+ expect(existsSync(join(vault, "Brain", "inbox"))).toBe(false);+ expect(listDeadLetters(vault).length).toBe(1);+ });++ test("--apply --yes re-runs the payload; already-written items dedup away", async () => {+ commitExtractedSignals(vault, SESSION, { items: [item()] }, { agent: AGENT, now: NOW });+ const letter = v2Letter(+ [item(), item({ topic: "module-names" })],+ ["items[0]:release-notes-style", "items[1]:module-names"],+ );+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ ok: boolean;+ mode: string;+ written: Array<{ topic: string }>;+ deduped: number;+ letter_retained: boolean;+ };+ expect(payload.ok).toBe(true);+ expect(payload.mode).toBe("apply");+ expect(payload.written.map((w) => w.topic)).toEqual(["module-names"]);+ expect(payload.deduped).toBe(1);+ expect(payload.letter_retained).toBe(true);+ });++ test("a mining-ledger failure on a written apply rides the JSON output by name", async () => {+ // The commit result's contract (`extract-signals.ts`): the failure+ // "rides here by name, and on both surface outputs" - a recovery that+ // wrote its signals but lost the mining record must never read as a+ // clean run.+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ corruptMiningLedger();+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ ok: boolean;+ mining_ledger_failure?: string;+ };+ expect(payload.ok).toBe(true);+ expect(payload.mining_ledger_failure).toContain("session mining ledger is corrupted JSON");+ });++ test("the same failure prints on the human-readable apply output", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ corruptMiningLedger();+ const r = await run(["recover", letter.id, "--apply", "--yes"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("mining ledger not updated:");+ expect(r.stdout).toContain("session mining ledger is corrupted JSON");+ });++ test("a clean apply carries no mining_ledger_failure key", async () => {+ // Absent-when-empty: a recovery whose mining record landed names no+ // failure, so the JSON shape stays what it always was.+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as { mining_ledger_failure?: string };+ expect(payload.mining_ledger_failure).toBeUndefined();+ });++ test("nothing ever deletes the letter, and the verb says the removal is by hand", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const r = await run(["recover", letter.id, "--apply", "--yes"]);+ expect(r.returncode).toBe(0);+ const after = listDeadLetters(vault);+ expect(after.length).toBe(1);+ expect(readFileSync(deadLetterPath(vault, letter.id), "utf8")).toContain(letter.id);+ expect(r.stdout).toContain("retained");+ expect(deadLetterDir(vault)).toBeTruthy();+ });++ test("recover refuses a letter that is not recoverable, naming the category", async () => {+ // A letter for a session the ledger does not know.+ const letter = recordDeadLetter(vault, {+ envelope: { ...ENVELOPE, reference: "sess-nowhere" },+ report: buildReconciliationReport({ attempted: 1, found: 0, missing: ["items[0]:x"] }),+ firstError: "disk full",+ now: NOW,+ payload: { items: [item({ topic: "x" })] },+ });+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("not_recoverable");+ });++ test("a denylist-refused letter refuses the apply at exit 1, naming the gate", async () => {+ // The item never reaches disk, so the letter used to read `recover`+ // forever and every apply reported success over zero writes. The+ // classifier answers not_recoverable and the verb refuses - on the+ // first apply and on every one after it.+ const letter = v2Letter(+ [item({ topic: "scratch-pad", principle: "temporary scratch note" })],+ ["items[0]:scratch-pad"],+ );+ const r = await runCli(+ [+ "brain",+ "dead-letters",+ "recover",+ letter.id,+ "--apply",+ "--yes",+ "--json",+ "--vault",+ vault,+ ],+ {+ env: {+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ OPEN_SECOND_BRAIN_DURABILITY_DENYLIST: "scratch",+ },+ },+ );+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("durability");+ expect(payload.message).toContain("denylisted");+ // The refused item was never written.+ expect(existsSync(join(vault, "Brain", "inbox"))).toBe(false);+ });++ test("an apply that delivers nothing exits 1 naming the reason", async () => {+ // A hand-edited letter whose missing list is empty: the classifier's+ // recover promise has nothing behind it and the re-run delivers+ // nothing - which used to print `wrote 0 signal(s)` and exit 0. The+ // verb refuses the empty success instead of reporting it.+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const path = deadLetterPath(vault, letter.id);+ const body = JSON.parse(readFileSync(path, "utf8")) as { missing: string[] };+ body.missing = [];+ writeFileSync(path, `${JSON.stringify(body, null, 2)}\n`);+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("nothing was delivered");+ expect(existsSync(join(vault, "Brain", "inbox"))).toBe(false);+ });++ test("a reworded re-extract reads as resolved: the apply exits 1 and writes nothing", async () => {+ // The review's scenario: the letter misses release-theme; the session+ // was mined again and a REWORDED release-theme signal landed. The+ // letter reads resolved, the apply refuses, and the inbox keeps ONE+ // release-theme page instead of gaining the stale wording back.+ commitExtractedSignals(+ vault,+ SESSION,+ {+ items: [+ item({ topic: "release-theme", principle: "Lead every release note with the theme." }),+ ],+ },+ { agent: AGENT, now: NOW },+ );+ const letter = v2Letter(+ [item({ topic: "release-theme", principle: "Name the release theme in the heading." })],+ ["items[0]:release-theme"],+ );+ const listing = await run([]);+ expect(listing.stdout).toContain("resolved");+ expect(listing.stdout).not.toContain("--apply");+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("resolved");+ const inbox = join(vault, "Brain", "inbox");+ const pages = readdirSync(inbox).filter((p) => p.includes("release-theme"));+ expect(pages).toHaveLength(1);+ });++ test("a frozen vault refuses the apply and points at unfreeze", async () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ freezeVault(vault, { agent: "@operator", reason: "migrating the fleet" });+ resetFreezeMarkerCache();+ resetVaultIdentityPins();+ const r = await run(["recover", letter.id, "--apply", "--yes", "--json"]);+ expect(r.returncode).toBe(1);+ const payload = JSON.parse(r.stdout) as { ok: boolean; message: string };+ expect(payload.ok).toBe(false);+ expect(payload.message).toContain("frozen");+ expect(payload.message).toContain("o2b brain unfreeze");+ // The letter's items were not written.+ expect(listDeadLetters(vault).length).toBe(1);+ });++ test("an unknown id is a typed usage error", async () => {+ const r = await run(["recover", "extract-signals-0123456789ab"]);+ expect(r.returncode).toBe(2);+ });++ test("a missing id argument is a usage error", async () => {+ const r = await run(["recover"]);+ expect(r.returncode).toBe(2);+ });+});++describe("the dry-run verdict rendering", () => {+ test("every known verdict renders its own words; an unknown one refuses by name", () => {+ // Enumerated against the vocabulary constant: a verdict joining+ // DEAD_LETTER_ITEM_VERDICT must be given its own words here, never+ // silently rendered as another verdict's - "quarantined" reading as+ // "refused" would tell the operator the wrong thing.+ expect(verdictText(DEAD_LETTER_ITEM_VERDICT.write)).toBe("will write");+ expect(verdictText(DEAD_LETTER_ITEM_VERDICT.staged)).toBe("will stage for approval");+ expect(verdictText(DEAD_LETTER_ITEM_VERDICT.dedup)).toBe("already on disk (dedup)");+ expect(verdictText(DEAD_LETTER_ITEM_VERDICT.refused)).toBe("refused");+ expect(() => verdictText("quarantined")).toThrow(/quarantined/);+ });+});++describe("wiring", () => {+ test("an unknown subcommand is a usage error naming the three forms", async () => {+ const r = await run(["frobnicate"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("list");+ expect(r.stderr).toContain("show");+ expect(r.stderr).toContain("recover");+ });++ test("--help prints the verb's own usage", async () => {+ const r = await runCli(["brain", "dead-letters", "--help"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout.startsWith("usage:")).toBe(true);+ expect(r.stdout).toContain("o2b brain dead-letters");+ });++ test("the manifest carries the verb, so the derived help surfaces list it", async () => {+ const help = await runCli(["help"], { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } });+ expect(help.returncode).toBe(0);+ expect(help.stdout).toContain("dead-letters");+ });++ test("the write error's diagnostic entry resolves to the verb", () => {+ const step = resolveNextStep("extract-signals-dead-letter");+ expect(step).not.toBeNull();+ expect(step?.nextCommand).toBe("o2b brain dead-letters");+ });+});diff --git a/tests/cli/brain-explorer.test.ts b/tests/cli/brain-explorer.test.tsindex 095e5128..b5686c89 100644--- a/tests/cli/brain-explorer.test.ts+++ b/tests/cli/brain-explorer.test.ts@@ -7,11 +7,21 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";-import { writePreference } from "../../src/core/brain/preference.ts";+import { collectExplorerData, renderExportedHtml } from "../../src/core/brain/explorer.ts";+import { moveToRetired, writePreference } from "../../src/core/brain/preference.ts";+import { BRAIN_RETIRED_REASON } from "../../src/core/brain/types.ts";import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";import { runCli } from "../helpers/run-cli.ts";@@ -220,6 +230,181 @@ describe("o2b brain explorer --export", () => {});});+describe("o2b brain explorer --export privacy denials", () => {+ /**+ * Hand-add an informal privacy marker the same way an operator does:+ * a user-tier frontmatter line on the node's file.+ */+ function stampMarker(relPath: string, line: string): void {+ const abs = join(vault, relPath);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+ }++ function seedReservedPref(): void {+ writePreference(vault, {+ slug: "reserved",+ topic: "reserved",+ principle: "Reserved principle",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-2026-05-01-reserved]]"],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: "high",+ confidence_value: 0.8,+ pinned: false,+ });+ stampMarker("Brain/preferences/pref-reserved.md", "access: private");+ }++ test("a reserved preference is absent from the HTML and named on stderr", async () => {+ await bootstrap();+ seedOnePref();+ seedReservedPref();+ const out = join(tmp, "brain.html");+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const body = readFileSync(out, "utf8");+ expect(body).not.toContain("pref-reserved");+ expect(body).not.toContain("Reserved principle");+ // The unmarked rule still ships.+ expect(body).toContain("pref-explorer-seed");+ // The omission is disclosed on stderr, with the key that denied it.+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("(access)");+ expect(r.stderr).toContain("left out");+ // stderr only: the HTML names the omission as absence, not prose.+ expect(r.stdout).not.toContain("left out");+ // The count answers for what was written: one node exported, one+ // named as withheld on stderr.+ expect(r.stdout).toContain("exported 1 ");+ });++ test("a reserved retired entry is absent too", async () => {+ await bootstrap();+ seedOnePref();+ writePreference(vault, {+ slug: "old-reserved",+ topic: "old-reserved",+ principle: "Old reserved principle",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-2026-05-01-old-reserved]]"],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: "high",+ confidence_value: 0.8,+ pinned: false,+ });+ const deadPath = join(vault, "Brain", "preferences", "pref-old-reserved.md");+ moveToRetired(vault, deadPath, BRAIN_RETIRED_REASON.staleNoEvidence, {+ now: new Date("2026-05-10T00:00:00Z"),+ retired_by: "[[Brain/log/2026-05-10]]",+ });+ stampMarker("Brain/retired/ret-old-reserved.md", "sensitivity: confidential");++ const out = join(tmp, "brain.html");+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const body = readFileSync(out, "utf8");+ expect(body).not.toContain("ret-old-reserved");+ expect(body).not.toContain("Old reserved principle");+ expect(r.stderr).toContain("ret-old-reserved");+ expect(r.stderr).toContain("(sensitivity)");+ });++ test("an unmarked vault exports byte-identically to the shared collector's rendering", async () => {+ await bootstrap();+ seedOnePref();+ const out = join(tmp, "brain.html");+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ // No reservation held anything back, so the file is exactly what the+ // pre-denial pipeline rendered - the denial pass changed no bytes.+ const stripTimestamp = (s: string): string =>+ s.replace(/"generated_at":"[^"]*"/, '"generated_at":"X"');+ expect(stripTimestamp(readFileSync(out, "utf8"))).toBe(+ stripTimestamp(renderExportedHtml(collectExplorerData(vault))),+ );+ expect(r.stderr).not.toContain("left out");+ });+});++describe("o2b brain explorer (live) store group", () => {+ test("a failed lock probe keeps the errno and drops the host path from the reason", async () => {+ await bootstrap();+ seedOnePref();+ // A lock path that cannot even be stat'd: a symlink loop where the+ // lock directory would sit - the throw shape whose fs message+ // embeds the full resolved host path.+ const { resolveSearchConfig } = await import("../../src/core/search/index.ts");+ const lockPath = `${resolveSearchConfig({ vault, configPath: config }).dbPath}.lock`;+ mkdirSync(dirname(lockPath), { recursive: true });+ symlinkSync(lockPath, lockPath);++ const port = pickPort();+ const proc = Bun.spawn(+ [+ "bun",+ "run",+ "src/cli/main.ts",+ "brain",+ "explorer",+ "--vault",+ vault,+ "--port",+ String(port),+ ],+ {+ cwd: process.cwd(),+ env: { ...process.env, OPEN_SECOND_BRAIN_CONFIG: config },+ stdout: "pipe",+ stderr: "pipe",+ },+ );+ try {+ const banner = await readUntil(proc.stdout, "Live explorer at ");+ if (!banner.found) {+ const stderr = await new Response(proc.stderr).text();+ throw new Error(`explorer exited before listening:\n${banner.text}${stderr}`);+ }+ const res = await fetch(`http://127.0.0.1:${port}/status.json`);+ expect(res.ok).toBe(true);+ const status = JSON.parse(await res.text()) as {+ store: {+ writerLock: string;+ writerLockPath: string | null;+ writerLockReason: string | null;+ };+ };+ // The path is withheld from the field AND from the reason: the+ // browser surface answers below local reach for the whole store+ // group, not for one field of it. The errno stays - "could not+ // find out, and here is why".+ expect(status.store.writerLock).toBe("unknown");+ expect(status.store.writerLockPath).toBeNull();+ expect(status.store.writerLockReason).toContain("ELOOP");+ expect(status.store.writerLockReason).not.toContain(lockPath);+ expect(status.store.writerLockReason).not.toContain(tmpdir());+ } finally {+ proc.kill("SIGINT");+ await proc.exited;+ }+ }, 20000);+});+describe("o2b brain explorer (live)", () => {test("binds to 127.0.0.1, serves all four routes, shuts down on SIGINT",@@ -299,9 +484,23 @@ describe("o2b brain explorer (live)", () => {healthy: boolean;counts: { preferences: number };activeProfile: string | null;+ store: {+ writerLock: string;+ writerLockPath: string | null;+ writerLockOwner: string | null;+ thisCaller: string;+ };};expect(typeof status.healthy).toBe("boolean");expect(status.counts.preferences).toBe(1);+ // The explorer serves browsers, not the operator's own reach, so+ // the lock PATH is withheld the way the MCP surface withholds it+ // below local reach (a resolved host path is not a browser+ // client's fact) - while the rest of the store group stays. The+ // local CLI status keeps the path; that is pinned in status.test.+ expect(status.store.writerLockPath).toBeNull();+ expect(typeof status.store.writerLock).toBe("string");+ expect(status.store.thisCaller).toBe("read-only");// The verb threads its resolved config path into the server, so// the operator snapshot sees this run's profile registry.writeFileSync(diff --git a/tests/cli/brain-export.test.ts b/tests/cli/brain-export.test.tsindex 1f106c94..92087dbb 100644--- a/tests/cli/brain-export.test.ts+++ b/tests/cli/brain-export.test.ts@@ -188,6 +188,74 @@ describe("brain export", () => {});});+describe("brain export privacy omissions", () => {+ /**+ * Hand-add an informal privacy marker the same way an operator does:+ * a user-tier frontmatter line on the preference file.+ */+ function stampMarker(slug: string, line: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+ }++ test("a reserved preference is omitted from the json envelope and named on stderr", async () => {+ await bootstrap();+ await seedPreference("alpha");+ await seedPreference("reserved");+ stampMarker("reserved", "access: private");++ const r = await runCli(["brain", "export", "--vault", vault, "--format", "json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ preferences: ReadonlyArray<{ id: string }>;+ omitted?: ReadonlyArray<{ id: string; reason: string; denied_by: string }>;+ };+ expect(payload.preferences.map((p) => p.id)).toEqual(["pref-alpha"]);+ expect(payload.omitted).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "access" },+ ]);+ // The omission is DISCLOSED, not silent: the notice names the rule and+ // the reservation key that denied it.+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("(access)");+ expect(r.stderr).toContain("left out");+ // stderr only - the json bytes name the omission as data, not prose.+ expect(r.stdout).not.toContain("left out");+ });++ test("llms-txt leaves the reserved row out of the sections and names it on stderr", async () => {+ await bootstrap();+ await seedPreference("alpha");+ await seedPreference("reserved");+ stampMarker("reserved", "sensitivity: confidential");++ const r = await runCli(["brain", "export", "--vault", vault, "--format", "llms-txt"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("- pref-alpha (topic: alpha, scope: writing): principle alpha");+ expect(r.stdout).not.toContain("pref-reserved");+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("(sensitivity)");+ expect(r.stderr).toContain("left out");+ });++ test("a vault with no reservation emits no notice and no omitted key", async () => {+ await bootstrap();+ await seedPreference("alpha");++ const r = await runCli(["brain", "export", "--vault", vault, "--format", "json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as { omitted?: unknown };+ expect("omitted" in payload).toBe(false);+ expect(r.stderr).not.toContain("left out");+ });+});+describe("brain export --format transcripts-jsonl", () => {interface TranscriptFixture {/** Turn id of the first line - the `turn_id` a record carries. */diff --git a/tests/cli/brain-note-lifecycle.test.ts b/tests/cli/brain-note-lifecycle.test.tsindex dc40b672..f957213b 100644--- a/tests/cli/brain-note-lifecycle.test.ts+++ b/tests/cli/brain-note-lifecycle.test.ts@@ -283,3 +283,200 @@ test("--delete-linked on a rename is a refusal, not a silently ignored flag", asexpect(res.stderr).toContain("delete-linked");expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);});++test("move-folder relocates the folder and renders the move report as JSON", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/b.md", "beta\n");+ note("Notes/Ref.md", "pathed [[Projects/Old/a]]\n");++ const res = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Old",+ "Archive",+ "--vault",+ vault,+ "--apply",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as {+ action: string;+ from: string;+ to: string;+ applied: boolean;+ moved: Array<{ from: string; to: string }>;+ move_failures: Array<{ path: string; reason: string }>;+ snapshot: null;+ references: { files_rewritten: number; files_scanned: number };+ };+ expect(body.action).toBe("move-folder");+ expect(body.applied).toBe(true);+ expect(body.from).toBe("Projects/Old");+ expect(body.to).toBe("Archive/Old");+ // The moved list, per file, and the per-file failure list - the report+ // style the folder module's result is read in.+ expect(body.moved).toEqual([+ { from: "Projects/Old/a.md", to: "Archive/Old/a.md" },+ { from: "Projects/Old/b.md", to: "Archive/Old/b.md" },+ ]);+ expect(body.move_failures).toEqual([]);+ // A relocation destroys nothing, so no snapshot rides the receipt.+ expect(body.snapshot).toBeNull();+ // Absent-when-empty: a clean move left nothing behind, so the key is+ // not on the receipt at all - its presence is the signal.+ expect("left_behind" in body).toBe(false);+ // No relative link broke either: every target the moved notes name is+ // a note that moved with the folder.+ expect("dangling_relative_links" in body).toBe(false);+ expect(body.references.files_rewritten).toBe(1);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old/b.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(false);+});++test("a folder action refuses --confirm and --delete-linked instead of dropping them", async () => {+ note("Projects/Old/a.md", "alpha\n");+ for (const flag of ["--confirm", "--delete-linked"]) {+ const res = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Old",+ "Archive",+ flag,+ "--vault",+ vault,+ "--json",+ ]);+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("takes neither");+ expect(res.stderr).toContain("never a delete");+ }+ // The refusal answered instead of the move: nothing was applied.+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive"))).toBe(false);+});++test("move-folder names non-Markdown residue and omits the field when clean", async () => {+ note("Projects/Old/a.md", "alpha\n");+ writeFileSync(join(vault, "Projects/Old/img.png"), "png\n");++ const res = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Old",+ "Archive",+ "--vault",+ vault,+ "--apply",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { left_behind?: string[] };+ expect(body.left_behind).toEqual(["img.png"]);++ // The human receipt names the residue too, in place. The folder holds+ // a note as well, so there is a move set; only the image stays.+ note("Projects/Ignored/a.md", "alpha\n");+ note("Projects/Ignored/keep.png", "png\n");+ const residueRun = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Ignored",+ "Archive",+ "--vault",+ vault,+ "--apply",+ ]);+ expect(residueRun.returncode).toBe(0);+ expect(residueRun.stdout).toContain("left behind (still in Projects/Ignored):");+ expect(residueRun.stdout).toContain("keep.png");+});++test("move-folder renders the moved list and failures on the human receipt too", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Old",+ "Archive",+ "--vault",+ vault,+ "--apply",+ ]);+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("move-folder: Projects/Old -> Archive/Old");+ expect(res.stdout).toContain("moved (1):");+ expect(res.stdout).toContain("Projects/Old/a.md -> Archive/Old/a.md");+});++test("move-folder names the relative embeds a Markdown-only move leaves dangling", async () => {+ note("Projects/Old/a.md", "\n");+ writeFileSync(join(vault, "Projects/Old/diagram.png"), "png\n");++ const res = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Old",+ "Archive",+ "--vault",+ vault,+ "--apply",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as {+ dangling_relative_links?: Array<{ note: string; target: string }>;+ left_behind?: string[];+ };+ // The JSON receipt names the pair, and the attachment is in the+ // residue: only Markdown moves, and the receipt says what that cost.+ expect(body.dangling_relative_links).toEqual([+ { note: "Archive/Old/a.md", target: "diagram.png" },+ ]);+ expect(body.left_behind).toEqual(["diagram.png"]);++ // The human receipt names the dangling spelling in place too.+ note("Projects/Embedded/a.md", "\n");+ writeFileSync(join(vault, "Projects/Embedded/diagram.png"), "png\n");+ const text = await runCli([+ "brain",+ "note-lifecycle",+ "move-folder",+ "Projects/Embedded",+ "Archive",+ "--vault",+ vault,+ "--apply",+ ]);+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("relative links now dangling");+ expect(text.stdout).toContain("Archive/Embedded/a.md: diagram.png");+});++test("rename-folder runs in the folder lifecycle through the same verb", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await runCli([+ "brain",+ "note-lifecycle",+ "rename-folder",+ "Projects/Old",+ "New",+ "--vault",+ vault,+ "--apply",+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as { action: string; to: string; moved: unknown[] };+ expect(body.action).toBe("rename-folder");+ expect(body.to).toBe("Projects/New");+ expect(body.moved).toEqual([{ from: "Projects/Old/a.md", to: "Projects/New/a.md" }]);+ expect(existsSync(join(vault, "Projects/New/a.md"))).toBe(true);+});diff --git a/tests/cli/brain-validate.test.ts b/tests/cli/brain-validate.test.tsnew file mode 100644index 00000000..6c0567b2--- /dev/null+++ b/tests/cli/brain-validate.test.ts@@ -0,0 +1,362 @@+/**+ * `o2b brain validate` - the standalone validation gate (t_dc782fd5,+ * task C4). Claims pinned here:+ *+ * 1. Selection is exactly one of `--paths` / `--dirty`; neither or both+ * is a usage error (exit 2), because whole-vault validation stays+ * doctor's job.+ * 2. Paths mode lints exactly the named set with the write-receipt+ * page-lint vocabulary: clean exits 0; an error finding exits 1.+ * 3. Warnings are non-blocking by default and block under `--strict`+ * (exit 2) - byte-for-byte the doctor exit contract.+ * 4. A named page the lint could not read is itself blocking (exit 1):+ * a gate that could not read what it was pointed at may not report+ * clean. An over-byte-cap skip is reported and non-blocking.+ * 5. A `--paths` spelling that escapes the vault is refused by name.+ * 6. Dirty mode lints every git-dirty Markdown note - modified, added+ * and untracked - and ignores dirty non-Markdown files; a vault that+ * is not a git worktree is a named refusal (exit 2), never a silent+ * clean pass.+ * 7. The gate is report-only: no `--apply`, no fix vocabulary.+ * 8. The verb is wired: router dispatch, `--help` usage text, manifest+ * row (so the derived help surfaces list it).+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++const CLEAN_PAGE = "---\ntitle: Clean\n---\n\nplain prose\n";+const ERROR_PAGE = "no frontmatter here\n";+const WARNING_PAGE = "---\ntitle: W\n---\n\nsee [[pref-ghost]]\n";++let tmp: string;+let vault: string;+let configPath: string;++function writePage(rel: string, text: string): string {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, text, "utf8");+ return rel;+}++/** Commit the vault's current state, making it a git worktree. */+function gitInit(): void {+ const run = (args: string[]) => execFileSync("git", ["-C", vault, ...args], { encoding: "utf8" });+ run(["init", "-q"]);+ run(["config", "user.email", "[email protected]"]);+ run(["config", "user.name", "test"]);+ run(["add", "-A"]);+ run(["commit", "-q", "-m", "base"]);+}++function run(args: ReadonlyArray<string>) {+ return runCli(["brain", "validate", ...args, "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-validate-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("selection", () => {+ test("neither selector is a usage error naming the rule", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ const r = await run([]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("--paths");+ expect(r.stderr).toContain("--dirty");+ });++ test("both selectors is a usage error", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ const r = await run(["--paths", "Brain/inbox/clean.md", "--dirty"]);+ expect(r.returncode).toBe(2);+ });++ test("a --paths spelling outside the vault is refused by name", async () => {+ const r = await run(["--paths", "../outside.md"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("../outside.md");+ });++ test("an empty --paths list is a usage error", async () => {+ const r = await run(["--paths"]);+ expect(r.returncode).toBe(2);+ });+});++describe("paths mode", () => {+ test("a clean named page exits 0 and says so", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ const r = await run(["--paths", "Brain/inbox/clean.md"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("ok");+ expect(r.stdout).toContain("Brain/inbox/clean.md");+ });++ test("an error finding exits 1 and names the page and the code", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ writePage("Brain/inbox/broken.md", ERROR_PAGE);+ // --paths is a repeatable flag (the parser's string-array convention),+ // one flag per page.+ const r = await run(["--paths", "Brain/inbox/clean.md", "--paths", "Brain/inbox/broken.md"]);+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("Brain/inbox/broken.md");+ expect(r.stdout).toContain("frontmatter-missing");+ });++ test("a warning is non-blocking by default and blocks under --strict", async () => {+ writePage("Brain/inbox/warn.md", WARNING_PAGE);+ const loose = await run(["--paths", "Brain/inbox/warn.md"]);+ expect(loose.returncode).toBe(0);+ expect(loose.stdout).toContain("broken-wikilink");+ const strict = await run(["--paths", "Brain/inbox/warn.md", "--strict"]);+ expect(strict.returncode).toBe(2);+ expect(strict.stdout).toContain("broken-wikilink");+ });++ test("an unreadable named page blocks even when nothing else is wrong", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ const r = await run(["--paths", "Brain/inbox/clean.md", "--paths", "Brain/inbox/gone.md"]);+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("Brain/inbox/gone.md");+ expect(r.stdout).toContain("page-unreadable");+ });++ test("--json carries the page-lint report shape and the verdict", async () => {+ writePage("Brain/inbox/warn.md", WARNING_PAGE);+ const r = await run(["--paths", "Brain/inbox/warn.md", "--strict", "--json"]);+ expect(r.returncode).toBe(2);+ const payload = JSON.parse(r.stdout) as {+ ok: boolean;+ selection: string;+ total: number;+ returned: number;+ truncated: boolean;+ findings: Array<{ code: string; page: string; severity: string; next_command?: string }>;+ skipped: Array<{ page: string; reason: string }>;+ };+ expect(payload.ok).toBe(false);+ expect(payload.selection).toBe("paths");+ expect(payload.total).toBe(1);+ expect(payload.truncated).toBe(false);+ expect(payload.findings[0]).toMatchObject({+ code: "broken-wikilink",+ page: "Brain/inbox/warn.md",+ severity: "warning",+ });+ expect(payload.skipped).toEqual([]);+ });++ test("the gate is report-only: --apply is not a flag it knows", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ // Unknown flags raise the parser's CliError, which the brain router+ // reports as `error: unknown flag: --apply` with exit 1 (the repo's+ // one contract for a flag no verb declares).+ const r = await run(["--paths", "Brain/inbox/clean.md", "--apply"]);+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("unknown flag: --apply");+ });+});++describe("dirty mode", () => {+ test("picks up modified, added and untracked Markdown and ignores non-Markdown", async () => {+ const base = writePage("Brain/inbox/base.md", CLEAN_PAGE);+ gitInit();+ // Modified...+ writePage(base, "---\ntitle: Clean\n---\n\nmore prose\n");+ // ...added (staged)...+ writePage("Brain/inbox/staged.md", CLEAN_PAGE);+ execFileSync("git", ["-C", vault, "add", "Brain/inbox/staged.md"]);+ // ...untracked...+ writePage("Brain/inbox/untracked.md", CLEAN_PAGE);+ // ...and a dirty non-Markdown file that must be ignored.+ writeFileSync(join(vault, "Brain", "scratch.txt"), "not a note\n");++ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("Brain/inbox/base.md");+ expect(r.stdout).toContain("Brain/inbox/staged.md");+ expect(r.stdout).toContain("Brain/inbox/untracked.md");+ expect(r.stdout).not.toContain("scratch.txt");+ expect(r.stdout).toContain("3 page");+ });++ test("a dirty error page blocks with exit 1", async () => {+ // A committed base page gives gitInit something to commit; the error+ // page stays untracked, exactly the population --dirty targets.+ writePage("Brain/inbox/base.md", CLEAN_PAGE);+ gitInit();+ writePage("Brain/inbox/untracked.md", ERROR_PAGE);+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("frontmatter-missing");+ });++ test("a vault that is not a git worktree refuses with exit 2, named", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("git");+ expect(r.stdout).not.toContain("ok");+ });++ test("a clean worktree is a clean pass, not an error", async () => {+ writePage("Brain/inbox/clean.md", CLEAN_PAGE);+ gitInit();+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("ok");+ });++ test("a staged rename lints the destination spelling git reports first", async () => {+ writePage("Brain/inbox/old-name.md", CLEAN_PAGE);+ gitInit();+ // In -z porcelain output a rename's entry carries the DESTINATION+ // and the next NUL field carries the origin - the reverse of the+ // line-oriented `old -> new` spelling. The gate lints the+ // destination, the spelling a commit would contain; the origin is+ // gone from disk and names no page to lint.+ execFileSync("git", ["-C", vault, "mv", "Brain/inbox/old-name.md", "Brain/inbox/new-name.md"]);+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("Brain/inbox/new-name.md");+ expect(r.stdout).not.toContain("old-name.md");+ expect(r.stdout).not.toContain("page-unreadable");+ });++ test("a page modified in the index and deleted from the worktree leaves nothing to lint", async () => {+ const page = writePage("Brain/inbox/gone.md", CLEAN_PAGE);+ gitInit();+ // Staged modification, then the worktree copy removed: the X/Y pair+ // is "MD", and the only truthful answer is that no page content a+ // commit would contain exists on disk.+ writePage(page, "---\ntitle: Gone\n---\n\nchanged\n");+ execFileSync("git", ["-C", vault, "add", page]);+ rmSync(join(vault, page));+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).not.toContain("gone.md");+ });++ test("a staged rename whose destination is then deleted leaves nothing to lint", async () => {+ writePage("Brain/inbox/old-name.md", CLEAN_PAGE);+ gitInit();+ // Staged rename, then the destination removed from the worktree: the+ // entry reads "RD", and neither spelling names a page a commit could+ // contain - the origin is gone by the rename, the destination by the+ // removal. Linting the destination spelled a page that is not on+ // disk, and the gate blocked on `page-unreadable`.+ execFileSync("git", ["-C", vault, "mv", "Brain/inbox/old-name.md", "Brain/inbox/new-name.md"]);+ rmSync(join(vault, "Brain", "inbox", "new-name.md"));+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("ok");+ expect(r.stdout).not.toContain("page-unreadable");+ });++ test("a vault whose top-level directory name starts with a space still lints its dirt", async () => {+ // The show-prefix is stripped of its trailing newline only: `.trim()`+ // would also strip the leading space of a top-level directory's+ // name, so no repo-relative path would match the prefix and the gate+ // would pass silently over the vault's real dirt.+ const repo = join(tmp, "repo");+ mkdirSync(join(repo, " notes", "Brain", "inbox"), { recursive: true });+ vault = join(repo, " notes");+ writeFileSync(configPath, `vault: ${vault}\n`);+ writePage("Brain/inbox/dirty.md", ERROR_PAGE);+ const git = (args: string[]) =>+ execFileSync("git", ["-C", repo, ...args], { encoding: "utf8" });+ git(["init", "-q"]);+ git(["config", "user.email", "[email protected]"]);+ git(["config", "user.name", "test"]);+ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("Brain/inbox/dirty.md");+ });++ test("a vault nested in a larger repository lints only the vault's own dirty pages", async () => {+ // The repo root is tmp, one level above the vault: git reports+ // repo-relative paths, so the gate must rebase them onto the vault+ // and must not inherit dirty Markdown that lives outside it.+ writePage("Brain/inbox/inner.md", CLEAN_PAGE);+ writeFileSync(join(tmp, "outside.md"), CLEAN_PAGE);+ const git = (args: string[]) => execFileSync("git", ["-C", tmp, ...args], { encoding: "utf8" });+ git(["init", "-q"]);+ git(["config", "user.email", "[email protected]"]);+ git(["config", "user.name", "test"]);+ git(["add", "-A"]);+ git(["commit", "-q", "-m", "base"]);+ writePage("Brain/inbox/inner.md", ERROR_PAGE);+ writeFileSync(join(tmp, "outside.md"), "no frontmatter here\n");++ const r = await run(["--dirty"]);+ expect(r.returncode).toBe(1);+ expect(r.stdout).toContain("Brain/inbox/inner.md");+ expect(r.stdout).not.toContain("outside.md");+ expect(r.stdout).not.toContain("page-unreadable");+ });++ test("a vault its enclosing repository ignores refuses, naming --paths as the remedy", async () => {+ // The M14 hole: `rev-parse --is-inside-work-tree` answers true inside+ // an ignored directory and `git status` omits ignored files, so a+ // vault a dotfiles or monorepo checkout ignores read as permanently+ // clean - dirty state git cannot measure, which the gate may never+ // report as a pass. The refusal names the selector that still works.+ const repo = join(tmp, "repo");+ mkdirSync(join(repo, "notes", "vault", "Brain", "inbox"), { recursive: true });+ vault = join(repo, "notes", "vault");+ writeFileSync(configPath, `vault: ${vault}\n`);+ const git = (args: string[]) =>+ execFileSync("git", ["-C", repo, ...args], { encoding: "utf8" });+ git(["init", "-q"]);+ git(["config", "user.email", "[email protected]"]);+ git(["config", "user.name", "test"]);+ writeFileSync(join(repo, ".gitignore"), "notes/\n");+ git(["add", ".gitignore"]);+ git(["commit", "-q", "-m", "base"]);+ writePage("Brain/inbox/broken.md", ERROR_PAGE);++ const dirty = await run(["--dirty"]);+ expect(dirty.returncode).toBe(2);+ expect(dirty.stderr).toContain("ignored");+ expect(dirty.stderr).toContain("--paths");++ // The remedy the refusal names still lints the broken note.+ const paths = await run(["--paths", "Brain/inbox/broken.md"]);+ expect(paths.returncode).toBe(1);+ expect(paths.stdout).toContain("frontmatter-missing");+ });+});++describe("wiring", () => {+ test("--help prints the verb's own usage", async () => {+ const r = await runCli(["brain", "validate", "--help"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout.startsWith("usage:")).toBe(true);+ expect(r.stdout).toContain("o2b brain validate");+ });++ test("the manifest carries the verb, so the derived help surfaces list it", async () => {+ const help = await runCli(["help"], { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } });+ expect(help.returncode).toBe(0);+ expect(help.stdout).toContain("brain validate");+ });+});diff --git a/tests/cli/doctor-exit.test.ts b/tests/cli/doctor-exit.test.tsindex bf175afd..3b2e3d7c 100644--- a/tests/cli/doctor-exit.test.ts+++ b/tests/cli/doctor-exit.test.ts@@ -135,9 +135,12 @@ describe("o2b doctor --readiness end to end", () => {const r = await runCli(["doctor", "--vault", tmp, "--readiness", "--json"], { env: env() });expect(r.returncode).toBe(DOCTOR_EXIT.probeIncomplete);const parsed = JSON.parse(r.stdout);- // Both readiness probes honestly report unknown for the same- // unreadable manifest: installed_runtimes and registered_commands.- expect(parsed.readiness_summary.unknown).toBe(2);+ // All three readiness probes honestly report unknown for the same+ // unreadable manifest: installed_runtimes, registered_commands and,+ // since v1.95.0, client_versions - its detection source is the same+ // install manifest, so a manifest nobody can read is a version+ // nobody can ask (an absent manifest would read skipped instead).+ expect(parsed.readiness_summary.unknown).toBe(3);expect(parsed.readiness_summary.failed).toBe(0);expect(parsed.readiness.some(diff --git a/tests/cli/export-redaction.test.ts b/tests/cli/export-redaction.test.tsindex 8ae23c1b..d231a4a9 100644--- a/tests/cli/export-redaction.test.ts+++ b/tests/cli/export-redaction.test.ts@@ -276,8 +276,106 @@ describe("an export with nothing to redact is byte-identical", () => {expect(r.stdout).toBe(exportPreferencesLlmsTxt(vault));});+ test("brain export --format json carries no omitted key when nothing is denied", async () => {+ // The json lane has no timestamp-free byte fixture to compare against,+ // so its byte-identity property is pinned through the envelope's+ // shape: the `omitted` field is absent-when-empty, which is what+ // keeps a reservation-free vault's bytes what they always were.+ await bootstrap();+ await seedPreference("alpha", "principle alpha");+ const r = await runCli(["brain", "export", "--vault", vault, "--format", "json"], ENV());+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;+ expect("omitted" in payload).toBe(false);+ // And nothing was withheld, so the omission notice is silent too.+ expect(r.stderr).not.toContain("left out");+ });+test("the byte-identity fixtures are not empty", () => {// A comparison over nothing passes for the wrong reason.expect(VENDOR_TOKEN.length).toBeGreaterThan(16);});});++describe("a visibility-reserved preference is left out and named by the shared lanes", () => {+ /** Hand-add an informal privacy marker, the way an operator does. */+ function stampPrefMarker(slug: string, line: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+ }++ /** Hand-edit the frontmatter id the same way an operator does. */+ function stampPrefId(slug: string, id: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^id: .*$/m, `id: ${id}`));+ }++ test("a reserved preference whose id carries URL credentials is named scrubbed, never raw", async () => {+ // The frontmatter id is read verbatim, so a hand-edited one can carry+ // a credential. The egress guard scrubs the identifier inside the+ // payload it releases; the stderr notices must name the SAME scrubbed+ // form on every lane, never the raw secret the vault still holds.+ await bootstrap();+ await seedPreference("reserved", "principle reserved");+ stampPrefMarker("reserved", "access: private");+ stampPrefId("reserved", "pref-https://bert:[email protected]/ops");++ const bank = await runCli(["brain", "bank-export", "--vault", vault], ENV());+ expect(bank.returncode).toBe(0);+ const payload = JSON.parse(bank.stdout) as {+ preferences_omitted?: ReadonlyArray<{ id: string }>;+ };+ expect(payload.preferences_omitted?.[0]?.id).toBe(+ `pref-https://${REDACTION_PLACEHOLDER}@internal.example/ops`,+ );+ expect(bank.stderr).toContain(`${REDACTION_PLACEHOLDER}@internal.example/ops`);+ expect(bank.stderr).toContain("left out");+ expect(bank.stderr).not.toContain("hunter2");++ const txt = await runCli(["brain", "export", "--vault", vault, "--format", "llms-txt"], ENV());+ expect(txt.returncode).toBe(0);+ expect(txt.stderr).toContain(`${REDACTION_PLACEHOLDER}@internal.example/ops`);+ expect(txt.stderr).toContain("left out");+ expect(txt.stderr).not.toContain("hunter2");+ expect(txt.stdout).not.toContain("hunter2");+ });++ test("bank-export omits it from the bundle and names it on stderr", async () => {+ await bootstrap();+ await seedPreference("reserved", "principle reserved");+ stampPrefMarker("reserved", "access: private");++ const r = await runCli(["brain", "bank-export", "--vault", vault], ENV());+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ preferences: ReadonlyArray<{ id: string }>;+ preferences_omitted?: ReadonlyArray<{+ id: string;+ reason: string;+ denied_by: string;+ }>;+ };+ expect(payload.preferences.map((p) => p.id)).toEqual([]);+ expect(payload.preferences_omitted).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "access" },+ ]);+ expect(r.stderr).toContain("pref-reserved");+ expect(r.stderr).toContain("left out");+ // stderr only: the bundle names the omission as data, not prose.+ expect(r.stdout).not.toContain("left out");+ });++ test("the bank bundle carries no preferences_omitted key when nothing is denied", async () => {+ // The bank bundle's byte-identity property, pinned through its shape:+ // the section-scoped omission field is absent-when-empty, so a vault+ // with no reservation serialises exactly the keys it always did.+ await bootstrap();+ await seedPreference("alpha", "principle alpha");++ const r = await runCli(["brain", "bank-export", "--vault", vault], ENV());+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;+ expect("preferences_omitted" in payload).toBe(false);+ expect(r.stderr).not.toContain("left out");+ });+});diff --git a/tests/cli/status.test.ts b/tests/cli/status.test.tsindex 85322afb..3798be81 100644--- a/tests/cli/status.test.ts+++ b/tests/cli/status.test.ts@@ -142,3 +142,40 @@ describe("o2b status — semantic fields (--json)", () => {expect(parsed.semantic_hint).toBeNull();});});++describe("o2b brain status — store group (t_cfe2ce5d)", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-status-store-"));+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ test("--json carries the store group and the human output carries the line", async () => {+ // `brain status` resolves its config through OPEN_SECOND_BRAIN_CONFIG+ // (brainVerbContext reads defaultConfigPath); an absent file is fine+ // because the vault is given explicitly.+ const env = {+ ...ENV_CLEAN,+ OPEN_SECOND_BRAIN_CONFIG: join(cfgDir, "config.yaml"),+ };+ const r = await runCli(["brain", "status", "--vault", vault, "--json"], { env });+ expect(r.returncode).toBe(0);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.store).toBeDefined();+ expect(parsed.store.writerLock).toBe("free");+ expect(parsed.store.writerLockOwner).toBeNull();+ expect(parsed.store.thisCaller).toBe("read-only");+ // The CLI payload is the operator's own read: local reach carries the+ // lock path so the operator can look at what holds it.+ expect(typeof parsed.store.writerLockPath).toBe("string");++ const human = await runCli(["brain", "status", "--vault", vault], { env });+ expect(human.returncode).toBe(0);+ expect(human.stdout).toContain("store: writer lock free");+ expect(human.stdout).toContain("this caller read-only");+ });+});diff --git a/tests/core/architecture/claim-attribution-census.test.ts b/tests/core/architecture/claim-attribution-census.test.tsindex 716baa9c..f5a8945b 100644--- a/tests/core/architecture/claim-attribution-census.test.ts+++ b/tests/core/architecture/claim-attribution-census.test.ts@@ -117,6 +117,11 @@ const PINNED_CONTINUITY_KINDS: ReadonlyArray<string> = Object.freeze([// confirmed receipt compaction. Disjoint from the Hermes// context-compaction kinds above by name and by producer."receipt_compaction",+ // The verified-delivery wave's additive kind (t_f8510c55): the+ // answer-quote-check hook's per-turn fold of per-injected-note+ // verdicts, session-keyed so the receipt read can join it. Written by+ // the hook only; the join reads it, no truth module appends it.+ "reply_presence",]);function truthModulePaths(): ReadonlyArray<string> {@@ -160,9 +165,11 @@ describe("claim-attribution census", () => {});test("(a) the continuity record-kind vocabulary is unchanged by the wave", () => {- // The wave introduces no new kind; the join reads existing- // `context_receipt` and `context_pack_outcome` rows. A new member- // here means a lane is minting a record kind the plan refused.+ // The wave's one additive kind, `reply_presence`, is pinned above+ // with its provenance; the join itself still reads existing+ // `context_receipt` and `context_pack_outcome` rows. Any member+ // beyond the pin means a lane is minting a record kind nothing+ // declared.const kinds = continuityKindVocabulary();expect(kinds.toSorted()).toEqual(PINNED_CONTINUITY_KINDS.toSorted());});diff --git a/tests/core/architecture/content-class-census.test.ts b/tests/core/architecture/content-class-census.test.tsindex 141962a8..e693dbf9 100644--- a/tests/core/architecture/content-class-census.test.ts+++ b/tests/core/architecture/content-class-census.test.ts@@ -28,7 +28,10 @@* unambiguous flag names the egress census reads);* 2. it redacts through the shared guard (`redactForEgress`);* 3. it composes vault page material: it imports a composer from the- * portability surface or the brain-export modules.+ * portability surface or the brain-export modules. The brain-export+ * arm reads the import's BINDINGS, not just its module path, because+ * the shared denial notice rides the same module and composes+ * nothing - see `importsPageComposer`.** All three, because each alone over- or under-states: a destination* without the guard is the egress census's finding, not this one's; the@@ -45,7 +48,13 @@* construction) and the decision-model routes. None imports a page* composer, so none is in population; the continuity and explorer* decisions are recorded in their registry reasons (commit 887cb142),- * and the snapshot carries no vault content at all.+ * and the snapshot carries no vault content at all. The explorer's+ * static export reads one helper from the brain-export module - the+ * denial notice it prints beside its reservation omissions (commit+ * 0d00e879) - so the composer rule credits a brain-export import only+ * when it binds something beyond that notice pair; the rows it+ * exports never take the prompt-derived stamp, and the registry+ * reason says so.* - A class filter delegated more than ONE hop. The knowledge-pack verb* composes through `selectKnowledgePack`, whose module applies the* filter inside `pageBlockReason`; that is the one named delegation@@ -104,9 +113,56 @@ function namedStringParamRe(names: ReadonlyArray<string>): RegExp {const DESTINATION_RE = namedStringParamRe(DESTINATION_NAMES);-/** A composer import: the portability surface or the brain-export modules. */-const COMPOSER_IMPORT_RE =- /from\s*"[^"]*(?:\/portability\/[^"]*|\/brain\/export(?:-transcripts)?\.ts)"/;+/**+ * A composer import from the portability surface or the transcript+ * export module. The brain-export module (`src/core/brain/export.ts`)+ * is handled by `importsPageComposer`, which reads the import's+ * bindings before crediting it.+ */+const PORTABILITY_OR_TRANSCRIPTS_IMPORT_RE =+ /from\s*"[^"]*(?:\/portability\/[^"]*|\/brain\/export-transcripts\.ts)"/;++/** One `import { ... } from "<...>/brain/export.ts"` statement. */+const BRAIN_EXPORT_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*"[^"]*\/brain\/export\.ts"/g;++/**+ * The shared denial notice and its row type. They ride the brain-export+ * module but compose nothing: they are the omission report an exporter+ * prints BESIDE the payload. The explorer's static export pulls exactly+ * this pair to name its reservation omissions (commit 0d00e879), so a+ * module-level path match would place a no-composer site in population+ * and demand a class filter the registry already records as removing+ * nothing - preference and retired rows never take the prompt-derived+ * stamp.+ */+const DENIAL_NOTICE_BINDINGS: ReadonlySet<string> = new Set([+ "preferenceDenialNotice",+ "PreferenceDenial",+]);++/**+ * Whether the module imports a page composer. A brain-export import is+ * a composer import only when it binds something beyond the denial+ * notice pair - a text census cannot otherwise tell the exporters'+ * composer imports from the explorer's notice import, because both name+ * the same module.+ */+function importsPageComposer(withoutComments: string): boolean {+ if (PORTABILITY_OR_TRANSCRIPTS_IMPORT_RE.test(withoutComments)) return true;+ for (const match of withoutComments.matchAll(BRAIN_EXPORT_IMPORT_RE)) {+ const bindings = (match[1] ?? "")+ .split(",")+ .map((binding) =>+ binding+ .trim()+ .replace(/^type\s+/, "")+ .trim(),+ )+ .filter((binding) => binding.length > 0);+ if (bindings.some((binding) => !DENIAL_NOTICE_BINDINGS.has(binding))) return true;+ }+ return false;+}/** The shared egress guard. A module that calls it redacts on the way out. */const GUARD_RE = /\bredactForEgress\s*\(/;@@ -154,7 +210,7 @@ function isPageCarryingRedactor(text: string): boolean {return (DESTINATION_RE.test(views.withoutComments) &&GUARD_RE.test(views.code) &&- COMPOSER_IMPORT_RE.test(views.withoutComments)+ importsPageComposer(views.withoutComments));}@@ -175,7 +231,7 @@ function classFilterCensus(files: ReadonlyArray<CensusFile>): ReadonlyArray<striif (!DESTINATION_RE.test(views.withoutComments) ||!GUARD_RE.test(views.code) ||- !COMPOSER_IMPORT_RE.test(views.withoutComments)+ !importsPageComposer(views.withoutComments)) {continue;}@@ -231,9 +287,12 @@ describe("content-class egress census", () => {expect(undeclared).toEqual([]);});+ // The census scans the whole source tree; it measured 2.0-4.5 s on main+ // and brushes the 5 s default on slower runners as the tree grows, so it+ // carries its own budget instead of riding the default.test("every page-carrying site applies the class filter", () => {expect(classFilterCensus(SOURCE_TREE)).toEqual([]);- });+ }, 20000);test("the pack verb's delegated filter is really there", () => {// The one hop the census credits. If the selection step's block scan@@ -332,6 +391,33 @@ describe("the content-class census cannot pass by finding nothing", () => {const text = readFileSync(join(REPO_ROOT, "src/cli/brain/verbs/continuity.ts"), "utf8");expect(isPageCarryingRedactor(text)).toBe(false);});++ test("the explorer's brain-export imports bind only the denial notice", () => {+ // The one module whose composer verdict turns on import BINDINGS+ // rather than the module path. If a composer binding ever joins the+ // explorer's brain-export import, the explorer becomes a+ // page-carrying shared export: the equality test above fails until+ // it is named and filtered, and this pin is the signpost naming+ // which import moved.+ const text = readFileSync(join(REPO_ROOT, "src/cli/brain/verbs/explorer.ts"), "utf8");+ const views = lexSource(text);+ const imports = [...views.withoutComments.matchAll(BRAIN_EXPORT_IMPORT_RE)].map((m) =>+ (m[1] ?? "")+ .split(",")+ .map((binding) =>+ binding+ .trim()+ .replace(/^type\s+/, "")+ .trim(),+ )+ .filter((binding) => binding.length > 0),+ );+ expect(imports.length).toBeGreaterThanOrEqual(1);+ for (const bindings of imports) {+ expect(bindings.every((binding) => DENIAL_NOTICE_BINDINGS.has(binding))).toBe(true);+ }+ expect(isPageCarryingRedactor(text)).toBe(false);+ });});describe("the class policy is disclosed where an operator reads", () => {diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex dfd04f53..ec7d4c05 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -580,6 +580,19 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object"reports a verdict saying the archive it took does not cover a note living " +"outside `Brain/`.",},+ "src/core/brain/notes/folder-lifecycle.ts": {+ categories: [C.lifecycleMove],+ calls: ["rmdirSync", "unlinkSync"],+ reason:+ "the folder move's per-file relocation rides the file surface's own shared " ++ "helpers, so the module's direct calls are the emptied-directories prune and " ++ "one fault cleanup: `rmdirSync` removes each directory the moves emptied, " ++ "deepest first, and refuses a non-empty directory, so a folder whose subtree " ++ "still holds a failed file keeps it; the one `unlinkSync` drops a destination " ++ "name a mid-set fault linked after the source name's drop had already failed, " ++ "with the source name still holding that inode. No byte is ever reached, and " ++ "the report names where every file stands.",+ },"src/core/brain/recompile.ts": {categories: [C.lifecycleMove],calls: ["renameSync"],@@ -1362,7 +1375,7 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);* (`src/core/brain/pledge-intake.ts`) - one rmSync that resets the vault to* the pre-intake state, its re-anchor rewrite still on the shared writer.*/-const DIRECT_WRITE_ROWS = 85;+const DIRECT_WRITE_ROWS = 86;/*** Measured modules reaching a write through a shared helper. An equality.@@ -1620,7 +1633,7 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(* (`src/core/brain/pledge-intake.ts`) - a reset to the pre-intake state* stamps no channel either.*/-const UNSTAMPED_DIRECT_ROWS = 84;+const UNSTAMPED_DIRECT_ROWS = 85;/*** Shared-helper write sites the stamp does not reach, measured the samediff --git a/tests/core/brain.operator-snapshot.test.ts b/tests/core/brain.operator-snapshot.test.tsindex c4cdadb2..b9b610ae 100644--- a/tests/core/brain.operator-snapshot.test.ts+++ b/tests/core/brain.operator-snapshot.test.ts@@ -20,6 +20,7 @@ import { resolveSignal } from "../../src/core/brain/diagnostics.ts";import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { resolveSearchConfig } from "../../src/core/search/index.ts";let tmp: string;@@ -98,3 +99,94 @@ describe("buildOperatorSnapshot", () => {}});});++describe("buildOperatorSnapshot store group (t_cfe2ce5d)", () => {+ /** The search index path the snapshot's own probe reads, for lock staging. */+ function dbPath(): string {+ return resolveSearchConfig({ vault: tmp }).dbPath;+ }++ /**+ * The lock directory `proper-lockfile` takes: `mkdirSync(`${dbPath}.lock`)`,+ * the exact shape `lockfile.lockSync` creates (getLockFile in+ * proper-lockfile/lib/lockfile.js).+ */+ function takeWriterLock(): string {+ const lockDir = `${dbPath()}.lock`;+ mkdirSync(lockDir, { recursive: true });+ return lockDir;+ }++ test("no lock directory reads free", async () => {+ const snap = await buildOperatorSnapshot(tmp, { now: new Date("2026-07-18T12:00:00Z") });+ expect(snap.store.writerLock).toBe("free");+ expect(snap.store.writerLockReason).toBeNull();+ expect(snap.store.writerLockAgeMs).toBeNull();+ expect(snap.store.writerLockPath).toBe(dbPath());+ expect(snap.store.thisCaller).toBe("read-only");+ });++ test("a lock directory created the way proper-lockfile takes the lock reads held with a non-negative age", async () => {+ takeWriterLock();+ const snap = await buildOperatorSnapshot(tmp, { now: new Date("2026-07-18T12:00:00Z") });+ expect(snap.store.writerLock).toBe("held");+ expect(snap.store.writerLockAgeMs).not.toBeNull();+ expect(snap.store.writerLockAgeMs!).toBeGreaterThanOrEqual(0);+ // v1 truth: the lock record is a bare directory carrying no identity,+ // so the owner field reads null rather than inventing a holder.+ expect(snap.store.writerLockOwner).toBeNull();+ });++ test("an injected throw reads unknown with the errno in the reason", async () => {+ const failure = Object.assign(new Error("permission denied"), { code: "EACCES" });+ const snap = await buildOperatorSnapshot(tmp, {+ now: new Date("2026-07-18T12:00:00Z"),+ writerLockHeldAt: () => {+ throw failure;+ },+ });+ expect(snap.store.writerLock).toBe("unknown");+ expect(snap.store.writerLockReason).toContain("EACCES");+ expect(snap.store.writerLockAgeMs).toBeNull();+ });++ test("a held lock is a live writer, not a fault: healthy stays true and problems are unchanged", async () => {+ const before = await buildOperatorSnapshot(tmp, { now: new Date("2026-07-18T12:00:00Z") });+ takeWriterLock();+ const held = await buildOperatorSnapshot(tmp, { now: new Date("2026-07-18T12:00:00Z") });+ expect(held.healthy).toBe(true);+ expect(held.problems).toEqual(before.problems);+ });++ test("the renderer prints the store line on both branches", async () => {+ const clear = await buildOperatorSnapshot(tmp, { now: new Date("2026-07-18T12:00:00Z") });+ expect(renderOperatorSnapshot(clear)).toContain("store: writer lock free");++ takeWriterLock();+ const held = await buildOperatorSnapshot(tmp, { now: new Date("2026-07-18T12:00:00Z") });+ const heldText = renderOperatorSnapshot(held);+ expect(heldText).toContain("store: writer lock held");+ // The owner's absence is a stated measurement, not a gap.+ expect(heldText).toContain("carries no identity");+ // The refusal is scoped to what the lock actually gates - index+ // writers only. The brain lane serializes on its own lock files, so+ // an unscoped "a write now would refuse" told every agent reading+ // this card that a memory write would fail when it would not (M8).+ expect(heldText).toContain(+ "an index write (o2b search index / reindex) would refuse with INDEX_LOCKED",+ );+ expect(heldText).toContain("vault and memory writes are not gated by this lock");+ expect(heldText).toContain("this caller read-only");++ const unclear = await buildOperatorSnapshot(tmp, {+ now: new Date("2026-07-18T12:00:00Z"),+ writerLockHeldAt: () => {+ throw Object.assign(new Error("permission denied"), { code: "EACCES" });+ },+ });+ const unclearText = renderOperatorSnapshot(unclear);+ expect(unclearText).toContain("store: writer lock state unknown");+ expect(unclearText).toContain("EACCES");+ expect(unclearText).toContain("this caller read-only");+ });+});diff --git a/tests/core/brain/answer-quotes/check.test.ts b/tests/core/brain/answer-quotes/check.test.tsindex 3340edf2..639aed86 100644--- a/tests/core/brain/answer-quotes/check.test.ts+++ b/tests/core/brain/answer-quotes/check.test.ts@@ -57,13 +57,14 @@ function verdictOf(answer: string, evidence: AnswerQuoteEvidence = TEXT): string}describe("ANSWER_QUOTE_VERDICT vocabulary", () => {- test("carries exactly the five pinned verdicts, in order", () => {+ test("carries exactly the six pinned verdicts, in order", () => {expect(ANSWER_QUOTE_VERDICT).toEqual({verified: "verified",notInNote: "not-in-note",sourceTruncated: "source-truncated",noteUnavailable: "note-unavailable",notText: "not-text",+ absent: "absent",});expect(ANSWER_QUOTE_VERDICTS).toEqual(["verified",@@ -71,6 +72,7 @@ describe("ANSWER_QUOTE_VERDICT vocabulary", () => {"source-truncated","note-unavailable","not-text",+ "absent",]);});diff --git a/tests/core/brain/context-pack-tail-trim.test.ts b/tests/core/brain/context-pack-tail-trim.test.tsnew file mode 100644index 00000000..7eb07713--- /dev/null+++ b/tests/core/brain/context-pack-tail-trim.test.ts@@ -0,0 +1,674 @@+/**+ * Score-aware tail trim for delivered evidence (t_cb6a5558).+ *+ * The trim runs after the unified tier/budget walk, only when the caller+ * opted in via `tailTrim` AND a query is present to score against. It+ * keeps the pack's top delivered items, keeps any tail item whose+ * query-term COVERAGE - the fraction of the query's tokens the item+ * carries - is at least TAIL_TRIM_KEEP_FRACTION of the top delivered+ * item's (it restates the question's terms), drops the rest whole with+ * `"tail-trim"` skips, and offers the freed budget back to+ * `over-budget` candidates in priority order.+ *+ * Claims pinned here:+ * 1. An absent option, an explicit false, a flag-on pack without a+ * query, and a flag-on pack with a tokenless query are all+ * byte-identical to the legacy pack.+ * 2. The trim keeps top-3 head items immune: a head item below the+ * bar survives while an equal-scoring tail item is dropped.+ * 3. The restatement keep-rule scores query-term coverage, so a long+ * body carrying every query term is kept whatever its length, and+ * the rule fires exactly at the fraction: a tail item at 0.8+ * coverage is kept.+ * 4. Dropped tail items become whole `"tail-trim"` skip entries and+ * the telemetry gap `tail_trim`; the report counters and the+ * receipt/telemetry budget metadata carry the trim only when it ran.+ * 5. The rescue re-admits `over-budget` candidates in priority order+ * within `maxTokens`, retracts their `over-budget` skips, and never+ * reorders or drops the synthesized attention item.+ * 6. The trim scores coverage in every mode - ranked included - never+ * the ranked comparator's jaccard, whose union grows with the+ * page's own length.+ * 7. The `packingPolicy` branch is untouched: a named policy never+ * produces the trim report.+ */++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 { packContext } from "../../../src/core/brain/context-pack.ts";+import { listAttentionFlows } from "../../../src/core/brain/attention-flows.ts";+import { listContextReceipts } from "../../../src/core/brain/context-receipts.ts";+import { RECALL_CHANNEL, listRecallTelemetry } from "../../../src/core/brain/recall-telemetry.ts";++let vault: string;++/** Five tokens, so the ranked-mode jaccard fractions land on controllable values. */+const QUERY = "alpha beta gamma delta epsilon";++/**+ * Four tokens, so a page that fuses the query's last term into a+ * longer token (`delta-off`) passes the substring filter while its+ * coverage - 3 of 4 terms, 0.75 - lands below the 0.8 bar. (With five+ * query terms the same trick misses one term and scores exactly 0.8,+ * which the inclusive bar keeps.)+ */+const PARTIAL_QUERY = "alpha beta gamma delta";++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-pack-tail-trim-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function writePref(+ slug: string,+ fields: { principle: string; created_at: string; body?: string },+): void {+ const lines = [+ "---",+ `id: pref-${slug}`,+ "topic: a b",+ `principle: ${fields.principle}`,+ "tier: core",+ `created_at: ${fields.created_at}`,+ "---",+ "",+ fields.body ?? "",+ ];+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"));+}++/**+ * Five pages whose `topic` tokenises to nothing and whose principle+ * carries the query verbatim, so substring mode keeps every page and+ * recency alone decides the delivery order. Every page covers all five+ * query terms - coverage 1.0 each - so the trim has nothing to drop+ * here; the flag-off byte-identity pins use it, and the trim-active+ * tests use {@link writePartialTailVault}, whose pages separate.+ */+function writeRestatementVault(): void {+ writePref("a", { principle: QUERY, created_at: "2026-05-05T00:00:00Z" });+ writePref("b", { principle: QUERY, created_at: "2026-05-04T00:00:00Z", body: "zeta" });+ writePref("c", {+ principle: QUERY,+ created_at: "2026-05-03T00:00:00Z",+ body: "zeta eta theta",+ });+ writePref("d", { principle: QUERY, created_at: "2026-05-02T00:00:00Z", body: "zeta" });+ writePref("e", {+ principle: QUERY,+ created_at: "2026-05-01T00:00:00Z",+ body: "zeta eta theta iota kappa lambda mu nu",+ });+}++/**+ * Five pages in recency order whose trim scores separate under+ * query-term coverage ({@link PARTIAL_QUERY}): a, b and c restate the+ * query verbatim; d restates it just as fully and carries a LONG body+ * that repeats every query term - coverage 1.0, where the jaccard+ * kernel the ranked comparator uses scores it 1/3 because the union+ * grows with the page's own vocabulary (the M1 defect: the trim kept+ * the short ones, not the restating ones); e passes the substring+ * filter only by fusing the query's last term into a longer token+ * (`delta-off`), so it covers 3 of the 4 query terms - 0.75, below+ * the bar.+ */+function writePartialTailVault(): void {+ writePref("a", { principle: PARTIAL_QUERY, created_at: "2026-05-05T00:00:00Z" });+ writePref("b", { principle: PARTIAL_QUERY, created_at: "2026-05-04T00:00:00Z", body: "zeta" });+ writePref("c", {+ principle: PARTIAL_QUERY,+ created_at: "2026-05-03T00:00:00Z",+ body: "zeta eta theta",+ });+ writePref("d", {+ principle: PARTIAL_QUERY,+ created_at: "2026-05-02T00:00:00Z",+ body: "zeta eta theta iota kappa lambda mu nu alpha beta gamma delta",+ });+ writePref("e", {+ principle: "alpha beta gamma delta-off",+ created_at: "2026-05-01T00:00:00Z",+ body: "omega",+ });+}++describe("packContext tailTrim byte identity", () => {+ test("an absent option and an explicit false are byte-identical", () => {+ writeRestatementVault();+ const absent = packContext(vault, { maxTokens: 10_000, query: QUERY });+ const off = packContext(vault, { maxTokens: 10_000, query: QUERY, tailTrim: false });+ expect(off.tailTrim).toBeUndefined();+ expect(JSON.stringify(off)).toBe(JSON.stringify(absent));+ // Nothing was trimmed: all five pages delivered in recency order.+ expect(absent.items.map((i) => i.id)).toEqual([+ "pref-a",+ "pref-b",+ "pref-c",+ "pref-d",+ "pref-e",+ ]);+ expect(absent.skipped).toEqual([]);+ });++ test("the flag on without a query is byte-identical - there is nothing to score against", () => {+ writeRestatementVault();+ const baseline = packContext(vault, { maxTokens: 10_000 });+ const noQuery = packContext(vault, { maxTokens: 10_000, tailTrim: true });+ expect(noQuery.tailTrim).toBeUndefined();+ expect(JSON.stringify(noQuery)).toBe(JSON.stringify(baseline));+ });++ test("the flag on with a tokenless query is byte-identical", () => {+ writeRestatementVault();+ // Ranked mode: no substring filter to trip, so the only difference a+ // tokenless query could make is the trim - and a query that+ // tokenises to nothing scores every candidate 0, cannot+ // discriminate, and must not run.+ const baseline = packContext(vault, { maxTokens: 10_000, query: " ", queryMode: "ranked" });+ const tokenless = packContext(vault, {+ maxTokens: 10_000,+ query: " ",+ queryMode: "ranked",+ tailTrim: true,+ });+ expect(tokenless.tailTrim).toBeUndefined();+ expect(JSON.stringify(tokenless)).toBe(JSON.stringify(baseline));+ });+});++describe("packContext tailTrim trim and keep rules", () => {+ test("substring mode: a tail item that restates every query term is kept whatever its length", () => {+ writePartialTailVault();+ const r = packContext(vault, { maxTokens: 10_000, query: PARTIAL_QUERY, tailTrim: true });+ // Head (3) immune: pref-a, pref-b, pref-c. The tail keeps pref-d -+ // coverage 1.0, every query term present even though the body is+ // the longest of the set - at the 0.8 bar, and drops pref-e (3 of+ // 4 terms, 0.75) whole. Under the jaccard kernel this trim ran+ // backwards: d's own vocabulary scored it 1/3 while the short,+ // partial e scored 3/5 and survived - the trim kept the short+ // ones, not the restating ones.+ expect(r.items.map((i) => i.id)).toEqual(["pref-a", "pref-b", "pref-c", "pref-d"]);+ const drop = r.skipped.find((s) => s.reason === "tail-trim");+ expect(drop).toEqual({ id: "pref-e", tokens: expect.any(Number), reason: "tail-trim" });+ expect(drop!.tokens).toBeGreaterThan(0);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 1,+ rescued: 0,+ tokensSaved: drop!.tokens,+ });+ // The freed budget is visible in the recomputed spend.+ expect(r.tokensUsed).toBe(r.items.reduce((sum, item) => sum + item.tokens, 0));+ });++ test("ranked mode: head immunity beats the bar - an equal-scoring tail item drops", () => {+ // pref-pa covers every query term (1.0); pb/pc/pd cover three of+ // the five (0.6 each). Ranked order: pa, then the three ties by+ // recency. The head keeps pb and pc even though both sit below the+ // 0.8 bar; pd, the equal-scoring tail item, is dropped - position,+ // not score, shields the head.+ writePref("pa", { principle: QUERY, created_at: "2026-05-04T00:00:00Z" });+ writePref("pb", { principle: "alpha beta gamma", created_at: "2026-05-03T00:00:00Z" });+ writePref("pc", { principle: "alpha beta gamma", created_at: "2026-05-02T00:00:00Z" });+ writePref("pd", { principle: "alpha beta gamma", created_at: "2026-05-01T00:00:00Z" });+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: QUERY,+ queryMode: "ranked",+ tailTrim: true,+ });+ expect(r.items.map((i) => i.id)).toEqual(["pref-pa", "pref-pb", "pref-pc"]);+ expect(r.skipped.map((s) => ({ id: s.id, reason: s.reason }))).toEqual([+ { id: "pref-pd", reason: "tail-trim" },+ ]);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 0,+ rescued: 0,+ tokensSaved: r.skipped[0]!.tokens,+ });+ });++ test("ranked mode: a long body carrying every query term is kept though the comparator ranked it last", () => {+ // The M1 case in the mode with no substring filter: pref-long+ // covers all five query terms inside a long body - coverage 1.0 -+ // but its own vocabulary drags the comparator's jaccard to 5/15,+ // ranking it last of four. The trim's keep rule scores coverage:+ // the long page stays, where the jaccard kernel dropped it.+ writePref("top", { principle: QUERY, created_at: "2026-05-04T00:00:00Z" });+ writePref("mid1", { principle: QUERY, created_at: "2026-05-03T00:00:00Z", body: "zeta" });+ writePref("mid2", { principle: QUERY, created_at: "2026-05-02T00:00:00Z", body: "zeta eta" });+ writePref("long", {+ principle: QUERY,+ created_at: "2026-05-01T00:00:00Z",+ body: "zeta eta theta iota kappa lambda mu nu xi omicron alpha beta gamma delta epsilon",+ });+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: QUERY,+ queryMode: "ranked",+ tailTrim: true,+ });+ expect(r.items.map((i) => i.id)).toEqual(["pref-top", "pref-mid1", "pref-mid2", "pref-long"]);+ expect(r.skipped).toEqual([]);+ expect(r.tailTrim).toEqual({ dropped: 0, keptByQueryTerms: 1, rescued: 0, tokensSaved: 0 });+ });++ test("ranked mode scores coverage, not the comparator: a tail item exactly at the fraction is kept", () => {+ // Coverage: p1 1.0 (the principle carries the whole query), p2 0.8+ // (four of five terms; the body adds none), p3 0.8, p4 0.8 (its+ // body's `delta` is the fifth term's own token), p5 0. The ranked+ // COMPARATOR still scores jaccard: p1 1.0, p3 0.8, p4 0.8, p2 2/3+ // (its extra body token inflates the union), p5 0 - so the+ // delivery order is p1, p3, p4, p2, p5 and p2 sits in the tail.+ // The trim scores coverage: p2's 0.8 is AT the bar and is kept+ // although its comparator score would have dropped it; p5 drops+ // whole.+ writePref("p1", { principle: QUERY, created_at: "2026-05-05T00:00:00Z" });+ writePref("p2", {+ principle: "alpha beta gamma delta",+ created_at: "2026-05-04T00:00:00Z",+ body: "zeta",+ });+ writePref("p3", { principle: "alpha beta gamma delta", created_at: "2026-05-03T00:00:00Z" });+ writePref("p4", {+ principle: "alpha beta gamma",+ created_at: "2026-05-02T00:00:00Z",+ body: "delta",+ });+ writePref("p5", {+ principle: "unrelated words about caching systems",+ created_at: "2026-05-01T00:00:00Z",+ });+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: QUERY,+ queryMode: "ranked",+ tailTrim: true,+ });+ expect(r.items.map((i) => i.id)).toEqual(["pref-p1", "pref-p3", "pref-p4", "pref-p2"]);+ expect(r.skipped.map((s) => ({ id: s.id, reason: s.reason }))).toEqual([+ { id: "pref-p5", reason: "tail-trim" },+ ]);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 1,+ rescued: 0,+ tokensSaved: r.skipped[0]!.tokens,+ });+ });++ test("ranked mode, a real-token query matching nothing: the zero bar keeps every delivered item", () => {+ // The query tokenises (so the trim runs - a tokenless query never+ // would) but shares no token with any page: every score is 0, the top+ // delivered score is 0, and the keep bar is 0 with it. Nothing was+ // dropped, so nothing is rescued and nothing is saved; the tail items+ // sit exactly AT the bar (0 >= 0) and are kept - a query that cannot+ // discriminate must not trim the pack it also could not rank.+ writePref("z1", {+ principle: "unrelated words about caching systems",+ created_at: "2026-05-05T00:00:00Z",+ });+ writePref("z2", {+ principle: "unrelated words about caching systems",+ created_at: "2026-05-04T00:00:00Z",+ body: "zeta",+ });+ writePref("z3", {+ principle: "unrelated words about caching systems",+ created_at: "2026-05-03T00:00:00Z",+ body: "zeta eta theta",+ });+ writePref("z4", {+ principle: "unrelated words about caching systems",+ created_at: "2026-05-02T00:00:00Z",+ body: "zeta",+ });+ writePref("z5", {+ principle: "unrelated words about caching systems",+ created_at: "2026-05-01T00:00:00Z",+ body: "zeta eta theta iota kappa lambda mu nu",+ });+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: "omega sigma tau",+ queryMode: "ranked",+ tailTrim: true,+ });+ // All scores 0: the ranked order falls through to recency, and the+ // whole delivered set survives the trim whole.+ expect(r.items.map((i) => i.id)).toEqual([+ "pref-z1",+ "pref-z2",+ "pref-z3",+ "pref-z4",+ "pref-z5",+ ]);+ expect(r.skipped).toEqual([]);+ expect(r.tailTrim).toEqual({ dropped: 0, keptByQueryTerms: 2, rescued: 0, tokensSaved: 0 });+ });++ test("a trim that ran but had no tail still reports, with zero counters", () => {+ writePref("s1", { principle: QUERY, created_at: "2026-05-03T00:00:00Z" });+ writePref("s2", { principle: QUERY, created_at: "2026-05-02T00:00:00Z", body: "zeta" });+ writePref("s3", { principle: QUERY, created_at: "2026-05-01T00:00:00Z", body: "zeta" });+ const r = packContext(vault, { maxTokens: 10_000, query: QUERY, tailTrim: true });+ expect(r.items.map((i) => i.id)).toEqual(["pref-s1", "pref-s2", "pref-s3"]);+ expect(r.tailTrim).toEqual({ dropped: 0, keptByQueryTerms: 0, rescued: 0, tokensSaved: 0 });+ });+});++describe("packContext tailTrim counters under the char ceiling and the freed budget", () => {+ test("the char ceiling cutting kept-tail items recounts the trim report", () => {+ // Ranked order (the comparator still scores jaccard): p1 (1.0),+ // p2 (0.8), p3 (5/7), p5 and p6 (2/3 each), p4 (3/7). The walk+ // (maxTokens 8) delivers all six. Coverage: p1 1.0, p2 0.8, p3+ // 1.0, p5 0.8, p6 0.8, p4 0.6 - the trim keeps the head p1-p3+ // immune, keeps p5 and p6 at the bar and drops p4 whole, freeing+ // its 2 tokens with no over-budget candidate to rescue.+ writePref("p1", { principle: QUERY, created_at: "2026-05-06T00:00:00Z" });+ writePref("p2", {+ principle: "alpha beta gamma delta",+ created_at: "2026-05-05T00:00:00Z",+ });+ writePref("p3", { principle: QUERY, created_at: "2026-05-04T00:00:00Z", body: "x1 x2" });+ writePref("p4", {+ principle: "alpha beta gamma",+ created_at: "2026-05-03T00:00:00Z",+ body: "z1 z2",+ });+ writePref("p5", {+ principle: "alpha beta gamma delta",+ created_at: "2026-05-02T00:00:00Z",+ body: "q1",+ });+ writePref("p6", {+ principle: "alpha beta gamma delta",+ created_at: "2026-05-01T00:00:00Z",+ body: "q2",+ });+ // The uncapped pack: p4 dropped whole (freed 2), p5 and p6 kept at+ // the tail - where the char ceiling later cuts from.+ const uncapped = packContext(vault, {+ maxTokens: 8,+ query: QUERY,+ queryMode: "ranked",+ tailTrim: true,+ });+ expect(uncapped.items.map((i) => i.id)).toEqual([+ "pref-p1",+ "pref-p2",+ "pref-p3",+ "pref-p5",+ "pref-p6",+ ]);+ expect(uncapped.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 2,+ rescued: 0,+ tokensSaved: expect.any(Number),+ });+ const headChars = uncapped.items.slice(0, 3).reduce((sum, item) => sum + item.body.length, 0);+ const drop = uncapped.skipped.find((skip) => skip.reason === "tail-trim")!;++ // A char budget that keeps exactly the head: both kept-tail items+ // are cut from the emitted set, and the report must describe what+ // actually shipped - nothing the trim kept by query terms+ // survived.+ const r = packContext(vault, {+ maxTokens: 8,+ query: QUERY,+ queryMode: "ranked",+ tailTrim: true,+ maxTotalChars: headChars,+ });+ expect(r.items.map((i) => i.id)).toEqual(["pref-p1", "pref-p2", "pref-p3"]);+ expect(r.skipped.map((s) => ({ id: s.id, reason: s.reason }))).toEqual([+ { id: "pref-p4", reason: "tail-trim" },+ { id: "pref-p5", reason: "over-char-budget" },+ { id: "pref-p6", reason: "over-char-budget" },+ ]);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 0,+ rescued: 0,+ tokensSaved: drop.tokens,+ });+ });++ test("the rescue spends the freed budget, never the walk's leftover slack", () => {+ // q1..q3 are the immune head; q4's principle fuses the query's+ // last term into a longer token, so it passes the substring filter+ // while covering 3 of the 4 query terms (0.75 < 0.8) and drops+ // whole (the freed budget); q5 and q6 cover every term and clear+ // the rescue bar. The walk cap leaves q5 and q6 over-budget with+ // one token of slack, and the two rescued together would re-spend+ // MORE than the trim freed - the freed budget is the rescue's+ // whole allowance, so only q5 fits and tokensSaved never goes+ // negative.+ const stem = "alpha beta gamma delta";+ writePref("q1", { principle: stem, created_at: "2026-05-06T00:00:00Z", body: "aaa" });+ writePref("q2", { principle: stem, created_at: "2026-05-05T00:00:00Z", body: "aaa" });+ writePref("q3", { principle: stem, created_at: "2026-05-04T00:00:00Z", body: "aaa" });+ writePref("q4", {+ principle: `${stem}-miss`,+ created_at: "2026-05-03T00:00:00Z",+ body: "aaa bbb ccc",+ });+ writePref("q5", { principle: stem, created_at: "2026-05-02T00:00:00Z", body: "aaa bbb" });+ writePref("q6", { principle: stem, created_at: "2026-05-01T00:00:00Z", body: "aaa bbb" });+ const probe = packContext(vault, { maxTokens: 10_000, query: stem, tailTrim: false });+ const tokens = new Map(probe.items.map((item) => [item.id, item.tokens]));+ const freed = tokens.get("pref-q4")!;+ const candidate = tokens.get("pref-q5")!;+ expect(freed).toBe(3);+ expect(candidate).toBe(2);+ // q1..q4 deliver; q5 goes over the cap by exactly its last token.+ const delivered = probe.items.slice(0, 4).reduce((sum, item) => sum + item.tokens, 0);+ const maxTokens = delivered + candidate - 1;++ const r = packContext(vault, { maxTokens, query: stem, tailTrim: true });+ expect(r.items.map((i) => i.id)).toEqual(["pref-q1", "pref-q2", "pref-q3", "pref-q5"]);+ expect(r.skipped.map((s) => ({ id: s.id, reason: s.reason }))).toEqual([+ { id: "pref-q6", reason: "over-budget" },+ { id: "pref-q4", reason: "tail-trim" },+ ]);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 0,+ rescued: 1,+ tokensSaved: freed - candidate,+ });+ expect(r.tokensUsed).toBeLessThanOrEqual(maxTokens);+ });+});++describe("packContext tailTrim rescue", () => {+ test("freed budget is offered to over-budget candidates in priority order within maxTokens", () => {+ // Substring mode keeps every page whose principle carries the+ // query and recency decides the walk order. p4's principle fuses+ // the query's last term into a longer token, so it passes the+ // substring filter while covering 3 of the 4 query terms (0.75 <+ // 0.8). Tokens: p1 0, p2 3, p3 3, p4 2, p5 1, p6 1. maxTokens 8:+ // the walk delivers p1-p4 (used 8) and reports p5 and p6+ // over-budget. The trim drops p4 whole, freeing 2 tokens; the+ // rescue then re-admits p5 (1.0 >= 0.8) and p6 (1.0 >= 0.8) in+ // walk order.+ const stem = "alpha beta gamma delta";+ writePref("p1", { principle: stem, created_at: "2026-05-06T00:00:00Z" });+ writePref("p2", { principle: stem, created_at: "2026-05-05T00:00:00Z", body: "x1 x2 x3 x4" });+ writePref("p3", { principle: stem, created_at: "2026-05-04T00:00:00Z", body: "y1 y2 y3 y4" });+ writePref("p4", {+ principle: `${stem}-partial`,+ created_at: "2026-05-03T00:00:00Z",+ body: "z1 z2",+ });+ writePref("p5", { principle: stem, created_at: "2026-05-02T00:00:00Z", body: "z1" });+ writePref("p6", { principle: stem, created_at: "2026-05-01T00:00:00Z", body: "z1" });+ const r = packContext(vault, { maxTokens: 8, query: stem, tailTrim: true });+ // p4 dropped whole, p5 and p6 rescued at the tail in priority order.+ expect(r.items.map((i) => i.id)).toEqual([+ "pref-p1",+ "pref-p2",+ "pref-p3",+ "pref-p5",+ "pref-p6",+ ]);+ expect(r.skipped).toEqual([{ id: "pref-p4", tokens: expect.any(Number), reason: "tail-trim" }]);+ expect(r.tailTrim).toEqual({ dropped: 1, keptByQueryTerms: 0, rescued: 2, tokensSaved: 0 });+ expect(r.tokensUsed).toBeLessThanOrEqual(8);+ });++ test("an over-budget candidate below the restatement bar keeps its over-budget skip", () => {+ const stem = "alpha beta gamma delta";+ writePref("p1", { principle: stem, created_at: "2026-05-05T00:00:00Z" });+ writePref("p2", { principle: stem, created_at: "2026-05-04T00:00:00Z", body: "x1 x2 x3 x4" });+ writePref("p3", { principle: stem, created_at: "2026-05-03T00:00:00Z", body: "y1 y2 y3 y4" });+ // p4's fused last term covers 3 of the 4 query terms (0.75 < 0.8):+ // delivered, in the tail, and dropped whole - the freed budget.+ writePref("p4", {+ principle: `${stem}-partial`,+ created_at: "2026-05-02T00:00:00Z",+ body: "z1 z2",+ });+ // p5 is older, over-budget at the walk, and below the bar: the+ // rescue must not re-admit it even though it would fit.+ writePref("p5", {+ principle: `${stem}-partial`,+ created_at: "2026-05-01T00:00:00Z",+ body: "z1 z2",+ });+ const r = packContext(vault, { maxTokens: 8, query: stem, tailTrim: true });+ expect(r.items.map((i) => i.id)).toEqual(["pref-p1", "pref-p2", "pref-p3"]);+ // Skips keep walk order (p5 went over-budget first); the trim's+ // whole-item drop appends after.+ expect(r.skipped.map((s) => ({ id: s.id, reason: s.reason }))).toEqual([+ { id: "pref-p5", reason: "over-budget" },+ { id: "pref-p4", reason: "tail-trim" },+ ]);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 0,+ rescued: 0,+ tokensSaved: r.skipped[1]!.tokens,+ });+ });++ test("the rescue never touches the synthesized attention item", () => {+ writePartialTailVault();+ listAttentionFlows(vault); // bootstraps the default flow fixtures+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: PARTIAL_QUERY,+ tailTrim: true,+ attentionFlowIds: ["open-loops"],+ });+ // The attention block sits at the head, inside the immune keep+ // count, and stays first after the trim. The tail past the head+ // keeps pref-c and pref-d - both cover every query term, d's long+ // body included - and drops pref-e (0.75) whole.+ expect(r.items[0]!.id).toBe("attention-flows");+ expect(r.items.map((i) => i.id)).toEqual([+ "attention-flows",+ "pref-a",+ "pref-b",+ "pref-c",+ "pref-d",+ ]);+ expect(r.skipped.filter((s) => s.id === "attention-flows")).toEqual([]);+ expect(r.skipped.map((s) => s.id)).toEqual(["pref-e"]);+ expect(r.tailTrim).toEqual({+ dropped: 1,+ keptByQueryTerms: 2,+ rescued: 0,+ tokensSaved: expect.any(Number),+ });+ });+});++describe("packContext tailTrim telemetry and receipts", () => {+ test("the trim counters ride the receipt budget and the telemetry metadata, and the gap surfaces", () => {+ writePartialTailVault();+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: PARTIAL_QUERY,+ tailTrim: true,+ receipt: { trigger: "context_pack", host: "tail-trim-test" },+ telemetry: { host: "tail-trim-test", channel: RECALL_CHANNEL.cli },+ });+ expect(r.tailTrim).toBeDefined();+ const telemetryRecords = listRecallTelemetry(vault, { mode: "context_pack" });+ expect(telemetryRecords).toHaveLength(1);+ const metadata = telemetryRecords[0]!.payload["metadata"] as Record<string, unknown>;+ expect(metadata["tail_trim_dropped"]).toBe(1);+ expect(metadata["tail_trim_kept_by_query_terms"]).toBe(1);+ expect(metadata["tail_trim_rescued"]).toBe(0);+ expect(metadata["tail_trim_tokens_saved"]).toBe(r.tailTrim!.tokensSaved);+ expect(telemetryRecords[0]!.payload["gaps"]).toContain("tail_trim");+ const receiptRecords = listContextReceipts(vault);+ expect(receiptRecords).toHaveLength(1);+ const budget = receiptRecords[0]!.payload["budget"] as Record<string, unknown>;+ expect(budget["tail_trim_dropped"]).toBe(1);+ expect(budget["tail_trim_kept_by_query_terms"]).toBe(1);+ expect(budget["tail_trim_rescued"]).toBe(0);+ expect(budget["tail_trim_tokens_saved"]).toBe(r.tailTrim!.tokensSaved);+ });++ test("an untrimmed pack carries no trim counters and no tail_trim gap", () => {+ writeRestatementVault();+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: QUERY,+ receipt: { trigger: "context_pack", host: "tail-trim-test" },+ telemetry: { host: "tail-trim-test", channel: RECALL_CHANNEL.cli },+ });+ expect(r.tailTrim).toBeUndefined();+ const telemetryRecords = listRecallTelemetry(vault, { mode: "context_pack" });+ expect(telemetryRecords).toHaveLength(1);+ const metadata = telemetryRecords[0]!.payload["metadata"] as Record<string, unknown>;+ expect("tail_trim_dropped" in metadata).toBe(false);+ expect("tail_trim_tokens_saved" in metadata).toBe(false);+ expect(telemetryRecords[0]!.payload["gaps"]).not.toContain("tail_trim");+ const receiptRecords = listContextReceipts(vault);+ expect(receiptRecords).toHaveLength(1);+ const budget = receiptRecords[0]!.payload["budget"] as Record<string, unknown>;+ expect("tail_trim_dropped" in budget).toBe(false);+ });+});++describe("packContext tailTrim scope", () => {+ test("the packingPolicy branch never produces the trim report", () => {+ writePref("a", { principle: QUERY, created_at: "2026-05-02T00:00:00Z" });+ writeFileSync(+ join(vault, "Brain", "retired", "retired-old.md"),+ [+ "---",+ "id: retired-old",+ "topic: a b",+ `principle: ${QUERY}`,+ "tier: core",+ "created_at: 2026-05-01T00:00:00Z",+ "---",+ "",+ "zeta",+ ].join("\n"),+ );+ const r = packContext(vault, {+ maxTokens: 10_000,+ query: QUERY,+ tailTrim: true,+ packingPolicy: "facts_first",+ });+ expect(r.packing).toBeDefined();+ expect(r.tailTrim).toBeUndefined();+ });+});diff --git a/tests/core/brain/context-receipts.test.ts b/tests/core/brain/context-receipts.test.tsindex 937d2dbf..3c9e9899 100644--- a/tests/core/brain/context-receipts.test.ts+++ b/tests/core/brain/context-receipts.test.ts@@ -1,19 +1,27 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";import { tmpdir } from "node:os";-import { join } from "node:path";-import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";+import {+ appendContinuityRecord,+ listContinuityRecords,+} from "../../../src/core/brain/continuity/store.ts";+import type { ContinuityRecord } from "../../../src/core/brain/continuity/types.ts";import { packContext } from "../../../src/core/brain/context-pack.ts";import {CONTEXT_RECEIPT_TRIGGERS,emitContextReceipt,isContextReceiptTrigger,+ lookupReceiptReplyPresence,+ summarizeContextReceipt,} from "../../../src/core/brain/context-receipts.ts";+import { reachView } from "../../../src/core/brain/reach-view.ts";import { brainActivePath } from "../../../src/core/brain/paths.ts";import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";import { writePreference } from "../../../src/core/brain/preference.ts";import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";let vault: string;@@ -139,6 +147,474 @@ describe("context receipts", () => {});});+// ----- receipt reply-presence join (t_f8510c55) ---------------------------++describe("receipt reply-presence join", () => {+ test("a sibling record joins by exact session_id", () => {+ const receipt = emitReceipt("session-join");+ const presence = appendPresence("session-join", "2026-05-31T12:05:00.000Z", [+ {+ path: "Brain/preferences/pref-alpha.md",+ start_line: 3,+ end_line: 5,+ verdict: "verified",+ },+ { path: "Brain/preferences/pref-bravo.md", verdict: "absent" },+ ]);++ const join = lookupReceiptReplyPresence(vault, receipt);+ expect(join).toEqual({+ joined: true,+ presence: {+ record_id: presence.id,+ created_at: "2026-05-31T12:05:00.000Z",+ checked: 2,+ per_note: [+ {+ path: "Brain/preferences/pref-alpha.md",+ start_line: 3,+ end_line: 5,+ verdict: "verified",+ },+ { path: "Brain/preferences/pref-bravo.md", verdict: "absent" },+ ],+ },+ });+ });++ test("a note no span measured reads absent, never verified", () => {+ const receipt = emitReceipt("session-absent-note");+ appendPresence("session-absent-note", "2026-05-31T12:05:00.000Z", [+ {+ path: "Brain/preferences/pref-alpha.md",+ start_line: 1,+ end_line: 2,+ verdict: "not-in-note",+ },+ { path: "Brain/preferences/pref-bravo.md", verdict: "absent" },+ ]);++ const join = lookupReceiptReplyPresence(vault, receipt);+ if (!join.joined) throw new Error("expected the sibling record to join");+ expect(join.presence.per_note.map((note) => note.verdict)).toEqual(["not-in-note", "absent"]);+ });++ test("no key match reads unjoined, never an inferred window match", () => {+ const receipt = emitReceipt("session-lonely");+ // A presence record from ANOTHER session, recorded inside the same+ // minute: the join is keyed, so this record must not be pulled in.+ appendPresence("session-other", "2026-05-31T12:00:30.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ ]);++ const join = lookupReceiptReplyPresence(vault, receipt);+ expect(join).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-lonely",+ });+ });++ test("a receipt with no session key reads unjoined, naming no session", () => {+ const receipt = emitReceipt(undefined);+ appendPresence(undefined, "2026-05-31T12:05:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ ]);++ const join = lookupReceiptReplyPresence(vault, receipt);+ expect(join).toEqual({ joined: false, reason: "unjoined" });+ expect("session_id" in join).toBe(false);+ });++ test("the fold spans every sibling from the receipt onward, the newest readable record naming the join", () => {+ const receipt = emitReceipt("session-turns");+ appendPresence("session-turns", "2026-05-31T12:01:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ ]);+ const later = appendPresence("session-turns", "2026-05-31T12:09:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "not-in-note" },+ { path: "Brain/preferences/pref-bravo.md", verdict: "verified" },+ ]);++ const join = lookupReceiptReplyPresence(vault, receipt);+ if (!join.joined) throw new Error("expected the sibling records to fold");+ // The join names the newest record the fold drew from, but the+ // verdicts are the FOLD's: alpha verified at 12:01 and missed at+ // 12:09 reads verified - a hit anywhere in the receipt's lifetime+ // wins over a later turn's miss.+ expect(join.presence.record_id).toBe(later.id);+ expect(join.presence.created_at).toBe("2026-05-31T12:09:00.000Z");+ expect(join.presence.checked).toBe(3);+ expect(join.presence.per_note).toEqual([+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ { path: "Brain/preferences/pref-bravo.md", verdict: "verified" },+ ]);+ });++ test("a receipt folds the presence records written at or after it, verified winning across turns", () => {+ // The review's timeline: R1 (10:00, note a), P1 (10:01, a verified),+ // R2 (10:05, note b), P2 (10:06, a zero-span turn whose every note+ // reads absent), R3 (10:30, note c). The Stop hook writes a record on+ // every checked turn, including turns that quote nothing, so the+ // newest record is usually an all-absent one - a receipt must never+ // read that newer absence over its own lifetime's verification.+ const noteA = "Brain/notes/note-a.md";+ const noteB = "Brain/notes/note-b.md";+ const noteC = "Brain/notes/note-c.md";+ const r1 = emitReceiptAt("session-timeline", "2026-05-31T10:00:00.000Z", [noteA]);+ appendPresence("session-timeline", "2026-05-31T10:01:00.000Z", [+ { path: noteA, start_line: 2, end_line: 3, verdict: "verified" },+ ]);+ const r2 = emitReceiptAt("session-timeline", "2026-05-31T10:05:00.000Z", [noteB]);+ const p2 = appendPresence(+ "session-timeline",+ "2026-05-31T10:06:00.000Z",+ [+ { path: noteA, verdict: "absent" },+ { path: noteB, verdict: "absent" },+ ],+ 0,+ );+ const r3 = emitReceiptAt("session-timeline", "2026-05-31T10:30:00.000Z", [noteC]);++ // R1 joins the fold from P1 onward: a's 10:01 verification survives+ // the later all-absent turn, and the join reports only the note R1+ // itself injected - never P2's row for b.+ const r1Join = lookupReceiptReplyPresence(vault, r1);+ if (!r1Join.joined) throw new Error("expected R1 to join the fold");+ expect(r1Join.presence.record_id).toBe(p2.id);+ expect(r1Join.presence.created_at).toBe("2026-05-31T10:06:00.000Z");+ expect(r1Join.presence.checked).toBe(1);+ expect(r1Join.presence.per_note).toEqual([+ { path: noteA, start_line: 2, end_line: 3, verdict: "verified" },+ ]);+ // Several answers fed the fold, so no single answer text hash binds+ // it: the member would claim a binding the fold cannot honor.+ expect("source_hash" in r1Join.presence).toBe(false);++ // R2 joins only what was written at or after it - P2 alone - so b+ // reads absent HONESTLY: that turn really quoted nothing. The record+ // R2's join names is P2, not the older P1.+ const r2Join = lookupReceiptReplyPresence(vault, r2);+ if (!r2Join.joined) throw new Error("expected R2 to join the fold");+ expect(r2Join.presence.record_id).toBe(p2.id);+ expect(r2Join.presence.checked).toBe(0);+ expect(r2Join.presence.per_note).toEqual([{ path: noteB, verdict: "absent" }]);++ // R3 was written after the last presence record: nothing answers it,+ // and the join says so instead of reaching back to a record that+ // predates R3's own injection.+ expect(lookupReceiptReplyPresence(vault, r3)).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-timeline",+ });+ });++ test("a receipt joins no presence record that predates it, however readable", () => {+ // A record written before the receipt describes turns the receipt's+ // injections did not exist for: joining it would answer the receipt+ // with checks it never benefited from.+ const receipt = emitReceiptAt("session-earlier", "2026-05-31T12:05:00.000Z", [+ "Brain/notes/note-a.md",+ ]);+ appendPresence("session-earlier", "2026-05-31T12:00:00.000Z", [+ { path: "Brain/notes/note-a.md", verdict: "verified" },+ ]);++ expect(lookupReceiptReplyPresence(vault, receipt)).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-earlier",+ });+ });++ test("a receipt whose only in-window records are unreadable reads unjoined, keyed", () => {+ // The walk-back stays per-record: an unreadable record is skipped,+ // never reported as the join - and a window holding nothing readable+ // is the named absence, not a reach-back before the receipt.+ const receipt = emitReceiptAt("session-late-corrupt", "2026-05-31T12:05:00.000Z", [+ "Brain/notes/note-a.md",+ ]);+ appendPresence("session-late-corrupt", "2026-05-31T12:00:00.000Z", [+ { path: "Brain/notes/note-a.md", verdict: "verified" },+ ]);+ appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-31T12:09:00.000Z",+ payload: {+ session_id: "session-late-corrupt",+ checked: 2,+ per_note: "not-an-array",+ },+ });++ expect(lookupReceiptReplyPresence(vault, receipt)).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-late-corrupt",+ });+ });++ test("per_note lists only the notes the receipt itself injected", () => {+ // The hook's record covers the session's whole ledger; the receipt's+ // join covers the receipt. A row for a note this receipt never+ // injected is not this receipt's history to report.+ const noteA = "Brain/notes/note-a.md";+ const noteB = "Brain/notes/note-b.md";+ const receipt = emitReceiptAt("session-scope", "2026-05-31T12:00:00.000Z", [noteA]);+ appendPresence("session-scope", "2026-05-31T12:01:00.000Z", [+ { path: noteA, verdict: "not-in-note" },+ { path: noteB, start_line: 1, end_line: 2, verdict: "not-in-note" },+ ]);++ const join = lookupReceiptReplyPresence(vault, receipt);+ if (!join.joined) throw new Error("expected the sibling record to join");+ expect(join.presence.per_note).toEqual([{ path: noteA, verdict: "not-in-note" }]);+ expect(join.presence.per_note.map((note) => note.path)).not.toContain(noteB);+ });++ test("a note missed in one turn and untouched in the next reads its strongest measured miss", () => {+ // Across the fold, `absent` neither upgrades nor downgrades a miss a+ // measured turn recorded: the note was checked once and missed, and+ // the untouched turn adds nothing to that finding.+ const noteA = "Brain/notes/note-a.md";+ const receipt = emitReceiptAt("session-miss-fold", "2026-05-31T12:00:00.000Z", [noteA]);+ appendPresence("session-miss-fold", "2026-05-31T12:01:00.000Z", [+ { path: noteA, start_line: 4, verdict: "not-in-note" },+ ]);+ const p2 = appendPresence(+ "session-miss-fold",+ "2026-05-31T12:06:00.000Z",+ [{ path: noteA, verdict: "absent" }],+ 0,+ );++ const join = lookupReceiptReplyPresence(vault, receipt);+ if (!join.joined) throw new Error("expected the sibling records to fold");+ expect(join.presence.record_id).toBe(p2.id);+ expect(join.presence.checked).toBe(1);+ expect(join.presence.per_note).toEqual([+ { path: noteA, start_line: 4, verdict: "not-in-note" },+ ]);+ });++ test("a fold over exactly one record carries that record's answer hash", () => {+ const receipt = emitReceipt("session-single-hash");+ const only = appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-31T12:05:00.000Z",+ payload: {+ session_id: "session-single-hash",+ checked: 1,+ per_note: [{ path: "Brain/preferences/pref-alpha.md", verdict: "not-in-note" }],+ source_hash: "b".repeat(64),+ },+ });++ const join = lookupReceiptReplyPresence(vault, receipt);+ if (!join.joined) throw new Error("expected the sibling record to join");+ expect(join.presence.record_id).toBe(only.id);+ expect(join.presence.source_hash).toBe("b".repeat(64));+ expect(join.presence.per_note).toEqual([+ { path: "Brain/preferences/pref-alpha.md", verdict: "not-in-note" },+ ]);+ });++ test("a page reserved against remote reads drops its row below local reach, counted as withheld", () => {+ const receipt = emitReceipt("session-reserved");+ // The pages the Stop hook recorded, both injected by this receipt:+ // one public, one that reserves itself against remote reads with the+ // formal token.+ writePage("Brain/preferences/pref-alpha.md", "Public body.\n");+ writePage(+ "Brain/preferences/pref-bravo.md",+ "---\nvisibility: private\n---\n\nWithheld plan body.\n",+ );+ appendPresence("session-reserved", "2026-05-31T12:05:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ {+ path: "Brain/preferences/pref-bravo.md",+ start_line: 3,+ end_line: 4,+ verdict: "verified",+ },+ ]);++ const below = lookupReceiptReplyPresence(+ vault,+ receipt,+ reachView(vault, TRANSPORT_REACH.remote),+ );+ if (!below.joined) throw new Error("expected the sibling record to join");+ expect(below.presence.per_note.map((note) => note.path)).toEqual([+ "Brain/preferences/pref-alpha.md",+ ]);+ // The drop is reported, never silent: the caller can tell a truncated+ // join from a session that checked one note.+ expect(below.presence.withheld).toBe(1);++ // Local reach keeps everything, and names no withholding.+ const local = lookupReceiptReplyPresence(+ vault,+ receipt,+ reachView(vault, TRANSPORT_REACH.local),+ );+ if (!local.joined) throw new Error("expected the sibling record to join");+ expect(local.presence.per_note.map((note) => note.path)).toEqual([+ "Brain/preferences/pref-alpha.md",+ "Brain/preferences/pref-bravo.md",+ ]);+ expect("withheld" in local.presence).toBe(false);+ });++ test("a row whose page cannot be read is withheld below local reach too, never shown", () => {+ // The fail-closed half of the same predicate: a path no file answers+ // (deleted or renamed since the hook recorded it) has an unknowable+ // visibility, and an unknowable claim is not the absence of one. The+ // unreadable path is one the receipt injected, so the withholding is+ // this join's to report.+ const receipt = emitReceipt("session-unmeasurable");+ writePage("Brain/preferences/pref-alpha.md", "Public body.\n");+ appendPresence("session-unmeasurable", "2026-05-31T12:05:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ { path: "Brain/preferences/pref-bravo.md", verdict: "not-in-note" },+ ]);++ const below = lookupReceiptReplyPresence(+ vault,+ receipt,+ reachView(vault, TRANSPORT_REACH.remote),+ );+ if (!below.joined) throw new Error("expected the sibling record to join");+ expect(below.presence.per_note.map((note) => note.path)).toEqual([+ "Brain/preferences/pref-alpha.md",+ ]);+ expect(below.presence.withheld).toBe(1);+ });++ test("a corrupt latest sibling walks back to the latest readable one", () => {+ const receipt = emitReceipt("session-corrupt");+ appendPresence("session-corrupt", "2026-05-31T12:01:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ ]);+ // A hand-edited or truncated line: the record exists and names the+ // session, but its payload carries no readable per-note list.+ appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-31T12:09:00.000Z",+ payload: {+ session_id: "session-corrupt",+ checked: 3,+ per_note: "not-an-array",+ },+ });++ const join = lookupReceiptReplyPresence(vault, receipt);+ if (!join.joined) throw new Error("expected the readable sibling to join");+ expect(join.presence.created_at).toBe("2026-05-31T12:01:00.000Z");+ expect(join.presence.per_note.map((note) => note.verdict)).toEqual(["verified"]);+ });++ test("a session whose every sibling is unreadable reads unjoined, keyed", () => {+ const receipt = emitReceipt("session-all-corrupt");+ appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-31T12:09:00.000Z",+ payload: {+ session_id: "session-all-corrupt",+ checked: 1,+ per_note: { broken: true },+ },+ });++ const join = lookupReceiptReplyPresence(vault, receipt);+ expect(join).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-all-corrupt",+ });+ });++ test("the summary carries the join only when one is handed to it", () => {+ const receipt = emitReceipt("session-summary");+ const join = lookupReceiptReplyPresence(vault, receipt);++ // No join computed (the list path): no member at all.+ expect("reply_presence" in summarizeContextReceipt(receipt)).toBe(false);+ // The unjoined outcome rides the summary verbatim (the show path's+ // honest absence - never silently dropped).+ const unjoined = summarizeContextReceipt(receipt, join);+ expect(unjoined.reply_presence).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-summary",+ });++ appendPresence("session-summary", "2026-05-31T12:05:00.000Z", [+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ ]);+ const joined = summarizeContextReceipt(receipt, lookupReceiptReplyPresence(vault, receipt));+ if (!joined.reply_presence?.joined) throw new Error("expected the join to land");+ expect(joined.reply_presence.presence.per_note).toEqual([+ { path: "Brain/preferences/pref-alpha.md", verdict: "verified" },+ ]);+ });+});++function emitReceipt(sessionId: string | undefined): ContinuityRecord {+ return emitContextReceipt(vault, {+ options: {+ host: "unit-test",+ trigger: "session_inject",+ createdAt: "2026-05-31T12:00:00.000Z",+ ...(sessionId !== undefined ? { sessionId } : {}),+ },+ items: [+ { id: "pref-alpha", path: "Brain/preferences/pref-alpha.md" },+ { id: "pref-bravo", path: "Brain/preferences/pref-bravo.md" },+ ],+ finalText: "eager layer text",+ });+}++/** A receipt created at a chosen instant, injecting exactly the named notes. */+function emitReceiptAt(+ sessionId: string,+ createdAt: string,+ paths: ReadonlyArray<string>,+): ContinuityRecord {+ return emitContextReceipt(vault, {+ options: { host: "unit-test", trigger: "session_inject", createdAt, sessionId },+ items: paths.map((path) => ({ id: path, path })),+ finalText: "eager layer text",+ });+}++function appendPresence(+ sessionId: string | undefined,+ createdAt: string,+ perNote: ReadonlyArray<Record<string, unknown>>,+ checked: number = perNote.length,+): ContinuityRecord {+ return appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt,+ payload: {+ ...(sessionId !== undefined ? { session_id: sessionId } : {}),+ checked,+ per_note: perNote,+ },+ });+}++/** A plain vault page at a vault-relative path, frontmatter and all. */+function writePage(rel: string, body: string): void {+ const abs = join(vault, rel);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, body, "utf8");+}+function writePref(slug: string, topic: string, principle: string, body: string): void {writePreference(vault, {slug,diff --git a/tests/core/brain/dead-letter-recovery.test.ts b/tests/core/brain/dead-letter-recovery.test.tsnew file mode 100644index 00000000..404cd1c9--- /dev/null+++ b/tests/core/brain/dead-letter-recovery.test.ts@@ -0,0 +1,730 @@+/**+ * The dead-letter recovery classifier (one-command recovery,+ * t_50794f57). Claims pinned here:+ *+ * 1. The classifier is total over five honest states: `recover` (v2+ * payload, session still capture-classified, missing items not yet+ * on disk), `pending` (the session's items sit staged in the+ * write-approval queue), `re-extract` (no frozen payload to re-run),+ * `not_recoverable` (unknown lane, unknown session, or a session the+ * capture boundary now refuses), and `resolved` (every missing key+ * now exists on disk - the retention rule's fifth state, so a+ * reconciled row never reads as still-broken).+ * 2. Every actionable state carries the exact copy-paste command;+ * `not_recoverable` and `resolved` carry none.+ * 3. The recovery plan labels each recorded item `write`, `staged`,+ * `dedup` or `refused` with the same gates, in the same order, the+ * commit itself applies.+ * 4. `applyRecovery` re-runs the recorded payload at CURRENT vault+ * state: already-written items dedup away, nothing stale is+ * replayed, and the letter survives - nothing in the project deletes+ * a dead letter.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ DEAD_LETTER_LANES,+ deadLetterDir,+ deadLetterPath,+ isDeadLetterLane,+ readDeadLetter,+ recordDeadLetter,+ type DeadLetterEnvelopeIdentity,+ type DeadLetterRecord,+} from "../../../src/core/brain/dead-letter.ts";+import {+ DEAD_LETTER_RECOVERY_CATEGORY,+ DeadLetterRecoveryError,+ applyRecovery,+ classifyDeadLetter,+ planRecovery,+} from "../../../src/core/brain/dead-letter-recovery.ts";+import {+ commitExtractedSignals,+ type ExtractedSignalItem,+} from "../../../src/core/brain/extract-signals.ts";+import { computeDedupHash } from "../../../src/core/brain/dedup-hash.ts";+import { redactRawOutput } from "../../../src/core/redactor.ts";+import { DURABILITY_DENYLIST_ENV_KEY } from "../../../src/core/brain/gates/durability.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";+import { brainConfigPath, brainDirs } from "../../../src/core/brain/paths.ts";+import { importSessionRecall } from "../../../src/core/brain/session-recall.ts";+import { buildReconciliationReport } from "../../../src/core/reconciliation-report.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const NOW = new Date("2026-08-23T10:15:00Z");+const SESSION = "sess-recover";+const AGENT = "tester";+const V1_FIXTURE_ID = "extract-signals-0123456789ab";++let vault: string;++function item(overrides: Partial<ExtractedSignalItem> = {}): ExtractedSignalItem {+ return {+ topic: "release-notes-style",+ signal: "positive",+ principle: "Name the release theme in the heading, never the ticket id.",+ confidence: 0.9,+ ...overrides,+ };+}++const ENVELOPE: DeadLetterEnvelopeIdentity = Object.freeze({+ lane: "extract-signals",+ step: "extract-signals",+ reference: SESSION,+ target: "Brain/inbox",+});++function report(items: number, missingKeys: ReadonlyArray<string>) {+ return buildReconciliationReport({+ attempted: items,+ found: items - missingKeys.length,+ missing: missingKeys,+ });+}++/** A well-formed schema-2 letter over `items`, naming `missingKeys`. */+function v2Letter(+ items: ReadonlyArray<ExtractedSignalItem>,+ missingKeys: ReadonlyArray<string>,+ reference = SESSION,+): DeadLetterRecord {+ return recordDeadLetter(vault, {+ envelope: { ...ENVELOPE, reference },+ report: report(items.length, missingKeys),+ firstError: "EIO: i/o error",+ now: NOW,+ payload: { items: [...items] },+ });+}++/**+ * A schema-2 letter frozen the way the extractor now freezes one: each+ * item's free-text fields redacted, the RAW text's dedup hash stored+ * beside it (`dead-letter.test.ts` pins the freeze itself; the tests+ * below pin what recovery reads out of that shape).+ */+function frozenLetter(+ items: ReadonlyArray<ExtractedSignalItem>,+ missingKeys: ReadonlyArray<string>,+): DeadLetterRecord {+ return recordDeadLetter(vault, {+ envelope: ENVELOPE,+ report: report(items.length, missingKeys),+ firstError: "EIO: i/o error",+ now: NOW,+ payload: {+ items: items.map((entry) => {+ const scope = entry.scope?.trim();+ return {+ topic: entry.topic,+ signal: entry.signal,+ principle: redactRawOutput(entry.principle),+ confidence: entry.confidence,+ ...(scope !== undefined && scope !== "" ? { scope: redactRawOutput(scope) } : {}),+ dedup_hash: computeDedupHash({+ topic: entry.topic,+ signal: entry.signal,+ principle: entry.principle,+ ...(scope !== undefined && scope !== "" ? { scope } : {}),+ }),+ };+ }),+ },+ });+}++/** Hand-write a record exactly as schema v1 wrote it: payload-less. */+function v1Letter(missingKeys: ReadonlyArray<string>): DeadLetterRecord {+ const body = {+ schema_version: 1,+ id: V1_FIXTURE_ID,+ lane: "extract-signals",+ step: "extract-signals",+ reference: SESSION,+ target: "Brain/inbox",+ attempted: 2,+ found: 1,+ missing: missingKeys,+ outcome: "partial",+ first_error: "disk full",+ recorded_at: "2026-08-23T10:15:00Z",+ };+ mkdirSync(deadLetterDir(vault), { recursive: true });+ writeFileSync(deadLetterPath(vault, V1_FIXTURE_ID), `${JSON.stringify(body, null, 2)}\n`);+ const record = readDeadLetter(vault, V1_FIXTURE_ID);+ if (record === null) throw new Error("the v1 fixture letter did not parse");+ return record;+}++/** Import one session whose single user turn is mining material. */+function importFixtureSession(sessionId = SESSION): void {+ importSessionRecall(vault, {+ sessionId,+ turns: [+ {+ turnId: "t1",+ timestamp: "2026-08-22T09:01:00Z",+ role: "user",+ text: "Always name the release theme in the heading.",+ },+ ],+ createdAt: "2026-08-22T10:00:00Z",+ });+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-dead-letter-recovery-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ importFixtureSession();+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("the recovery classifier", () => {+ test("a v2 letter with undelivered missing items classifies recover, with the exact command", () => {+ const letter = v2Letter([item(), item({ topic: "module-names" })], ["items[1]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.recover);+ expect(c.command).toBe(`o2b brain dead-letters recover ${letter.id} --apply --yes`);+ expect(c.reason).toContain("not yet on disk");+ });++ test("a letter whose missing items all exist on disk classifies resolved, with no command", () => {+ // The items were written after the failure: a successful commit over+ // the same payload puts both signals in the inbox.+ const items = [item(), item({ topic: "module-names" })];+ commitExtractedSignals(vault, SESSION, { items }, { agent: AGENT, now: NOW });+ const letter = v2Letter(items, ["items[0]:release-notes-style", "items[1]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.resolved);+ expect(c.command).toBeNull();+ });++ test("a v1 letter whose missing items exist on disk classifies resolved too", () => {+ // Retention keeps reconciled v1 rows on disk; the classifier+ // re-measures them by topic, the only identity a payload-less letter+ // names.+ const items = [item(), item({ topic: "module-names" })];+ commitExtractedSignals(vault, SESSION, { items }, { agent: AGENT, now: NOW });+ const letter = v1Letter(["items[0]:release-notes-style", "items[1]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.resolved);+ expect(c.command).toBeNull();+ });++ test("a frozen item's stored hash is the raw identity: the same content delivered later reads as delivered", () => {+ // The freeze redacts the frozen principle, so a hash recomputed from+ // the frozen fields is NOT the identity the original delivery would+ // have carried. The raw-text hash stored beside the item is: a later+ // delivery of the same raw content - here by another session, which+ // the session-scoped topic measure deliberately cannot see - is+ // recognised, and the letter reads resolved instead of promising a+ // re-run that would only duplicate what is already on disk.+ const raw = "Use token password=hunter2secret when scraping.";+ const letter = frozenLetter(+ [item({ topic: "scraping-auth", principle: raw })],+ ["items[0]:scraping-auth"],+ );+ commitExtractedSignals(+ vault,+ "sess-other-delivery",+ { items: [item({ topic: "scraping-auth", principle: raw })] },+ { agent: AGENT, now: NOW },+ );+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.resolved);+ expect(c.command).toBeNull();+ });++ test("a v2 item the session re-delivered by re-extracting reads as delivered", () => {+ // The operator mined the session again (the `re-extract` route the+ // write error names) and the model REWORDED the principle: the exact+ // content hash never matches, and reading the item undelivered made+ // the apply replay the stale wording as a second release-theme signal+ // on the same session. The topic is the delivery evidence a v1 letter+ // always had; a v2 item counts it too.+ commitExtractedSignals(+ vault,+ SESSION,+ {+ items: [+ item({ topic: "release-theme", principle: "Lead every release note with the theme." }),+ ],+ },+ { agent: AGENT, now: NOW },+ );+ const letter = v2Letter(+ [item({ topic: "release-theme", principle: "Name the release theme in the heading." })],+ ["items[0]:release-theme"],+ );+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.resolved);+ expect(c.command).toBeNull();+ // ...and the apply writes nothing - the stale wording is not replayed.+ const inbox = join(vault, "Brain", "inbox");+ const before = existsSync(inbox) ? readdirSync(inbox).length : 0;+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ DeadLetterRecoveryError,+ );+ expect(existsSync(inbox) ? readdirSync(inbox).length : 0).toBe(before);+ });++ test("a re-extracted item is left out of the plan and the apply, not replayed as a duplicate", () => {+ // Same delivery shape as above, with a second item still missing: the+ // re-extracted one is delivered (by topic) and must not be handed+ // back to the commit - its frozen wording would land as a SECOND+ // release-theme page - while the genuinely missing one still writes.+ commitExtractedSignals(+ vault,+ SESSION,+ {+ items: [+ item({ topic: "release-theme", principle: "Lead every release note with the theme." }),+ ],+ },+ { agent: AGENT, now: NOW },+ );+ const letter = v2Letter(+ [+ item({ topic: "release-theme", principle: "Name the release theme in the heading." }),+ item({ topic: "module-names" }),+ ],+ ["items[0]:release-theme", "items[1]:module-names"],+ );+ expect(classifyDeadLetter(vault, letter).category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.recover);+ const plan = planRecovery(vault, letter);+ expect(plan.items.map((i) => i.topic)).toEqual(["module-names"]);+ const res = applyRecovery(vault, letter, { agent: AGENT, now: NOW });+ expect(res.written.map((w) => w.topic)).toEqual(["module-names"]);+ const pages = readdirSync(join(vault, "Brain", "inbox"));+ expect(pages.filter((p) => p.includes("release-theme"))).toHaveLength(1);+ });++ test("a letter whose undelivered items the durability gate refuses classifies not_recoverable", () => {+ // A denylisted item never reaches disk, so the dedup index never+ // shows it delivered: the letter used to read `recover` forever and+ // every apply reported success over zero writes. The classifier runs+ // the same gate over the undelivered items and names the state+ // honestly instead.+ const letter = v2Letter(+ [item({ topic: "scratch-pad", principle: "temporary scratch note" })],+ ["items[0]:scratch-pad"],+ );+ process.env[DURABILITY_DENYLIST_ENV_KEY] = "scratch";+ try {+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.reason).toContain("durability");+ expect(c.reason).toContain("denylisted");+ expect(c.command).toBeNull();+ expect(() => planRecovery(vault, letter)).toThrow(DeadLetterRecoveryError);+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ DeadLetterRecoveryError,+ );+ } finally {+ delete process.env[DURABILITY_DENYLIST_ENV_KEY];+ }+ });++ test("a letter with one refused and one writable item stays recover - the writable one still writes", () => {+ // The refusal answer is for letters whose EVERY undelivered item is+ // refused; a mixed letter keeps the recover exit, and the apply+ // writes the writable item and names the refused one.+ const letter = v2Letter(+ [+ item({ topic: "module-names" }),+ item({ topic: "scratch-pad", principle: "temporary scratch note" }),+ ],+ ["items[0]:module-names", "items[1]:scratch-pad"],+ );+ process.env[DURABILITY_DENYLIST_ENV_KEY] = "scratch";+ try {+ expect(classifyDeadLetter(vault, letter).category).toBe(+ DEAD_LETTER_RECOVERY_CATEGORY.recover,+ );+ const res = applyRecovery(vault, letter, { agent: AGENT, now: NOW });+ expect(res.written.map((w) => w.topic)).toEqual(["module-names"]);+ expect(res.durabilityRejected).toBe(1);+ expect(res.rejected[0]?.reason).toContain("denylisted");+ } finally {+ delete process.env[DURABILITY_DENYLIST_ENV_KEY];+ }+ });++ test("a missing key the frozen payload cannot resolve classifies not_recoverable, by name", () => {+ // The key names an index the payload does not carry: a hand-edited,+ // truncated or foreign letter. Counting the key undelivered would+ // classify `recover`, and the apply would then re-run an empty plan+ // and report success over a write that never happened.+ const letter = v2Letter([item()], ["items[3]:release-notes-style"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.reason).toContain("items[3]:release-notes-style");+ expect(c.command).toBeNull();+ });++ test("a missing key naming another item's topic classifies not_recoverable too", () => {+ // The index exists, but the key's topic is not that item's own: the+ // letter does not vouch for the item, so replaying it would be a+ // guess at which content was lost.+ const letter = v2Letter([item()], ["items[0]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.reason).toContain("items[0]:module-names");+ });++ test("a repeated missing key is a hand-edit and refuses, never double-counts", () => {+ // The commit's own report builder refuses duplicate keys, so a+ // letter with a repeated key on disk is a hand-edit - exactly the+ // input this module must not guess over. The same key twice used to+ // count its item twice: a letter with one real missing item read+ // resolved (both "keys" on disk), and the apply handed the commit+ // the same item twice. The refusal names the repetition as the+ // cause - the key names a real item, it just names it twice - on+ // the classifier and on the plan and apply that lean on it.+ const letter = v2Letter(+ [item(), item({ topic: "module-names" })],+ ["items[0]:release-notes-style"],+ );+ const path = deadLetterPath(vault, letter.id);+ const body = JSON.parse(readFileSync(path, "utf8")) as { missing: string[] };+ body.missing = ["items[0]:release-notes-style", "items[0]:release-notes-style"];+ writeFileSync(path, `${JSON.stringify(body, null, 2)}\n`);+ const handEdited = readDeadLetter(vault, letter.id);+ if (handEdited === null) throw new Error("the hand-edited fixture letter did not parse");+ const c = classifyDeadLetter(vault, handEdited);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.reason).toContain("items[0]:release-notes-style");+ expect(c.reason).toContain("repeats an earlier key");+ expect(() => planRecovery(vault, handEdited)).toThrow(DeadLetterRecoveryError);+ expect(() => planRecovery(vault, handEdited)).toThrow(/repeats an earlier key/);+ expect(() => applyRecovery(vault, handEdited, { agent: AGENT, now: NOW })).toThrow(+ DeadLetterRecoveryError,+ );+ expect(() => applyRecovery(vault, handEdited, { agent: AGENT, now: NOW })).toThrow(+ /repeats an earlier key/,+ );+ });++ test("a zero-padded respelling of a missing key is the same hand-edit", () => {+ // items[00]:a parses to the same item as items[0]:a; an exact string+ // compare let the pair through and the v1 topic count read a+ // half-delivered letter resolved (both "keys" answered by the one+ // topic on disk). The keys compare in canonical form.+ commitExtractedSignals(vault, SESSION, { items: [item()] }, { agent: AGENT, now: NOW });+ const letter = v1Letter(["items[0]:release-notes-style", "items[1]:module-names"]);+ const path = deadLetterPath(vault, letter.id);+ const body = JSON.parse(readFileSync(path, "utf8")) as { missing: string[] };+ body.missing = ["items[0]:release-notes-style", "items[00]:release-notes-style"];+ writeFileSync(path, `${JSON.stringify(body, null, 2)}\n`);+ const handEdited = readDeadLetter(vault, letter.id);+ if (handEdited === null) throw new Error("the hand-edited fixture letter did not parse");+ const c = classifyDeadLetter(vault, handEdited);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.reason).toContain("repeats an earlier key");+ });++ test("one signal page answers one v1 key, not every key naming its topic", () => {+ // Two keys may name one topic - two payload items on one subject, a+ // shape a real commit can produce, or a hand-edit. One page on disk+ // answers ONE of them; counting the topic once per key read a+ // half-delivered letter resolved.+ commitExtractedSignals(vault, SESSION, { items: [item()] }, { agent: AGENT, now: NOW });+ const letter = v1Letter(["items[0]:release-notes-style", "items[1]:release-notes-style"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.reExtract);+ });++ test("a session whose items sit staged in the write-approval queue classifies pending", () => {+ // Write approval was on when the commit ran: the item that LANDED is+ // staged in Brain/pending/ carrying the session_ref, and the letter's+ // remaining item is undelivered. The queue - not a re-run - is the+ // exit.+ const staged = commitExtractedSignals(+ vault,+ SESSION,+ { items: [item()] },+ { agent: AGENT, now: NOW, writeApprovalEnabled: true },+ );+ expect(staged.staged).toBe(1);+ const letter = v2Letter([item(), item({ topic: "module-names" })], ["items[1]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.pending);+ expect(c.command).toBe(`o2b brain pending apply ${staged.written[0]?.id}`);+ expect(c.reason).toContain("write-approval queue");+ });++ test("a v1 letter classifies re-extract and names the extraction command", () => {+ const letter = v1Letter(["items[1]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.reExtract);+ expect(c.command).toBe(`o2b brain extract-signals ${SESSION}`);+ });++ test("a v2 letter that carries no payload classifies re-extract", () => {+ const letter = recordDeadLetter(vault, {+ envelope: ENVELOPE,+ report: report(2, ["items[1]:module-names"]),+ firstError: "disk full",+ now: NOW,+ });+ expect(letter.schema_version).toBe(2);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.reExtract);+ expect(c.command).toBe(`o2b brain extract-signals ${SESSION}`);+ });++ test("a session unknown to the import ledger classifies not_recoverable", () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"], "sess-nowhere");+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.command).toBeNull();+ expect(c.reason).toContain("sess-nowhere");+ });++ test("a session the capture boundary now refuses classifies not_recoverable", () => {+ // Seed the vault config exactly as `brain init` writes it, then+ // append an ignore pattern that matches the session, so the boundary+ // read below parses a real config rather than a minimal fragment.+ mkdirSync(brainDirs(vault).brain, { recursive: true });+ atomicWriteFileSync(+ brainConfigPath(vault),+ `${DEFAULT_BRAIN_CONFIG_YAML}\nsessions:\n ignore_patterns:\n - "${SESSION}"\n`,+ );+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.command).toBeNull();+ expect(c.reason).toContain(SESSION);+ });++ test("a record whose lane is unknown to this build classifies not_recoverable by name", () => {+ mkdirSync(deadLetterDir(vault), { recursive: true });+ const id = "time-machine-0123456789ab";+ const body = {+ schema_version: 2,+ id,+ lane: "time-machine",+ step: "time-machine",+ reference: SESSION,+ target: "Brain/inbox",+ attempted: 1,+ found: 0,+ missing: ["items[0]:x"],+ outcome: "partial",+ first_error: "disk full",+ recorded_at: "2026-08-23T10:15:00Z",+ payload: { items: [item()] },+ };+ writeFileSync(deadLetterPath(vault, id), `${JSON.stringify(body, null, 2)}\n`);+ const letter = readDeadLetter(vault, id);+ if (letter === null) throw new Error("the unknown-lane fixture letter did not parse");+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.notRecoverable);+ expect(c.command).toBeNull();+ expect(c.reason).toContain("time-machine");+ });++ test("a payload that no longer passes the lane's own validation classifies re-extract", () => {+ // An item below the confidence floor refuses the whole payload at+ // commit time, so a letter frozen with one cannot be re-run verbatim.+ const letter = recordDeadLetter(vault, {+ envelope: ENVELOPE,+ report: report(1, ["items[0]:shaky"]),+ firstError: "disk full",+ now: NOW,+ payload: {+ items: [{ topic: "shaky", signal: "positive", principle: "Try harder.", confidence: 0.2 }],+ },+ });+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.reExtract);+ });+});++describe("the recovery plan", () => {+ test("each MISSING item is labelled with the verdict the commit's own gates produce", () => {+ // `release-notes-style` landed before the failure and is not in the+ // letter's missing set, so the plan - the preview of exactly what+ // the apply would re-run - never labels it: replaying a delivered+ // item would resurrect it even if an operator removed it later.+ // `module-names` is missing and writable (write), `scratch-pad`+ // fails the denylist (refused).+ commitExtractedSignals(vault, SESSION, { items: [item()] }, { agent: AGENT, now: NOW });+ const letter = v2Letter(+ [+ item(),+ item({ topic: "module-names" }),+ item({ topic: "scratch-pad", principle: "temporary scratch note" }),+ ],+ ["items[1]:module-names", "items[2]:scratch-pad"],+ );+ const plan = planRecovery(vault, letter, { durabilityDenylist: [/scratch/] });+ expect(plan.classification.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.recover);+ expect(plan.items.map((i) => [i.topic, i.verdict])).toEqual([+ ["module-names", "write"],+ ["scratch-pad", "refused"],+ ]);+ expect(plan.items[1]?.reason).toContain("denylisted");+ });++ test("with write approval on, a writable item plans as staged", () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ const plan = planRecovery(vault, letter, { writeApprovalEnabled: true });+ expect(plan.items[0]?.verdict).toBe("staged");+ });++ test("a plan refuses a missing key the payload cannot resolve", () => {+ // A plan over an unresolvable key set would list no items - a+ // forecast of nothing, one refusal away from an apply that reports+ // success over it.+ const letter = v2Letter([item()], ["items[2]:release-notes-style"]);+ expect(() => planRecovery(vault, letter)).toThrow(DeadLetterRecoveryError);+ expect(() => planRecovery(vault, letter)).toThrow(/items\[2\]:release-notes-style/);+ });+});++describe("the apply", () => {+ test("apply re-runs the payload at current state; already-written items dedup away", () => {+ // `release-notes-style` landed before the recovery; the letter still+ // names both items missing, because the commit that failed part way+ // never wrote the second one.+ commitExtractedSignals(vault, SESSION, { items: [item()] }, { agent: AGENT, now: NOW });+ const letter = v2Letter(+ [item(), item({ topic: "module-names" })],+ ["items[0]:release-notes-style", "items[1]:module-names"],+ );+ expect(classifyDeadLetter(vault, letter).category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.recover);+ const res = applyRecovery(vault, letter, { agent: AGENT, now: NOW });+ expect(res.written.map((w) => w.topic)).toEqual(["module-names"]);+ expect(res.deduped).toBe(1);+ });++ test("the apply re-runs only the missing items, never the delivered ones", () => {+ // Item 0 landed before the failure, so the letter's missing set+ // names item 1 alone. The operator then removes the delivered+ // signal; the letter stays recoverable (its MISSING item is not on+ // disk), and the re-run must resurrect nothing but that missing+ // item - replaying the removed one is the stale replay the module+ // promises can never happen.+ const commit = commitExtractedSignals(+ vault,+ SESSION,+ { items: [item()] },+ { agent: AGENT, now: NOW },+ );+ expect(commit.written).toHaveLength(1);+ const deliveredPath = join(vault, commit.written[0]!.path);+ const letter = v2Letter([item(), item({ topic: "module-names" })], ["items[1]:module-names"]);+ rmSync(deliveredPath, { force: true });+ expect(existsSync(deliveredPath)).toBe(false);+ expect(classifyDeadLetter(vault, letter).category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.recover);++ // The plan previews exactly the apply's input: the missing item.+ const plan = planRecovery(vault, letter);+ expect(plan.items.map((i) => i.topic)).toEqual(["module-names"]);++ const res = applyRecovery(vault, letter, { agent: AGENT, now: NOW });+ expect(res.written.map((w) => w.topic)).toEqual(["module-names"]);+ expect(existsSync(deliveredPath)).toBe(false);+ });++ test("a v1 letter is not resolved by another session's signal sharing the topic", () => {+ // The topic is the only identity a payload-less letter names, but+ // the delivery it asks about is THIS session's: a same-topic signal+ // committed by a different session confirms nothing about what this+ // session's commit delivered, and counting it would read a real+ // partial write as resolved.+ const other = commitExtractedSignals(+ vault,+ "sess-other-session",+ { items: [item({ topic: "module-names" })] },+ { agent: AGENT, now: NOW },+ );+ expect(other.written).toHaveLength(1);+ const letter = v1Letter(["items[0]:module-names"]);+ const c = classifyDeadLetter(vault, letter);+ expect(c.category).not.toBe(DEAD_LETTER_RECOVERY_CATEGORY.resolved);+ // A payload-less letter whose own session delivered nothing re-extracts.+ expect(c.category).toBe(DEAD_LETTER_RECOVERY_CATEGORY.reExtract);+ });++ test("apply refuses a letter that is not recoverable, naming the category", () => {+ const letter = v1Letter(["items[1]:module-names"]);+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ DeadLetterRecoveryError,+ );+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(/re-extract/);+ });++ test("a refusal carries the classification's own command, so the row stays actionable", () => {+ // A pending letter refuses both the plan and the apply; the refusal+ // names the exact command the classifier computed for the state, the+ // same copy-paste row the listing renders - an operator holding the+ // error alone should not have to re-derive the exit.+ const staged = commitExtractedSignals(+ vault,+ SESSION,+ { items: [item()] },+ { agent: AGENT, now: NOW, writeApprovalEnabled: true },+ );+ const letter = v2Letter([item(), item({ topic: "module-names" })], ["items[1]:module-names"]);+ const stagedId = staged.written[0]?.id ?? "never";+ expect(classifyDeadLetter(vault, letter).command).toBe(`o2b brain pending apply ${stagedId}`);+ expect(() => planRecovery(vault, letter)).toThrow(DeadLetterRecoveryError);+ expect(() => planRecovery(vault, letter)).toThrow(/o2b brain pending apply/);+ expect(() => planRecovery(vault, letter)).toThrow(new RegExp(stagedId));+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ DeadLetterRecoveryError,+ );+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ /o2b brain pending apply/,+ );+ });++ test("nothing in the apply deletes the letter", () => {+ const letter = v2Letter([item()], ["items[0]:release-notes-style"]);+ applyRecovery(vault, letter, { agent: AGENT, now: NOW });+ expect(readDeadLetter(vault, letter.id)).not.toBeNull();+ });++ test("an apply refuses a missing key the payload cannot resolve instead of writing nothing", () => {+ // The exact success-over-nothing shape: an unresolvable key set used+ // to classify `recover`, the apply re-ran an empty plan, and the+ // commit returned cleanly - a green exit over a write that never+ // happened. The refusal keeps the row's truth on the record.+ const letter = v2Letter([item()], ["items[1]:release-notes-style"]);+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ DeadLetterRecoveryError,+ );+ expect(() => applyRecovery(vault, letter, { agent: AGENT, now: NOW })).toThrow(+ /items\[1\]:release-notes-style/,+ );+ // Nothing was written under the letter's session either.+ expect(existsSync(join(vault, "Brain", "inbox"))).toBe(false);+ });+});++describe("the lane guard", () => {+ test("the lane union has exactly the member this build recovers", () => {+ expect(DEAD_LETTER_LANES).toEqual(["extract-signals"]);+ expect(isDeadLetterLane("extract-signals")).toBe(true);+ expect(isDeadLetterLane("time-machine")).toBe(false);+ });+});diff --git a/tests/core/brain/dead-letter.test.ts b/tests/core/brain/dead-letter.test.tsindex 6927f278..f0c2a06b 100644--- a/tests/core/brain/dead-letter.test.ts+++ b/tests/core/brain/dead-letter.test.ts@@ -21,10 +21,14 @@* 6. `tryRecordDeadLetter` never throws - it reports why it could not* write - because it runs inside a catch block whose original error* must survive.+ * 7. Schema v2 freezes the failing commit's validated payload into the+ * record, so recovery can re-run it without a second model call; a+ * v1 letter parses unchanged and carries no payload; an unknown+ * version still refuses.*/import { describe, expect, test } from "bun:test";-import { existsSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";import { basename, dirname, join } from "node:path";import {@@ -33,11 +37,15 @@ import {deadLetterDir,deadLetterPath,listDeadLetters,+ PARSED_DEAD_LETTER_SCHEMA_VERSIONS,readDeadLetter,recordDeadLetter,tryRecordDeadLetter,type DeadLetterEnvelopeIdentity,} from "../../../src/core/brain/dead-letter.ts";+import { commitExtractedSignals } from "../../../src/core/brain/extract-signals.ts";+import { computeDedupHash } from "../../../src/core/brain/dedup-hash.ts";+import { importSessionRecall } from "../../../src/core/brain/session-recall.ts";import { DERIVED_STORE_DIR } from "../../../src/core/brain/path-constants.ts";import { buildReconciliationReport } from "../../../src/core/reconciliation-report.ts";import { tempDirs } from "../../helpers/temp-dir.ts";@@ -269,3 +277,301 @@ describe("the recorder used inside a catch block cannot throw", () => {}});});++// ----- Schema v2: the frozen payload (one-command recovery, t_50794f57) ------+//+// 7. The current schema version is 2, and a v2 record carries the+// failing commit's validated payload so recovery can re-run it+// without a second model call.+// 8. A record without a payload carries no payload key at all - absent,+// never present-and-null.+// 9. Parsing is strict PER VERSION: a v1 letter keeps parsing and names+// no payload; a v1 letter that claims a payload is refused; a v2+// payload that is not an object is refused; an unknown version still+// refuses with the same error as before.++const PAYLOAD = Object.freeze({+ items: [+ {+ topic: "module-names",+ signal: "positive",+ principle: "Never abbreviate a module name.",+ confidence: 0.9,+ },+ ],+});++describe("schema v2 freezes the payload", () => {+ test("the current schema version is 2", () => {+ expect(DEAD_LETTER_SCHEMA_VERSION).toBe(2);+ });++ test("a v2 record round-trips with the payload", () => {+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:module-names"]),+ firstError: "disk full",+ now: NOW,+ payload: PAYLOAD,+ });+ expect(record.schema_version).toBe(2);+ expect(record.payload).toEqual(PAYLOAD);+ const back = readDeadLetter(v, record.id);+ expect(back).toEqual(record);+ expect(back?.payload).toEqual(PAYLOAD);+ expect(listDeadLetters(v)[0]?.payload).toEqual(PAYLOAD);+ });++ test("a record without a payload carries no payload key, on disk least of all", () => {+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "boom",+ now: NOW,+ });+ expect("payload" in record).toBe(false);+ const raw = JSON.parse(readFileSync(deadLetterPath(v, record.id), "utf8")) as Record<+ string,+ unknown+ >;+ expect("payload" in raw).toBe(false);+ });++ test("the payload sits in the fixed serialized field order, after the missing list", () => {+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:module-names"]),+ firstError: "disk full",+ now: NOW,+ payload: PAYLOAD,+ });+ const raw = JSON.parse(readFileSync(deadLetterPath(v, record.id), "utf8")) as Record<+ string,+ unknown+ >;+ expect(Object.keys(raw)).toEqual([+ "schema_version",+ "id",+ "lane",+ "step",+ "reference",+ "target",+ "attempted",+ "found",+ "missing",+ "payload",+ "outcome",+ "first_error",+ "recorded_at",+ ]);+ expect(record.id.length).toBeGreaterThan(0);+ });++ test("two failures differing only in their payload get different ids", () => {+ const v = vault();+ const withPayload = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "disk full",+ now: NOW,+ payload: PAYLOAD,+ });+ const without = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "disk full",+ now: NOW,+ });+ expect(without.id).not.toBe(withPayload.id);+ expect(listDeadLetters(v)).toHaveLength(2);+ });++ test("a v1 letter parses unchanged and carries no payload", () => {+ // Hand-written exactly as schema v1 wrote it, so the back-compat path+ // is pinned against the real on-disk shape and not a v2 record with+ // the version number edited.+ const v = vault();+ const v1: Record<string, unknown> = {+ schema_version: 1,+ id: "extract-signals-000000000000",+ lane: "extract-signals",+ step: "extract-signals",+ reference: "sess-2026-08-23",+ target: "Brain/inbox",+ attempted: 2,+ found: 1,+ missing: ["items[1]:module-names"],+ outcome: "partial",+ first_error: "disk full",+ recorded_at: "2026-08-23T10:15:00Z",+ };+ mkdirSync(deadLetterDir(v), { recursive: true });+ writeFileSync(+ deadLetterPath(v, "extract-signals-000000000000"),+ `${JSON.stringify(v1, null, 2)}\n`,+ );+ const parsed = readDeadLetter(v, "extract-signals-000000000000");+ expect(parsed).not.toBeNull();+ expect(parsed?.schema_version).toBe(1);+ expect("payload" in (parsed ?? {})).toBe(false);+ expect(parsed?.missing).toEqual(["items[1]:module-names"]);+ expect(listDeadLetters(v)).toHaveLength(1);+ });++ test("a v1 record that claims a payload is refused by name", () => {+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "boom",+ now: NOW,+ });+ writeFileSync(+ deadLetterPath(v, record.id),+ JSON.stringify({ ...record, schema_version: 1, payload: PAYLOAD }),+ );+ expect(() => readDeadLetter(v, record.id)).toThrow(DeadLetterError);+ expect(() => readDeadLetter(v, record.id)).toThrow(/payload/);+ expect(() => listDeadLetters(v)).toThrow(/payload/);+ });++ test("a v2 payload that is not an object is refused by name", () => {+ for (const bad of [[PAYLOAD], "nope", null]) {+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "boom",+ now: NOW,+ payload: PAYLOAD,+ });+ writeFileSync(deadLetterPath(v, record.id), JSON.stringify({ ...record, payload: bad }));+ expect(() => readDeadLetter(v, record.id)).toThrow(DeadLetterError);+ expect(() => readDeadLetter(v, record.id)).toThrow(/payload/);+ }+ });++ test("the version gate admits exactly the PARSED_DEAD_LETTER_SCHEMA_VERSIONS list", () => {+ // Derived from the constant, not from literals: a version joining the+ // list must parse the day it lands, and anything outside it must+ // keep refusing - the gate and the list cannot drift apart.+ for (const version of PARSED_DEAD_LETTER_SCHEMA_VERSIONS) {+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "boom",+ now: NOW,+ });+ writeFileSync(+ deadLetterPath(v, record.id),+ JSON.stringify({ ...record, schema_version: version }),+ );+ expect(readDeadLetter(v, record.id)?.schema_version).toBe(version);+ }+ const outside = Math.max(...PARSED_DEAD_LETTER_SCHEMA_VERSIONS) + 1;+ const v = vault();+ const record = recordDeadLetter(v, {+ envelope: ENVELOPE,+ report: report(["items[1]:x"]),+ firstError: "boom",+ now: NOW,+ });+ writeFileSync(+ deadLetterPath(v, record.id),+ JSON.stringify({ ...record, schema_version: outside }),+ );+ expect(() => readDeadLetter(v, record.id)).toThrow(DeadLetterError);+ expect(() => readDeadLetter(v, record.id)).toThrow(/schema_version/);+ });+});++describe("the extractor freezes its payload into the letter", () => {+ test("the frozen items are redacted, with the raw text's dedup hash kept beside each", () => {+ // The letter sits in `.open-second-brain/dead-letters/` forever and+ // `show --json` prints it: the same redaction `writeSignal` applies+ // before disk applies at freeze time, and the dedup hash frozen+ // beside each item is the RAW text's, so recovery still matches the+ // original delivery identity (the redacted fields alone would hash+ // differently and a re-delivery of the real content would dedup+ // nothing).+ const v = vault();+ mkdirSync(join(v, "Brain"), { recursive: true });+ importSessionRecall(v, {+ sessionId: ENVELOPE.reference,+ turns: [+ {+ turnId: "t1",+ timestamp: "2026-08-22T09:01:00Z",+ role: "user",+ text: "Never abbreviate a module name.",+ },+ ],+ createdAt: "2026-08-22T10:00:00Z",+ });+ const rawPrinciple = "Use token password=hunter2secret when scraping.";+ const rawScope = "password=hunter2secret";+ const payload = {+ items: [+ {+ topic: "release-style",+ signal: "positive",+ principle: rawPrinciple,+ confidence: 0.9,+ },+ {+ // A colon is not a legal slug character, so this item's write+ // refuses and the commit fails PART WAY through the payload.+ // (Its scope never reaches the tag gate, so a secret-shaped one+ // is safe to freeze-test here.)+ topic: "module:names",+ signal: "positive",+ principle: "Never abbreviate a module name.",+ confidence: 0.9,+ scope: rawScope,+ },+ ],+ };+ expect(() =>+ commitExtractedSignals(v, ENVELOPE.reference, payload, { agent: "tester", now: NOW }),+ ).toThrow(/failed to write extracted signal/);+ const letters = listDeadLetters(v);+ expect(letters).toHaveLength(1);+ expect(letters[0]?.schema_version).toBe(2);+ expect(letters[0]?.missing).toEqual(["items[1]:module:names"]);++ // The letter file - read raw, not through the parser - carries no+ // secret anywhere.+ const rawFile = readFileSync(deadLetterPath(v, letters[0]!.id), "utf8");+ expect(rawFile).not.toContain("hunter2secret");++ const frozen = letters[0]?.payload?.["items"] as Array<Record<string, unknown>>;+ expect(frozen).toHaveLength(2);+ expect(frozen[0]?.["principle"]).not.toContain("hunter2secret");+ expect(frozen[0]?.["principle"]).toContain("***REDACTED***");+ expect(frozen[1]?.["principle"]).toBe("Never abbreviate a module name.");+ expect(frozen[1]?.["scope"]).not.toContain("hunter2secret");+ expect(frozen[1]?.["scope"]).toContain("***REDACTED***");++ // The hashes are the RAW text's identity: exactly what the commit+ // wrote into the delivered page's `dedup_hash` frontmatter.+ expect(frozen[0]?.["dedup_hash"]).toBe(+ computeDedupHash({+ topic: "release-style",+ signal: "positive",+ principle: rawPrinciple,+ }),+ );+ expect(frozen[1]?.["dedup_hash"]).toBe(+ computeDedupHash({+ topic: "module:names",+ signal: "positive",+ principle: "Never abbreviate a module name.",+ scope: rawScope,+ }),+ );+ });+});diff --git a/tests/core/brain/explorer-denials.test.ts b/tests/core/brain/explorer-denials.test.tsnew file mode 100644index 00000000..39e6c645--- /dev/null+++ b/tests/core/brain/explorer-denials.test.ts@@ -0,0 +1,100 @@+/**+ * Tests for `collectExplorerDenials` (§14 explorer, shared-lane+ * withholding report).+ *+ * The live collector keeps every parsed node; this report is what the+ * export narrows by. Pinned here: one list over both node kinds, the+ * denying key named per row, id-sorted determinism, and an empty answer+ * for an unmarked vault.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { collectExplorerDenials } from "../../../src/core/brain/explorer.ts";+import {+ moveToRetired,+ writePreference,+ type WritePreferenceInput,+} from "../../../src/core/brain/preference.ts";+import { BRAIN_RETIRED_REASON } from "../../../src/core/brain/types.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-explorer-denials-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+});+afterEach(() => rmSync(vault, { recursive: true, force: true }));++function basePref(+ slug: string,+ overrides: Partial<WritePreferenceInput> = {},+): WritePreferenceInput {+ return {+ slug,+ topic: slug,+ principle: `Principle for ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: "high",+ confidence_value: 0.8,+ pinned: false,+ ...overrides,+ };+}++/** Hand-add a frontmatter line the way an operator does. */+function stampMarker(relPath: string, line: string): void {+ const abs = join(vault, relPath);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+}++describe("collectExplorerDenials", () => {+ test("an unmarked vault denies nothing", () => {+ writePreference(vault, basePref("plain"));+ expect(collectExplorerDenials(vault)).toEqual([]);+ });++ test("reserved preference and retired nodes are one sorted list, each with its key", () => {+ writePreference(vault, basePref("open"));+ writePreference(vault, basePref("reserved"));+ stampMarker("Brain/preferences/pref-reserved.md", "access: private");++ writePreference(vault, basePref("old"));+ const deadPath = join(vault, "Brain", "preferences", "pref-old.md");+ moveToRetired(vault, deadPath, BRAIN_RETIRED_REASON.staleNoEvidence, {+ now: new Date("2026-05-10T00:00:00Z"),+ retired_by: "[[Brain/log/2026-05-10]]",+ });+ stampMarker("Brain/retired/ret-old.md", "visibility: private");++ const denied = collectExplorerDenials(vault);+ expect(denied).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "access" },+ { id: "ret-old", reason: "visibility", denied_by: "visibility" },+ ]);+ });++ test("the formal reserved token denies under its own key", () => {+ writePreference(vault, basePref("formal", { visibility: ["private"] }));+ const denied = collectExplorerDenials(vault);+ expect(denied).toEqual([{ id: "pref-formal", reason: "visibility", denied_by: "visibility" }]);+ });++ test("an unparsable file denies nothing - the export refuses on it first", () => {+ writePreference(vault, basePref("good"));+ writeFileSync(join(vault, "Brain", "preferences", "pref-broken.md"), "no frontmatter here\n");+ expect(collectExplorerDenials(vault)).toEqual([]);+ });+});diff --git a/tests/core/brain/export.test.ts b/tests/core/brain/export.test.tsindex d3ad9d94..b0fe5480 100644--- a/tests/core/brain/export.test.ts+++ b/tests/core/brain/export.test.ts@@ -9,15 +9,25 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import {BRAIN_EXPORT_SCHEMA_VERSION,+ collectExportRows,+ collectPreferenceRows,exportPreferencesJson,exportPreferencesLlmsTxt,+ exportPreferencesLlmsTxtDetailed,+ PreferenceParseError,+ type PreferenceDenyKey,} from "../../../src/core/brain/export.ts";+import {+ PRIVACY_DENY_MARKER_VALUES,+ PRIVACY_MARKER_KEYS,+} from "../../../src/core/graph/privacy-markers.ts";+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../../src/core/graph/visibility.ts";import {moveToRetired,writePreference,@@ -203,3 +213,127 @@ describe("exportPreferencesLlmsTxt", () => {expect(txt).toContain("- pref-unscoped (topic: unscoped): Principle for unscoped");});});++describe("collector privacy denial reporting", () => {+ /**+ * Stamp one extra frontmatter line onto a written preference file.+ * The informal markers (`access:` and siblings) have no write-input+ * field - they are hand-added user-tier lines - so the test adds one+ * the same way an operator does.+ */+ function stampMarker(slug: string, line: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+ }++ test("every informal marker key times deny value denies, and rows stay complete", () => {+ // One unmarked control row plus one file per marker key x deny value.+ // Denial is a report BESIDE the rows: the collector's `rows` stay+ // complete because the import-side topic maps must keep seeing every+ // rule, marker or not.+ writePreference(vault, basePref("open"));+ const marked: string[] = [];+ for (const key of PRIVACY_MARKER_KEYS) {+ for (const value of PRIVACY_DENY_MARKER_VALUES) {+ const slug = `marked-${key}-${value}`;+ writePreference(vault, basePref(slug));+ stampMarker(slug, `${key}: ${value}`);+ marked.push(`pref-${slug}`);+ }+ }++ const out = collectPreferenceRows(vault);+ expect(out.rows).toHaveLength(1 + marked.length);+ expect(out.rows.map((r) => r.id)).toContain("pref-open");+ // Sorted by id, like the rows: the denial list rides byte-deterministic+ // surfaces (the json envelope's omitted, the bundle's preferences_omitted).+ expect(out.denied.map((d) => d.id)).toEqual(marked.toSorted());+ // The reason stays the "visibility" class for machine readers; the key+ // names the frontmatter key whose value actually denied the row.+ const expectedKeys = new Map<string, PreferenceDenyKey>(+ marked.map((id) => [id, id.replace("pref-marked-", "").split("-")[0] as PreferenceDenyKey]),+ );+ for (const d of out.denied) {+ expect(d.reason).toBe("visibility");+ // Every denied id is asserted above to come from `marked`, so the+ // expected key is always present.+ expect(d.denied_by).toBe(expectedKeys.get(d.id)!);+ }+ });++ test("visibility: private denies the row", () => {+ writePreference(vault, basePref("reserved", { visibility: [REMOTE_DENY_VISIBILITY_TOKEN] }));+ writePreference(vault, basePref("open"));++ const out = collectPreferenceRows(vault);+ expect(out.denied).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "visibility" },+ ]);+ // Denied rows ride beside the kept ones, never inside them.+ expect(out.rows.map((r) => r.id).toSorted()).toEqual(["pref-open", "pref-reserved"]);+ });++ test("a vault without reservations denies nothing", () => {+ writePreference(vault, basePref("plain"));++ const out = collectPreferenceRows(vault);+ expect(out.denied).toEqual([]);+ expect(out.rows).toHaveLength(1);+ });++ test("parse refusals behave exactly as before denial reporting", () => {+ writePreference(vault, basePref("good"));+ writeFileSync(join(vault, "Brain", "preferences", "pref-broken.md"), "no frontmatter here\n");++ const scan = collectPreferenceRows(vault);+ expect(scan.failures.map((f) => f.path)).toEqual(["Brain/preferences/pref-broken.md"]);+ expect(scan.denied).toEqual([]);+ expect(() => collectExportRows(vault)).toThrow(PreferenceParseError);+ });+});++describe("shared-lane omission reporting", () => {+ function stampMarker(slug: string, line: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+ }++ test("a reserved preference leaves the json envelope and is named in omitted", () => {+ writePreference(vault, basePref("open"));+ writePreference(vault, basePref("reserved"));+ stampMarker("reserved", "access: private");++ const out = exportPreferencesJson(vault);+ expect(out.preferences.map((p) => p.id)).toEqual(["pref-open"]);+ expect(out.omitted).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "access" },+ ]);+ // The envelope's version is additive, not a bump: a consumer written+ // against the field-less envelope keeps working.+ expect(out.schema).toBe(BRAIN_EXPORT_SCHEMA_VERSION);+ });++ test("omitted is absent when nothing is denied", () => {+ writePreference(vault, basePref("plain"));++ const out = exportPreferencesJson(vault);+ expect("omitted" in out).toBe(false);+ });++ test("the llms-txt detailed variant leaves the reserved row out of the text and names it", () => {+ writePreference(vault, basePref("open", { scope: "writing" }));+ writePreference(vault, basePref("reserved"));+ stampMarker("reserved", "confidentiality: secret");++ const detail = exportPreferencesLlmsTxtDetailed(vault);+ expect(detail.text).toContain("- pref-open (topic: open, scope: writing): Principle for open");+ expect(detail.text).not.toContain("pref-reserved");+ expect(detail.text).not.toContain("Principle for reserved");+ expect(detail.omitted).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "confidentiality" },+ ]);+ // The stable string signature delegates to the detailed one, so the+ // two never disagree about what the document contains.+ expect(exportPreferencesLlmsTxt(vault)).toBe(detail.text);+ });+});diff --git a/tests/core/brain/notes/folder-lifecycle.test.ts b/tests/core/brain/notes/folder-lifecycle.test.tsnew file mode 100644index 00000000..a2049431--- /dev/null+++ b/tests/core/brain/notes/folder-lifecycle.test.ts@@ -0,0 +1,1501 @@+/**+ * Folder-level note lifecycle: `move-folder` and `rename-folder`+ * (t_9571a47f).+ *+ * The note-file surface is defined per FILE; reorganizing a vault by+ * folder means moving notes one at a time by hand, which breaks inbound+ * path-spelled wikilinks. A folder move never changes a basename, so the+ * bare `[[Name]]` spellings keep resolving and only PATH-spelled links+ * break - which one `retargetWikilinks` pass over the successfully moved+ * set fixes completely. There is no second (bare-name repair) pass here,+ * and the tests pin that the single pass is genuinely complete.+ *+ * The operation is explicitly NOT atomic and the tests hold it to that+ * honesty: occupancy is eliminated by a pre-flight that refuses before+ * the first byte moves, and a mid-set I/O failure is NAMED in+ * `moveFailures` with the rewrite pairs computed from the successfully+ * moved set only - never rolled back, matching the settled partial-+ * failure doctrine of the file surface.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import {+ BASENAME_REWRITE,+ isNoteLifecycleAction,+ NOTE_ARCHIVE_ROOT,+ NOTE_LIFECYCLE_ACTION,+ NOTE_LIFECYCLE_ACTIONS,+ noteLifecycle,+ NoteLifecycleError,+} from "../../../../src/core/brain/notes/lifecycle.ts";+import {+ folderLifecycle,+ isFolderLifecycleAction,+} from "../../../../src/core/brain/notes/folder-lifecycle.ts";+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;+let configPath: string;++/**+ * Whether the filesystem hosting the test tmpdir folds case in names:+ * probed once, at load, because `test.skipIf` decides at declaration -+ * before any per-test vault exists - and the folding behavior belongs to+ * the volume, not to the process.+ */+const FOLDS_CASE = (() => {+ const probe = mkdtempSync(join(tmpdir(), "o2b-case-probe-"));+ try {+ mkdirSync(join(probe, "Fold"));+ const plain = statSync(join(probe, "Fold"));+ const folded = statSync(join(probe, "fold"));+ return plain.dev === folded.dev && plain.ino === folded.ino;+ } catch {+ return false;+ } finally {+ rmSync(probe, { recursive: true, force: true });+ }+})();++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-folder-lifecycle-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-folder-lifecycle-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 });+});++/** Write a note verbatim, creating its parents. */+function note(rel: string, body: string): void {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, body);+}++function read(rel: string): string {+ return readFileSync(join(vault, rel), "utf8");+}++function isDir(rel: string): boolean {+ try {+ return statSync(join(vault, rel)).isDirectory();+ } catch {+ return false;+ }+}++describe("the folder action vocabulary", () => {+ test("move-folder and rename-folder are members of the one lifecycle vocabulary", () => {+ expect(NOTE_LIFECYCLE_ACTION.moveFolder).toBe("move-folder");+ expect(NOTE_LIFECYCLE_ACTION.renameFolder).toBe("rename-folder");+ expect(NOTE_LIFECYCLE_ACTIONS).toContain("move-folder");+ expect(NOTE_LIFECYCLE_ACTIONS).toContain("rename-folder");+ // The guard reads the same constant, so the CLI check, MCP enum and+ // manifest stay in sync from one place.+ expect(isNoteLifecycleAction("move-folder")).toBe(true);+ expect(isNoteLifecycleAction("rename-folder")).toBe(true);+ expect(isNoteLifecycleAction("Move-Folder")).toBe(false);+ });++ test("the folder guard accepts exactly the two folder actions", () => {+ expect(isFolderLifecycleAction("move-folder")).toBe(true);+ expect(isFolderLifecycleAction("rename-folder")).toBe(true);+ for (const outsider of ["delete", "archive", "rename", "move", null, 42, {}, ""]) {+ expect(isFolderLifecycleAction(outsider)).toBe(false);+ }+ });+});++describe("the folder envelope", () => {+ test("a missing source is a typed source_missing refusal", async () => {+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Nope",+ to: "Archive-elsewhere",+ apply: true,+ }),+ ).rejects.toThrow(NoteLifecycleError);+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/NotAFolder",+ to: "Elsewhere",+ apply: true,+ }),+ ).rejects.toThrow(/source_missing|no note folder/);+ });++ test("the vault root is refused as a source", async () => {+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: "",+ to: "Everything",+ apply: true,+ }),+ ).rejects.toThrow();+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: ".",+ to: "Everything",+ apply: true,+ }),+ ).rejects.toThrow();+ });++ test("the Brain machinery root is refused for source and destination alike", async () => {+ note("Projects/Old/a.md", "x\n");+ // Source under Brain/.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Brain/reports",+ to: "Projects",+ apply: true,+ }),+ ).rejects.toThrow(/Brain/);+ // Destination under Brain/.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Brain",+ apply: true,+ }),+ ).rejects.toThrow(/Brain/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });++ test("a vault-scope excluded path is refused, naming the entry", async () => {+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: ".obsidian/plugins",+ to: "Projects",+ apply: true,+ }),+ ).rejects.toThrow(/excluded by vault\.ignore_paths \(\.obsidian\)/);+ });++ test("traversal is refused for source and destination", async () => {+ note("Projects/Old.md", "x\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/../..",+ to: "Elsewhere",+ apply: true,+ }),+ ).rejects.toThrow();+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "../outside",+ apply: true,+ }),+ ).rejects.toThrow();+ expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);+ });+});++describe("the caller's reach over the folder", () => {+ test("a move set the caller may not read refuses exactly as a missing folder", async () => {+ note("Projects/Old/a.md", "alpha\n");+ for (const apply of [false, true]) {+ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply,+ readable: () => false,+ });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(NoteLifecycleError);+ expect((caught as NoteLifecycleError).code).toBe("source_missing");+ }+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive"))).toBe(false);+ });++ test("a folder holding one note the caller may not read refuses without naming it", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/quiet.md", "reserved\n");+ for (const apply of [false, true]) {+ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply,+ readable: (rel) => !rel.endsWith("quiet.md"),+ });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(NoteLifecycleError);+ const refusal = caught as NoteLifecycleError;+ expect(refusal.code).toBe("source_missing");+ // The refusal reads exactly as a missing folder's: the denied+ // note's path names nothing the caller could otherwise learn.+ expect(refusal.message).not.toContain("quiet");+ }+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/quiet.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive"))).toBe(false);+ });++ test("a denied folder answers a destination mistake as a missing folder, never the destination's error", async () => {+ // The reach check runs BEFORE the destination is resolved: a folder+ // holding a note the caller may not read answers every later error+ // path as a missing folder too. A destination refusal would let a+ // deliberately bad `to` tell an existing-but-denied folder apart+ // from a missing one - an existence oracle.+ note("Projects/Old/quiet.md", "reserved\n");+ for (const apply of [false, true]) {+ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Projects/Old/nested",+ apply,+ readable: () => false,+ });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(NoteLifecycleError);+ expect((caught as NoteLifecycleError).code).toBe("source_missing");+ }+ expect(existsSync(join(vault, "Projects/Old/quiet.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/nested"))).toBe(false);+ });+});++describe("move-folder", () => {+ test("moves every file and rewrites path-spelled inbound links to the minimal spelling", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/b.md", "beta\n");+ note("Notes/Ref.md", "pathed [[Projects/Old/a]] and suffixed [[Projects/Old/a.md]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.applied).toBe(true);+ expect(res.from).toBe("Projects/Old");+ expect(res.to).toBe("Archive/Old");+ expect(res.moved.map((m) => m.to).toSorted()).toEqual(["Archive/Old/a.md", "Archive/Old/b.md"]);+ expect(res.moveFailures).toEqual([]);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old/b.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(false);+ // The minimal spelling of the moved note: the basename is unique, so+ // both path-spelled forms collapse onto it.+ expect(read("Notes/Ref.md")).toBe("pathed [[a]] and suffixed [[a]]\n");+ expect(res.references.filesRewritten).toBe(1);+ expect(res.references.basename).toBe(BASENAME_REWRITE.notNeeded);+ });++ test("leaves bare-basename links untouched and resolving", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Notes/Ref.md", "bare [[a]] and pathed [[Projects/Old/a]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ // A folder move never changes a basename, so the bare spelling never+ // breaks; rewriting it is not this operation's business.+ expect(read("Notes/Ref.md")).toBe("bare [[a]] and pathed [[a]]\n");+ expect(res.references.rewrittenSpellings).toEqual([+ { from: "Projects/Old/a.md", to: "a" },+ { from: "Projects/Old/a", to: "a" },+ ]);+ });++ test("rewrites to the suffix-less path when the destination basename is contested", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Archive/Other/a.md", "another note that already owns the basename\n");+ note("Notes/Ref.md", "pathed [[Projects/Old/a]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ // Bare `a` has two carriers after the move, so the minimal honest+ // spelling is the suffix-less path.+ expect(read("Notes/Ref.md")).toBe("pathed [[Archive/Old/a]]\n");+ expect(res.references.rewrittenSpellings).toEqual([+ { from: "Projects/Old/a.md", to: "Archive/Old/a" },+ { from: "Projects/Old/a", to: "Archive/Old/a" },+ ]);+ });++ test("rewrites sibling path-spelled links inside the moved folder itself", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/b.md", "see [[Projects/Old/a]]\n");++ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(read("Archive/Old/b.md")).toBe("see [[a]]\n");+ });++ test("rewrites Brain artifact references and never rewrites the append-only log", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Brain/reports/weekly.md", "- ref [[Projects/Old/a]]\n");+ note("Brain/log/2026-10-26.md", "- saw [[Projects/Old/a]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(read("Brain/reports/weekly.md")).toBe("- ref [[a]]\n");+ // Testimony is read and reported, never rewritten.+ expect(read("Brain/log/2026-10-26.md")).toBe("- saw [[Projects/Old/a]]\n");+ expect(res.references.inboundFiles).toContain("Brain/log/2026-10-26.md");+ });++ test("refuses a destination sharing the source's parent - that is rename-folder", async () => {+ note("Projects/Old/a.md", "x\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Projects/Elsewhere",+ apply: true,+ }),+ ).rejects.toThrow(/wrong_action|use rename-folder/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });++ test("a destination directory in another parent's subtree moves without complaint", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive/2026",+ apply: true,+ });+ // `Archive/2026` sits in `Archive`, not in `Projects`, so the folder's+ // parent genuinely changes and the move is exactly what was asked for.+ expect(res.to).toBe("Archive/2026/Old");+ expect(existsSync(join(vault, "Archive/2026/Old/a.md"))).toBe(true);+ });++ test("moving to the vault root lands the folder at the top level", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "",+ apply: true,+ });+ // The root is a legitimate DESTINATION directory (a folder may land+ // at the top level) while staying refused as a SUBJECT.+ expect(res.to).toBe("Old");+ expect(existsSync(join(vault, "Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(false);+ });++ test("a destination inside the source subtree is refused - the folder would nest inside itself", async () => {+ note("Projects/Old/a.md", "alpha\n");+ mkdirSync(join(vault, "Projects/Sub"), { recursive: true });++ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects",+ to: "Projects/Sub",+ apply: true,+ });+ } catch (err) {+ caught = err;+ }++ expect(caught).toBeInstanceOf(NoteLifecycleError);+ const refusal = caught as NoteLifecycleError;+ expect(refusal.code).toBe("destination_inside_source");+ // The refusal names both paths, so the caller can see the collision.+ expect(refusal.message).toContain("Projects/Sub");+ expect(refusal.message).toContain("Projects");+ // Deeper nesting is the same refusal.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects",+ to: "Projects/Sub/Deeper",+ apply: true,+ }),+ ).rejects.toThrow(NoteLifecycleError);+ // Nothing moved: the tree is exactly where it was.+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Sub/Projects"))).toBe(false);+ });++ test("a destination that collapses onto the source folder is refused as unchanged", async () => {+ note("Projects/Old/a.md", "x\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Projects",+ apply: true,+ }),+ ).rejects.toThrow(/destination is the source folder/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });++ test("a FILE occupying the destination folder path refuses with nothing moved", async () => {+ note("Projects/Old/a.md", "source\n");+ note("Archive/Old", "occupied by a stranger\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ }),+ ).rejects.toThrow(/nothing was moved/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(read("Archive/Old")).toBe("occupied by a stranger\n");+ });++ test("an occupied destination DIRECTORY refuses with nothing moved", async () => {+ note("Projects/Old/a.md", "source\n");+ note("Archive/Old/stranger.md", "occupied\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ }),+ ).rejects.toThrow(/nothing was moved/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(read("Archive/Old/stranger.md")).toBe("occupied\n");+ });++ test("an empty destination directory is not an occupancy: the files land in it", async () => {+ note("Projects/Old/a.md", "source\n");+ mkdirSync(join(vault, "Archive/Old"), { recursive: true });++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(false);+ });++ test("an empty folder moves with an empty moved set and no residue", async () => {+ mkdirSync(join(vault, "Projects/Empty"), { recursive: true });++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Empty",+ to: "Archive",+ apply: true,+ });++ expect(res.moved).toEqual([]);+ expect(res.moveFailures).toEqual([]);+ expect(existsSync(join(vault, "Projects/Empty"))).toBe(false);+ expect(isDir("Archive/Empty")).toBe(true);+ });++ test("a spelling that matches nothing in the walk refuses instead of succeeding as a no-op", async () => {+ // The vault's real folder, as the walk spells it.+ note("Projects/Old/a.md", "alpha\n");+ // A second, differently-cased directory this host tells apart: the+ // caller's spelling stats as a real, non-empty folder while matching+ // none of the walked paths - the shape a case or normalization+ // mismatch takes on a case-insensitive host.+ mkdirSync(join(vault, "projects/old"), { recursive: true });+ writeFileSync(join(vault, "projects/old/img.png"), "png\n");++ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "projects/old",+ to: "Archive",+ apply: true,+ });+ } catch (err) {+ caught = err;+ }++ expect(caught).toBeInstanceOf(NoteLifecycleError);+ const refusal = caught as NoteLifecycleError;+ expect(refusal.code).toBe("move_set_empty");+ expect(refusal.message).toContain("projects/old");+ expect(refusal.message).toMatch(/case|normaliz/i);+ // Nothing was touched: the real folder stands and no destination+ // skeleton appeared.+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive/old"))).toBe(false);++ // A plan-only run of the same spelling is the same refusal: a plan+ // of nothing over a non-empty folder is a preview of a lie.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "projects/old",+ to: "Archive",+ }),+ ).rejects.toThrow(/move_set_empty|not empty on disk/);+ });++ test("non-Markdown residue in the source folder is named, not silently clean", async () => {+ note("Projects/Old/a.md", "alpha\n");+ writeFileSync(join(vault, "Projects/Old/img.png"), "png\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ // The note relocated; the image is not a note and did not move - and+ // the result names what stayed in the source folder after the prune.+ expect(res.leftBehind).toEqual(["img.png"]);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/img.png"))).toBe(true);++ // A move that genuinely empties its source folder names nothing.+ note("Other/Sub/b.md", "beta\n");+ const clean = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Other/Sub",+ to: "Archive",+ apply: true,+ });+ expect(clean.leftBehind).toEqual([]);+ expect(existsSync(join(vault, "Other/Sub"))).toBe(false);+ });++ test("dry run is the default: it reports the full plan and writes nothing", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Notes/Ref.md", "[[Projects/Old/a]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ });++ expect(res.applied).toBe(false);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(res.references.inboundFiles).toEqual(["Notes/Ref.md"]);+ expect(res.references.filesRewritten).toBe(0);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old"))).toBe(false);+ expect(read("Notes/Ref.md")).toBe("[[Projects/Old/a]]\n");+ });++ test.skipIf(CHMOD_CANNOT_DENY)(+ "a mid-set move failure is named, not rolled back, and the rewrite uses the moved set only",+ async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/sub/b.md", "beta\n");+ note("Notes/A.md", "moves [[Projects/Old/a]]\n");+ note("Notes/B.md", "moves [[Projects/Old/sub/b]]\n");+ // The nested directory becomes unmovable AFTER the plan and after+ // `a.md` has already relocated: the EACCES lands mid-set.+ chmodSync(join(vault, "Projects/Old/sub"), 0o500);++ let res;+ try {+ res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ } finally {+ chmodSync(join(vault, "Projects/Old/sub"), 0o700);+ }++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(res.moveFailures).toHaveLength(1);+ expect(res.moveFailures[0]!.path).toBe("Projects/Old/sub/b.md");+ // The prune could not empty the source, and the residue names what+ // is still sitting in it.+ expect(res.leftBehind).toEqual(["sub"]);+ // The residue is exactly where the report says: `a.md` is at its+ // new path, `b.md` stays at its old one.+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/sub/b.md"))).toBe(true);+ // Pairs were computed from the moved set ONLY: the link to the+ // moved note is rewritten, the link to the failed note still+ // resolves to where the bytes actually are.+ expect(read("Notes/A.md")).toBe("moves [[a]]\n");+ expect(read("Notes/B.md")).toBe("moves [[Projects/Old/sub/b]]\n");+ // The failed move leaves exactly one name for the file: the fault+ // struck after the destination name was linked, and that second+ // name was dropped - the report's "never moved" stays true.+ expect(existsSync(join(vault, "Archive/Old/sub/b.md"))).toBe(false);+ },+ );++ test.skipIf(CHMOD_CANNOT_DENY)(+ "a set where nothing moves leaves no invented destination folder behind",+ async () => {+ note("Projects/Old/a.md", "alpha\n");+ // Every relocation fails the same way: the destination name lands,+ // then dropping the source name is refused, so the set finishes+ // with nothing moved - and the destination folder the apply+ // created for the set must not stay behind as residue the report+ // contradicts.+ chmodSync(join(vault, "Projects/Old"), 0o500);+ let res;+ try {+ res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ } finally {+ chmodSync(join(vault, "Projects/Old"), 0o700);+ }++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([]);+ expect(res.moveFailures).toHaveLength(1);+ // Nothing was invented at the destination, and the source stands+ // exactly where the report says its bytes are.+ expect(existsSync(join(vault, "Archive"))).toBe(false);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ },+ );++ test.skipIf(CHMOD_CANNOT_DENY)(+ "a fully-failed set cleans its invented subtree and spares a pre-existing destination parent",+ async () => {+ // Nested source: the per-file machinery creates Archive/Old/sub for+ // the failed move, and the cleanup takes the whole invented branch,+ // not just the destination folder itself. An EMPTY Archive that was+ // already here stays - a directory that existed before is not this+ // operation's to remove, and the move lands under it.+ note("Projects/Old/sub/a.md", "alpha\n");+ mkdirSync(join(vault, "Archive"), { recursive: true });+ chmodSync(join(vault, "Projects/Old/sub"), 0o500);+ let res;+ try {+ res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ } finally {+ chmodSync(join(vault, "Projects/Old/sub"), 0o700);+ }++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([]);+ expect(res.moveFailures).toHaveLength(1);+ // The invented branch is gone down to the destination folder; the+ // pre-existing parent stands, and the source is exactly where the+ // report says its bytes are.+ expect(existsSync(join(vault, "Archive/Old"))).toBe(false);+ expect(isDir("Archive")).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/sub/a.md"))).toBe(true);+ },+ );++ test.skipIf(CHMOD_CANNOT_DENY)(+ "a partially-failed set still cleans the empty branch a failed move invented",+ async () => {+ // One note relocates; the nested one fails the source-name drop+ // after its branch was created for it. The set ends half-moved, and+ // the empty branch the failed move invented must not stand beside a+ // report that says it never moved - while the moved note's own+ // branch, holding real bytes, does.+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/sub/b.md", "beta\n");+ chmodSync(join(vault, "Projects/Old/sub"), 0o500);+ let res;+ try {+ res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ } finally {+ chmodSync(join(vault, "Projects/Old/sub"), 0o700);+ }++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(res.moveFailures).toHaveLength(1);+ expect(res.moveFailures[0]!.path).toBe("Projects/Old/sub/b.md");+ // The moved note stands; the failed move's invented branch is gone.+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old/sub"))).toBe(false);+ // The source keeps the failed file exactly where the report says.+ expect(existsSync(join(vault, "Projects/Old/sub/b.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(true);+ },+ );++ test("a foreign file at a cleared destination name survives the move's fault", async () => {+ note("Projects/Old/a.md", "alpha\n");+ // The pre-flight cleared the destination name; a foreign file appears+ // there before the link - the race the occupied-name guard exists+ // for, produced through the relocation seam. The refusal is the move's+ // own, and the cleanup must not unlink bytes it did not write.+ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ relocate: (_fromAbs, toAbs, label) => {+ writeFileSync(toAbs, "foreign bytes\n");+ throw new NoteLifecycleError(+ "destination_occupied",+ `destination already exists: ${label}`,+ );+ },+ });++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([]);+ expect(res.moveFailures).toHaveLength(1);+ expect(res.moveFailures[0]!.path).toBe("Projects/Old/a.md");+ expect(res.moveFailures[0]!.reason).toContain("destination already exists");+ // The foreign file stands, and the invented branch around it stands+ // with it; the source still holds the note.+ expect(readFileSync(join(vault, "Archive/Old/a.md"), "utf8")).toBe("foreign bytes\n");+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });++ test("a top-level folder moves under a sibling top-level directory", async () => {+ note("Old/a.md", "alpha\n");+ mkdirSync(join(vault, "Archive"), { recursive: true });++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Old",+ to: "Archive",+ apply: true,+ });++ expect(res.from).toBe("Old");+ expect(res.to).toBe("Archive/Old");+ expect(res.moved).toEqual([{ from: "Old/a.md", to: "Archive/Old/a.md" }]);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Old"))).toBe(false);+ });++ test("a clean nested move leaves no empty skeleton and names no residue", async () => {+ note("Projects/Old/sub/deep/b.md", "beta\n");+ note("Projects/Old/a.md", "alpha\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.moveFailures).toEqual([]);+ expect(res.leftBehind).toEqual([]);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(false);+ expect(existsSync(join(vault, "Projects/Old/sub"))).toBe(false);+ expect(existsSync(join(vault, "Archive/Old/sub/deep/b.md"))).toBe(true);+ });++ test("directories the move never touched keep standing after a partial prune", async () => {+ // One note moves; a no-Markdown subtree and a pre-existing empty+ // sibling stay. The prune's candidates are the MOVED files' ancestor+ // chains, so the removal cannot walk the source's subtree and delete+ // directories this operation never touched - and the source folder+ // itself stands because the untouched residue still fills it.+ note("Projects/Old/a.md", "alpha\n");+ mkdirSync(join(vault, "Projects/Old/sub"), { recursive: true });+ writeFileSync(join(vault, "Projects/Old/sub/img.png"), "png\n");+ mkdirSync(join(vault, "Projects/Old/empty"), { recursive: true });++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(res.leftBehind).toEqual(["empty", "sub"]);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/sub/img.png"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/empty"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ });++ test("the prune never follows a symlinked directory out of the source", async () => {+ // The candidates are derived from moved files' vault-relative+ // spellings, never from a filesystem walk of the source: a linked+ // directory under the source is neither descended into nor offered+ // to the removal, so nothing outside the source - here a real empty+ // directory the link resolves to - is this operation's to delete.+ note("Projects/Old/a.md", "alpha\n");+ mkdirSync(join(vault, "Outside/inner"), { recursive: true });+ symlinkSync(join(vault, "Outside"), join(vault, "Projects/Old/link"), "dir");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(existsSync(join(vault, "Outside/inner"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/link"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ });++ test.skipIf(!FOLDS_CASE)(+ "a case-only folder rename is refused rather than half-reported",+ async () => {+ note("Projects/Old/a.md", "alpha\n");+ // The refusal exists for the host that folds case: there the two+ // spellings name one directory entry, which moving files cannot+ // re-case. A host that tells them apart reaches an ordinary rename+ // instead, so the test is SKIPPED there - reported as a skip, never+ // a silent early pass.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: "Projects/Old",+ to: "old",+ apply: true,+ }),+ ).rejects.toThrow(/destination_unchanged|case-only/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ },+ );++ test("a folder holding only attachments moves an empty set and keeps its contents", async () => {+ mkdirSync(join(vault, "Assets/img"), { recursive: true });+ writeFileSync(join(vault, "Assets/img/logo.png"), "png\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Assets/img",+ to: "Archive",+ apply: true,+ });++ expect(res.moved).toEqual([]);+ expect(res.moveFailures).toEqual([]);+ expect(res.leftBehind).toEqual(["logo.png"]);+ expect(existsSync(join(vault, "Assets/img/logo.png"))).toBe(true);+ expect(existsSync(join(vault, "Archive/img/logo.png"))).toBe(false);+ // A folder that keeps its entries creates nothing at the destination:+ // an empty directory the move invented is residue in the vault.+ expect(existsSync(join(vault, "Archive/img"))).toBe(false);+ });++ test("a dry run reports the spellings the apply would write", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Notes/Ref.md", "pathed [[Projects/Old/a]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Elsewhere",+ });++ expect(res.applied).toBe(false);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Elsewhere/Old/a.md" }]);+ expect(res.references.rewrittenSpellings).toEqual([+ { from: "Projects/Old/a.md", to: "a" },+ { from: "Projects/Old/a", to: "a" },+ ]);+ });+});++describe("rename-folder", () => {+ test("renames in place and rewrites path-spelled links", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Notes/Ref.md", "pathed [[Projects/Old/a]]\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: "Projects/Old",+ to: "New",+ apply: true,+ });++ expect(res.from).toBe("Projects/Old");+ expect(res.to).toBe("Projects/New");+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Projects/New/a.md" }]);+ expect(existsSync(join(vault, "Projects/New/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(false);+ expect(read("Notes/Ref.md")).toBe("pathed [[a]]\n");+ });++ test("a cross-parent destination is refused - that is move-folder", async () => {+ note("Projects/Old/a.md", "x\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: "Projects/Old",+ to: "Elsewhere/Old",+ apply: true,+ }),+ ).rejects.toThrow(/wrong_action|use move-folder/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });++ test("a multi-segment name is a cross-parent move and is refused by name", async () => {+ note("Projects/Old/a.md", "x\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: "Projects/Old",+ to: "Sub/New",+ apply: true,+ }),+ ).rejects.toThrow(/wrong_action|use move-folder/);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });++ test("delete and archive are note-file actions and refuse a folder subject", async () => {+ mkdirSync(join(vault, "Projects/Old"), { recursive: true });+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.delete,+ path: "Projects/Old",+ apply: true,+ }),+ ).rejects.toThrow(NoteLifecycleError);+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.archive,+ path: "Projects/Old",+ apply: true,+ }),+ ).rejects.toThrow(NoteLifecycleError);+ expect(isDir("Projects/Old")).toBe(true);+ });++ test("the archive root is an ordinary destination for move-folder - no archive semantics here", async () => {+ note("Projects/Old/a.md", "x\n");+ // The folder surface has no archive action; a caller-chosen+ // destination that happens to be named like one is just a move, with+ // no confirm ladder beyond the surface's own.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: NOTE_ARCHIVE_ROOT,+ apply: true,+ }),+ ).resolves.toBeDefined();+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ });+});++describe("the count guard over the folder move set", () => {+ test("--expect counts the files the apply will write, not the files moved", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/b.md", "beta\n");+ note("Notes/Ref.md", "[[Projects/Old/a]] and [[Projects/Old/b]]\n");++ // Two notes move; ONE file holds the inbound references the apply+ // will write. The plan names that file and `--expect` counts it.+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ expect: 7,+ }),+ ).rejects.toThrow();+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ expect: 1,+ });+ expect(res.applied).toBe(true);+ expect(res.moved).toHaveLength(2);+ expect(res.references.inboundFiles).toEqual(["Notes/Ref.md"]);+ });++ test("a strict mutation without --expect is refused before anything moves", async () => {+ note("Projects/Old/a.md", "x\n");+ note("Notes/Ref.md", "[[Projects/Old/a]]\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ strict: true,+ }),+ ).rejects.toThrow();+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });+});++describe("the folder result's evidence tail", () => {+ test("an applied move claims the detached index refresh and reports the index evidence", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ expect(res.references.index.state.length).toBeGreaterThan(0);+ expect(res.references.index.nextCommand.length).toBeGreaterThan(0);+ expect(res.references.refresh).toBeDefined();+ // A relocation destroys nothing, so no snapshot is taken - the field+ // is null for shape parity with the file surface, and the verdict+ // covers the REWRITE.+ expect(res.snapshot).toBeNull();+ expect(res.recoverability.state.length).toBeGreaterThan(0);+ });++ test("a plan-only run claims nothing and refused nothing", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ });+ expect(res.references.refresh).toBeDefined();+ expect(res.references.refreshReason).toBeNull();+ });+});++describe("the file surface keeps refusing folder subjects", () => {+ test("noteLifecycle refuses a folder path - it has no .md rung to pass", async () => {+ mkdirSync(join(vault, "Projects/Old"), { recursive: true });+ await expect(+ noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old",+ to: "Projects/New",+ apply: true,+ }),+ ).rejects.toThrow(/\.md/);+ await expect(+ noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.delete,+ path: "Projects/Old",+ apply: true,+ confirm: true,+ }),+ ).rejects.toThrow(/\.md/);+ expect(readdirSync(join(vault, "Projects"))).toContain("Old");+ });++ test("noteLifecycle refuses the folder actions by name - the machinery is two modules", async () => {+ note("Projects/a.md", "x\n");+ // One vocabulary, two machines: `move-folder` sent to the FILE surface+ // must not fall through to the file envelope and report a one-file+ // result for a many-file operation.+ await expect(+ noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/a.md",+ to: "Elsewhere",+ apply: true,+ }),+ ).rejects.toThrow(/wrong_action|folder action/);+ await expect(+ noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.renameFolder,+ path: "Projects/a.md",+ to: "Renamed",+ apply: true,+ }),+ ).rejects.toThrow(NoteLifecycleError);+ expect(existsSync(join(vault, "Projects/a.md"))).toBe(true);+ });+});++/**+ * The move set is judged by REAL LOCATION (H2, M18): the vault walk lists+ * a file under whichever alias of its directory won the walk, so both the+ * membership decision and the spelling every report and rewrite pair+ * carries are decided by where a file really lives - inside the source's+ * real path - never by the spelling the walk happened to reach it+ * through. The two alias orders below are written to hold regardless of+ * which spelling wins the walk on any host.+ */+describe("symlinked entries in the move set (judged by real location)", () => {+ test("a symlinked directory inside the source excludes the foreign notes it reaches (H2, order one)", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Alpha/Deep/real.md", "real body\n");+ note("Index.md", "[[Projects/Old/a]] and [[Alpha/Deep/real]]\n");+ symlinkSync(join(vault, "Alpha/Deep"), join(vault, "Projects/Old/link"), "dir");++ // The plan already shows the truth: only the folder's OWN note moves.+ const plan = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ });+ expect(plan.applied).toBe(false);+ expect(plan.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ // The foreign note keeps its real location under either walked+ // spelling, and no name for it appears at the destination.+ expect(existsSync(join(vault, "Alpha/Deep/real.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive/Old/link/real.md"))).toBe(false);+ // The link itself is neither followed nor removed: it is the residue,+ // named like any other entry the move could not carry.+ expect(res.leftBehind).toEqual(["link"]);+ expect(existsSync(join(vault, "Projects/Old/link"))).toBe(true);+ // The foreign note's inbound link is untouched; the moved note's is+ // rewritten. Before the real-location judgment the foreign note was+ // relocated under the link spelling with NO rewrite pair, and+ // `[[Alpha/Deep/real]]` dangled.+ expect(read("Index.md")).toBe("[[a]] and [[Alpha/Deep/real]]\n");+ });++ test("an alias walked before the source is normalized to the real spelling, not a silent no-op (H2, order two)", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Index.md", "[[Projects/Old/a]]\n");+ // `Zed` sorts after `Projects`, so the walk reaches the source THROUGH+ // the alias first and lists the note under the alias spelling only -+ // the order that used to leave `movingSet` empty and report+ // applied:true with nothing moved.+ mkdirSync(join(vault, "Zed"), { recursive: true });+ symlinkSync(join(vault, "Projects/Old"), join(vault, "Zed/alias"), "dir");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.applied).toBe(true);+ // The move set carries the REAL spelling - the name the disk answers+ // to and the name inbound links are spelled with - so the rewrite+ // pair exists and `[[Projects/Old/a]]` does not dangle.+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(false);+ expect(read("Index.md")).toBe("[[a]]\n");+ // The source folder genuinely emptied and went; the operator's own+ // alias is the only thing left pointing at a former address.+ expect(existsSync(join(vault, "Projects/Old"))).toBe(false);+ expect(res.leftBehind).toEqual([]);+ });++ test("a symlinked note is excluded and named, never hard-linked (M18)", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Other/x.md", "elsewhere\n");+ // A RELATIVE target, the shape that dangles when the symlink itself is+ // hard-linked at a new depth.+ symlinkSync("../../Other/x.md", join(vault, "Projects/Old/l.md"));++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ // The symlinked note is named as what stayed...+ expect(res.leftBehind).toEqual(["l.md"]);+ expect(lstatSync(join(vault, "Projects/Old/l.md")).isSymbolicLink()).toBe(true);+ // ...and no name for it was created at the destination: linking the+ // symlink used to leave a dangling `Archive/Old/l.md` behind.+ expect(lstatSync(join(vault, "Archive/Old/l.md"), { throwIfNoEntry: false })).toBeUndefined();+ // The real target is untouched at its real location.+ expect(read("Other/x.md")).toBe("elsewhere\n");+ });++ test("a dangling name a mid-set fault created is dropped by the cleanup (M18)", async () => {+ note("Projects/Old/a.md", "alpha\n");+ // The relocation seam leaves a SYMLINK at the destination name whose+ // target does not exist - the exact shape a hard-linked symlinked+ // note produced - and then reports the fault. `existsSync` follows+ // the link, sees nothing and skips the unlink; a name this call+ // created must be dropped even when it dangles.+ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ relocate: (fromAbs, toAbs, label) => {+ symlinkSync(join(fromAbs, "../never-here.md"), toAbs);+ throw new Error(`noteLifecycle: write of ${label} reported success but the file is absent`);+ },+ });++ expect(res.applied).toBe(true);+ expect(res.moved).toEqual([]);+ expect(res.moveFailures).toHaveLength(1);+ expect(res.moveFailures[0]!.path).toBe("Projects/Old/a.md");+ expect(lstatSync(join(vault, "Archive/Old/a.md"), { throwIfNoEntry: false })).toBeUndefined();+ expect(existsSync(join(vault, "Archive/Old"))).toBe(false);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ });+});++/**+ * The destination is judged by real path on both sides (M15), and the+ * rename-intent heuristic only fires when the named destination directory+ * does not exist (M16).+ */+describe("the destination's real path and existence", () => {+ test("a destination that is a symlink alias of the source is refused as nesting (M15)", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Index.md", "[[Projects/Old/a]]\n");+ mkdirSync(join(vault, "Aa/Deep"), { recursive: true });+ symlinkSync(join(vault, "Projects/Old"), join(vault, "Aa/Deep/Link"), "dir");++ for (const apply of [false, true]) {+ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Aa/Deep/Link",+ apply,+ });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(NoteLifecycleError);+ const refusal = caught as NoteLifecycleError;+ expect(refusal.code).toBe("destination_inside_source");+ expect(refusal.message).toContain("Projects/Old");+ }+ // Nothing was linked into the source: the alias spelled a path+ // outside the folder while naming the folder itself, and the spelled+ // guard used to let it fold `Old/` inside `Projects/Old`.+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/Old"))).toBe(false);+ expect(read("Index.md")).toBe("[[Projects/Old/a]]\n");+ });++ test.skipIf(!FOLDS_CASE)(+ "a case-folded destination inside the source is refused by real path (M15)",+ async () => {+ note("Projects/Old/a.md", "alpha\n");+ // On the folding host this IS `Projects/Old/sub/deeper` - inside the+ // source but not the source itself - although its spelling never+ // matches the spelled guard. (A destination folding onto the source+ // itself is the destination_unchanged refusal, covered elsewhere.)+ mkdirSync(join(vault, "projects/old/sub/deeper"), { recursive: true });+ let caught: unknown;+ try {+ await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "projects/old/sub/deeper",+ apply: true,+ });+ } catch (err) {+ caught = err;+ }+ // On a case-sensitive host the spelled rung refuses (the spelled+ // destination realpaths strictly inside the source); on a folding+ // host the platform realpath preserves the caller's casing, so the+ // refusal comes from the identity rung - the directory entry IS the+ // source. Either way the code is the same.+ expect(caught).toBeInstanceOf(NoteLifecycleError);+ expect((caught as NoteLifecycleError).code).toBe("destination_inside_source");+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/sub/Old"))).toBe(false);+ },+ );++ test("a move into an EXISTING sibling folder works in one call (M16)", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/b.md", "beta\n");+ note("Index.md", "[[Projects/Old/a]]\n");+ mkdirSync(join(vault, "Projects/Archive"), { recursive: true });++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Projects/Archive",+ apply: true,+ });++ // An existing sibling directory is a real move target, not the+ // spelling of a rename intent - the refusal that pointed at+ // rename-folder (which points back here for a cross-parent move)+ // used to make this move impossible in one call.+ expect(res.applied).toBe(true);+ expect(res.to).toBe("Projects/Archive/Old");+ expect(res.moved.map((m) => m.to).toSorted()).toEqual([+ "Projects/Archive/Old/a.md",+ "Projects/Archive/Old/b.md",+ ]);+ expect(existsSync(join(vault, "Projects/Old"))).toBe(false);+ expect(read("Index.md")).toBe("[[a]]\n");+ });++ test("a NON-existent sibling destination is still the rename-intent refusal (M16)", async () => {+ note("Projects/Second/c.md", "c\n");+ await expect(+ folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Second",+ to: "Projects/Nowhere",+ apply: true,+ }),+ ).rejects.toThrow(/use rename-folder/);+ expect(existsSync(join(vault, "Projects/Second/c.md"))).toBe(true);+ });+});++/**+ * Only Markdown moves; the receipt says what that honestly costs (M17):+ * a moved note's RELATIVE Markdown links and images depend on the note's+ * directory, which the move changed, and when the target stayed behind+ * the receipt names the pair instead of letting `files_rewritten: 0`+ * read as "nothing broke".+ */+describe("relative links the move leaves dangling (M17)", () => {+ test("a moved note's relative embed whose target stayed behind is named; targets that moved are not", async () => {+ note(+ "Projects/Old/a.md",+ "\n" ++ "[nested](./sub/other.md)\n" ++ "\n" ++ "[remote](https://example.com/x.png)\n" ++ "\n",+ );+ note("Projects/Old/sub/other.md", "nested\n");+ writeFileSync(join(vault, "Projects/Old/diagram.png"), "png\n");++ // The plan previews the same judgment from the planned set.+ const plan = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ });+ expect(plan.applied).toBe(false);+ expect(plan.danglingRelativeLinks).toEqual([+ { note: "Archive/Old/a.md", target: "diagram.png" },+ ]);++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.applied).toBe(true);+ // The embed whose target is not a note stayed behind - named per note+ // and target, exactly as the note spells it.+ expect(res.danglingRelativeLinks).toEqual([+ { note: "Archive/Old/a.md", target: "diagram.png" },+ ]);+ // The attachment itself is in the residue, the file surface's own+ // honest answer for what a Markdown-only move leaves.+ expect(res.leftBehind).toEqual(["diagram.png"]);+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/diagram.png"))).toBe(true);+ // A target that moved WITH the folder still resolves and is not+ // named; a vault-absolute or scheme spelling never depended on the+ // note's directory; a link that was already dangling is not this+ // operation's doing.+ expect(existsSync(join(vault, "Archive/Old/sub/other.md"))).toBe(true);+ });++ test("a move whose relative targets all move with it names no dangling links", async () => {+ note("Projects/Old/a.md", "\n");+ note("Projects/Old/img/keep.md", "the target set is Markdown, so this moves too\n");++ const res = await folderLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.moveFolder,+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res.moved).toHaveLength(2);+ expect(res.danglingRelativeLinks).toEqual([]);+ });+});diff --git a/tests/core/brain/portability/knowledge-pack.test.ts b/tests/core/brain/portability/knowledge-pack.test.tsindex 1d4043ce..ec154cad 100644--- a/tests/core/brain/portability/knowledge-pack.test.ts+++ b/tests/core/brain/portability/knowledge-pack.test.ts@@ -92,6 +92,15 @@ function page(vault: string, rel: string, content: string): void {writeFileSync(abs, content, "utf8");}+/**+ * Hand-add an informal privacy marker to a written preference, the way+ * an operator does: a user-tier frontmatter line on the file.+ */+function stampPrefMarker(vault: string, slug: string, line: string): void {+ const abs = join(brainDirs(vault).preferences, `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+}+/** The source vault every test starts from. */function seedSource(): void {pref(src, { slug: "writing-rule", topic: "writing" });@@ -185,6 +194,39 @@ describe("export", () => {});expect(JSON.stringify(selected)).not.toContain("informally marked incident notes");});++ test("a privacy-marked preference is blocked as visibility, not carried redacted", () => {+ // The pack carries preferences with the body dropped but the+ // principle line verbatim, so there is no redacted ride for a+ // reserved rule: it is dropped from the carried rows and named in+ // `blocked`, the same way a page carrying `visibility:` is.+ pref(src, { slug: "writing-rule", topic: "writing" });+ pref(src, { slug: "marked-rule", topic: "writing" });+ stampPrefMarker(src, "marked-rule", "access: private");++ const selected = selectKnowledgePack(src, ["pref-marked-rule", "pref-writing-rule"]);+ expect(selected.preferences.map((row) => row.id)).toEqual(["pref-writing-rule"]);+ expect(selected.blocked).toContainEqual({+ kind: "preference",+ id: "pref-marked-rule",+ reason: "visibility",+ });+ // The selector naming the reserved rule was MATCHED - the block names+ // it - so the run is a named omission, never "matched nothing".+ expect(JSON.stringify(selected)).not.toContain("rule marked-rule");+ });++ test("selecting only a denied preference refuses with the every-entry-blocked error", () => {+ pref(src, { slug: "marked-rule", topic: "writing" });+ stampPrefMarker(src, "marked-rule", "sensitivity: confidential");++ // The every-entry-blocked path must still read correctly when the+ // only selected entry was withheld by the privacy markers rather+ // than by an owner claim.+ expect(() => selectKnowledgePack(src, ["pref-marked-rule"])).toThrow(+ "every selected entry was blocked as private; nothing is left to pack",+ );+ });});describe("preview", () => {diff --git a/tests/core/brain/sdk-llms-txt.test.ts b/tests/core/brain/sdk-llms-txt.test.tsnew file mode 100644index 00000000..38f675bf--- /dev/null+++ b/tests/core/brain/sdk-llms-txt.test.ts@@ -0,0 +1,84 @@+/**+ * SDK llms-txt export surface (facade test).+ *+ * The SDK's `exportPreferencesLlmsTxt` string form carries no denial+ * report - reserved rows leave the text silently. The detailed variant+ * on the facade is what an in-process caller uses to name what stayed+ * out, the same additive report the json lane carries in its envelope.+ * The string form keeps its exact behavior: same text, no report.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createBrain } from "../../../src/core/brain/sdk.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-sdk-llms-txt-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+});+afterEach(() => rmSync(vault, { recursive: true, force: true }));++/** Hand-add an informal privacy marker, the way an operator does. */+function stampMarker(slug: string, line: string): void {+ const abs = join(vault, "Brain", "preferences", `pref-${slug}.md`);+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/^---\n/, `---\n${line}\n`));+}++function seed(slug: string, principle: string): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: "high",+ confidence_value: 0.8,+ pinned: false,+ });+}++describe("createBrain llms-txt export", () => {+ test("the detailed variant returns the text beside the omissions", () => {+ seed("open", "Open principle");+ seed("reserved", "Reserved principle");+ stampMarker("reserved", "access: private");++ const brain = createBrain(vault);+ const detail = brain.exportPreferencesLlmsTxtDetailed();+ expect(detail.text).toContain("pref-open");+ expect(detail.text).toContain("Open principle");+ expect(detail.text).not.toContain("pref-reserved");+ expect(detail.omitted).toEqual([+ { id: "pref-reserved", reason: "visibility", denied_by: "access" },+ ]);+ });++ test("the string form keeps its behavior and agrees with the detailed text", () => {+ seed("open", "Open principle");+ seed("reserved", "Reserved principle");+ stampMarker("reserved", "access: private");++ const brain = createBrain(vault);+ expect(brain.exportPreferencesLlmsTxt()).toBe(brain.exportPreferencesLlmsTxtDetailed().text);+ expect(brain.exportPreferencesLlmsTxt()).not.toContain("pref-reserved");+ });++ test("an unmarked vault omits nothing", () => {+ seed("plain", "Plain principle");+ const detail = createBrain(vault).exportPreferencesLlmsTxtDetailed();+ expect(detail.omitted).toEqual([]);+ expect(detail.text).toContain("pref-plain");+ });+});diff --git a/tests/core/brain/session-identity-check.test.ts b/tests/core/brain/session-identity-check.test.tsindex 59a2684c..89826d9f 100644--- a/tests/core/brain/session-identity-check.test.ts+++ b/tests/core/brain/session-identity-check.test.ts@@ -270,11 +270,13 @@ const APPEND_PRIMITIVES: ReadonlyArray<string> = Object.freeze([/*** A payload stamp written unconditionally, from a required binding.- * `session_id: sessionId`, `session_id: input.sessionId`, ...- * (`session_id?: string` in an interface is not a stamp; a read of- * `payload["session_id"]` is not one either.)+ * `session_id: sessionId`, `session_id: input.sessionId`, or the same+ * stamp under the shared key constant the hook writers use+ * (`[CONTINUITY_SESSION_ID_KEY]: sessionId`). (`session_id?: string` in+ * an interface is not a stamp; a read of `payload["session_id"]` is not+ * one either.)*/-const UNCONDITIONAL_STAMP_RE = /session_id: [A-Za-z$_]/;+const UNCONDITIONAL_STAMP_RE = /(?:session_id|\[CONTINUITY_SESSION_ID_KEY\]): [A-Za-z$_]/;/*** The conditional-spread shape the sessionless lanes stamp with:@@ -283,6 +285,9 @@ const UNCONDITIONAL_STAMP_RE = /session_id: [A-Za-z$_]/;*/const CONDITIONAL_STAMP_RE = /\? \{ (?:\[CONTINUITY_SESSION_ID_KEY\]|session_id\b)/;+/** The Stop hook that writes `reply_presence`, outside src. */+const HOOK_WRITER = "../hooks/answer-quote-check.ts";+/*** Every kind the census classifies, with the module(s) whose code shapes* that kind's payload. The writers of `source_invalidation` all funnel@@ -386,6 +391,19 @@ const KIND_WRITERS: ReadonlyArray<{sessionScoped: false,writers: ["core/brain/receipts/compact.ts"],},+ {+ // The verified-delivery wave's additive kind (t_f8510c55): the+ // answer-quote-check Stop hook's per-turn fold of per-injected-note+ // verdicts. Written ONLY by the Stop hook, outside src - the one+ // kind whose writer lives past the src root, named with its root so+ // the writer-shape check reads it where it lives. The hook appends+ // the record only when the host names a session, and stamps the key+ // on every payload it appends, so a record never exists without one:+ // session-scoped, exactly like the session_turn lane.+ kind: "reply_presence",+ sessionScoped: true,+ writers: [HOOK_WRITER],+ },]);/**@@ -482,8 +500,13 @@ describe("blank-session-identity classification census", () => {// Any module that binds an append primitive writes SOME kind's// payload; if it is not classified above, its kinds are counted (or// spared) by a writer this census never read. Exempted: the bench- // fixture, which writes throwaway ledgers for timing runs.- const writers = new Set(KIND_WRITERS.flatMap((row) => row.writers));+ // fixture, which writes throwaway ledgers for timing runs, and the+ // Stop hook, which writes `reply_presence` from outside the src+ // tree this population walks - both named writers above, never+ // silent ones.+ const writers = new Set(+ KIND_WRITERS.flatMap((row) => row.writers).filter((writer) => writer !== HOOK_WRITER),+ );const population = srcModulePaths().filter((path) => {const code = lexSource(readFileSync(join(SRC_ROOT, path), "utf8")).code;return APPEND_PRIMITIVES.some((primitive) => code.includes(primitive));diff --git a/tests/core/config-counterparty-brief.test.ts b/tests/core/config-counterparty-brief.test.tsindex ad9c767a..87c56465 100644--- a/tests/core/config-counterparty-brief.test.ts+++ b/tests/core/config-counterparty-brief.test.ts@@ -7,12 +7,14 @@ import {resolveCounterpartyBriefEnabled,resolveCounterpartyBriefTriggers,resolveEntityFactsContextPack,+ resolveTailTrimContextPack,} from "../../src/core/config.ts";/** Env keys these tests own outright, whatever the outer shell set. */const OWNED_ENV = ["OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED","OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK",+ "OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK",] as const;let tmp: string;@@ -120,6 +122,36 @@ describe("resolveCounterpartyBriefTriggers", () => {});});+describe("resolveTailTrimContextPack", () => {+ test("defaults to false with no config and no env", () => {+ expect(resolveTailTrimContextPack(configPath)).toBe(false);+ });++ test("turns on from the config key", () => {+ writeConfig({ tail_trim_context_pack: "true" });+ expect(resolveTailTrimContextPack(configPath)).toBe(true);+ });++ test("the env override wins over the config key", () => {+ writeConfig({ tail_trim_context_pack: "false" });+ process.env["OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK"] = "1";+ expect(resolveTailTrimContextPack(configPath)).toBe(true);+ process.env["OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK"] = "true";+ expect(resolveTailTrimContextPack(configPath)).toBe(true);+ });++ test("an env override can hold the gate off against an on config", () => {+ writeConfig({ tail_trim_context_pack: "true" });+ process.env["OPEN_SECOND_BRAIN_TAIL_TRIM_CONTEXT_PACK"] = "0";+ expect(resolveTailTrimContextPack(configPath)).toBe(false);+ });++ test("only the truthy literals turn it on", () => {+ writeConfig({ tail_trim_context_pack: "on" });+ expect(resolveTailTrimContextPack(configPath)).toBe(false);+ });+});+describe("resolveEntityFactsContextPack", () => {test("defaults to false with no config and no env", () => {expect(resolveEntityFactsContextPack(configPath)).toBe(false);diff --git a/tests/core/doctor-readiness.test.ts b/tests/core/doctor-readiness.test.tsindex e5996fa5..2249d378 100644--- a/tests/core/doctor-readiness.test.ts+++ b/tests/core/doctor-readiness.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";@@ -10,7 +10,9 @@ import {READINESS_STATUS,READINESS_STATUSES,ReadinessTimeoutError,+ clientAskBudgetMs,isReadinessStatus,+ probeClientVersions,probeEmbeddingProvider,probeInstalledRuntimes,probeLlmKey,@@ -18,8 +20,10 @@ import {probeRuntimeAdapterWiring,probeWritebackContract,runReadinessProbes,+ spawnClientVersion,withReadinessTimeout,} from "../../src/core/doctor-readiness.ts";+import { DOCTOR_EXIT, doctorExitCode } from "../../src/cli/main.ts";import { buildPayload } from "../../src/core/install/payload.ts";import { serializeMcpServerTable } from "../../src/core/install/grok-config.ts";import { registerAllAdapters } from "../../src/core/install/adapters/all.ts";@@ -875,9 +879,14 @@ describe("probeWritebackContract", () => {test("the probe is registered in DEFAULT_PROBES beside registered_commands", () => {const names = DEFAULT_PROBES.map((p) => p.name);expect(names).toContain(READINESS_PROBE.writebackContract);- expect(names.indexOf(READINESS_PROBE.writebackContract)).toBe(+ // client_versions (t_8e49ec96) slots in after registered_commands;+ // writeback_contract follows it.+ expect(names.indexOf(READINESS_PROBE.clientVersions)).toBe(names.indexOf(READINESS_PROBE.registeredCommands) + 1,);+ expect(names.indexOf(READINESS_PROBE.writebackContract)).toBe(+ names.indexOf(READINESS_PROBE.clientVersions) + 1,+ );});test("a default readiness run includes the probe verdict", async () => {@@ -893,3 +902,350 @@ describe("probeWritebackContract", () => {expect(probe!.status).toBe(READINESS_STATUS.skipped);});});++describe("probeClientVersions", () => {+ /**+ * The probe reads the install manifest and asks each recorded target's+ * client its version through the injected `clientVersionRunner` seam,+ * so no test spawns a real client binary and a developer shell cannot+ * flip a verdict.+ */+ function versionsOpts(+ runner: (argv: ReadonlyArray<string>) => Promise<{ exitCode: number; stdout: string }>,+ ) {+ return { ...installedRuntimeOpts(), clientVersionRunner: runner };+ }++ function codexManifest(): void {+ writeManifestEntries({ codex: manifestEntry("codex", null, "codex-toml") });+ }++ /**+ * Poll a pid's liveness by signal 0 until it is gone, bounded - the+ * kill a timeout issues is asynchronous, so the reap lands a tick+ * after the runner's promise rejects.+ */+ async function pollUntilGone(pid: number, deadlineMs: number): Promise<boolean> {+ let alive = true;+ try {+ process.kill(pid, 0);+ } catch {+ alive = false;+ }+ if (!alive) return true;+ if (Date.now() > deadlineMs) return false;+ await Bun.sleep(25);+ return pollUntilGone(pid, deadlineMs);+ }++ test("an answered spawn passes with the raw first stdout line, never semver-parsed", async () => {+ writeConfig("");+ codexManifest();+ const v = await probeClientVersions(+ versionsOpts(async () => ({+ exitCode: 0,+ stdout: "codex-cli 0.9.0 (2026-10-01)\n",+ })),+ );+ expect(v.status).toBe(READINESS_STATUS.pass);+ expect(v.rows).toBeDefined();+ expect(v.rows).toHaveLength(1);+ expect(v.rows![0]).toMatchObject({+ target: "codex",+ status: READINESS_STATUS.pass,+ version: "codex-cli 0.9.0 (2026-10-01)",+ });+ });++ test("a runner throw yields an unknown row pointing at registered_commands, never a fail", async () => {+ writeConfig("");+ codexManifest();+ const v = await probeClientVersions(+ versionsOpts(async () => {+ throw Object.assign(new Error("spawn codex ENOENT"), { code: "ENOENT" });+ }),+ );+ expect(v.status).toBe(READINESS_STATUS.unknown);+ expect(v.status).not.toBe(READINESS_STATUS.fail);+ expect(v.rows![0]!.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.version).toBeNull();+ expect(v.rows![0]!.detail).toContain("ENOENT");+ // Resolvability is registered_commands' finding, not this row's.+ expect(v.rows![0]!.detail).toContain("registered_commands");+ });++ test("a non-zero exit yields an unknown row naming the exit code", async () => {+ writeConfig("");+ codexManifest();+ const v = await probeClientVersions(+ versionsOpts(async () => ({+ exitCode: 1,+ stdout: "",+ })),+ );+ expect(v.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.version).toBeNull();+ // The runner contract carries exit code and stdout only - stderr is+ // ignored - so the row's reason names the exit it saw.+ expect(v.rows![0]!.detail).toContain("exited 1");+ });++ test("an empty stdout with exit 0 yields an unknown row - no answer is not a version", async () => {+ writeConfig("");+ codexManifest();+ const v = await probeClientVersions(+ versionsOpts(async () => ({+ exitCode: 0,+ stdout: " \n",+ })),+ );+ expect(v.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.detail.toLowerCase()).toContain("no version output");+ });++ test("a runner sleeping past the per-probe budget is cut off as unknown", async () => {+ writeConfig("");+ codexManifest();+ const small = await runReadinessProbes(+ { ...versionsOpts(() => new Promise(() => {})), perCheckTimeoutMs: 50 },+ [{ name: READINESS_PROBE.clientVersions, fn: probeClientVersions }],+ );+ expect(small.failed).toBe(0);+ const probe = small.probes[0]!;+ expect(probe.status).toBe(READINESS_STATUS.unknown);+ expect(probe.detail).toContain("timed out");+ });++ test("a hung version child is killed at its ask's budget, never orphaned", async () => {+ writeConfig("");+ codexManifest();+ const pidFile = join(tmp, "version-child.pid");+ // The production runner itself, through the same seam every other+ // row is graded by, at a test-sized budget, against a child that+ // would sleep far past it: `exec` replaces the shell with the+ // sleeper in place, so the pid the script wrote is the one process+ // that must die when the budget cuts the ask off.+ const v = await probeClientVersions(+ versionsOpts(() =>+ spawnClientVersion(["sh", "-c", `echo $$ > '${pidFile}'; exec sleep 30`], 150),+ ),+ );+ expect(v.rows![0]!.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.detail).toContain("timed out");+ const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);+ expect(Number.isInteger(pid)).toBe(true);+ // The kill is issued asynchronously: poll until the pid is gone,+ // bounded, rather than sleeping a fixed grace period.+ const gone = await pollUntilGone(pid, Date.now() + 5_000);+ expect(gone).toBe(true);+ }, 20000);++ test("a client whose helper holds stdout still delivers the version it printed", async () => {+ writeConfig("");+ codexManifest();+ // The M9 shape: a client whose `--version` prints the answer, forks a+ // background helper that INHERITS stdout (an update checker, a+ // daemon), and exits 0. The pipe's write end stays open in the+ // helper, so an await of stdout EOF never returns even though the+ // child answered - the ask must settle on the child's exit and read+ // what stdout buffered, not on the pipe closing.+ const v = await probeClientVersions(+ versionsOpts(() =>+ spawnClientVersion(["sh", "-c", "printf 'codex-cli 9.9.9\\n'; sleep 5 &"], 1000),+ ),+ );+ expect(v.status).toBe(READINESS_STATUS.pass);+ expect(v.rows![0]!.status).toBe(READINESS_STATUS.pass);+ expect(v.rows![0]!.version).toBe("codex-cli 9.9.9");+ }, 20000);++ test("a TERM-ignoring version child is escalated to SIGKILL and reaped", async () => {+ writeConfig("");+ codexManifest();+ const pidFile = join(tmp, "term-child.pid");+ // The M10 shape: a client that ignores SIGTERM (`trap "" TERM` keeps+ // the disposition across `exec`, so the sleeper itself never dies of+ // the first kill) outlived doctor together with its children, because+ // the budget's cut was one SIGTERM with no follow-up. The sleeper is+ // bounded at 8s so a regression cannot leak an unbounded orphan.+ const v = await probeClientVersions(+ versionsOpts(() =>+ spawnClientVersion(["sh", "-c", `echo $$ > '${pidFile}'; trap "" TERM; exec sleep 8`], 150),+ ),+ );+ expect(v.rows![0]!.status).toBe(READINESS_STATUS.unknown);+ expect(v.rows![0]!.detail).toContain("timed out");+ const pid = Number.parseInt(readFileSync(pidFile, "utf8").trim(), 10);+ expect(Number.isInteger(pid)).toBe(true);+ // The escalation lands a grace period after the SIGTERM: poll until+ // the pid is gone, bounded, rather than sleeping a fixed window.+ const gone = await pollUntilGone(pid, Date.now() + 5_000);+ expect(gone).toBe(true);+ }, 20000);++ test("a manifest recording no installs is skipped", async () => {+ writeConfig("");+ const v = await probeClientVersions(versionsOpts(async () => ({ exitCode: 0, stdout: "x\n" })));+ expect(v.status).toBe(READINESS_STATUS.skipped);+ expect(v.detail).toContain("no installs");+ });++ test("the version asks run together, not one per wait", async () => {+ writeConfig("");+ writeManifestEntries({+ codex: manifestEntry("codex", null, "codex-toml"),+ cursor: manifestEntry("cursor", null, "json-merge"),+ });+ let inFlight = 0;+ let peak = 0;+ const v = await probeClientVersions(+ versionsOpts(async (argv) => {+ inFlight += 1;+ peak = Math.max(peak, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 20));+ inFlight -= 1;+ return { exitCode: 0, stdout: `${String(argv[0])} 1.0\n` };+ }),+ );+ expect(v.status).toBe(READINESS_STATUS.pass);+ expect(peak).toBe(2);+ });++ test("slow asks inside one probe budget deliver their rows, not a bare timeout", async () => {+ writeConfig("");+ writeManifestEntries({+ codex: manifestEntry("codex", null, "codex-toml"),+ cursor: manifestEntry("cursor", null, "json-merge"),+ });+ // Two asks of 300ms each inside a 500ms probe budget: asked one at a+ // time they overrun the budget and the probe-level cutoff replaces+ // every row with a bare timeout; asked together they settle inside+ // it and the verdict carries both rows.+ const report = await runReadinessProbes(+ {+ ...versionsOpts(+ (argv) =>+ new Promise((resolve) =>+ setTimeout(() => resolve({ exitCode: 0, stdout: `${String(argv[0])} 1.0\n` }), 300),+ ),+ ),+ perCheckTimeoutMs: 500,+ },+ [{ name: READINESS_PROBE.clientVersions, fn: probeClientVersions }],+ );+ const probe = report.probes[0]!;+ expect(probe.detail).not.toContain("timed out after 500");+ expect(probe.rows).toBeDefined();+ expect(probe.rows).toHaveLength(2);+ expect(probe.status).toBe(READINESS_STATUS.pass);+ });++ test("the ask's own budget stays strictly below the probe's, at every budget", () => {+ // The 50 ms floor once clamped the child budget ABOVE a probe budget+ // under ~63 ms: the wrapper's cutoff then fired first and replaced+ // the rows with a bare timeout - the exact loss asking together+ // exists to prevent. The cap at the probe budget minus a margin,+ // less whatever the probe already spent, keeps the ask's timer ahead+ // of the wrapper's at every budget - the wrapper armed first and+ // each ask's timer is armed one spawn later, so the headroom is a+ // real margin, not a one-millisecond subtraction - and the verdict+ // always carries its rows, each naming its own timeout.+ for (const probeBudgetMs of [1, 2, 5, 40, 50, 62, 63, 64, 100, DEFAULT_READINESS_TIMEOUT_MS]) {+ expect(clientAskBudgetMs(probeBudgetMs)).toBeLessThan(probeBudgetMs);+ }+ // Normal budgets keep the 80% share's headroom between the two+ // timers, and the 50 ms floor stands whenever the probe budget+ // allows it.+ expect(clientAskBudgetMs(DEFAULT_READINESS_TIMEOUT_MS)).toBe(+ Math.floor(DEFAULT_READINESS_TIMEOUT_MS * 0.8),+ );+ expect(clientAskBudgetMs(500)).toBe(400);+ // A budget under the floor: the ask dies the margin before the+ // wrapper, and time the probe already spent comes off the ask's+ // share first.+ expect(clientAskBudgetMs(40)).toBe(35);+ expect(clientAskBudgetMs(40, 4)).toBe(31);+ // A degenerate budget clamps at zero instead of going negative: the+ // row reads timed out after 0ms, never after -1ms.+ expect(clientAskBudgetMs(0)).toBe(0);+ expect(clientAskBudgetMs(1)).toBe(0);+ });++ test("the generic target has no client binary of its own and is skipped by name", async () => {+ writeConfig("");+ writeManifestEntries({ generic: manifestEntry("generic", null, "manual") });+ const v = await probeClientVersions(versionsOpts(async () => ({ exitCode: 0, stdout: "x\n" })));+ expect(v.status).toBe(READINESS_STATUS.skipped);+ expect(v.rows).toBeDefined();+ expect(v.rows![0]).toMatchObject({+ target: "generic",+ status: READINESS_STATUS.skipped,+ version: null,+ });+ // The row, not the census detail, names the target and why.+ expect(v.rows![0]!.detail).toContain("no client binary of its own");+ expect(v.detail).toContain("1 of 1");+ });++ test("a mixed pass/unknown aggregate reads unknown with the census", async () => {+ writeConfig("");+ writeManifestEntries({+ codex: manifestEntry("codex", null, "codex-toml"),+ cursor: manifestEntry("cursor", null, "json-merge"),+ });+ const v = await probeClientVersions(+ versionsOpts(async (argv) =>+ argv[0] === "codex"+ ? { exitCode: 0, stdout: "codex-cli 0.9.0\n" }+ : { exitCode: 1, stdout: "" },+ ),+ );+ expect(v.status).toBe(READINESS_STATUS.unknown);+ expect(v.detail).toContain("1 pass");+ expect(v.detail).toContain("1 unknown");+ // The detail is the census; the rows name each client and its answer.+ expect(v.rows!.map((row) => row.target)).toEqual(["codex", "cursor"]);+ expect(v.rows!.find((row) => row.target === "cursor")!.detail).toContain("exited 1");+ });++ test("an unreadable manifest is unknown, like registered_commands", async () => {+ writeConfig("");+ writeInstallManifest("{ this is not json");+ const v = await probeClientVersions(versionsOpts(async () => ({ exitCode: 0, stdout: "x\n" })));+ expect(v.status).toBe(READINESS_STATUS.unknown);+ expect(v.detail).toContain("manifest");+ });++ test("rows ride this probe only, and a fully-unknown probe keeps the exit at 6", async () => {+ writeConfig("");+ codexManifest();+ const report = await runReadinessProbes(+ { ...versionsOpts(async () => ({ exitCode: 1, stdout: "" })), perCheckTimeoutMs: 2_000 },+ [+ { name: READINESS_PROBE.clientVersions, fn: probeClientVersions },+ {+ name: "sibling_probe",+ fn: async () => ({ status: READINESS_STATUS.pass, detail: "sibling answered" }),+ },+ ],+ );+ const versions = report.probes.find((p) => p.name === READINESS_PROBE.clientVersions)!;+ const sibling = report.probes.find((p) => p.name === "sibling_probe")!;+ expect(versions.rows).toBeDefined();+ expect(sibling.rows).toBeUndefined();++ // A fully-unknown version probe is an unmeasured surface, not a broken+ // one: the doctor exit contract keeps it at 6 (probeIncomplete), never 1.+ // The report is fabricated because `doctorExitCode` reads only the two+ // counts - the shape cast names exactly what is being faked.+ const fabricated = {+ probes: [versions],+ failed: 0,+ unknown: 1,+ } as Parameters<typeof doctorExitCode>[1];+ expect(doctorExitCode(0, fabricated)).toBe(DOCTOR_EXIT.probeIncomplete);+ expect(doctorExitCode(0, fabricated)).not.toBe(DOCTOR_EXIT.failed);+ });+});diff --git a/tests/hooks/active-inject-receipt-session.test.ts b/tests/hooks/active-inject-receipt-session.test.tsnew file mode 100644index 00000000..787d57eb--- /dev/null+++ b/tests/hooks/active-inject-receipt-session.test.ts@@ -0,0 +1,130 @@+/**+ * The `session_inject` receipt's session key (verified-delivery-honest-writes,+ * t_f8510c55 task A5): the SessionStart eager layer's context receipt carries+ * the hook payload's `session_id`, so the receipt the read surface serves can+ * be joined to the session's `reply_presence` records by exact key instead of+ * an inferred time window.+ *+ * Pinned here: a real session id lands on the receipt payload; a payload+ * without one leaves the key absent (additive optionality, the same shape+ * every other session-keyed record keeps) - and the injected context and+ * exit code are exactly what they were without the key.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { homeEnv } from "../helpers/platform.ts";+import { waitForSelfHealChildren } from "../helpers/self-heal-children.ts";++const HOOK = resolve(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ "hooks",+ "active-inject.ts",+);++const SESSION = "sess-inject-receipt-1";++let vault: string;+let configHome: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-inject-session-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-inject-session-cfg-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(async () => {+ // A SessionStart on an initialised vault spawns a detached reindex that+ // would otherwise recreate the directories removed below.+ await waitForSelfHealChildren(vault);+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++async function runHook(+ payload: Record<string, unknown>,+): Promise<{ readonly stdout: string; readonly exit: number }> {+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ env: {+ PATH: process.env["PATH"] ?? "",+ ...homeEnv(configHome),+ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",+ VAULT_DIR: vault,+ },+ });+ proc.stdin.write(JSON.stringify(payload));+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const exit = await proc.exited;+ return { stdout, exit };+}++function writeActive(body: string): void {+ writeFileSync(join(vault, "Brain", "active.md"), body, "utf8");+}++interface ReceiptRecord {+ readonly kind: string;+ readonly payload: Record<string, unknown>;+}++function injectionReceipts(): ReadonlyArray<ReceiptRecord> {+ const dir = join(vault, "Brain", "log", "continuity");+ if (!existsSync(dir)) return [];+ const out: ReceiptRecord[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".jsonl")) continue;+ for (const line of readFileSync(join(dir, name), "utf8").split("\n")) {+ if (!line.trim()) continue;+ const record = JSON.parse(line) as ReceiptRecord;+ if (record.kind === "context_receipt" && record.payload["trigger"] === "session_inject") {+ out.push(record);+ }+ }+ }+ return out;+}++const ACTIVE_BODY =+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (1)\n\n- `pref-foo` — Rule body\n";++describe("active-inject session_inject receipt session key", () => {+ test("the receipt carries the hook payload's session_id", async () => {+ writeActive(ACTIVE_BODY);+ const r = await runHook({ hook_event_name: "SessionStart", session_id: SESSION });+ expect(r.exit).toBe(0);+ const receipts = injectionReceipts();+ expect(receipts.length).toBe(1);+ expect(receipts[0]!.payload["session_id"]).toBe(SESSION);+ // The injected context is unchanged: the key is bookkeeping, not payload.+ const injected: string = JSON.parse(r.stdout).hookSpecificOutput.additionalContext;+ expect(injected.length).toBeGreaterThan(0);+ // Each test here spawns a real `bun run` hook child; pin the per-test+ // budget past bun's 5 s default so a loaded runner cannot flake it.+ }, 20000);++ test("a payload without a session_id leaves the key absent, never invented", async () => {+ writeActive(ACTIVE_BODY);+ const r = await runHook({ hook_event_name: "SessionStart" });+ expect(r.exit).toBe(0);+ const receipts = injectionReceipts();+ expect(receipts.length).toBe(1);+ expect("session_id" in receipts[0]!.payload).toBe(false);+ }, 20000);+});diff --git a/tests/hooks/answer-quote-check.test.ts b/tests/hooks/answer-quote-check.test.tsindex b4de9fca..680afde5 100644--- a/tests/hooks/answer-quote-check.test.ts+++ b/tests/hooks/answer-quote-check.test.ts@@ -31,6 +31,8 @@ import {recordSubagentDeliveredId,} from "../../hooks/lib/injection-ledger.ts";import { hookStateFilePath } from "../../hooks/lib/session-state.ts";+import { listContinuityRecords } from "../../src/core/brain/continuity/store.ts";+import type { ContinuityRecord } from "../../src/core/brain/continuity/types.ts";import {ANSWER_QUOTE_MAX_CHARS,ANSWER_QUOTE_MAX_FINDINGS,@@ -42,10 +44,7 @@ import {checkAnswerQuotes,type AnswerQuoteEvidence,} from "../../src/core/brain/answer-quotes/check.ts";-import {- neutralizeUntrustedText,- untrustedFramingHeader,-} from "../../src/core/brain/untrusted-source.ts";+import { untrustedFramingHeader } from "../../src/core/brain/untrusted-source.ts";import { QUOTE_SPAN_PREVIEW_MAX_CHARS } from "../../src/core/brain/distill/quote-verdict.ts";const HOOK = resolve(@@ -138,7 +137,10 @@ interface RunResult {readonly exit: number;}-async function runHook(overrides: Record<string, unknown> = {}): Promise<RunResult> {+async function runHook(+ overrides: Record<string, unknown> = {},+ envOverrides: Record<string, string> = {},+): Promise<RunResult> {const transcriptPath =typeof overrides["transcript_path"] === "string"? (overrides["transcript_path"] as string)@@ -150,7 +152,12 @@ async function runHook(overrides: Record<string, unknown> = {}): Promise<RunResu// Bun hands a child without `env` the environment this process STARTED// with; pass the live one so the child keeps the hermetic defaults the// suite preload installed, plus this test's VAULT_DIR and recall gate.- env: { ...process.env, VAULT_DIR: vault, OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED: "true" },+ env: {+ ...process.env,+ VAULT_DIR: vault,+ OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED: "true",+ ...envOverrides,+ },});proc.stdin.write(JSON.stringify({@@ -190,6 +197,11 @@ function logDays(): ReadonlyArray<string> {return readdirSync(logDir).toSorted();}+/** The reply-presence continuity records the hook wrote to the vault. */+function presenceRecords(): ReadonlyArray<ContinuityRecord> {+ return listContinuityRecords(vault, { kind: "reply_presence" });+}+describe("answer-quote-check hook - output shape", () => {test("a verified cited span is silent, exit 0, no stderr", async () => {writeConfig("shadow");@@ -1028,3 +1040,361 @@ describe("answer-quote-check hook - fail-open arms", () => {expect(run.stderr).toBe("");});});++describe("answer-quote-check hook - reply presence records", () => {+ test("a checked turn writes exactly one reply_presence record with a verdict per injected note", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/elsewhere.md", "Elsewhere collects unrelated facts.\n");+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/elsewhere.md#L1-L1",+ "local:Brain/notes/restaking.md#L1-L1",+ ]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ // The span verified against `restaking.md`, so that is the only note+ // the span reports on: `elsewhere.md` was never measured - no span+ // was checked against it - and reads `absent`. A note that sorts+ // before the verifier does not inherit the span's miss, and the+ // record's verdicts cannot depend on filename order.+ expect(annotations(run)).toEqual([]);+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ const payload = records[0]!.payload as {+ session_id?: unknown;+ checked?: unknown;+ per_note?: unknown;+ source_hash?: unknown;+ };+ expect(payload.session_id).toBe(SESSION);+ expect(payload.checked).toBe(1);+ expect(payload.per_note).toEqual([+ { path: "Brain/notes/elsewhere.md", start_line: 1, end_line: 1, verdict: "absent" },+ { path: "Brain/notes/restaking.md", start_line: 1, end_line: 1, verdict: "verified" },+ ]);+ // The hash binds the verdicts to the exact answer text checked; it+ // carries no answer text itself.+ expect(typeof payload.source_hash).toBe("string");+ expect(payload.source_hash).toMatch(/^[0-9a-f]{64}$/);+ // Every test here spawns a real `bun run` hook child; pin the per-test+ // budget past bun's 5 s default so a loaded runner cannot flake it.+ }, 20000);++ test("an unrelated note reads the same verdict sorting before the verifying note", async () => {+ // M4: for a span that verified, ONLY the verifying candidate reports+ // an outcome. `aaa-unrelated.md` sorts before the verifier and would+ // once have inherited the span's miss; it must read exactly what a+ // note sorting after the verifier reads - `absent`.+ writeConfig("shadow");+ writeNote("Brain/notes/aaa-unrelated.md", "Unrelated collects other facts.\n");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/aaa-unrelated.md#L1-L1",+ "local:Brain/notes/restaking.md#L1-L1",+ ]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/aaa-unrelated.md", start_line: 1, end_line: 1, verdict: "absent" },+ { path: "Brain/notes/restaking.md", start_line: 1, end_line: 1, verdict: "verified" },+ ]);+ }, 20000);++ test("an unrelated note reads the same verdict sorting after the verifying note", async () => {+ // The mirror fixture: the same reply, the same verifying note, the+ // unrelated name sorting after it. The verdict must be the SAME+ // `absent` the before-sorting fixture read - a note's presence is a+ // fact about the reply, not about its filename.+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/zzz-unrelated.md", "Unrelated collects other facts.\n");+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/restaking.md#L1-L1",+ "local:Brain/notes/zzz-unrelated.md#L1-L1",+ ]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/restaking.md", start_line: 1, end_line: 1, verdict: "verified" },+ { path: "Brain/notes/zzz-unrelated.md", start_line: 1, end_line: 1, verdict: "absent" },+ ]);+ }, 20000);++ test("a note whose spans all miss reads its strongest miss verdict", async () => {+ // Two candidates, one span missing from both: the whole-file+ // subagent delivery reads the readable miss `not-in-note`; the+ // recall range delivers only a partial view, so its miss is the+ // degradation `source-truncated` - the ladder per note, not per+ // turn.+ writeConfigFor({ recall: "shadow", active: "off", subagent: "shadow" });+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/ranged.md", "Ranged note body line.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/ranged.md#L1-L1"])).toBe(true);+ expect(+ recordSubagentDeliveredId(vault, SESSION, "agent-cccc", ["Brain/notes/restaking.md"]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('The answer cites "wholly absent material" here.'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/ranged.md", start_line: 1, end_line: 1, verdict: "source-truncated" },+ { path: "Brain/notes/restaking.md", verdict: "not-in-note" },+ ]);+ expect(records[0]!.payload["checked"]).toBe(1);+ }, 20000);++ test("a reply with no quoted spans at all reads absent for every injected note", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/elsewhere.md", "Elsewhere collects unrelated facts.\n");+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/elsewhere.md#L1-L1",+ "local:Brain/notes/restaking.md#L1-L1",+ ]),+ ).toBe(true);+ writeTranscript([ccUser("summarize"), ccAssistant("A plain prose answer quoting nothing.")]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["checked"]).toBe(0);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/elsewhere.md", start_line: 1, end_line: 1, verdict: "absent" },+ { path: "Brain/notes/restaking.md", start_line: 1, end_line: 1, verdict: "absent" },+ ]);+ }, 20000);++ test("a note the budget cut before it was measured reads note-unavailable, never absent", async () => {+ // The note is quoted only in the SECOND message; a budget that expires+ // before that message is scanned leaves it never-measured. The fold's+ // invariant: a budget-cut candidate reads the transcript as UNREAD+ // (`note-unavailable`), never the note as untouched (`absent` - the+ // verdict reserved for a reply that quoted nothing from it).+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant("A first answer that quotes nothing at all."),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ // The hook's test-only budget seam: any finite value is honored once at+ // module load. A negative budget is already past at the FIRST deadline+ // comparison (`Date.now() > started - 1` holds always), so the outer+ // break fires deterministically before any span is measured.+ const run = await runHook({}, { ANSWER_QUOTE_BUDGET_MS: "-1" });+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["checked"]).toBe(0);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/restaking.md", start_line: 1, end_line: 1, verdict: "note-unavailable" },+ ]);+ }, 20000);++ test("a note the reply cites reads its check verdict, never absent", async () => {+ // The span sits under a wikilink mark naming the injected note: the+ // check measured the span against that note's evidence, so the note+ // rides the outcome - citing an injected note is the most explicit+ // way to surface it, and folding it `absent` would invert the signal+ // the record exists to carry.+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/elsewhere.md", "Elsewhere collects unrelated facts.\n");+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/elsewhere.md#L1-L1",+ "local:Brain/notes/restaking.md#L1-L1",+ ]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('Per [[Brain/notes/restaking]], "reuses staked capital" holds.'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["checked"]).toBe(1);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/elsewhere.md", start_line: 1, end_line: 1, verdict: "absent" },+ { path: "Brain/notes/restaking.md", start_line: 1, end_line: 1, verdict: "verified" },+ ]);+ }, 20000);++ test("a ranged citation of a whole-delivered note reads the check verdict, never absent", async () => {+ // The ledger delivered the note whole (the subagent lane) and by+ // range (recall); the merge folds every range of a path away once+ // the whole view exists, so the only candidate left is the whole+ // note. A citation that names a line range must still credit that+ // candidate: its key is the path alone, and the path is what the+ // reply surfaced - folding it `absent` would deny content the turn+ // delivered and cited.+ writeConfigFor({ recall: "shadow", active: "off", subagent: "shadow" });+ writeNote("Brain/notes/restaking.md", "First line about staking.\nSecond line about risk.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ expect(+ recordSubagentDeliveredId(vault, SESSION, "agent-cccc", ["Brain/notes/restaking.md"]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('The note says "First line about staking" (Brain/notes/restaking.md:L1-L1).'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["checked"]).toBe(1);+ expect(records[0]!.payload["per_note"]).toEqual([+ { path: "Brain/notes/restaking.md", verdict: "verified" },+ ]);+ }, 20000);++ test("a turn whose reply text never arrived reads note-unavailable, never absent", async () => {+ // The tail window holds no assistant message after the last user+ // boundary - the host never flushed a reply. No span was measured,+ // and not because the notes were unused: the fold answers+ // `note-unavailable` for every injected note instead of claiming+ // they were never surfaced.+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/elsewhere.md", "Elsewhere collects unrelated facts.\n");+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/elsewhere.md#L1-L1",+ "local:Brain/notes/restaking.md#L1-L1",+ ]),+ ).toBe(true);+ writeTranscript([ccUser("summarize")]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ const records = presenceRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["checked"]).toBe(0);+ expect(records[0]!.payload["per_note"]).toEqual([+ {+ path: "Brain/notes/elsewhere.md",+ start_line: 1,+ end_line: 1,+ verdict: "note-unavailable",+ },+ {+ path: "Brain/notes/restaking.md",+ start_line: 1,+ end_line: 1,+ verdict: "note-unavailable",+ },+ ]);+ // No reply text was read, so the payload binds no answer hash.+ expect(records[0]!.payload["source_hash"]).toBeUndefined();+ }, 20000);++ test("stop_hook_active silence writes no record", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As shown, restaking "reuses staked capital".'),+ ]);+ const run = await runHook({ stop_hook_active: true });+ expect(run.exit).toBe(0);+ expect(run.stdout).toBe("");+ expect(presenceRecords()).toEqual([]);+ }, 20000);++ test("every phase off runs no check and writes no record", async () => {+ writeConfig("off");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ writeTranscript([ccUser("summarize"), ccAssistant("A plain prose answer quoting nothing.")]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(presenceRecords()).toEqual([]);+ }, 20000);++ test("a failed presence write is fail-open: one audit line, the annotation still goes out", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('The answer cites "wholly absent material" here.'),+ ]);+ // The continuity ledger's directory is a file: the append throws,+ // the hook names it on stderr and still annotates.+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(join(vault, "Brain", "log", "continuity"), "not a directory\n");+ const run = await runHook();+ expect(run.exit).toBe(0);+ const found = annotations(run);+ expect(found.length).toBe(1);+ const lines = run.stderr.split(/\r?\n/).filter((line) => line.length > 0);+ expect(lines.length).toBe(1);+ expect(lines[0]!.startsWith("answer-quote-check:")).toBe(true);+ }, 20000);++ test("an unreadable transcript writes no record", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ const dirAsTranscript = join(tmp, "not-a-transcript");+ mkdirSync(dirAsTranscript);+ const run = await runHook({ transcript_path: dirAsTranscript });+ expect(run.exit).toBe(0);+ expect(run.stdout).toBe("");+ expect(presenceRecords()).toEqual([]);+ }, 20000);+});diff --git a/tests/mcp/context-pack-tool.test.ts b/tests/mcp/context-pack-tool.test.tsindex da674256..9f4a683e 100644--- a/tests/mcp/context-pack-tool.test.ts+++ b/tests/mcp/context-pack-tool.test.ts@@ -309,6 +309,96 @@ describe("brain_context_pack tool — round trip", () => {});});+ test("tail_trim_context_pack config gate emits the trim block and skip reasons", async () => {+ atomicWriteFileSync(+ configPath,+ `vault: ${vault}\nagent_name: claude\ntail_trim_context_pack: "true"\n`,+ );+ // Five pages in recency order whose tail separates under the keep+ // rule's own measure, query-term coverage (M1): pref-tail-a through+ // pref-tail-d carry the query verbatim - coverage 1.0 each, and d's+ // long body repeating every term stays kept, where the jaccard+ // kernel the ranked comparator uses scored the body's vocabulary+ // against it; pref-tail-e passes the substring reading only by+ // fusing the query's last term into a longer token (`delta-off`),+ // so it covers 3 of the 4 query terms - 0.75, below the 0.8 bar -+ // and drops whole.+ const QUERY = "alpha beta gamma delta";+ const pages: Array<[string, string, string]> = [+ ["pref-tail-a", "2026-05-05T00:00:00Z", ""],+ ["pref-tail-b", "2026-05-04T00:00:00Z", "zeta"],+ ["pref-tail-c", "2026-05-03T00:00:00Z", "zeta eta theta"],+ [+ "pref-tail-d",+ "2026-05-02T00:00:00Z",+ "zeta eta theta iota kappa lambda mu nu alpha beta gamma delta",+ ],+ ["pref-tail-e", "2026-05-01T00:00:00Z", "omega"],+ ];+ for (const [slug, created, body] of pages) {+ const principle = slug === "pref-tail-e" ? "alpha beta gamma delta-off" : QUERY;+ writeFileSync(+ join(vault, "Brain", "preferences", `pref-${slug}.md`),+ `---\nid: ${slug}\ntopic: x\nprinciple: ${principle}\ntier: core\ncreated_at: ${created}\n---\n\n${body}\n`,+ );+ }+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callPack(server, { max_tokens: 10_000, query: QUERY });+ const trim = out["tail_trim"] as {+ dropped: number;+ kept_by_query_terms: number;+ rescued: number;+ tokens_saved: number;+ };+ expect(trim).toBeDefined();+ expect(trim.dropped).toBe(1);+ expect(trim.kept_by_query_terms).toBe(1);+ expect(trim.rescued).toBe(0);+ expect(trim.tokens_saved).toBeGreaterThan(0);+ // The dropped tail item names the new skip reason on the wire.+ expect(out["skipped"]).toEqual([+ { id: "pref-tail-e", tokens: expect.any(Number), reason: "tail-trim" },+ ]);+ const items = out["items"] as Array<{ id: string }>;+ expect(items.map((i) => i.id)).toEqual([+ "pref-tail-a",+ "pref-tail-b",+ "pref-tail-c",+ "pref-tail-d",+ ]);+ });++ test("the config key absent leaves the response without the trim member", async () => {+ const QUERY = "alpha beta gamma delta epsilon";+ const pages: Array<[string, string, string]> = [+ ["pref-tail-a", "2026-05-05T00:00:00Z", ""],+ ["pref-tail-b", "2026-05-04T00:00:00Z", "zeta"],+ ["pref-tail-c", "2026-05-03T00:00:00Z", "zeta eta theta"],+ ["pref-tail-d", "2026-05-02T00:00:00Z", "zeta"],+ ["pref-tail-e", "2026-05-01T00:00:00Z", "zeta eta theta iota kappa lambda mu nu"],+ ];+ for (const [slug, created, body] of pages) {+ writeFileSync(+ join(vault, "Brain", "preferences", `pref-${slug}.md`),+ `---\nid: ${slug}\ntopic: x\nprinciple: ${QUERY}\ntier: core\ncreated_at: ${created}\n---\n\n${body}\n`,+ );+ }+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callPack(server, { max_tokens: 10_000, query: QUERY });+ expect(out["tail_trim"]).toBeUndefined();+ expect(out["skipped"]).toEqual([]);+ const items = out["items"] as Array<{ id: string }>;+ expect(items.map((i) => i.id)).toEqual([+ "pref-tail-a",+ "pref-tail-b",+ "pref-tail-c",+ "pref-tail-d",+ "pref-tail-e",+ ]);+ });+test("rejects non-positive max_tokens via INVALID_PARAMS", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);diff --git a/tests/mcp/context-receipts-tool.test.ts b/tests/mcp/context-receipts-tool.test.tsindex f5f8d6b5..fed4b3ad 100644--- a/tests/mcp/context-receipts-tool.test.ts+++ b/tests/mcp/context-receipts-tool.test.ts@@ -1,14 +1,23 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";import { emitObservedUse } from "../../src/core/brain/observed-use.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";+/** A plain vault page at a vault-relative path, frontmatter and all. */+function writePage(rel: string, body: string): void {+ const abs = join(vault, rel);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, body, "utf8");+}+let tmp: string;let vault: string;let configHome: string;@@ -120,6 +129,213 @@ describe("brain_context_receipts tool", () => {expect((show["payload"] as Record<string, unknown>)["session_id"]).toBe("session-mcp");});+ test("show joins the session's reply_presence record and names unjoined honestly", async () => {+ // The pages the hook recorded: readable and unreserved, so the join+ // keeps their rows at the default (below-local) reach too.+ writePage("Brain/preferences/pref-alpha.md", "Public body.\n");+ writePage("Brain/preferences/pref-bravo.md", "Public body.\n");+ const joined = emitContextReceipt(vault, {+ options: {+ host: "mcp-test",+ trigger: "session_inject",+ createdAt: "2026-05-20T14:00:00.000Z",+ sessionId: "session-present",+ },+ finalText: "eager layer",+ items: [{ id: "pref-alpha", path: "Brain/preferences/pref-alpha.md" }],+ });+ const lonely = emitContextReceipt(vault, {+ options: {+ host: "mcp-test",+ trigger: "session_inject",+ createdAt: "2026-05-20T14:05:00.000Z",+ sessionId: "session-absent",+ },+ finalText: "eager layer",+ items: [{ id: "pref-bravo", path: "Brain/preferences/pref-bravo.md" }],+ });+ const presence = appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-20T14:10:00.000Z",+ payload: {+ session_id: "session-present",+ checked: 1,+ per_note: [+ { path: "Brain/preferences/pref-alpha.md", start_line: 2, verdict: "not-in-note" },+ ],+ },+ });+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const showJoined = await callReceipts(server, { operation: "show", id: joined.id });+ expect(showJoined["reply_presence"]).toEqual({+ joined: true,+ presence: {+ record_id: presence.id,+ created_at: "2026-05-20T14:10:00.000Z",+ checked: 1,+ per_note: [+ { path: "Brain/preferences/pref-alpha.md", start_line: 2, verdict: "not-in-note" },+ ],+ },+ });++ // No reply_presence record for this receipt's session: the outcome is+ // NAMED on the response, never a silent absence.+ const showLonely = await callReceipts(server, { operation: "show", id: lonely.id });+ expect(showLonely["reply_presence"]).toEqual({+ joined: false,+ reason: "unjoined",+ session_id: "session-absent",+ });++ // The list summaries stay summaries: no per-row presence join.+ const list = await callReceipts(server, { operation: "list", trigger: "session_inject" });+ for (const entry of list["receipts"] as Array<Record<string, unknown>>) {+ expect("reply_presence" in entry).toBe(false);+ }+ });++ test("a note verified in the next turn reads verified through show, whatever later turns did", async () => {+ // The review's timeline, through the tool surface: the Stop hook+ // writes a record on every checked turn, including later turns that+ // quote nothing, so the receipt's join must fold its own lifetime -+ // a later all-absent turn never erases an earlier verification, and+ // the row list stays the receipt's own injection.+ writePage("Brain/notes/note-a.md", "Note a body.\n");+ writePage("Brain/notes/note-b.md", "Note b body.\n");+ const receipt = emitContextReceipt(vault, {+ options: {+ host: "mcp-test",+ trigger: "session_inject",+ createdAt: "2026-05-20T15:00:00.000Z",+ sessionId: "session-fold",+ },+ finalText: "eager layer",+ items: [{ id: "note-a", path: "Brain/notes/note-a.md" }],+ });+ appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-20T15:01:00.000Z",+ payload: {+ session_id: "session-fold",+ checked: 1,+ per_note: [+ { path: "Brain/notes/note-a.md", start_line: 1, end_line: 1, verdict: "verified" },+ ],+ },+ });+ const last = appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-20T15:06:00.000Z",+ payload: {+ session_id: "session-fold",+ checked: 0,+ per_note: [+ { path: "Brain/notes/note-a.md", verdict: "absent" },+ { path: "Brain/notes/note-b.md", verdict: "absent" },+ ],+ },+ });+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const show = await callReceipts(server, { operation: "show", id: receipt.id });+ expect(show["reply_presence"]).toEqual({+ joined: true,+ presence: {+ record_id: last.id,+ created_at: "2026-05-20T15:06:00.000Z",+ checked: 1,+ per_note: [+ { path: "Brain/notes/note-a.md", start_line: 1, end_line: 1, verdict: "verified" },+ ],+ },+ });+ });++ test("below local reach the join withholds a reserved page's row and counts the withholding", async () => {+ writePage("Brain/preferences/pref-open.md", "Open body.\n");+ writePage(+ "Brain/preferences/pref-reserved.md",+ "---\nvisibility: private\n---\n\nReserved body.\n",+ );+ const receipt = emitContextReceipt(vault, {+ options: {+ host: "mcp-test",+ trigger: "session_inject",+ createdAt: "2026-05-20T14:00:00.000Z",+ sessionId: "session-withheld-page",+ },+ finalText: "eager layer",+ items: [+ { id: "pref-open", path: "Brain/preferences/pref-open.md" },+ { id: "pref-reserved", path: "Brain/preferences/pref-reserved.md" },+ ],+ });+ appendContinuityRecord(vault, {+ kind: "reply_presence",+ createdAt: "2026-05-20T14:10:00.000Z",+ payload: {+ session_id: "session-withheld-page",+ checked: 2,+ per_note: [+ { path: "Brain/preferences/pref-open.md", verdict: "verified" },+ {+ path: "Brain/preferences/pref-reserved.md",+ start_line: 3,+ end_line: 5,+ verdict: "verified",+ },+ ],+ },+ });++ // A caller that established nothing answers at the narrowest reach:+ // the reserved page's path, range and verdict are gone, and the join+ // says it withheld one row rather than reading as an absent note.+ const remote = new MCPServer({ vault, configPath });+ await initialize(remote);+ const below = await callReceipts(remote, { operation: "show", id: receipt.id });+ expect(below["reply_presence"]).toEqual({+ joined: true,+ presence: {+ record_id: expect.any(String),+ created_at: "2026-05-20T14:10:00.000Z",+ checked: 2,+ per_note: [{ path: "Brain/preferences/pref-open.md", verdict: "verified" }],+ withheld: 1,+ },+ });+ // The JOIN carries no trace of the withheld page - not its path, not+ // its line range, not its verdict. (The receipt's own items are the+ // record of what was injected; this pin is the join's.)+ expect(JSON.stringify(below["reply_presence"])).not.toContain("pref-reserved");++ // At local reach the operator still sees every row, and no withholding.+ const local = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await initialize(local);+ const above = await callReceipts(local, { operation: "show", id: receipt.id });+ expect(above["reply_presence"]).toEqual({+ joined: true,+ presence: {+ record_id: expect.any(String),+ created_at: "2026-05-20T14:10:00.000Z",+ checked: 2,+ per_note: [+ { path: "Brain/preferences/pref-open.md", verdict: "verified" },+ {+ path: "Brain/preferences/pref-reserved.md",+ start_line: 3,+ end_line: 5,+ verdict: "verified",+ },+ ],+ },+ });+ });+test("summary folds a session and joins the observed-use verdicts", async () => {for (const [createdAt, tokens] of [["2026-05-21T14:00:00.000Z", 10],diff --git a/tests/mcp/doctor-schema-reach.test.ts b/tests/mcp/doctor-schema-reach.test.tsindex a9ca1de4..807aa424 100644--- a/tests/mcp/doctor-schema-reach.test.ts+++ b/tests/mcp/doctor-schema-reach.test.ts@@ -24,10 +24,20 @@ import { MCPServer } from "../../src/mcp/server.ts";const PREF = "Brain/preferences/pref-secret.md";+/**+ * A creation date inside every staleness window the doctor reads: fixed+ * offsets from the run date keep the fixture from crossing a stale-stable+ * boundary (a hardcoded date silently flipped the maintenance reach shape+ * half a year after it was written).+ */+function stableCreatedAt(): string {+ return new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();+}+/** A private preference with no `status`, whose identity field is `id`. */function prefBody(id: string, body: string): string {return (- `---\nkind: brain-preference\nid: ${id}\ncreated_at: 2026-05-01T00:00:00Z\n` ++ `---\nkind: brain-preference\nid: ${id}\ncreated_at: ${stableCreatedAt()}\n` +`topic: style\nvisibility: private\n---\n\n${body}`);}diff --git a/tests/mcp/maintenance-status-reach.test.ts b/tests/mcp/maintenance-status-reach.test.tsindex d8a784e8..320ffd7a 100644--- a/tests/mcp/maintenance-status-reach.test.ts+++ b/tests/mcp/maintenance-status-reach.test.ts@@ -23,19 +23,22 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";import { MAINTENANCE_VERDICT, appendJournal } from "../../src/core/brain/maintenance/journal.ts";import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { resolveSearchConfig } from "../../src/core/search/index.ts";import { ADMIN_TOOLS } from "../../src/mcp/brain/admin-tools.ts";+import { HEALTH_TOOLS } from "../../src/mcp/brain/health-tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";const maintenance = ADMIN_TOOLS.find((tool) => tool.name === "brain_maintenance")!.handler;+const brainStatus = HEALTH_TOOLS.find((tool) => tool.name === "brain_status")!.handler;let vault: string;let configHome: string;@@ -163,3 +166,70 @@ describe("brain_maintenance status journal cursor pagination", () => {);});});++describe("brain_status store group at the caller's reach (t_cfe2ce5d)", () => {+ interface StoreGroup {+ readonly writerLock: string;+ readonly writerLockReason: string | null;+ readonly writerLockAgeMs: number | null;+ readonly writerLockOwner: string | null;+ readonly writerLockPath: string | null;+ readonly thisCaller: string;+ }++ async function statusStore(reach: TransportReach): Promise<StoreGroup> {+ const res = (await brainStatus({ ...ctx, reach }, {})) as Record<string, unknown>;+ return res["store"] as StoreGroup;+ }++ test("the payload carries the store group at both reaches, with the state fields intact", async () => {+ for (const reach of [TRANSPORT_REACH.local, TRANSPORT_REACH.remote]) {+ const store = await statusStore(reach);+ expect(store.writerLock).toBe("free");+ expect(store.writerLockReason).toBeNull();+ expect(store.writerLockOwner).toBeNull();+ expect(store.thisCaller).toBe("read-only");+ }+ });++ test("the lock path is withheld below local reach", async () => {+ const local = await statusStore(TRANSPORT_REACH.local);+ // The lock rides the resolved index path, which is inside the vault here.+ expect(typeof local.writerLockPath).toBe("string");++ const remote = await statusStore(TRANSPORT_REACH.remote);+ // The path may live outside the vault (the resolved index path is a+ // host path), so below local reach it reads null while every state+ // field stays - the same split `state_files.search_index` boolean makes.+ expect(remote.writerLockPath).toBeNull();+ expect(remote.writerLock).toBe("free");+ });++ test("below local reach a failed lock probe keeps the errno but not the host path", async () => {+ // A lock path that cannot even be stat'd: a symlink loop where the+ // lock directory would sit. `isWriterLockHeld`'s contract names this+ // throw shape (ELOOP, beside the EACCES the audit quotes) and the+ // snapshot reads it `unknown` with the reason carrying the fs error -+ // whose message embeds the full host path.+ const lockPath = `${resolveSearchConfig({ vault, configPath: ctx.configPath ?? undefined }).dbPath}.lock`;+ mkdirSync(dirname(lockPath), { recursive: true });+ symlinkSync(lockPath, lockPath);++ // At local reach the reason is the operator's own diagnostic: the+ // errno and the path the probe failed on, verbatim.+ const local = await statusStore(TRANSPORT_REACH.local);+ expect(local.writerLock).toBe("unknown");+ expect(local.writerLockReason).toContain("ELOOP");+ expect(local.writerLockReason).toContain(lockPath);++ // Below local reach the errno keeps - "I could not find out, and+ // here is why" - while the host path goes the way every other error+ // leaving the process goes: through the redactor.+ const remote = await statusStore(TRANSPORT_REACH.remote);+ expect(remote.writerLock).toBe("unknown");+ expect(remote.writerLockReason).toContain("ELOOP");+ expect(remote.writerLockReason).not.toContain(lockPath);+ expect(remote.writerLockReason).not.toContain(tmpdir());+ expect(remote.writerLockPath).toBeNull();+ });+});diff --git a/tests/mcp/note-lifecycle.test.ts b/tests/mcp/note-lifecycle.test.tsindex 921921ea..1f8b51d3 100644--- a/tests/mcp/note-lifecycle.test.ts+++ b/tests/mcp/note-lifecycle.test.ts@@ -22,6 +22,7 @@ import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { INDEX_EVIDENCE, INDEX_REFRESH } from "../../src/core/brain/notes/lifecycle.ts";+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";import { LIFECYCLE_FILE_TOOLS } from "../../src/mcp/brain/lifecycle-file-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";@@ -64,7 +65,155 @@ describe("brain_note_lifecycle registration", () => {expect(tool).toBeDefined();expect(tool.inputSchema.required).toEqual(["action", "path"]);const properties = tool.inputSchema.properties as Record<string, { enum?: string[] }>;- expect(properties["action"]?.enum).toEqual(["rename", "move", "archive", "delete"]);+ expect(properties["action"]?.enum).toEqual([+ "rename",+ "move",+ "archive",+ "delete",+ "move-folder",+ "rename-folder",+ ]);+ });++ test("the description names the folder actions and where they run", () => {+ // The enum admits the folder actions, so the description must say the+ // same thing the refusal says: they address a whole folder and run in+ // the folder lifecycle - and the path argument covers a folder, which+ // carries no .md suffix.+ expect(tool.description).toContain("move-folder");+ expect(tool.description).toContain("rename-folder");+ expect(tool.description).toContain("folder lifecycle");+ const properties = tool.inputSchema.properties as Record<string, { description?: string }>;+ expect(properties["path"]?.description).toContain("folder");+ });+});++describe("folder actions through the tool", () => {+ test("a folder action refuses confirm and delete_linked instead of dropping them", async () => {+ note("Projects/Old/a.md", "alpha\n");+ for (const extra of [{ confirm: true }, { delete_linked: true }]) {+ await expect(+ call({ action: "move-folder", path: "Projects/Old", to: "Archive", ...extra }),+ ).rejects.toThrow(/takes neither confirm nor delete_linked/);+ }+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive"))).toBe(false);+ });++ test("a folder holding a note the caller's reach denies refuses exactly as a missing one", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Projects/Old/quiet.md", "---\nvisibility: private\n---\nreserved\n");+ const remote = { ...ctx, reach: TRANSPORT_REACH.remote };++ for (const apply of [false, true]) {+ await expect(+ tool.handler(remote, { action: "move-folder", path: "Projects/Old", to: "Archive", apply }),+ ).rejects.toThrow(/no note folder/);+ }+ // Nothing was planned, moved or renamed on either run, and the+ // refusal never names the denied page.+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/quiet.md"))).toBe(true);+ expect(existsSync(join(vault, "Archive"))).toBe(false);+ });++ test("move-folder relocates the folder and renders the move report", async () => {+ note("Projects/Old/a.md", "alpha\n");+ note("Notes/Ref.md", "pathed [[Projects/Old/a]]\n");++ const res = await call({+ action: "move-folder",+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });++ expect(res).toMatchObject({+ action: "move-folder",+ applied: true,+ from: "Projects/Old",+ to: "Archive/Old",+ });+ // The moved list, per file, and the per-file failure list.+ expect(res["moved"]).toEqual([{ from: "Projects/Old/a.md", to: "Archive/Old/a.md" }]);+ expect(res["move_failures"]).toEqual([]);+ // A relocation destroys nothing, so no snapshot rides the response.+ expect(res["snapshot"]).toBeNull();+ const references = res["references"] as Record<string, unknown>;+ expect(references["files_rewritten"]).toBe(1);+ expect(references["inbound_files"]).toEqual(["Notes/Ref.md"]);+ expect(readFileSync(join(vault, "Notes/Ref.md"), "utf8")).toContain("[[a]]");+ expect(existsSync(join(vault, "Archive/Old/a.md"))).toBe(true);+ expect(existsSync(join(vault, "Projects/Old/a.md"))).toBe(false);+ });++ test("move-folder names non-Markdown residue and omits the field when clean", async () => {+ note("Projects/Old/a.md", "alpha\n");+ writeFileSync(join(vault, "Projects/Old/img.png"), "png\n");++ const res = await call({+ action: "move-folder",+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ expect(res["left_behind"]).toEqual(["img.png"]);+ expect(existsSync(join(vault, "Projects/Old/img.png"))).toBe(true);++ // Absent-when-empty: the rename-folder response of a move that+ // empties its folder carries no left_behind key at all.+ note("Other/Sub/b.md", "beta\n");+ const clean = await call({+ action: "move-folder",+ path: "Other/Sub",+ to: "Archive2",+ apply: true,+ });+ expect("left_behind" in clean).toBe(false);+ });++ test("move-folder names the relative embeds whose targets stayed behind (M17)", async () => {+ note("Projects/Old/a.md", "\n");+ writeFileSync(join(vault, "Projects/Old/diagram.png"), "png\n");++ const res = await call({+ action: "move-folder",+ path: "Projects/Old",+ to: "Archive",+ apply: true,+ });+ // The wikilink pass rewrites [[path]] spellings only; a relative+ // image depends on the note's directory, so the response names the+ // pair instead of letting files_rewritten: 0 read as "nothing broke".+ expect(res["dangling_relative_links"]).toEqual([+ { note: "Archive/Old/a.md", target: "diagram.png" },+ ]);+ expect(res["left_behind"]).toEqual(["diagram.png"]);++ // Absent-when-empty: a move whose relative targets move with the+ // folder carries no dangling_relative_links key at all.+ note("Whole/Sub/b.md", "[link](kept.md)\n");+ note("Whole/Sub/kept.md", "the target is a note; it moves too\n");+ const clean = await call({+ action: "move-folder",+ path: "Whole/Sub",+ to: "Archive3",+ apply: true,+ });+ expect("dangling_relative_links" in clean).toBe(false);+ });++ test("rename-folder renames within the parent through the same tool", async () => {+ note("Projects/Old/a.md", "alpha\n");+ const res = await call({+ action: "rename-folder",+ path: "Projects/Old",+ to: "New",+ apply: true,+ });+ expect(res).toMatchObject({ action: "rename-folder", applied: true, to: "Projects/New" });+ expect(res["moved"]).toEqual([{ from: "Projects/Old/a.md", to: "Projects/New/a.md" }]);+ expect(existsSync(join(vault, "Projects/New/a.md"))).toBe(true);});});diff --git a/tests/mcp/surface-error-codes.test.ts b/tests/mcp/surface-error-codes.test.tsindex 00ae85ce..6fa69b39 100644--- a/tests/mcp/surface-error-codes.test.ts+++ b/tests/mcp/surface-error-codes.test.ts@@ -506,7 +506,7 @@ describe("every operation-dispatching tool answers unknown_operation", () => {["brain_note_lifecycle",{ action: BOGUS },- "brain_note_lifecycle: 'action' must be one of rename, move, archive, delete",+ "brain_note_lifecycle: 'action' must be one of rename, move, archive, delete, move-folder, rename-folder",],["brain_scaffold_stub",diff --git a/tests/mcp/tool-error-codes.test.ts b/tests/mcp/tool-error-codes.test.tsindex 2c802aca..4c52852f 100644--- a/tests/mcp/tool-error-codes.test.ts+++ b/tests/mcp/tool-error-codes.test.ts@@ -126,6 +126,8 @@ const TYPE_ONLY_MEMBERS = ["destination_forbidden","destination_occupied","destination_unchanged",+ "destination_inside_source",+ "move_set_empty","wrong_action","not_confirmed","already_archived",diff --git a/uv.lock b/uv.lockindex 860b146a..61e85bad 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.94.0"+version = "1.95.0"source = { editable = "." }