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: trust and responsiveness hardening - neutralized imports, gitignore guardrails, shadowed-contract detection, parallel MCP reads (v1.96.0) (#281)
Serg Eroshe285cb9a83392
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex cabd946d..b719b2da 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.95.0",+ "version": "1.96.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 44865ab6..12e10388 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.95.0",+ "version": "1.96.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 d53f3528..f475c29a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,27 @@ 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.96.0] - 2026-10-29++Open Second Brain 1.96.0 is the guarded seams and concurrent reads release: the places where other systems' text, other tools' state directories and the host's own instruction files meet the vault each state what they accept, and the stdio transport stops serializing what never needed to be. The write side gains an optional neutralization gate that escapes the structure-bearing markdown in imported third-party text at the capture and ingest seams - off by default as a deliberate operator choice, with a shadow mode that measures without writing and a read-only doctor audit naming the pages that already carry planted rows. The install side seeds a managed .gitignore block at `o2b brain init` so the derived state under `.open-second-brain/` stays out of git, and a doctor error names every path git already tracks. The readiness probe fails a workspace whose write-back contract is installed into a file the operative host never reads. And the stdio MCP transport classifies every tool as read or write in the registry, runs reads concurrently up to four in flight, and keeps writes exclusive and arrival-ordered behind a dispatch-level gate.++### Added++- **Write-time markdown neutralization at the third-party seams, gated off/shadow/enforce.** Third-party text that carries structure-bearing markdown - wikilinks, `@osb` inline markers, ```osb fence lines, ATX headings - lands in capture pages and untrusted-source ingest summaries as live vault structure: the link graph, the marker scanners and the section parsers read it as the vault's own. `markdown_neutralize_mode` (env `OPEN_SECOND_BRAIN_MARKDOWN_NEUTRALIZE_MODE`, `off | shadow | enforce`, default `off`) runs the gate at the two seams - capture writes (`o2b brain capture` and the capture kernel) and untrusted ingest summaries: `enforce` backslash-escapes the structure-bearing markdown in caller text before it is written, so no scanner treats it as the vault's own, and stamps a `neutralized_markers` frontmatter key naming the escaped families - a write that changes nothing adds nothing, and vault-authored sections appended after caller text are never touched; `shadow` leaves every write byte-identical and lets the would-be families surface through the doctor audit below; `off` - the default, a deliberate operator choice - runs no gate and every write stays byte-identical. The env twin wins over the config key and an invalid value is refused by name at the seam. Because capture identity hashes the persisted bytes, flipping the mode between captures of the same text yields an honest duplicate rather than a silent mutation.+- **A read-only doctor audit names the pages that already carry planted rows.** The `o2b brain doctor` pass gains the fail-soft `planted-structure-rows` warning: one finding counting the live structure rows third-party text planted in capture pages, untrusted-stamped pages, quarantined entity pages and source summaries, naming up to five paths and counting the rest, deduplicating `Brain/pending/` staged copies against their publish targets and skipping pages the caller may not read, silent on a vault with none. Under `markdown_neutralize_mode: shadow` the finding appends the preview of what enforce would escape on the next capture or untrusted ingest of the same text. The audit is read-only by contract - the rows leave only by re-capturing the text with the gate in `enforce` or by a later repair pass - so the finding carries no `o2b` command.+- **`o2b brain init` seeds a managed .gitignore block, and a doctor error names derived state git already tracks.** A fresh init in a git repository now writes a managed guard block into the vault `.gitignore` covering `/.open-second-brain/` - the derived runtime state, bench runs included - beside the identity stamp, so a fresh vault no longer leaves `brain.sqlite` visible to `git status`. The seeder merges with existing content and never clobbers a conforming block, checks exact-line membership first so an operator's own ignore line yields a skip, keeps CRLF endings, reports malformed markers as a named conflict and continues without writing, and `--force` never rewrites the guard block; the fresh-vault created count moves from seven to eight. The `o2b brain doctor` pass answers for existing vaults with the `git-tracked-derived-state` check: derived state under `.open-second-brain/` that git actually tracks - measured by `git ls-files`, never inferred from status - is an ERROR naming one location-independent `git -C <vault> rm -r --cached -- .open-second-brain` command plus the missing `/.open-second-brain/` ignore line; a present-but-unignored untracked store is a warning; the check is silent outside a git worktree, when the store directory is absent, and when git cannot answer, and it never edits anything - the ignore half is remediated by init's guard block and the untracking is git's own.+- **`o2b doctor --readiness` fails a shadowed instruction contract.** A workspace where the file the operative host reads carries no managed write-back block while another candidate file carries it has the contract installed where it never runs. The readiness probe now grades that placement as a fail from a pure resolver over the audit rows alone: per the host-to-file precedence table, claude-code reads `CLAUDE.md`, codex, cursor, opencode and aider read `AGENTS.md`, and gemini-cli reads `GEMINI.md`; the finding names the host, the file the host reads, the file carrying the contract and the same read-only recovery clause the per-file findings carry, and the fail census counts findings, not files. Symlinked candidates keep their refused unknown treatment, and a workspace with no instruction file at all stays skipped - nothing installed is not a contract violation.+- **Parallel reads with exclusive writes on the stdio MCP transport.** Read-classified `tools/call`s run concurrently, up to four in flight - a constant, not a knob, backpressured at the cap so the bound holds by construction - while write-classified calls run one at a time behind a dispatch-level FIFO gate and never beside a read: the loop reads no further line until a dispatched write has settled, and the write waits out the reads already in flight before it starts. The concurrency pays only where a handler awaits I/O: read handlers whose work runs synchronously between awaits (the measured SQLite, filesystem and scoring reads) finish no sooner than serialized dispatch, so a batch's total time does not shrink, its responses shift toward the end of the batch, and its first response can arrive later than arrival-order delivery would - time-to-first-response may grow - while write-classified tools still run one at a time (`brain_search` among them, write-classified by the write-mode-dominant rule). Every tool is classified `read` or `write` in the registry at registration - write-mode-dominant, so a tool that can write is `write`, decided per operation family and never from arguments at dispatch, and fail-soft telemetry appends do not make a tool `write` - and the classification is metadata only: it never reaches the `tools/list` wire payload, and a definition that arrives without one is treated as `write`, so it can only ever lose concurrency, never safety. Cross-request frame order is intentionally surrendered in one direction: responses may arrive out of arrival order, which is legal JSON-RPC - correlate by response `id` and progress by `progressToken` - while each request's own progress notifications all precede its response, every frame stays newline-terminated, and on EOF or drain the server still waits for every dispatched request before the process exits.+- **Docs:** `docs/cli-reference.md` documents the `markdown_neutralize_mode` write-side trust switch, the `git-tracked-derived-state` and `planted-structure-rows` doctor rows, the placement-shadowing failure on the doctor readiness row and the bench-runs ignore the init guard block seeds; `docs/mcp.md` documents the stdio request-ordering contract - concurrent reads, exclusive writes, out-of-order responses correlated by id; `docs/observability.md` names the guard block behind the bench-runs path.++### Fixed++- **Backslash-escaped wikilink brackets no longer produce links.** The link readers (`extractWikilinks`, the backlink body walker, the page lint's link targets, the merged-link convergence and the Sources-section reader) now hold a `[[` or `]]` preceded by an odd backslash run to the same rule the write-time neutralizer's detector applies - escaped punctuation is literal text and opens or closes no link - so the escape-aware detection grammar and the readers that consume it answer with one truth, and the same shared helper serves both. Every link-graph input (backlinks, co-occurrence, portability, entity links, doctor checks) and the planted-rows audit inherit the rule.++- **Digest maintenance actions now honor agent scope.** The `actions` list in `view: digest` is collected vault-wide, and its rows were filtered by transport reach alone, so a caller delivering the digest under `agent_scope` could receive maintenance rows naming preferences the sections beside them had already withheld. The enforced ownership rule now joins the reach view for the actions rows - the same judgment `brain_doctor`'s `suggested_actions` and the operator summary's `top_actions` already apply - and `osb://digest/latest` threads its resolved scope into the render the way `osb://preferences/active` does. Without `integrity.owner_scope_delivery: fail`, or with no scope requested, every output is byte-identical.++- **The brief views and the digest's dream-parsed rows honor the enforced owner scope at every reach.** The daily and weekly envelopes judged their rows by transport reach alone and stepped past the ownership rule at local reach, so under `integrity.owner_scope_delivery: fail` a caller with a resolved identity could receive another owner's preference ids, transition reasons and source pointers from `status_transitions`, `retired` and `contradictions`; those rows are now kept through the same enforced-rule view the digest's actions use, with the counts recomputed from the same selection. The digest's confidence-shift and contradiction rows - parsed from dream log lines whose preference id the log-level filter cannot resolve - are kept through the same view. And a caller the enforced scope narrows now takes no report snapshot and is shown no delta, since a per-caller render must not land under the shared date key for the next caller's delta to be diffed against. `view=monthly`, `view=today` and the operator summary were already scoped and are pinned by regression rows; without the gate, or under `warn`, every output is byte-identical.+## [1.95.0] - 2026-10-27Open 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.@@ -8766,6 +8787,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.96.0]: https://github.com/itechmeat/open-second-brain/compare/v1.95.0...v1.96.0[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.0diff --git a/docs/brainstorm/trust-and-responsiveness-hardening/cli-output/claude.md b/docs/brainstorm/trust-and-responsiveness-hardening/cli-output/claude.mdnew file mode 100644index 00000000..2babb75b--- /dev/null+++ b/docs/brainstorm/trust-and-responsiveness-hardening/cli-output/claude.md@@ -0,0 +1,34 @@+# Consultant output - trust-and-responsiveness-hardening++The consultant role was performed in-session against the prompt at `cli-output/prompt.md`; the output below is preserved verbatim.++### Variant 1: Per-feature parallel lanes with an append-only shared protocol++- **Approach**: Four lanes with strictly disjoint file ownership implement the four cards independently and simultaneously; the only shared surfaces are the doctor registry, the two code-classification tables, the shared doctor test files, docs and CHANGELOG, all governed by an append-only protocol - each lane appends its entries in its own final commit via `git commit --only`, and one integrator reconciles ordering and prose and runs the full gates. Each lane leans on the substrate that already exists in the tree: the frozen `DOCTOR_CHECKS` registry, the managed-block merger, `RequestDrain`'s N-in-flight register, and the `SEARCH_TRUST_GATE_MODE` gate shape.+- **Trade-offs**:+ - Pros: four agents work truly in parallel (the wave's main cost is wall time); every card ships as an atomic conventional commit; no infrastructure is built that the tree does not already need; the append-only protocol makes the four shared files textual merges rather than design coordination.+ - Cons: the shared files are a serialization point at lane end (registry order and census must be reconciled); lane discipline can slip without the `--only` commit rule being enforced; cross-lane interactions (e.g. two new doctor rows landing in one release) are only seen at integration.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Shared-substrate-first++- **Approach**: Build a common foundation first - a doctor-row framework (registration helper, counting-check template, classification wiring, census scaffolding), a shared gate-mode/config resolver extracted from `retrieval-gate.ts`, and a transport concurrency primitive - then implement the four cards as thin consumers of that substrate.+- **Trade-offs**:+ - Pros: the doctor rows for the gitignore and marker cards and the gate modes land on one tested abstraction; classification wiring cannot diverge between the two new codes; the extracted resolver removes one duplicated pattern.+ - Cons: serializes the start of all four lanes behind a fifth work package; most of the "substrate" already exists in this tree, so the phase mostly renames and moves working code (a refactor PR riding a hardening wave); the abstraction risks being shaped by imagined needs - three of the four cards need exactly one registry entry each, which is not a framework.+- **Complexity**: large+- **Risk**: medium++### Variant 3: Integration-heavy single spine++- **Approach**: One integrator owns the branch throughout; the four features are implemented serially against a continuously integrated spine, with an integration pass (registry order, census, docs, full suite) after every feature rather than once at the end. Parallel agents, if any, work strictly inside one feature at a time under the integrator's sequencing.+- **Trade-offs**:+ - Pros: shared files never merge concurrently, so no protocol is needed; every integration hazard surfaces immediately after the feature that caused it; the branch is always releasable.+ - Cons: gives up the wave's parallelism entirely (four features times an integration pass each); the integrator becomes a bottleneck and context swamps; the per-feature integration passes mostly re-run the same registry/census/docs checks that a single end pass covers.+- **Complexity**: medium+- **Risk**: low++### Recommended: Variant 1++**Rationale**: The substrate Variant 2 would build already exists - the doctor registry, the managed-block merger, the drain register and the gate-mode pattern are shipped, tested code - so substrate-first buys a refactor, not a foundation, and three of the four cards need exactly one append entry each. Variant 1 is the only shape that lets four agents work simultaneously, and its one real hazard, concurrent edits to four small shared files, is bounded by an append-only protocol whose merges are textual. Variant 3's continuous integration is the safest but converts the wave's defining constraint - four independent P4 cards - into a serial queue for no correctness gain the end-pass integrator does not already provide.diff --git a/docs/brainstorm/trust-and-responsiveness-hardening/cli-output/prompt.md b/docs/brainstorm/trust-and-responsiveness-hardening/cli-output/prompt.mdnew file mode 100644index 00000000..13458845--- /dev/null+++ b/docs/brainstorm/trust-and-responsiveness-hardening/cli-output/prompt.md@@ -0,0 +1,71 @@+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 "trust-and-responsiveness-hardening" (option 1): implement all four P4 kanban cards in one PR on one feature branch.++- t_c2ac4fc8 - Neutralize structure-bearing markdown markers (wikilinks, agent-facing inline markers, fenced marker blocks, semantic headings) in imported third-party text at capture/write time, behind an off/shadow/enforce gate, plus a read-only doctor audit of already-planted rows. Doctrine: neutralization keys off structure only, never vocabulary, is idempotent, and adds zero bytes when the gate is off.+- t_206562ae - Seeded .gitignore guardrails for derived brain state (.open-second-brain) at brain init (merge-safe for existing user files, idempotent), plus a doctor row that FAILs when derived runtime state is already tracked by git.+- t_00b617b6 - Doctor readiness row catching shadowed agent instruction files (AGENTS.md/CLAUDE.md/GEMINI.md): when the file a host reads is not the file carrying the write-back contract, the probe must fail naming both files, read-only.+- t_90409204 - Parallel MCP reads on the stdio transport with writes kept exclusive: classify every tool as read or write, dispatch reads concurrently under a bounded cap, serialize writes, and make EOF await the in-flight set. The tools-list wire output must stay byte-identical.++The four cards are independent; the task is to argue the SHAPE of the wave - how the four implementations are organized against each other on one branch.++# Project context++Open Second Brain - local-first agent memory for OpenClaw/Claude Code/Codex as an MCP server and CLI (`o2b`), TypeScript on Bun.++Recent commits:+88c118aa feat: verified delivery and honest write surfaces (v1.95.0) (#280)+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)+89a921ba feat: one-off pledges with verified evidence and a counterparty brief (#270)+f203591e feat: measured autonomy - a rule-promoting dream pass, model-aware context budgets and honest benchmarks (#269)+9e579820 feat: note-change truth maintenance for links, index freshness and entity anchoring (#268)+f7c1c88c feat: entity merge repair, write destinations, cross-agent catch-up and OKF v0.2 (v1.88.0) (#267)+f6d9f95f feat: guarded host writes, walkable list results, a converse decision route and a snoozable trigger queue (v1.87.0) (#266)+b183b6c3 fix: one holder per hook-state scope through a stale-lock takeover (v1.86.2) (#261)+e0d11656 feat: session-mining economy - mining tombstones, a shadow trust-gate mode and a live-counts console (v1.86.0) (#258)+948a0403 feat: storage lifecycle for long-lived vaults (v1.85.0) (#257)++Related files:+- src/core/brain/untrusted-source.ts (read-time neutralizer), src/core/brain/capture/capture-note.ts (capture seam), src/core/brain/ingest/ingest.ts (ingest review gate), src/core/brain/wikilink.ts (wikilink detectors, code-region masking), src/core/brain/inline.ts (@osb marker grammar), src/core/brain/log.ts (log-row grammar)+- src/core/brain/init.ts (bootstrapBrain), src/core/brain/secrets/crypto.ts (existing .gitignore writer + invariant docblock), src/core/install/managed-block.ts (managed-block merger), src/core/brain/vault-dirty.ts (git-reading posture: ls-files vs status, check-ignore discipline)+- src/core/brain/doctor.ts (frozen DOCTOR_CHECKS registry), src/core/brain/doctor-exits.ts and src/core/brain/diagnostics.ts (exit-code classification, enforced by tests/core/brain/doctor-exit-census.test.ts), src/core/brain/doctor/privacy-marker-check.ts (counting-check pattern)+- src/core/brain/writeback-contract.ts (AGENT_INSTRUCTION_FILES, per-file audits), src/core/doctor-readiness.ts (probeWritebackContract readiness probe), src/core/brain/trust/instruction-file-ceiling.ts, src/core/brain/doctor/removed-tool-checks.ts (the other two instruction-file lists)+- src/mcp/stdio.ts (serveStdio production loop, serveStdioFromString test harness), src/mcp/server.ts (MCPServer.handleRequest, tools/list projection), src/mcp/tool-contract.ts (ToolDefinition), src/mcp/tools.ts and src/mcp/brain/*-tools.ts (registration slices), src/mcp/drain.ts (RequestDrain with N in-flight), src/mcp/http.ts (already-concurrent transport)++Conventions:+- SOLID/KISS/DRY; named constants over literals; errors surface explicitly by name; no stubs; everything English.+- Doctor findings follow no-dead-ends: every new code is classified in DIAGNOSTIC_SIGNALS (has a next command) or DOCTOR_EXIT_EXCLUSIONS (reason it has none), enforced by a census test; the doctor never mutates and never throws.+- Gate-mode precedent: SEARCH_TRUST_GATE_MODE (off/shadow/enforce, env twin wins over machine-config key, invalid values refused naming the key, default off).+- .gitignore writing precedent: the secrets sync-exclusion marker; its docblock claims an invariant ("nothing in src ever writes a .gitignore elsewhere") that a seeded guard must update.+- Version bump and CHANGELOG entry land inside the feature PR before the first push (CLAUDE.md overrides the release-time default).+- Each prior cycle documents design, plan, variants and the consultant prompt under docs/brainstorm/<slug>/.++Constraints:+- Do not change existing public APIs or any wire-visible schema; the MCP tools-list payload must remain byte-identical.+- No new external dependencies.+- Four implementation agents must be able to work simultaneously with disjoint file ownership; shared files need an explicit append-only protocol.+- The doctor stays read-only and fail-soft; nothing neutralizes or rewrites already-planted content in this wave (audit only).+- Neutralization must never key on natural-language vocabulary, never delete content, never introduce invisible characters, and must be idempotent.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/trust-and-responsiveness-hardening/design.md b/docs/brainstorm/trust-and-responsiveness-hardening/design.mdnew file mode 100644index 00000000..52c6596a--- /dev/null+++ b/docs/brainstorm/trust-and-responsiveness-hardening/design.md@@ -0,0 +1,106 @@+# Trust and responsiveness hardening - write-time marker neutralization, gitignore guardrails, shadowed instruction detection and parallel MCP reads++**Status:** draft+**Author:** ZCode orchestrator (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain defends third-party text at read time (the model-payload neutralizer), at ingest trust (quarantine plus staged review) and by containment fencing in derived sections - but nothing neutralizes structure-bearing markdown at the moment third-party text is written into the vault. A captured or ingested body can plant wikilinks, `@osb` markers, ```osb blocks or semantic headings that the link graph, the marker scanners and the section parsers then treat as the vault's own structure. Derived runtime state under `.open-second-brain/` is treated as ignore-worthy by the vault scope but nothing seeds a git-side guard, so a fresh `o2b brain init` in a git repository leaves `brain.sqlite` and friends visible to `git status`, and no doctor row fails an operator who has already committed that state. The doctor readiness probe audits each agent instruction file in isolation, so a workspace where Claude Code reads a bare `CLAUDE.md` while the write-back contract lives in `AGENTS.md` passes every row while the operative host never sees the contract. And the stdio MCP transport serves requests strictly one at a time even though the server dispatch and the HTTP transport are already re-entrant, so one slow read head-of-line blocks every later request.++## Premise verification++Verdicts from targeted reads against this tree at 88c118aa, recording the corrections from the four recon reports. The recons were premise-verified against live source; the corrections below are binding for the plan.++- **t_00b617b6 — premise_corrected (anchor).** `probeWritebackContract` is NOT under `src/core/brain/` - the card's `src/core/brain/doctor-readiness.ts` does not exist. It is at `src/core/doctor-readiness.ts:1742` (line 1738 falls inside its docblock), registered in `DEFAULT_PROBES` at :1807. The candidate list anchor is correct: `AGENT_INSTRUCTION_FILES` at `src/core/brain/writeback-contract.ts:72`, frozen, AGENTS.md first.+- **t_90409204 — premise_corrected (anchors).** `src/mcp/stdio.ts:258-262` is inside `serveStdioFromString` (the synchronous in-memory test-harness loop, stdio.ts:219-268), not the production loop. Production is `serveStdio` (stdio.ts:82), sequential only because each request is awaited inside the `for await` body. There is no `src/mcp/lifecycle.ts`; the intended anchor is `src/core/search/store/lifecycle.ts:434-438` (openReadDatabase: no lock, no migration). `store.ts:158` is `private closed = false`, not a mode flag; the live facts are `StoreOpenOptions.mode` (store.ts:117-122) and lifecycle.ts:434-438.+- **t_c2ac4fc8 — premise_confirmed with two scope facts.** No write-time neutralizer exists today (defense is read-time `neutralizeUntrustedText` at src/core/brain/untrusted-source.ts:85-90, the ingest trust lane, and containment fencing). No GFM tasklist parser exists anywhere in src/core - the card's "task rows" resolve to the log-row grammar and `@osb` markers; `render/activity-line.ts:47-50` is render-only. The design proceeds with task checkboxes OUT of the neutralization set (decision below).+- **t_206562ae — premise_confirmed with a docs correction.** `bootstrapBrain` is at `src/core/brain/init.ts:318`; the crypto invariant docblock is at `src/core/brain/secrets/crypto.ts:62-66` ("Nothing in src ever writes a `.gitignore` elsewhere"). The docs claiming the bench runs dir is "(gitignored)" are stale - `docs/observability.md:18` and `docs/cli-reference.md:584` state it but nothing in src seeds it; both are reworded in this wave.+- **Verified live, load-bearing for lane D.** The `tools/list` projection (`handleToolsList`, src/mcp/server.ts:484-494) picks fields explicitly (`name`, `description`, `inputSchema`, optional `outputSchema`), so a new metadata field on `ToolDefinition` structurally cannot reach the wire; a test pins this. `tests/core/brain.init.test.ts:64-67` pins `created.length` at 7 and is updated deliberately. The three instruction-file lists are divergent as reported: `writeback-contract.ts:72` (AGENTS.md first), `src/core/brain/trust/instruction-file-ceiling.ts:22` (CLAUDE.md first, includes GEMINI.md), `src/core/brain/doctor/removed-tool-checks.ts:43` (CLAUDE.md first, no GEMINI.md).+- **Verified live, load-bearing for lanes A and B.** `SEARCH_TRUST_GATE_MODE` (src/core/brain/trust/retrieval-gate.ts:79-97) is the gate-mode precedent including `resolveSearchTrustGateMode` (:115) with env-over-config and invalid-value refusal naming the key; the gate key is a plain string-keyed config record, not a policy block. `privacyMarkerCheck` (src/core/brain/doctor/privacy-marker-check.ts:34-61) is the counting-check pattern: pure planner module, one warning, `NAMED_PATH_LIMIT = 5`, `ctx.readable` filter, `failSoft: true`, code classified in `DOCTOR_EXIT_EXCLUSIONS` (doctor-exits.ts:152). `check-ignore` exit discipline and the worktree ls-files rule are documented in `src/core/brain/vault-dirty.ts` (:10-15, :37-42, :77-126).++## Scope++- Lane A (t_c2ac4fc8): a pure write-time neutralizer for structure-bearing markdown on third-party bodies, applied at the capture seam and the ingest review gate; a gate with `off|shadow|enforce` modes (default off); a read-only doctor audit (`planted-structure-rows` warning) over already-planted rows, sharing one detection grammar with the neutralizer - the audit population split by family: the marker and osb-fence families scan every readable page under `Brain/` (no Brain writer ever emits a live marker line or osb fence, so one anywhere in the derived layer is planted), while the wikilink and heading families scan only the third-party provenance lanes (captures, untrusted-stamped pages, quarantined entities, source summaries), and on both populations the sections the Brain's own writers render (a capture's marker-authorized `## Guidance`, a source summary's `## Sources`/`## Premises`/link and derivation sections) are excluded as the vault's own output.+- Lane B (t_206562ae): a seeded, merge-safe `.gitignore` managed block at `o2b brain init` covering `<vault>/.open-second-brain/`; a doctor row that FAILs when derived runtime state is already tracked by git; the crypto.ts invariant docblock updated; the stale "(gitignored)" doc claims reworded.+- Lane C (t_00b617b6): host instruction precedence constants beside `AGENT_INSTRUCTION_FILES`; a pure shadow resolver over the per-candidate audits; the readiness probe gains a fail finding when the file a host reads is not the file carrying the write-back contract, with a read-only recovery clause; a docblock sweep of the three divergent lists.+- Lane D (t_90409204): a required `read | write` classification on every tool definition; the stdio production loop dispatches reads concurrently under a small cap while writes stay exclusive behind a dispatch-level gate; EOF and drain always await the in-flight set; `tools/list` wire output stays byte-identical.+- Integrator: reconciliation of the shared append-only registries, docs and CHANGELOG; full local gates.++## Out of scope++- Deleting or rewriting already-planted rows: the doctor audit is read-only; remediation is re-capture or a later repair pass.+- Neutralizing vault-authored structure: `renderProvenanceSection` / `renderLinkSection` output, renderer-written `## Guidance` headings, `Brain/_BRAIN.md`, log files the writers themselves emit.+- Tier B `Brain/` derived content (`.snapshots`, `.artifacts`, `.state`, `.archives`, `.payloads`, `claim-graph.json`, rollups): stays un-gitignored. `Brain/` is user-visible vault content by design; excluding inside the knowledge tree is an operator choice, recorded here as the boundary.+- Parent-directory and user-level instruction surfaces (`~/.claude/CLAUDE.md`, `CLAUDE.local.md`, `~/.codex/AGENTS.md`, `context.fileName` overrides, parent-dir traversal): the probe stays at `join(opts.vault, name)`; documented limitation, follow-up territory.+- The instruction-file installer (sibling card t_af5e252f): lane C ships detection and constants only, shaped so the installer can share `HOST_INSTRUCTION_PRECEDENCE`.+- Uninstall handling for the seeded gitignore block: deliberate keep (the derived state exists as long as the vault does); not wired into any remove path.+- HTTP transport changes (already concurrent), core writer-lock semantics (search store writer-lock, sync-lockfile), and `serveStdioFromString` (stays sequential; comment rewritten only).+- GFM task-checkbox neutralization (no parser exists), and write-time escaping of markdown links, reference definitions and tags (decision below; the doctor audit observes them).+- Changes to `WRITER_TOOL_NAMES`, the MCP tools-advertising set, or any wire-visible schema.++## Chosen approach++Per-feature parallel lanes with an append-only shared-registry protocol (Variant 1 in variants.md). The wave splits into four lanes with disjoint file ownership - marker escaping (A), gitignore guardrails (B), shadowed instruction detection (C), stdio read parallelism (D) - plus one integrator. The shared substrate already exists in this tree (the frozen `DOCTOR_CHECKS` registry, the managed-block merger, `RequestDrain`'s N-in-flight register, the `SEARCH_TRUST_GATE_MODE` gate pattern), so no lane builds infrastructure first; the only shared surfaces are four append-only files whose edits are textual merges, plus docs and CHANGELOG appended last in each lane's own commit and reconciled by the integrator. Lane decisions per area are in Design decisions; the variant comparison and why substrate-first and integration-heavy lost are in variants.md.++## Design decisions++- **Marker-escape set: structure only, four families, never vocabulary.** The neutralizer keys on grammar a parser consumes, never on words. Families: (1) wikilinks - `[[target]]` and `[[target|alias]]`, detected with the `wikilink.ts` regex family (WIKILINK_TARGET_RE:59 through EXACT:80); (2) `@osb` inline markers and ```osb fenced blocks, per `inline.ts` (REQUIRED_FIELDS:69, KNOWN_KINDS:96, discoverMarkers:914); (3) ATX headings, which covers the semantic headings (`## Sources`, `## Premises`, `## Parts`, `## Table`, `## Guidance`) and log headings; (4) log/timeline rows, whose grammar is headed by `## <HH:MM:SS>Z - <event-kind>` (log.ts:1-20) - escaping the heading breaks the day-file parse, so the bullet rows ride along without separate treatment. Task checkboxes are excluded: no parser consumes GFM tasklists in this tree (recon §2). Markdown links, reference definitions and tags are excluded from write-time escaping this wave - they are additive index noise, and bracket/`#` escaping in quoted prose has the worst legibility cost per byte; the doctor audit observes them so the follow-up decision is made on data, not on taste.+- **Escaping choice per family: backslash-escape the sigils, never delete, never invisible characters.** One uniform mechanism: for each detector match span, backslash-escape the minimal sigil characters (brackets in wikilinks, `@` in inline markers, backticks on fence lines, the leading `#` run on headings). CommonMark renders a backslash before ASCII punctuation as the literal character, so captured text stays readable verbatim, while every line-grammar detector in src/core stops matching (`\@osb` no longer anchors, `\#\#` is not an ATX heading, escaped backticks cannot open a fence, `\[[x\]]` is not a wikilink). Escaped ```osb fence lines break the block as a unit; interior `key: value` field lines carry no independent sigils. HTML-entity escapes are rejected: `<`-style encoding does not neutralize `[[...]]` for markdown readers (recon risk 7).+- **Fence-awareness and idempotence doctrine.** Detection is fence-masked per family, each family answering to the fence model its own readers run, because the grammars disagree about what a fence even is: the marker families fence with `inline.ts`'s exactly-3-backtick walk (a tilde or 4-backtick fence fences nothing for them, and an unterminated fence masks the rest of the text), the heading family reuses the `source-links.ts` `fencedLineMask` shape where only a closed fence is a fence, and the wikilink family reuses `wikilink.ts` `codeRegions` (fences and inline code inert). Fence lines themselves are boundaries, not masked content. Idempotence by fixpoint, not by construction alone: the detectors are escape-aware (a sigil preceded by an odd backslash run is data, not structure), but escaping a fence line dissolves the fence and can expose interior text, so the neutralizer re-detects its own output in a bounded walk (`NEUTRALIZE_FIXPOINT_STEPS`) whose exit - the output's own detection coming back empty - is the doctrine's `neutralize(neutralize(x)) === neutralize(x)`; a bound exhausted with live structure still detected throws `MarkdownNeutralizeFixpointError` instead of returning the bytes it exists to neutralize. Regexes stay single-pass and non-backtracking. The neutralizer never opens new fences and never rewrites on-disk bodies after the fact.+- **One detection grammar, two consumers.** The auditor and the neutralizer share the detection layer in `neutralize-markdown.ts`: the writer escapes the spans, the doctor planner counts them. The finding, its count and what enforce mode would change cannot drift apart - the `planPrivacyMarkerRestamp` pattern (planner module + one counting check).+- **Gate mode off/shadow/enforce.** `MARKDOWN_NEUTRALIZE_MODE` (`off | shadow | enforce`), machine-config key `markdown_neutralize_mode`, env twin `OPEN_SECOND_BRAIN_MARKDOWN_NEUTRALIZE_MODE`, default off, env wins, invalid values refused by name - the `resolveSearchTrustGateMode` shape (retrieval-gate.ts:115-141) with no legacy boolean. Off: the helper is not invoked; byte-identity asserted end to end at both seams. Shadow: byte-identical to off at every seam - no seam-side detection runs at all (a shadow call would compute an answer nobody consumes) - and the preview is the doctor's `planted-structure-rows` finding, whose audit recomputes the would-be rows from the vault's bytes on its own and switches only its wording under the mode. Enforce: the seams write neutralized bytes. Neutralization keys off provenance, not content: it applies in the third-party lanes only (capture, untrusted ingest), never to vault-authored sections appended after caller text.+- **Record escaping when it happened, zero bytes when it did not.** When enforce-mode neutralization changed bytes, the page's frontmatter gains a conditional key naming the neutralized kinds - the `untrustedSourceFrontmatter` conditional-spread precedent (trust/untrusted-provenance.ts:88-90); unchanged bodies gain zero bytes. `captureBaseId` (capture-note.ts:167-175) hashes the persisted post-neutralize body, so identity follows what is actually on disk; a gate flip legitimately changes identity, and that is documented behavior, not an accident.+- **.gitignore: managed-block merge, never a blind append.** `gitignore-guard.ts` seeds a managed block (install/managed-block.ts markers; `insertManagedBlock` :105-132 is idempotent and CRLF-safe) whose entry list starts as exactly one vault-root-anchored line, `/.open-second-brain/` - one entry covers every Tier A writer (brain.sqlite, hook-audit, secrets, maintenance sqlite and journals, ingest checkpoints, dead-letters, session ledgers, watchdog fallback, self-heal state, locks, bench-runs). Exact-line membership is checked first, so a user who already ignores the path yields a skip, not a duplicate. A vault with no `.gitignore` gets one created; markers present but malformed surface as a named conflict (validateMarkers posture) with warn-and-continue, and the doctor row reports the unprotected state. The seeder never shells out to git; git is asked only by the doctor probe. The vault-scope asymmetry closes: `.open-second-brain` is already in `DEFAULT_VAULT_IGNORE_PATHS` (vault-scope/defaults.ts:75); the git side now matches.+- **crypto.ts invariant update, secrets marker kept.** The docblock invariant at crypto.ts:62-66 ("Nothing in src ever writes a `.gitignore` elsewhere") is reworded to name the three sanctioned writers: the secrets sync-exclusion marker (kept - the secrets dir can pre-date brain init), the vault-level managed block seeded by `ensureVaultGitignoreEntries` in `gitignore-guard.ts`, and `ensureBackupRootIgnored` in `trust.ts`, which writes its own `.gitignore` into the `.o2b-backups/` root - so the invariant was already false before this wave, and the reworded docblock says so rather than crediting the wave with breaking it. The comment is updated in the same commit that adds the managed-block writer, not after.+- **Tracked-vs-ignored: `ls-files` for tracking, `check-ignore` for ignoring, never `git status`.** The doctor probe measures tracking with `git ls-files -z -- <path>` run vault-bounded (`-C`, fixed argv, no shell - the vault-dirty.ts :78-126 posture): in a linked worktree `git status` omits ignored files, so only ls-files answers "is this committed". Ignoring is measured with `check-ignore` exit discipline (0 = ignored, 1 = not, other = refuse to say). Fail-soft throughout: not a worktree, directory absent, or git unable to answer means silence or an unknown - the doctor never throws. Findings: any tracked path is severity error naming `git rm -r --cached <path>` per path (named-path cap) plus the exact missing ignore line; present-but-unignored and untracked is severity warning (the only signal a vault whose init ran without git ever gets). The error code registers in `DIAGNOSTIC_SIGNALS` with `nextCommand` "o2b brain init" - the seeder is idempotent and merge-safe, so one command remediates the ignore half by seeding the missing `/.open-second-brain/` line, while a path git already tracks still needs the operator's `git rm -r --cached`, which the finding names per path - keeping the exit census green.+- **Host-instruction precedence constants; the three divergent lists are documented, not unified.** `HOST_INSTRUCTION_PRECEDENCE` (host to ordered instruction files: claude-code reads CLAUDE.md; codex, cursor, opencode, aider read AGENTS.md; gemini-cli reads GEMINI.md) is exported beside `AGENT_INSTRUCTION_FILES` in writeback-contract.ts so the probe and the future t_af5e252f installer share one definition; its docblock cites `docs/cross-project-pointer.md:13-17` and marks which entries are repo-cited versus name-implied. The three existing lists keep their shapes: the ceiling's `TRACKED_FILES` and removed-tool-checks' `ROOT_INSTRUCTION_FILES` are existence-loop lists, not precedence orders, and unifying them could change behavior (whether ROOT_INSTRUCTION_FILES deliberately omits GEMINI.md is an open question); lane C adds docblocks stating order rationale and cross-references so no fourth divergent list appears. Shadow detection keys on candidate co-existence, not the install manifest - there is no claude-code install target, so "which host" cannot be derived from manifests for the most important case.+- **Shadowing semantics: pure resolver, fail severity, read-only recovery clause.** Over the per-candidate audits, a host is shadowed when its preferred existing candidate (first in precedence order that exists) lacks the managed block while another candidate carries it (block present in any state: conforming, malformed-block, missing-clauses). Absent-only workspaces stay `skipped` ("nothing installed is not a contract violation"); shadow-free multi-file workspaces keep passing. A shadow finding grades `fail` in `probeWritebackContract`, its detail naming the host, the file the host reads and the file carrying the contract, with an embedded recovery clause following `WRITEBACK_CONTRACT_RECOVERY` phrasing (read-only: the probe never writes or offers a command that does; block surgery is content-editing, so no fake `o2b` command). Symlinked candidates stay refused evidence (`symlink` to `unknown`) - reading link targets to admit the common `AGENTS.md -> CLAUDE.md` dotfiles setup is a deliberate deferral, recorded as a limitation.+- **Read/write classification: required on the definition, write-mode-dominant, settled by an audit.** `ToolDefinition` gains a required `readonly kind: "read" | "write"` (tool-contract.ts:207; distinct from the host-facts `ToolCeilingKind.kind` on its own interface). Populated per slice at the aggregation seams, not inferred: nothing canonical exists today (`WRITER_TOOL_NAMES` is an advertising set that even includes a reader; description prose is not a contract). Rule: a tool that CAN write is `write` - the dual-mode tools (brain_watchdog remediate, brain_lifecycle apply, brain_dream, brain_receipts fold) are write, while brain_retention and brain_review_candidates ship as read (parity-pinned: their planners are recommendation-only, the dream leg a dry run, and their own descriptions promise no mutation). No args parsing at dispatch, ever. A registry-guard-style walk fails the build when any registered tool lacks the field, and the partition is pinned beside `FROZEN_BRAIN_TOOL_NAMES` in the parity test. Dispatch treats a missing kind as write (fail-closed) for hand-built definitions. The field is metadata: the `tools/list` projection picks its fields explicitly (server.ts:484-494), so the wire output stays byte-identical, asserted by a test.+- **Parallel reads behind a bounded cap, exclusive writes at dispatch only.** The stdio production loop dispatches read-classified requests without awaiting them, up to a named read-concurrency cap (constant, default 4); when the cap is reached the loop backpressures by awaiting a slot before reading further lines, so in-flight count is bounded by construction. Writes serialize through an in-loop async mutex at dispatch ONLY - never a lock inside core handlers, where re-entrant writers (brain_write_batch composing note kernels) would self-block. Classification is a server helper over `findTool` (non-`tools/call` methods are reads). Responses are written inside their own drain begin/finish window, preserving per-request adjacency (all of request K's notifications before response K); frames stay single-write atomic; out-of-order arrival is JSON-RPC-legal; cross-request progress interleaving is surrendered (clients correlate by progress token) and the progress-refusal envelope still holds - documented behavior change. `serveStdioFromString` stays sequential; its comment (:258-262) is rewritten to say the harness loop is sequential for positional assertions, not because the transport is.+- **EOF must await the in-flight set.** With parallel dispatch, loop exit becomes a real requirement rather than a structural accident: EOF, a drain break (:134), and `rl.close()` (:122-124) all resolve only after every dispatched request settles (drain.drain already waits the whole register). Without this, exit hooks - the search store WAL checkpoint and the sync-lockfile unlink - would run under floating handlers. Reads never take retrying locks: `acquireLockSyncWithRetry`'s `Bun.sleepSync` can block the thread up to ~5s, which under parallel reads would stall every in-flight request, so the read path adds no locking and the telemetry `ELOCKED` fail-open loss stays accepted.++## File changes++New:++- `src/core/brain/text/neutralize-markdown.ts` - the pure neutralizer, its gate constants (`MARKDOWN_NEUTRALIZE_MODE`, config key, env twin, resolver) and the shared escape-aware detection grammar (lane A).+- `src/core/brain/planted-rows.ts` - pure audit planner over the shared detectors (lane A).+- `src/core/brain/doctor/planted-rows-check.ts` - the counting check, `failSoft`, named-path cap (lane A).+- `src/core/brain/gitignore-guard.ts` - managed-block seeder/merger for the vault `.gitignore` (lane B).+- `src/core/brain/doctor/git-tracked-state-check.ts` - the ls-files/check-ignore probe (lane B).+- `tests/core/brain/text/neutralize-markdown.test.ts`, `tests/core/brain/ingest/ingest-marker-neutralize.test.ts`, `tests/core/brain/doctor/planted-rows-check.test.ts` (lane A); `tests/core/brain/gitignore-guard.test.ts`, `tests/core/brain/doctor/git-tracked-state-check.test.ts` (lane B); `tests/mcp/stdio-parallel.test.ts` (lane D).++Modified:++- `src/core/brain/capture/capture-note.ts` - neutralize caller text before `renderCaptureBody`; conditional provenance key; id-hash note (lane A).+- `src/core/brain/ingest/ingest.ts` - neutralize `input.summary` at body assembly (:449-457) per gate mode; same bytes stage and publish (lane A).+- `src/core/brain/init.ts` - `bootstrapBrain` gains the gitignore step, reported via created/skipped (lane B).+- `src/core/brain/secrets/crypto.ts` - invariant docblock reworded (lane B).+- `src/core/brain/path-constants.ts`, `src/cli/brain/verbs/bench.ts` - bench runs dir hoisted to a named constant (lane B).+- `src/core/brain/writeback-contract.ts` - `HOST_INSTRUCTION_PRECEDENCE`, the pure shadow resolver, docblock (lane C).+- `src/core/doctor-readiness.ts` - `probeWritebackContract` grades shadow findings (lane C).+- `src/core/brain/trust/instruction-file-ceiling.ts`, `src/core/brain/doctor/removed-tool-checks.ts` - docblock-only sweep (lane C).+- `src/mcp/tool-contract.ts` - `kind` on `ToolDefinition`; `src/mcp/tools.ts` and every slice (`src/mcp/brain/*-tools.ts`, `search-tools.ts`, `schema-tools.ts`, `skill-tools.ts`, `wiring-tools.ts`, `watchdog-tools.ts`, `hydrate-tool.ts`) - per-tool classification (lane D).+- `src/mcp/server.ts` - the write-classifier helper over `findTool` (lane D).+- `src/mcp/stdio.ts` - parallel read dispatch, exclusive write gate, in-flight-set EOF, comment rewrites (:13 module docblock, :258-262) (lane D).++Shared, append-only (protocol in plan.md):++- `src/core/brain/doctor.ts` - lane A registers `plantedRowsCheck` after `privacyMarkerCheck`; lane B registers `gitTrackedStateCheck` after `secretsSyncExposureCheck`.+- `src/core/brain/doctor-exits.ts` - lane A classifies `planted-structure-rows`.+- `src/core/brain/diagnostics.ts` - lane B classifies the tracked-state code with `nextCommand` "o2b brain init".+- `tests/core/brain/doctor-exit-census.test.ts`, `tests/core/brain/doctor.test.ts`, `tests/core/brain.doctor.test.ts` - extended only by the lane that added the code/entry.+- `docs/observability.md`, `docs/cli-reference.md`, `docs/mcp.md`, `CHANGELOG.md` - each lane appends its own rows in its final lane commit; the integrator reconciles.++## Risks and open questions++- **Mangling legitimate quoted markdown.** People quote documents, which is why `## Guidance` exists (capture-note.ts:185-191). Mitigations: gate default off; provenance-keyed lanes only; escaping over deletion; shadow mode lets an operator preview exactly what enforce would change before turning it on; the doctor audit reports planted rows vault-wide regardless of mode.+- **Escaped-form tolerance.** The doctrine assumes renderers and this repo's own readers treat backslash-escaped sigils as literal text. QA verifies `renderPrefLink`, the search tokenizer and the wikilink scanners do not match escaped forms; if a reader disagrees, that family's escape character is a per-family decision point, not a doctrine change.+- **Gate flips and capture identity.** Because the id hashes the persisted body, toggling enforce between captures of the same third-party text yields different identities (an honest duplicate rather than a silent mutation). Documented; revisit only if operators hit it.+- **Staged-versus-published double reporting.** The audit dedupes Brain/pending/ staged copies against publish targets (report the publish target; count staged once), keeping the warning truthful without noise.+- **Windows.** Backslash path separators, CRLF preservation in the managed block (managed-block.ts:80-99 handles it), `core.ignoreCase` affecting check-ignore, and git-on-PATH resolution for the doctor probe. The payload-windows test precedent covers the merge mechanics.+- **Grading impact of the shadow row.** A currently-passing multi-file workspace can start failing once shadowing grades fail - deliberate and documented in cli-reference and CHANGELOG; the detail is a flattened row string, so the finding stays concise and names both paths.+- **Lane D residual risks.** A future two-write frame refactor would break atomicity - the extended PassThrough test guards it. `acquireLockSyncWithRetry` blocking stays a core-side hazard: no read path takes retrying locks. Telemetry continuity appends under `ELOCKED` remain fail-open (accepted loss).+- **Open: GEMINI.md's absence from `ROOT_INSTRUCTION_FILES`.** Possibly deliberate. The docblock sweep asks the question in place; answering it behaviorally is a follow-up decision, not a silent unification.+- **Open: aider's convention file.** The repo doc claims Aider follows agents.md (unverified upstream); the precedence entry carries that uncertainty in its docblock.diff --git a/docs/brainstorm/trust-and-responsiveness-hardening/plan.md b/docs/brainstorm/trust-and-responsiveness-hardening/plan.mdnew file mode 100644index 00000000..c2fa0fec--- /dev/null+++ b/docs/brainstorm/trust-and-responsiveness-hardening/plan.md@@ -0,0 +1,141 @@+# Trust and responsiveness hardening - implementation plan++Four implementation lanes with disjoint file ownership plus one integrator. Each task is TDD-ready: write the failing test first, implement until green, refactor with all tests green, format and lint before every commit, commit only the task's own files (`git commit --only <paths>`, never a plain `git add` + `git commit`). Each lane runs ONLY its own new or changed test files locally (never the full suite); the integrator runs the full gates.++## File ownership table++Each file is owned by exactly one lane (or nobody). A lane that needs a file outside its ownership stops and renegotiates this contract; it never reaches into another lane's files.++| Files | Owner |+|---|---|+| `src/core/brain/text/neutralize-markdown.ts`, `src/core/brain/planted-rows.ts`, `src/core/brain/doctor/planted-rows-check.ts`, `src/core/brain/capture/capture-note.ts`, `src/core/brain/ingest/ingest.ts` | Lane A |+| `tests/core/brain/text/neutralize-markdown.test.ts`, `tests/core/brain/ingest/ingest-marker-neutralize.test.ts`, `tests/core/brain/doctor/planted-rows-check.test.ts`, extended `tests/core/brain/capture/capture-note.test.ts` | Lane A |+| `src/core/brain/gitignore-guard.ts`, `src/core/brain/doctor/git-tracked-state-check.ts`, `src/core/brain/init.ts`, `src/core/brain/secrets/crypto.ts`, `src/core/brain/path-constants.ts`, `src/cli/brain/verbs/bench.ts` | Lane B |+| `tests/core/brain/gitignore-guard.test.ts`, `tests/core/brain/doctor/git-tracked-state-check.test.ts`, extended `tests/core/brain.init.test.ts` | Lane B |+| `src/core/brain/writeback-contract.ts`, `src/core/doctor-readiness.ts`, `src/core/brain/trust/instruction-file-ceiling.ts` (docblock only), `src/core/brain/doctor/removed-tool-checks.ts` (docblock only) | Lane C |+| `tests/core/brain/writeback-contract.test.ts`, `tests/core/doctor-readiness.test.ts` | Lane C |+| `src/mcp/tool-contract.ts`, `src/mcp/tools.ts`, `src/mcp/server.ts`, `src/mcp/stdio.ts`, `src/mcp/hydrate-tool.ts`, `src/mcp/search-tools.ts`, `src/mcp/schema-tools.ts`, `src/mcp/skill-tools.ts`, `src/mcp/wiring-tools.ts`, `src/mcp/watchdog-tools.ts`, every file under `src/mcp/brain/` | Lane D |+| `tests/mcp/stdio-parallel.test.ts`, extended `tests/mcp/brain-tools-parity.test.ts`, `tests/mcp/progress-token.test.ts`, `tests/mcp/mcp.test.ts` | Lane D |+| `src/core/brain/vault-dirty.ts`, `src/core/search/store/writer-lock.ts`, `src/core/brain/sync-lockfile.ts`, `src/core/install/managed-block.ts`, `hooks/` | Nobody - read-only precedents; no lane modifies them |++## Shared files and the append-only protocol++These files are touched by more than one lane. The protocol: a lane edits shared files ONLY in its final lane task, appends only (never edits, reorders or deletes another lane's entries), and commits them in that lane's own final commit via `git commit --only`. The integrator reconciles any textual overlap and re-freezes ordering in one pass.++- **`src/core/brain/doctor.ts` (DOCTOR_CHECKS registry).** Lane A appends exactly one entry, `plantedRowsCheck`, immediately after `privacyMarkerCheck`. Lane B appends exactly one entry, `gitTrackedStateCheck`, immediately after `secretsSyncExposureCheck`. Neither lane reorders existing entries; the registry's order is a report contract.+- **`src/core/brain/doctor-exits.ts` (DOCTOR_EXIT_EXCLUSIONS).** Lane A appends one entry for `planted-structure-rows` (no single command remediates third-party text). Reason may not name an `o2b` invocation (:31-33).+- **`src/core/brain/diagnostics.ts` (DIAGNOSTIC_SIGNALS).** Lane B appends one entry for the tracked-state code with `nextCommand` "o2b brain init" (the seeder is idempotent and merge-safe).+- **`tests/core/brain/doctor-exit-census.test.ts`, `tests/core/brain/doctor.test.ts`, `tests/core/brain.doctor.test.ts`.** Append-only: a lane extends them only with assertions for its own code/entry (census coverage, registry-order position). Neither lane edits the other's assertions.+- **`docs/` files and `CHANGELOG.md`.** Each lane's final task appends its own rows (its own doc sections, one CHANGELOG bullet under the unreleased heading). Appends only; the integrator reconciles into one coherent pass and owns any prose that spans lanes.++## Lane A - write-time marker neutralization (t_c2ac4fc8)++### Task A1: Pure neutralizer and shared detection grammar++- **Files**: new `src/core/brain/text/neutralize-markdown.ts` (families: wikilinks, `@osb` inline markers, ```osb fence lines, ATX headings including log headings; backslash-escape of sigils within detector match spans; fence-masked detection reusing `wikilink.ts` codeRegions/maskCodeRegions; escape-aware detectors, odd-backslash-run rule; single-pass non-backtracking regexes; API returns `{ text, changed, kinds }`); new `tests/core/brain/text/neutralize-markdown.test.ts`.+- **Acceptance**: passing unit tests prove each family is detected and escaped (wikilink plain and aliased, `@osb` inline per `KNOWN_KINDS`, ```osb open and close fence lines, `##` headings incl. the log-heading shape); content inside fenced code and inline code is untouched; already-escaped sigils are not re-escaped (odd backslash run is data); `neutralize(neutralize(x))` is byte-identical to `neutralize(x)`; unchanged input returns `changed: false` and identical bytes; vault-authored samples (`- [[id]]` link rows, `## Guidance` renderer output) escape only when fed through the caller-text entry point; no invisible characters are ever introduced.+- **Depends on**: none.++### Task A2: Gate mode resolver++- **Files**: modified `src/core/brain/text/neutralize-markdown.ts` (frozen `MARKDOWN_NEUTRALIZE_MODE` vocab `off|shadow|enforce`, `MARKDOWN_NEUTRALIZE_MODE_CONFIG = "markdown_neutralize_mode"`, env twin `OPEN_SECOND_BRAIN_MARKDOWN_NEUTRALIZE_MODE`, `resolveMarkdownNeutralizeMode` with env-over-config and invalid-value refusal naming the key actually in force - the `resolveSearchTrustGateMode` shape); extended `tests/core/brain/text/neutralize-markdown.test.ts`.+- **Acceptance**: passing resolver tests prove: absent everywhere resolves `off`; env wins over config; `shadow` and `enforce` resolve; an invalid value throws naming the key and the received value; the resolver reads only its arguments (pure).+- **Depends on**: A1.++### Task A3: Capture seam++- **Files**: modified `src/core/brain/capture/capture-note.ts` (in `writeCaptureNote` (:233): resolve gate mode; on `enforce`, neutralize the caller-supplied body text before `renderCaptureBody` composes it, and the guidance tail; renderer-authored structure stays untouched; on `changed`, write the conditional provenance key naming the kinds; `captureBaseId` hashes the persisted post-neutralize body; on `off`/`shadow` bytes are unchanged); extended `tests/core/brain/capture/capture-note.test.ts`.+- **Acceptance**: passing tests prove: gate off, a body full of live `[[...]]`/`@osb`/`##` markers persists byte-identical to today (end-to-end byte-identity); gate enforce, the persisted body has no live markers per a fence-masked scan, renders read as literal text, and the provenance key names the kinds; gate shadow, bytes are unchanged; the guidance split still fires only on writer-set frontmatter, never on a neutralized heading; re-capture of the same text under a stable gate is idempotent; zero bytes are added when nothing changed.+- **Depends on**: A1, A2.++### Task A4: Ingest seam++- **Files**: modified `src/core/brain/ingest/ingest.ts` (at body assembly (:449-457): on gate `enforce` and an untrusted source, neutralize `input.summary` once so staged and published bytes are the same `nextContents`; vault-authored sections (`renderProvenanceSection`, `renderLinkSection`, derivation.section) appended after, untouched; conditional frontmatter key rides the existing provenance merge); new `tests/core/brain/ingest/ingest-marker-neutralize.test.ts`.+- **Acceptance**: passing tests prove: enforce + untrusted, planted markers are inert on BOTH the published page and the Brain/pending/ staged copy (identical bytes); re-ingest of the published page never re-stages and stays idempotent; gate off and trusted-source paths are byte-identical to today; vault-authored sections never appear escaped; the write disposition gate (:465-492) is unaffected.+- **Depends on**: A1, A2.++### Task A5: Doctor audit and shared registrations (lane final)++- **Files**: new `src/core/brain/planted-rows.ts` (pure planner importing the A1 detectors; population split by family: the marker and osb-fence families on every readable page under `Brain/` - no Brain writer ever emits a live marker line or osb fence - and the wikilink and heading families on the third-party lanes only (capture pages, untrusted-stamped pages, quarantined entity pages, source summaries), whose structure the Brain's own writers render by design elsewhere; the sections those writers render - a capture's marker-authorized `## Guidance`, a source summary's `## Sources`/`## Premises`/link and derivation sections - excluded from the report as the vault's own output; fence-masked body scan; staged-vs-published dedupe); new `src/core/brain/doctor/planted-rows-check.ts` (`failSoft: true`, one warning, code `planted-structure-rows`, `NAMED_PATH_LIMIT = 5`, `ctx.readable` filter - the privacyMarkerCheck shape; shadow mode adds the would-be-enforce wording); new `tests/core/brain/doctor/planted-rows-check.test.ts`; SHARED appends: `src/core/brain/doctor.ts` (registry entry after `privacyMarkerCheck`), `src/core/brain/doctor-exits.ts` (exclusion entry), the three shared test files; lane-final docs append (`docs/cli-reference.md` doctor row, CHANGELOG bullet).+- **Acceptance**: passing tests mirror the privacy-marker suite: silent when nothing planted; one warning with count and capped named paths; unreadable pages excluded via `ctx.readable`; staged copies counted once; registry-order assertions pass with the new entry in position; exit census and doctor-order tests stay green with the new classification; the check never mutates and never throws.+- **Depends on**: A1 (A2 for the shadow wording).++## Lane B - gitignore guardrails (t_206562ae)++### Task B1: Guard module and derived-state census++- **Files**: new `src/core/brain/gitignore-guard.ts` (managed-block seeder: block markers with a named id, entry list starting as exactly `/.open-second-brain/`; exact-line membership pre-check; create-with-block when no `.gitignore` exists; insertManagedBlock merge when it does; named conflict on malformed existing markers, warn-and-continue; CRLF-safe; returns created/skipped); modified `src/core/brain/path-constants.ts` and `src/cli/brain/verbs/bench.ts` (bench runs dir hoisted from the locally-spelled join at bench.ts:37 to a named constant beside `DERIVED_STORE_DIR`); new `tests/core/brain/gitignore-guard.test.ts` including a source-reading census pinning every known derived-state writer (brain.sqlite, hook-audit, maintenance sqlite and journals, ingest checkpoints, dead-letters, session ledgers, watchdog fallback, self-heal state, locks, bench runs) under `DERIVED_STORE_DIR`.+- **Acceptance**: passing tests prove: a missing `.gitignore` is created containing only the block; an existing user `.gitignore` is byte-preserved outside the block and gains the block appended with a separator; a second run is a no-op (idempotent, byte-equal); CRLF files keep their line endings; malformed existing markers surface the named conflict without writing; the census test fails if a derived-state writer moves outside the covered directory.+- **Depends on**: none.++### Task B2: Brain-init wiring and invariant update++- **Files**: modified `src/core/brain/init.ts` (`bootstrapBrain` (:318) gains the gitignore step beside the identity stamp, reported through the existing created/skipped arrays); modified `src/core/brain/secrets/crypto.ts` (docblock :62-66 reworded to name the two sanctioned `.gitignore` writers; behavior unchanged, secrets marker kept); extended `tests/core/brain.init.test.ts`.+- **Acceptance**: passing tests prove: fresh `o2b brain init` in a git-inited temp vault leaves `git status --porcelain` empty after runtime creates `.open-second-brain/brain.sqlite`; `created.length` assertions updated deliberately (7 to 8) with the `.gitignore` named; a second init reports no creations; a pre-existing user `.gitignore` survives init byte-preserved outside the block; init into a non-git folder succeeds identically (no git dependency at init).+- **Depends on**: B1.++### Task B3: Doctor tracked-state row and shared registrations (lane final)++- **Files**: new `src/core/brain/doctor/git-tracked-state-check.ts` (`failSoft`; worktree detection first, silent when not a worktree or the directory is absent; `git ls-files -z -- .open-second-brain` vault-bounded for tracking, `git check-ignore` exit discipline for the ignore state; tracked paths to severity error naming `git rm -r --cached <path>` capped by the named-path limit plus the missing ignore line; present-but-unignored untracked state to severity warning; git that cannot answer means silence); new `tests/core/brain/doctor/git-tracked-state-check.test.ts` (real temp git repos per the sync-exposure test shape); SHARED appends: `src/core/brain/doctor.ts` (registry entry after `secretsSyncExposureCheck`), `src/core/brain/diagnostics.ts` (signal with `nextCommand` "o2b brain init"), the three shared test files; lane-final docs append (`docs/cli-reference.md` doctor row, CHANGELOG bullet).+- **Acceptance**: passing tests prove: doctor exits 1 on a fixture with a committed `.open-second-brain` file; exits 0 after `git rm -r --cached` plus the ignore line; warning (not error) for untracked-but-unignored; silent in a non-git folder, when the directory is absent, and when git is missing; the doctor never edits anything; census and registry-order tests stay green.+- **Depends on**: B1 (B2 for the end-to-end remediation assertion).++## Lane C - shadowed agent instruction files (t_00b617b6)++### Task C1: Host precedence constants and pure shadow resolver++- **Files**: modified `src/core/brain/writeback-contract.ts` (exported `HOST_INSTRUCTION_PRECEDENCE`: host to ordered instruction files - claude-code reads CLAUDE.md; codex, cursor, opencode, aider read AGENTS.md; gemini-cli reads GEMINI.md - docblock citing `docs/cross-project-pointer.md:13-17` and marking repo-cited versus name-implied entries; pure resolver over the per-candidate audits returning shadowed triples `{ host, readsPath, contractPath }`: the host's first existing candidate lacks the managed block while another candidate carries it in any block-bearing state); extended `tests/core/brain/writeback-contract.test.ts`.+- **Acceptance**: passing unit tests prove: CLAUDE.md present without a block plus AGENTS.md carrying a conforming block yields the claude-code shadow triple naming both paths; GEMINI.md-only and AGENTS.md-only workspaces yield no shadow; a host whose preferred file carries the block yields no shadow; absent-only workspaces yield nothing; symlink candidates are ignored by the resolver without crashing (evidence refused, never read); the resolver performs no writes and no I/O (pure over its input).+- **Depends on**: none.++### Task C2: Shadow row in the readiness probe++- **Files**: modified `src/core/doctor-readiness.ts` (in `probeWritebackContract` (:1742): between the workspace audit (:1744) and the aggregation (:1750), grade each shadow triple as a `fail` row whose detail names the host, the file the host reads, the file carrying the contract, and an embedded read-only recovery clause following `WRITEBACK_CONTRACT_RECOVERY` phrasing; absent-only workspaces stay `skipped`; shadow-free multi-file workspaces keep passing; census arithmetic stays coherent); extended `tests/core/doctor-readiness.test.ts`.+- **Acceptance**: passing tests prove: conforming AGENTS.md plus bare CLAUDE.md fails naming both files with the recovery clause; the probe verdict is fail and exits non-zero under `--readiness`; one-conforming-among-absent still passes; the no-file case still skips with the existing wording; the worst-of aggregate and census stay correct when a shadow coexists with a malformed block elsewhere; the probe performs only reads and lstats (no writes, no symlink following).+- **Depends on**: C1.++### Task C3: List-consistency sweep and docs (lane final)++- **Files**: modified `src/core/brain/trust/instruction-file-ceiling.ts` and `src/core/brain/doctor/removed-tool-checks.ts` (docblock-only: state the list's purpose - existence loop, not precedence - cross-reference `AGENT_INSTRUCTION_FILES` and `HOST_INSTRUCTION_PRECEDENCE`, and record the open question on GEMINI.md's absence; NO behavior change, list contents and orders untouched); modified `docs/cli-reference.md` (the `--readiness` probe description gains the shadowed-instruction finding and its grading impact); SHARED: CHANGELOG bullet.+- **Acceptance**: passing tests prove no behavior change in either swept module (existing suites green unchanged); the CLI reference documents the new vocabulary; no fourth divergent filename list was introduced (the repo now has exactly the three existing lists plus the precedence table that references them).+- **Depends on**: C2.++## Lane D - parallel MCP reads on stdio (t_90409204)++### Task D1: Registry classification (no behavior change)++- **Files**: modified `src/mcp/tool-contract.ts` (required `readonly kind: "read" | "write"` on `ToolDefinition`, docblock distinguishing it from the host-facts `ToolCeilingKind.kind` and stating the write-mode-dominant rule and that the field never reaches the wire); modified `src/mcp/tools.ts` and every slice - `src/mcp/brain/` tools files, `src/mcp/search-tools.ts`, `src/mcp/schema-tools.ts`, `src/mcp/skill-tools.ts`, `src/mcp/wiring-tools.ts`, `src/mcp/watchdog-tools.ts`, `src/mcp/hydrate-tool.ts` - setting `kind` per tool (dual-capability tools are write: brain_watchdog, brain_lifecycle, brain_dream, brain_receipts; brain_retention and brain_review_candidates ship as read - parity-pinned, recommendation-only/dry-run planners whose descriptions promise no mutation); extended `tests/mcp/brain-tools-parity.test.ts` (registry-guard-style walk failing when any registered tool lacks `kind`, and the read/write partition pinned beside `FROZEN_BRAIN_TOOL_NAMES`); extended `tests/mcp/mcp.test.ts` (a wire-identity assertion: the `tools/list` result serializes exactly `name`, `description`, `inputSchema`, optional `outputSchema` - byte-identical to the pre-change payload).+- **Acceptance**: passing tests prove every registered tool carries `kind`; the partition matches the pinned list (a deliberately wrong entry fails the test); `tools/list` output is byte-identical; no dispatch behavior changed in this task.+- **Depends on**: none.++### Task D2: stdio parallel dispatch with exclusive writes++- **Files**: modified `src/mcp/server.ts` (classifier helper over `findTool`: non-`tools/call` methods are reads; `tools/call` is a write when the tool's `kind` is `write`, fail-closed on a missing kind); modified `src/mcp/stdio.ts` (production `serveStdio` loop: reads dispatched unawaited up to a named concurrency cap constant, default 4, with the loop backpressuring on a slot before reading further lines; writes through an in-loop async mutex, FIFO, one write in flight; each request's response written inside its own drain begin/finish window; EOF, drain break and `rl.close()` resolve only after the in-flight set empties; `serveStdioFromString` untouched and still sequential).+- **Acceptance**: passing tests prove: two reads issued back-to-back with a held first handler both complete (the second no longer head-of-line blocks); a write issued between them waits for the write gate and runs alone (interleaving log shows no read/write overlap and no write/write overlap); responses carry their own ids regardless of completion order; the in-flight count never exceeds the cap; after stdin EOF the loop resolves only when every dispatched request settled.+- **Depends on**: D1.++### Task D3: Invariant tests for the new concurrency++- **Files**: new `tests/mcp/stdio-parallel.test.ts` (PassThrough real-stream fixture plus the http-drain held-request pattern: frame integrity under N concurrent calls, per-request adjacency - all of request K's notifications before response K - write exclusivity via an interleaving log, drain abandoned labels, EOF awaiting the in-flight set with a controllable slow handler); extended `tests/mcp/progress-token.test.ts` (two concurrent calls with progress tokens: every notification precedes its own response, cross-request interleaving is legal, the progress-refusal envelope still holds); updated `tests/mcp/mcp.test.ts` (order-dependent frame assertions rewritten for legal reordering; the harness loop's sequential assertions kept for `serveStdioFromString` only).+- **Acceptance**: passing tests prove frame atomicity under concurrency (no notification splices inside a response frame on a real stream); reordering across requests is asserted legal and adjacent-per-request; the drain reports abandoned labels; EOF never resolves under a floating handler.+- **Depends on**: D2.++### Task D4: Comment and docs reconciliation (lane final)++- **Files**: modified `src/mcp/stdio.ts` (comment-only: module docblock :13 "the one request that can be in flight" reworded for bounded parallel reads with exclusive writes; the `serveStdioFromString` comment :258-262 rewritten to say the harness loop is sequential for positional assertions, not because the transport serializes); SHARED: `docs/mcp.md` (transport note: stdio now runs reads concurrently under a cap with writes exclusive, out-of-order responses are JSON-RPC-legal, cross-request progress interleaving is the documented behavior change), CHANGELOG bullet.+- **Acceptance**: a repo-wide comment scan finds no doc or comment still claiming strict stdio request sequencing; `docs/mcp.md` matches the shipped behavior; no code change in this task beyond comments (existing suites green).+- **Depends on**: D3.++## Integrator++### Task I1: Reconciliation and full gates++- **Files**: the shared files if any lane-overlap needs re-freezing (`src/core/brain/doctor.ts` final registry order, the three shared test files, `docs/` and `CHANGELOG.md` coherence pass).+- **Acceptance**: the full local gates pass in CI order - formatter check, lint, typecheck, and the FULL test suite (the only place the full suite runs); `tests/core/brain/doctor-exit-census.test.ts` green with both new codes classified; the doctor registry order assertions reflect the final frozen order; every user-visible surface added by lanes A-D has a docs row; no placeholders anywhere; the branch contains only lane commits plus this reconciliation.+- **Depends on**: A5, B3, C3, D4.++## Commit shape++- Lane commits use conventional messages on this branch, each committing only its own files via `git commit --only <paths>`: `feat(brain): neutralize structure-bearing markdown in imported text` (lane A), `feat(brain): seed gitignore guardrails for derived brain state` (lane B), `feat(doctor): detect shadowed agent instruction files` (lane C), `feat(mcp): parallel reads on the stdio transport` (lane D). The integrator commits `chore(brainstorm): reconcile shared registries and docs` or folds into the release-preparation pass.+- The brainstorm artifacts commit separately as `chore(brainstorm): trust-and-responsiveness-hardening` before any lane work.+- Lane D's wire constraint is a review gate, not just a test: any diff showing `kind` in a `tools/list` payload, an added advertised field, or a reordered advertised list is a defect regardless of test outcome.diff --git a/docs/brainstorm/trust-and-responsiveness-hardening/variants.md b/docs/brainstorm/trust-and-responsiveness-hardening/variants.mdnew file mode 100644index 00000000..bbfd1385--- /dev/null+++ b/docs/brainstorm/trust-and-responsiveness-hardening/variants.md@@ -0,0 +1,34 @@+# Variants - trust-and-responsiveness-hardening++Audit trail for the phase-0 brainstorm. These variants are generated in-session for this run; the same text lives at `cli-output/claude.md`. Each variant is a shape for the whole wave - how the four cards are organized against each other - not a per-card design (the per-card approaches come from the four recon reports and are identical across variants).++## Variant 1: Per-feature parallel lanes with an append-only shared protocol++- **Approach**: Four lanes with strictly disjoint file ownership implement the four cards independently and simultaneously; the only shared surfaces are the doctor registry, the two code-classification tables, the shared doctor test files, docs and CHANGELOG, all governed by an append-only protocol - each lane appends its entries in its own final commit via `git commit --only`, and one integrator reconciles ordering and prose and runs the full gates. Each lane leans on the substrate that already exists in the tree: the frozen `DOCTOR_CHECKS` registry, the managed-block merger, `RequestDrain`'s N-in-flight register, and the `SEARCH_TRUST_GATE_MODE` gate shape.+- **Trade-offs**:+ - Pros: four agents work truly in parallel (the wave's main cost is wall time); every card ships as an atomic conventional commit; no infrastructure is built that the tree does not already need; the append-only protocol makes the four shared files textual merges rather than design coordination.+ - Cons: the shared files are a serialization point at lane end (registry order and census must be reconciled); lane discipline can slip without the `--only` commit rule being enforced; cross-lane interactions (e.g. two new doctor rows landing in one release) are only seen at integration.+- **Complexity**: medium+- **Risk**: low++## Variant 2: Shared-substrate-first++- **Approach**: Build a common foundation first - a doctor-row framework (registration helper, counting-check template, classification wiring, census scaffolding), a shared gate-mode/config resolver extracted from `retrieval-gate.ts`, and a transport concurrency primitive - then implement the four cards as thin consumers of that substrate.+- **Trade-offs**:+ - Pros: the doctor rows for lanes A and B and the gate modes for lane A land on one tested abstraction; classification wiring cannot diverge between the two new codes; the extracted resolver removes one duplicated pattern.+ - Cons: serializes the start of all four lanes behind a fifth work package; most of the "substrate" already exists in this tree, so the phase mostly renames and moves working code (a refactor PR riding a hardening wave); the abstraction risks being shaped by imagined needs - three of the four cards need exactly one registry entry each, which is not a framework.+- **Complexity**: large+- **Risk**: medium++## Variant 3: Integration-heavy single spine++- **Approach**: One integrator owns the branch throughout; the four features are implemented serially against a continuously integrated spine, with an integration pass (registry order, census, docs, full suite) after every feature rather than once at the end. Parallel agents, if any, work strictly inside one feature at a time under the integrator's sequencing.+- **Trade-offs**:+ - Pros: shared files never merge concurrently, so no protocol is needed; every integration hazard surfaces immediately after the feature that caused it; the branch is always releasable.+ - Cons: gives up the wave's parallelism entirely (four features times an integration pass each); the integrator becomes a bottleneck and context swamps; the per-feature integration passes mostly re-run the same registry/census/docs checks that a single end pass covers.+- **Complexity**: medium+- **Risk**: low++## Recommended: Variant 1++**Rationale**: The substrate Variant 2 would build already exists - the doctor registry, the managed-block merger, the drain register and the gate-mode pattern are shipped, tested code - so substrate-first buys a refactor, not a foundation, and three of the four cards need exactly one append entry each. Variant 1 is the only shape that lets four agents work simultaneously, and its one real hazard, concurrent edits to four small shared files, is bounded by an append-only protocol whose merges are textual. Variant 3's continuous integration is the safest but converts the wave's defining constraint - four independent P4 cards - into a serial queue for no correctness gain the end-pass integrator does not already provide.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 44654851..669d4f17 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -447,7 +447,7 @@ o2b brain export Read-only dump of active preferences, or (since v1o2b 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 fail-o2b 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+o2b 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. Since v1.96.0 the pass runs the fail-soft `git-tracked-derived-state` check - derived runtime state under `.open-second-brain/` that git already tracks (measured by `git ls-files`, never inferred from status) is an ERROR naming one location-independent untrack command (`git -C '<vault>' rm -r --cached -- .open-second-brain`, single-quoted, runnable from any directory) plus the missing `/.open-second-brain/` ignore line, with the tracked paths listed as capped evidence and the remainder counted, a present-but-unignored untracked store is a warning, and the check is silent outside a git worktree, when the store directory is absent, and when git cannot answer; the ignore half is remediated by `o2b brain init`'s idempotent guard block, the untracking is git's own, and the check never edits anything. Since v1.96.0 the pass also runs the fail-soft `planted-structure-rows` audit - one warning counting live structure rows (wikilinks, `@osb` markers, ```osb fence lines, ATX headings). The population splits by family: the marker and osb-fence families are scanned on every readable page under `Brain/` - no Brain writer emits a live marker line or an osb fence, so one anywhere in the derived layer is planted - while the wikilink and heading families are scanned only on the third-party provenance lanes (brain-capture captures, brain-source summaries, untrusted-stamped pages, quarantined entities), where caller text lands; on both populations the sections the Brain writers themselves render are excluded, not reported - a capture's marker-authorized `## Guidance` section and a source summary's `## Sources`, `## Premises`, `## Entities` and `## Connections to existing notes` citation sections, plus its `## Parts` and `## Table` derivation headings, are this vault's own output. The finding names up to five paths and counts the rest, names lane pages first, deduplicates `Brain/pending/` staged copies against their publish targets, skips pages the caller may not read, and is silent on a vault with none; under `markdown_neutralize_mode: shadow` the finding appends the preview naming what enforce would escape on the next capture or untrusted ingest of the same text. The audit is read-only by contract: the rows leave only by re-capturing the text with the gate in `enforce` or by a later repair pass, so the finding carries no `o2b` commando2b brain health Semantic-health report (since v0.14.0): contradictory confirmed preferences, recurring concepts with no dedicated preference, stale claims, plus a clean | watch | investigate verdicto2b brain history Render a preference's edit-history timeline (since v0.14.0): one entry per content mutation (principle / scope / status before -> after)o2b brain audit Render a preference's full mutation audit trail (since v0.21.0): create / promote / update / retire / merge with agent, reason, revision + content-hash before/after. ret- or bare-slug arg resolves to the same trail@@ -581,7 +581,7 @@ o2b brain continuity export --format atof|atif [--session <id>] [--monto2b brain bench memory --fixture <name|path> [--suite <name>] [--sample-seed <value>] [--sample-cap <n>] [--resume <run-id>] [--runs-dir <dir>] [--json] - memory quality benchmark over a disposable fixture vault; quality, latency, and context cost reported separately; checkpoint/resume by run id; exit 1 on any failed question. Suites (since v1.82.0): longmemeval (strict recall_all@5 over the LongMemEval dataset shape; committed sample fixture, full dataset operator-supplied, judge glue over bench_judge_cmd) and surfacing-replay (replays a recorded prompt corpus through the shipped decision core and scores know_to_ask / false_fire). Sampling (since v1.83.0): --sample-seed plus --sample-cap run a seeded, question-type-proportional subset of the dataset instead of the whole fixture; longmemeval is the only suite that declares the capability```-The benchmark never touches the configured vault - the fixture materializes into `<runs-dir>/<run-id>/vault` (default runs dir `.open-second-brain/bench-runs/`, gitignored). The optional `bench_judge_cmd` config key (env `OPEN_SECOND_BRAIN_BENCH_JUDGE_CMD`) arms an advisory external judge; absent means the judge phase is skipped. The full observability contract (event kinds, gates, correlation ids, payload safety, schema version) lives in `docs/observability.md`.+The benchmark never touches the configured vault - the fixture materializes into `<runs-dir>/<run-id>/vault` (default runs dir `.open-second-brain/bench-runs/`, which `o2b brain init` excludes from git through the managed guard block it seeds into the vault `.gitignore`). The optional `bench_judge_cmd` config key (env `OPEN_SECOND_BRAIN_BENCH_JUDGE_CMD`) arms an advisory external judge; absent means the judge phase is skipped. The full observability contract (event kinds, gates, correlation ids, payload safety, schema version) lives in `docs/observability.md`.Since v1.82.0 the verb's suite registry maps a `--suite` name to its loader plus a declared capability set (`{embeddings: boolean}`, plus `sampling` since v1.83.0): omitting `--suite` stays the byte-identical default path, and the semantic lane is reachable only for a suite that declared the embeddings capability (longmemeval does; arming the pin is an API-only move this wave - the CLI exposes no knob or floor flag). The run identity folds the pinned search knobs and the proactive-recall admission floor into the checkpoint hash beside the fixture hash, so a resumed run that would mix configurations fails the identity guard by name instead of comparing two pipelines; in-flight runs started before the change fail the resume guard loudly and restart. Since v1.83.0 `--sample-seed <value>` plus `--sample-cap <n>` (longmemeval only - the only suite that declares the sampling capability) run a seeded, question-type-proportional subset of the dataset instead of the whole fixture: the two flags are refused apart, a non-positive or non-integer cap is refused naming the value, and a suite whose registration lacks the capability is refused naming the suite, so the flags can never be silently ignored. Sampling selects before conversion - abstention questions are excluded first (their count still lands in `abstention_excluded`), the survivors are stratified by the dataset's own `question_type` values, each stratum contributes its population-proportional share of the cap by largest-remainder apportionment (remainders compared as integers, ties by stratum name), and the draw is a seeded shuffle over entries sorted by question id, so dataset file order cannot change the subset and the same seed and cap always select the same questions. A sampled run's `--json` report carries the sampling receipt in its `longmemeval` family: `sample_population`, `sample_selected` and the per-stratum `sample_strata` sit beside `abstention_excluded`, each present only on a sampled run and absent from a whole-dataset report, and the human report line gains `sample_selected N` only on a sampled run; the seed and cap fold into the run identity: run ids without sampling are unchanged, and a resumed run whose sampling options changed fails the identity guard by name. `--suite longmemeval` converts the official LongMemEval dataset shape - abstention questions drop at conversion with the count recorded, gold sessions join by direct id membership and an unknown id is a named parse error - and reports the strict `longmemeval: {recall_all_at_5, abstention_excluded}` family beside the untouched quality, latency and context_cost families; the committed sample fixture `tests/fixtures/bench/longmemeval-sample.json` certifies CI and the full dataset is an operator-supplied path (never downloaded at run time). The judge glue reuses `bench_judge_cmd`: when the suite provides them, the stdin payload's questions carry `question`, `answer` and `gold` beside the usual result fields, and the official prompt text ships as module constants pinned to a named upstream revision, so the external command stays a dumb model call; suites without judge input keep the payload byte for byte. `--suite surfacing-replay` replays a recorded prompt corpus (a committed session fixture, or a vault's own session turns converted to the same shape) through the shipped decision core and scores the graded surfacing gate's know_to_ask / false_fire rates under the same denominations the proactive-recall metric uses, so the gate's calibration is a measured number a re-run re-measures.@@ -775,7 +775,7 @@ the wait.### Trusted recall and memory write surface (since v1.35.0)```text-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-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; placement shadowing fails too: a host whose preferred instruction file carries no managed block while another candidate file carries the block (the host-to-file precedence table lives in `brain/writeback-contract.ts`: claude-code reads `CLAUDE.md`; codex, cursor, opencode and aider read `AGENTS.md`; gemini-cli reads `GEMINI.md`) is one fail finding naming the host, the file the host reads, the file carrying the contract and the same read-only recovery clause, so a workspace whose every per-file row is clean can still fail on where the contract was installed, and the fail census counts findings, not files; symlinked candidates keep their refused unknown treatment, and a workspace with no instruction file at all stays skipped because nothing installed is not a contract violation; 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```@@ -871,6 +871,28 @@ behavior it always had, so measuring first is named explicitly withnote by a named multiplier. All default off and leave rankingbyte-identical when unset.+Write-side trust switches: `markdown_neutralize_mode` (env+`OPEN_SECOND_BRAIN_MARKDOWN_NEUTRALIZE_MODE`, `off | shadow | enforce`)+runs the write-time markdown neutralization gate at the third-party write+seams - capture writes (`o2b brain capture` and the capture kernel) and+untrusted-source ingest summaries: `enforce` backslash-escapes the+structure-bearing markdown in caller text before it is written - wikilinks,+`@osb` inline markers, ```osb fence lines and ATX headings, the same+grammar the doctor audit counts - so the link graph, the marker scanners+and the section parsers never treat it as the vault's own structure, and+stamps a `neutralized_markers` frontmatter key naming the escaped families+(a write that changes nothing adds nothing, and vault-authored sections+appended after caller text are never touched); `shadow` leaves every seam+write byte-identical to `off` - no seam-side detection runs at all - and+only switches the `planted-structure-rows` doctor audit to its preview+wording, the audit recomputing the would-be rows from the vault's bytes on+its own; `off` - the default -+runs no gate and every write stays byte-identical. The env twin wins over+the config key and an invalid value is refused by name at the seam. Because+capture identity hashes the persisted bytes, flipping the mode between+captures of the same text yields an honest duplicate rather than a silent+mutation.+### Knowledge intake and consolidation (since v1.36.0)```textdiff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 962a0d9f..eb6c6e6f 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -686,7 +686,7 @@ are mirrored in MCP; destructive operations are CLI-only by design.| Validate invariants | `o2b brain doctor` | `brain_doctor` | read-only; structural lints + semantic-health findings; `--remediate [--dry-run]` applies auto-safe content-hash re-stamps || Semantic health | `o2b brain health` | `brain_health` | read-only; contradictions, concept gaps, stale claims + clean/watch/investigate verdict || Preference edit-history | `o2b brain history <slug>` | — (CLI-only) | read-only; one entry per content mutation (principle / scope / status before -> after) |-| Full-text search | `o2b search "<query>"` | `brain_search` | read-only; FTS5 + optional semantic |+| Full-text search | `o2b search "<query>"` | `brain_search` | FTS5 + optional semantic; write-classified MCP tool (persists access and opt-in reinforce/telemetry ledgers under `Brain/search/`) || Manage search index | `o2b search index \| reindex \| status \| check` | — (CLI-only) | builds / inspects `<vault>/.open-second-brain/brain.sqlite`. `search check` ends with a `recommendations:` block on missing pieces (key, sqlite-vec, first reindex) || Cron template for reindex | `o2b search reindex --cron-template [--interval N]` | — (CLI-only) | prints a watchdog script, native crontab line, and `hermes cron create` recipe to stdout (writes nothing) || Operational snapshot | `o2b status` | `second_brain_status` | read-only; `brain.*` + `search.*` blocks |diff --git a/docs/mcp.md b/docs/mcp.mdindex 2ab0a2ed..9ac2fd30 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -16,6 +16,27 @@ in Open Second Brain depends on the MCP server being running.below). No `prompts` or `sampling`.- Standard MCP lifecycle: `initialize`, `notifications/initialized`,`tools/list`, `tools/call`, optional `ping`.+- Request ordering (stdio, since v1.96.0): read-classified calls run+ concurrently, up to four in flight — a constant, not a knob, backpressured+ at the cap so the bound holds by construction — while write-classified+ calls (every tool that CAN mutate vault state — the registry's `kind`+ classification is write-mode-dominant) run one at a time and never beside a+ read. The overlap pays only across awaited I/O: a read handler whose work+ runs synchronously between awaits (the SQLite, filesystem and scoring+ reads) finishes no sooner than serialized dispatch, so pipelining does not+ shrink a batch's total time, and its responses shift toward the end of the+ batch — the first response can arrive later than arrival-order delivery+ would. Write-classified tools, including `brain_search` (write-classified+ by the write-mode-dominant rule), still run one at a time. Responses may+ therefore arrive out of arrival order, which is legal JSON-RPC: correlate+ by response `id`, and progress by `progressToken`. Each request's own+ notifications all precede its response, and every frame stays+ newline-terminated. On EOF the server still waits for every dispatched+ request before the process exits. A signal drain instead stops at a request+ boundary and waits only up to its deadline (10 000 ms, `O2B_MCP_DRAIN_MS`;+ see "Shutdown and draining" below): a request still open when the deadline+ expires is named on stderr, and a line read but parked behind the+ concurrency cap when the drain started is left unanswered.### Argument contract (since v1.46.0)@@ -74,7 +95,7 @@ A request with no `_meta`, or a `_meta` carrying other members but no| Transport | With a token | With no token ||---|---|---|-| stdio | Emits `notifications/progress` frames as the operation runs, all of them ahead of the response frame | No notification frames at all |+| stdio | Emits `notifications/progress` frames as the operation runs, all of them ahead of that request's response frame (two concurrent calls may interleave each other's frames; correlate by the frame's own `progressToken`) | No notification frames at all || HTTP | Answers the call normally and carries a typed refusal on `result._meta` | No `_meta` on the result |stdio owns a duplex newline-delimited stream, so it can write a frame@@ -377,9 +398,9 @@ flags for a narrower per-process full server.| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — || `brain_writes` | Read-only listing of recorded note writes (create / update / append / revert), newest first, with the agent, the device the log shard names, the target path and the content digest on each side. Filters by agent, device, path, op and time window. `action: plan_revert` returns the sealed plan for undoing a selection of those writes - one entry per target with its action, refusal reason and both digests - and never applies it; applying is CLI-only. | — || `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |-| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest \| today`. `view=today` embeds the operator dashboard: obligations sorted due-today and overdue first, one-off pledges, open loops, merged recent activity, totals. | `view` |-| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` |-| `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_brief` | Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest \| today`. `view=today` embeds the operator dashboard: obligations sorted due-today and overdue first, one-off pledges, open loops, merged recent activity, totals. `view=digest` also snapshots its report under `Brain/reports/` for the run-over-run delta when report snapshots are enabled (skipped below local reach and under an enforced owner scope). | `view` |+| `brain_analytics` | Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=attention_flows` seeds its default flow recipe when the vault lacks one; `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` |+| `brain_search` | 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. Write-classified: it persists activation access events by default and the opt-in reinforce, recall-telemetry and query-demand ledgers under `Brain/search/` - ranking state later searches read back. | `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. 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` |@@ -946,7 +967,7 @@ trapped by it.| --- | --- | --- || new work | answered `503` with `Retry-After: 1` and `Connection: close` — a code a client retries, not a protocol error | the next line is left unread; the loop stops cleanly at a request boundary rather than half-serving the shutdown || the listener | deliberately stays up until the drain finishes, so a supervisor can watch | — |-| in-flight | tracked from the first header to the response's `close` event, so a request is not counted as finished while its bytes are still queued | tracked across the dispatch AND the response write |+| in-flight | tracked from the first header to the response's `close` event, so a request is not counted as finished while its bytes are still queued | tracked from acceptance — a write parked behind in-flight reads included — across the dispatch AND the response write, so a drain waits for queued work it cannot see running yet |`GET /health` gains a third field and is **never refused during a drain** — ashutdown a supervisor cannot observe is a shutdown it will report as a@@ -1501,7 +1522,7 @@ server to your Codex MCP config the same way as Hermes.The plugin manifest `.claude-plugin/plugin.json` declares **two** MCP-server entries inline under `mcpServers` (there is deliberately no `.mcp.json` at the repository root: Claude Code would also load it as a project config for sessions started in a checkout, where `${CLAUDE_PLUGIN_ROOT}` is unset and both servers fail to spawn):- `open-second-brain` - the full surface, whose advertised tool count is stated once under "Tool Highlights" above (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_memory_bridge`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.-- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.+- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` and `brain_context` (the pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0; its handler regenerates the shared `active.md` when absent or stale, so it is a writer under the concurrency kind too). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`), and since v1.70.0 both are registered with `--harness claude-code`. Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).diff --git a/docs/observability.md b/docs/observability.mdindex 7418bb8e..46aeba8e 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -15,7 +15,7 @@ Open Second Brain records what it did - learning events, recall decisions, serve| Session lifecycle audit | `Brain/log/session-lifecycle/<ISO-week>[.<device-id>].jsonl` | `captureSessionLifecycleEvent()` in `src/core/brain/session-lifecycle.ts` | JSONL audit rows || Other audit weeks | `<ISO-week>[.<device-id>].jsonl` under `Brain/log/hygiene/`, `Brain/log/secret-custody/`, `Brain/log/schema-mutations/`, `Brain/log/watchdog/` (fallback `.open-second-brain/watchdog-audit/`) and `.open-second-brain/hook-audit/` | `appendAuditRecord()` in `src/core/reliability/audit.ts`, the one writer every audit site calls | JSONL audit rows || Fixed-name ledgers | `Brain/log/query-demand`, `Brain/log/recurrence-support`, `Brain/log/capture-decisions`, `Brain/skill-proposals/verifier-rejections`, `Brain/preferences/pref-<slug>.history`, `Brain/projects/git/<repo>/commits` and `.open-second-brain/maintenance-runs`, each `<stem>[.<device-id>].jsonl` | the owning module's path helper through `shardedFileName()` in `src/core/brain/ledger-shards.ts` | one JSON record per line |-| Bench runs | `<runs-dir>/<run-id>/` (default `.open-second-brain/bench-runs/`, gitignored) | `runMemoryBench()` in `src/core/bench/phases.ts` | `checkpoint.json`, per-question results, `report.json` |+| Bench runs | `<runs-dir>/<run-id>/` (default `.open-second-brain/bench-runs/`; excluded from git by the guard block `o2b brain init` seeds into the vault `.gitignore`) | `runMemoryBench()` in `src/core/bench/phases.ts` | `checkpoint.json`, per-question results, `report.json` || Failed automatic upgrade | `.open-second-brain/self-heal-upgrade.json` (per device, not synced with `Brain/`) | `recordSelfHealUpgradeFailure()` in `src/core/maintenance/self-heal-upgrade-state.ts` | one JSON object: `failed_at`, `error`, `consecutive_failures`, `pending`, `retry_after`; read by `o2b doctor` (`self_heal_upgrade`), `o2b brain status` and `o2b brain upgrade --dry-run` || Metrics | `Brain/metrics/<surface>[.<device-id>].jsonl` | `appendMetric()` in `src/core/brain/metrics.ts` | one run-level JSON record per line (see `docs/metrics.md`) || Signal archive | `Brain/inbox/archived/sig-*.md` | the dream pass (`archiveStaleSignals()` in `src/core/brain/dream-apply.ts`, policy in `src/core/brain/signal-archive.ts`) | the inbox signal file, moved byte for byte; the moving run's `dream` log event lists every id under `archived_signals` |diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 6c299ddb..dd88ccf6 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.95.0",+ "version": "1.96.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex ceec7b10..cb901eb2 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -2153,7 +2153,7 @@ var init_errors = __esm(() => {// src/core/brain/path-constants.tsimport { posix } from "node:path";-var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_PLEDGES_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;+var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_PLEDGES_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, DERIVED_STORE_DIR = ".open-second-brain", BENCH_RUNS_REL, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;var init_path_constants = __esm(() => {BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");@@ -2194,6 +2194,7 @@ var init_path_constants = __esm(() => {BRAIN_SNAPSHOTS_DIR,BRAIN_ARTIFACTS_DIR]);+ BENCH_RUNS_REL = posix.join(DERIVED_STORE_DIR, "bench-runs");BRAIN_COMPILED_DIGEST_RELS = Object.freeze([posix.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE),posix.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)diff --git a/package.json b/package.jsonindex 2d3a7f6f..04625e9a 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.95.0",+ "version": "1.96.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 16be1944..33257a2a 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.95.0"+version: "1.96.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 305b8969..6292171f 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.95.0",+ "version": "1.96.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/_schemas.py b/plugins/hermes/_schemas.pyindex 79979b2a..04c5064d 100644--- a/plugins/hermes/_schemas.py+++ b/plugins/hermes/_schemas.py@@ -277,7 +277,8 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = ( { 'name': 'brain_feedbac{ 'name': 'brain_context','description': 'Pull the current Brain/active.md body, pinned current-task context, ''and active-preference counts. Use at session start when SessionStart '- 'hook is unavailable (Cursor, Aider, raw Claude API). Read-only.',+ 'hook is unavailable (Cursor, Aider, raw Claude API). Regenerates '+ 'Brain/active.md when absent or stale.','inputSchema': {'type': 'object', 'properties': {}, 'additionalProperties': False}},{ 'name': 'brain_context_pack','description': 'Return the highest-tier, most recent vault slice under `max_tokens` - '@@ -1045,8 +1046,10 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = ( { 'name': 'brain_feedbac'additionalProperties': False}},{ 'name': 'brain_search','description': 'Full-text search across the vault. Optional semantic layer when '- 'configured. Read-only. When a query misses, consult brain_recall_gate '- 'before widening recall: it classifies whether widening is warranted.',+ 'configured. Persists access events and opt-in reinforce/telemetry '+ 'ledgers under Brain/search/. When a query misses, consult '+ 'brain_recall_gate before widening recall: it classifies whether '+ 'widening is warranted.','inputSchema': { 'type': 'object','properties': { 'query': { 'type': 'string','minLength': 1,diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 16be1944..33257a2a 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.95.0"+version: "1.96.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 b1338d98..e93f5558 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.95.0"+version = "1.96.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/bench.ts b/src/cli/brain/verbs/bench.tsindex 897c7f7a..e771ce45 100644--- a/src/cli/brain/verbs/bench.ts+++ b/src/cli/brain/verbs/bench.ts@@ -27,6 +27,7 @@ import type {BenchSuiteRegistration,} from "../../../core/bench/types.ts";import { defaultConfigPath, resolveBenchJudgeCmd } from "../../../core/config.ts";+import { BENCH_RUNS_REL } from "../../../core/brain/path-constants.ts";import { CliError, fail, parse } from "../helpers.ts";const USAGE =@@ -34,7 +35,12 @@ const USAGE ="[--recall-floor <n>] [--sample-seed <value>] [--sample-cap <n>] " +"[--resume <run-id>] [--runs-dir <dir>] [--json]";-const DEFAULT_RUNS_DIR = join(".open-second-brain", "bench-runs");+// Named in `path-constants.ts` as a member of the derived store, not as+// a path of its own: the runs dir is gitignored only once brain init has+// seeded the vault's .gitignore guard, whose single vault-root-anchored+// `/.open-second-brain/` entry covers the whole store, bench-runs+// included - until that seeding, nothing here is ignored.+const DEFAULT_RUNS_DIR = BENCH_RUNS_REL;const REPO_FIXTURE_DIR = join("tests", "fixtures", "bench");/**diff --git a/src/cli/brain/verbs/init.ts b/src/cli/brain/verbs/init.tsindex 0ebaf437..b228f5ea 100644--- a/src/cli/brain/verbs/init.ts+++ b/src/cli/brain/verbs/init.ts@@ -67,6 +67,11 @@ export async function cmdBrainInit(argv: string[]): Promise<number> {created: result.created,overwritten: result.overwritten,skipped: result.skipped,+ // The bootstrap result's guard field is always set, and the+ // docblock's contract is that machine readers use it instead of+ // parsing stderr: without it a conflict or a failed seed rendered+ // in JSON as a plain skipped, indistinguishable from a clean one.+ guard: result.guard,...(empty ? nextCommandField("brain-empty") : {}),});} else {@@ -74,6 +79,13 @@ export async function cmdBrainInit(argv: string[]): Promise<number> {for (const p of result.created) info(` created: ${p}`);for (const p of result.overwritten) info(` overwritten: ${p}`);for (const p of result.skipped) info(` exists: ${p}`);+ // Named like the lists above. Clean statuses say so in one word; a+ // conflict or a failed seed carries its detail so the human output+ // reads alongside the stderr warning instead of instead of it.+ info(+ ` guard: ${result.guard.status}` ++ (result.guard.detail !== undefined ? `: ${result.guard.detail}` : ""),+ );}// no-dead-ends, task 5. This verb creates the tree and then saysdiff --git a/src/core/brain/capture/capture-note.ts b/src/core/brain/capture/capture-note.tsindex 08476271..5f9962d6 100644--- a/src/core/brain/capture/capture-note.ts+++ b/src/core/brain/capture/capture-note.ts@@ -26,6 +26,31 @@* and hand the second to the `-2` allocator. Both additions are* conditional on the field being present, so a capture without guidance* is byte-identical to one written before the field existed.+ *+ * ## Write-time marker neutralization (t_c2ac4fc8)+ *+ * The body and the guidance are CALLER text - the one thing in the page+ * this contract did not author - so under the markdown-neutralization+ * gate's `enforce` mode they pass through the pure neutralizer+ * (`text/neutralize-markdown.ts`) before anything is composed: planted+ * wikilinks, `@osb` markers, ```osb fence lines and ATX headings are+ * backslash-escaped, and the conditional `neutralized_markers` key names+ * the kinds that changed. The writer's own `## Guidance` heading is+ * renderer-authored and never passes through the neutralizer, so a body+ * whose captured text quoted a guidance heading can never win the split+ * the frontmatter marker authorizes. The two halves are neutralized in+ * order and the guidance's detection runs in the fence context the+ * rendered prefix leaves (body, separator, heading): the page is one text+ * to every scanner, so a fence split across the two halves - opened by+ * the body, closed or left open by the guidance's own bytes - has+ * combined-page meaning neither half's standalone scan can see, and a+ * marker that page-scanner verdict makes live is caught in the guidance+ * half while a marker it masks stays untouched there. `captureBaseId`+ * hashes the PERSISTED post-neutralize body, so identity follows what is+ * on disk; a gate flip between captures of the same text therefore yields+ * a different id - an honest duplicate, documented rather than accidental.+ * Under `off` (the default) and `shadow` the bytes are untouched: the+ * seam never reaches the neutralizer under either mode.*/import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";@@ -48,6 +73,12 @@ import {} from "../paths.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";import { declaredPageTypes } from "../schema-pack.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE,+ neutralizeMarkdown,+ neutralizedMarkersFrontmatter,+ resolveMarkdownNeutralizeModeForProcess,+} from "../text/neutralize-markdown.ts";/** Frontmatter `kind:` marker of a staged inbound capture. */export const BRAIN_CAPTURE_KIND = "brain-capture";@@ -207,6 +238,18 @@ function renderCaptureBody(body: string, guidance: string | null): string {return guidance === null ? body : `${body}\n\n${GUIDANCE_HEADING}\n\n${guidance}`;}+/**+ * The exact rendered bytes ahead of the guidance on the page: the body+ * half, the blank-line separator and the writer's own heading. This - not+ * the body alone - is the fence context the guidance's neutralization runs+ * in, because it is what every scanner of the rendered page sees before+ * the guidance's first byte (see the seam comment in+ * {@link writeCaptureNote}).+ */+function renderedGuidanceContext(body: string): string {+ return `${body}\n\n${GUIDANCE_HEADING}\n\n`;+}+/*** Split a marked body back into its two halves.*@@ -246,9 +289,53 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captu// refused capture creates no directory and consumes no allocator name.requireDeclaredCaptureKind(vault, BRAIN_CAPTURE_KIND);+ // Write-time marker neutralization (t_c2ac4fc8), resolved before the+ // id so the hash follows the bytes that will actually be persisted.+ // Only `enforce` writes neutralized bytes; `off` and `shadow` leave+ // the caller's text byte-identical - shadow's preview is the doctor's+ // planted-rows audit, which recomputes the would-be rows from the+ // vault's bytes on its own, so a shadow-mode seam has nothing to run.+ // The caller's body and guidance are the only caller-authored halves -+ // the guidance HEADING below is renderer-authored and never passes+ // through the neutralizer.+ //+ // The two halves are neutralized in order, and the guidance's detection+ // runs in the fence context the rendered prefix leaves: the page is one+ // text to every scanner, so a fence the body opens and the guidance's+ // own bytes close (or leave open) has combined-page meaning neither+ // half's standalone scan can see - the split-fence hole, where a+ // planted marker live on the combined page scanned clean in both+ // halves. The context is the exact rendered bytes ahead of the guidance+ // (the neutralized body, the separator, the writer heading), so the+ // half's verdict agrees with the combined page's in both directions.+ const gate = resolveMarkdownNeutralizeModeForProcess();+ let storedBody = body;+ let storedGuidance = guidance;+ let neutralized: FrontmatterMap = {};+ if (gate === MARKDOWN_NEUTRALIZE_MODE.enforce) {+ const neutralBody = neutralizeMarkdown(body);+ const neutralGuidance =+ guidance === null+ ? null+ : neutralizeMarkdown(guidance, {+ precedingContext: renderedGuidanceContext(neutralBody.text),+ });+ if (neutralBody.changed || (neutralGuidance !== null && neutralGuidance.changed)) {+ storedBody = neutralBody.text;+ if (neutralGuidance !== null) storedGuidance = neutralGuidance.text;+ neutralized = neutralizedMarkersFrontmatter(+ [...new Set([...neutralBody.kinds, ...(neutralGuidance?.kinds ?? [])])].toSorted(),+ );+ }+ }+const dir = capturesDir(vault);mkdirSync(dir, { recursive: true });- const { prefix, slug } = captureBaseId(body, { source, sender, capturedAt }, guidance);+ const { prefix, slug } = captureBaseId(+ storedBody,+ { source, sender, capturedAt },+ storedGuidance,+ );const provenance: CaptureProvenance = { source, sender, capturedAt };// Allocation and creation are one step: two captures that hash to the@@ -266,8 +353,8 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captu// CLI output and MCP envelopes and never says what collided.writeFrontmatterAtomic(allocation.path,- captureFrontmatter(captureId, provenance, guidance),- renderCaptureBody(body, guidance),+ captureFrontmatter(captureId, provenance, storedGuidance, neutralized),+ renderCaptureBody(storedBody, storedGuidance),{overwrite: false,existsErrorKind: "capture",@@ -280,8 +367,10 @@ export function writeCaptureNote(vault: string, input: WriteCaptureInput): Captureturn Object.freeze({id,path: vaultRelative(allocated.path, vault),- body,- guidance,+ // What was persisted - under enforce mode the neutralized bytes, so+ // the returned note answers for the file it shipped in.+ body: storedBody,+ guidance: storedGuidance,provenance,staged: true,});@@ -291,6 +380,7 @@ function captureFrontmatter(id: string,provenance: CaptureProvenance,guidance: string | null,+ neutralized: FrontmatterMap,): FrontmatterMap {return {kind: BRAIN_CAPTURE_KIND,@@ -301,6 +391,10 @@ function captureFrontmatter(// Emitted only when there IS guidance, so a capture without it is// byte-identical to one written before this field existed....(guidance === null ? {} : { [GUIDANCE_MARKER_FIELD]: true }),+ // Emitted only when enforce-mode neutralization CHANGED bytes; a+ // clean capture adds nothing and stays byte-identical to the shape+ // this contract wrote before the gate existed.+ ...neutralized,tags: ["brain", "brain/capture"],};}diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 74af4412..ce385472 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -61,6 +61,7 @@ import {ENTITY_QUOTE_VARIANT_COLLISION_CODE,ENTITY_QUOTE_VARIANT_COLLISION_COMMAND,} from "./entities/canonical.ts";+import { GIT_TRACKED_DERIVED_STATE_CODE } from "./doctor/git-tracked-state-check.ts";import { scanDanglingWorkruns, WORKRUN_PHASE } from "./dream-workrun.ts";import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";import { LINT_CONSOLIDATE_KIND } from "./lint-consolidate.ts";@@ -1026,6 +1027,18 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new Map"o2b brain feedback --topic <topic> --signal=positive --principle <principle> --scope <scope>",autoRepairable: false,},+ {+ // The git tracked-state row (t_206562ae). The ignore half of the+ // remediation is the seeder, and the seeder is idempotent and+ // merge-safe on an existing vault, so one command ends the+ // warning - and the ignore half of the error. The untrack half+ // is git's own (one location-independent `git -C <vault> rm -r --cached --+ // .open-second-brain` command, named in the finding) because no verb in this tool untracks a file.+ code: GIT_TRACKED_DERIVED_STATE_CODE,+ issueClass: "derived brain state tracked by git, or present and not git-ignored",+ nextCommand: "o2b brain init",+ autoRepairable: false,+ },] satisfies ReadonlyArray<DiagnosticSignal>).map((s) => [s.code, Object.freeze(s)]),);diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex 1c699c7c..7bec52ac 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -38,7 +38,7 @@import { existsSync, readdirSync } from "node:fs";import { join, posix } from "node:path";-import { readerRefView, type ArtifactRefView } from "./artifact-ref-view.ts";+import { everyArtifactRefView, readerRefView, type ArtifactRefView } from "./artifact-ref-view.ts";import { logEntriesAtReach, logEntryAtReach } from "./log-events-at-reach.ts";import { buildBacklinkIndex, type BacklinkIndex } from "./backlinks.ts";import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summary.ts";@@ -61,6 +61,7 @@ import {resolveOwnerScopeDelivery,} from "./preferences-collect.ts";import { isPreferenceVisible } from "./owner-scoped-facts.ts";+import { gatedOwnerScopeView } from "./owner-scope-view.ts";import type { BrainLogEntry } from "./log.ts";import { listLogDates, readLogDay } from "./log-jsonl.ts";import {@@ -554,12 +555,17 @@ function collectDigestData(const logEntries = logEntriesAtReach(refs, readLogsInWindow(vault, since, until));// A shift or contradiction line is one string naming its preference// inside other text, so the event-level filter above cannot resolve it;- // the parsed id is asked on its own.+ // the parsed id is asked on its own. The id resolves through the Brain+ // id-directories, so the enforced ownership rule joins the reach view+ // for these rows - the same composed view the actions below are kept+ // through, so every section that reads past the windowed records asks+ // one question about what "hidden" means.+ const scopedRefs = everyArtifactRefView(gatedOwnerScopeView(vault, agentScope), refs);const confidenceShifts = extractConfidenceShifts(logEntries, idToPrinciple).filter((row) =>- refs.visible(row.id),+ scopedRefs.visible(row.id),);const contradictions = extractContradictions(logEntries, idToPrinciple).filter((row) =>- refs.visible(row.id),+ scopedRefs.visible(row.id),);// Stable ordering — id ascending so two runs on the same fixture@@ -642,6 +648,21 @@ function collectDigestData(// the digest can say why its actions list came back thin.const collectErrors: MaintenanceCollectError[] = [];+ // The actions list is collected vault-wide (lint demotions, dedup+ // candidates, merged-link rewrites), so a row can name a preference+ // every section beside it already withholds. The enforced ownership+ // rule therefore joins the reach view for these rows too - the+ // `scopedRefs` composed above for the shift and contradiction lines.+ // `gatedOwnerScopeView` is the same adapter `brain_doctor`'s+ // `suggested_actions` and the operator summary's `top_actions` ask+ // over the same collector output, so the sinks cannot disagree+ // about what "hidden" means. The composed predicate is threaded INTO+ // the collector, so it applies to the candidate inputs before the+ // scorer caps: hidden top-ranked rows take no slot a visible one+ // could fill, and a dedup count excludes hidden secondaries. It+ // hides nothing until `integrity.owner_scope_delivery` is `fail`+ // with a scope, so an unscoped digest stays byte-identical; under+ // `warn` it withholds nothing too, matching every section above.return {new_unconfirmed,confirmed,@@ -654,8 +675,11 @@ function collectDigestData(agent_summary,most_applied,connection_health: computeConnectionHealth(vault, inbound, preferences, refs),- actions: refs.keep(- collectMaintenanceActions(vault, { onError: (e) => collectErrors.push(e) }),+ actions: scopedRefs.keep(+ collectMaintenanceActions(vault, {+ onError: (e) => collectErrors.push(e),+ visible: scopedRefs.visible,+ }),(action) => [action.target],),collect_errors: collectErrors,diff --git a/src/core/brain/distill/claim.ts b/src/core/brain/distill/claim.tsindex 4b374ea9..dcf95c77 100644--- a/src/core/brain/distill/claim.ts+++ b/src/core/brain/distill/claim.ts@@ -4,6 +4,16 @@* depend on it, and neither depends on the other for it.*/+/**+ * Frontmatter `kind:` marker of a distillation page. Defined here rather+ * than in `distill-source.ts` because the planted-rows audit reads it from+ * inside an import graph that must not run through the distill writer (the+ * writer's graph reaches page-lint, which reaches the doctor, which reads+ * the audit) - `distill-source.ts` re-exports it, so every existing+ * consumer is unchanged.+ */+export const BRAIN_DISTILLATION_KIND = "brain-distillation";+/** One atomic claim distilled from the source, with an optional block ref. */export interface DistillClaim {/** The atomic claim text. */diff --git a/src/core/brain/distill/distill-source.ts b/src/core/brain/distill/distill-source.tsindex 3af279f5..a9dc3838 100644--- a/src/core/brain/distill/distill-source.ts+++ b/src/core/brain/distill/distill-source.ts@@ -44,6 +44,17 @@* ({@link readSourceOrigin}, the byte-keeping form of `classifySourceOrigin`),* so a source this vault does not own commits in the quarantine lane the* retrieval trust gate can actually see.+ *+ * MARKDOWN NEUTRALIZATION (t_c2ac4fc8, review M4). The claim text is caller+ * text composed into the page verbatim - on the untrusted lane it is+ * third-party material the same way an untrusted summary's prose is. Under+ * the markdown-neutralization gate's enforce mode, an UNTRUSTED source's+ * claim text passes through the pure neutralizer at body assembly, after+ * the quote check (which must verify the spans the caller actually sent);+ * the writer's own block citation after the text is composed live. The+ * page stamps `neutralized_markers` with the families it escaped, on+ * change only. Off, shadow and the trusted lane write the claims+ * verbatim.*/import { existsSync, mkdirSync, readFileSync } from "node:fs";@@ -66,6 +77,7 @@ import {assertResponseShape,} from "../response-shape.ts";import {+ INTAKE_TRUST,sourceContentHashFrontmatter,untrustedSourceFrontmatter,type IntakeTrust,@@ -77,6 +89,13 @@ import {type Provenance,} from "../provenance/provenance.ts";import { isoSecond } from "../time.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE,+ neutralizeMarkdown,+ neutralizedMarkersFrontmatter,+ resolveMarkdownNeutralizeModeForProcess,+ type MarkdownStructureKind,+} from "../text/neutralize-markdown.ts";import {CAPTURE_SCOPE,EXCERPT_HASH_KEY,@@ -88,6 +107,7 @@ import {type CaptureScope,} from "../provenance/capture-scope.ts";import { BLOCK_ID_RE } from "./block-resolve.ts";+import { BRAIN_DISTILLATION_KIND } from "./claim.ts";import type { DistillClaim } from "./claim.ts";import { checkClaimQuotes, type QuoteEvidence } from "./quote-check.ts";import {@@ -98,8 +118,8 @@ import {type QuoteCheckReport,} from "./quote-verdict.ts";-/** Frontmatter `kind:` marker of a distillation page. */-export const BRAIN_DISTILLATION_KIND = "brain-distillation";+/** Frontmatter `kind:` marker of a distillation page (defined in the claim leaf). */+export { BRAIN_DISTILLATION_KIND };export type { DistillClaim } from "./claim.ts";@@ -302,6 +322,13 @@ export function distillSource(): DistillSourceResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);+ // The write-time markdown neutralization gate (t_c2ac4fc8, review M4),+ // resolved BEFORE ANY WRITE like every seam: a misconfigured mode is a+ // misconfiguration of the process, not a verdict about this source, and+ // refusing it after the page exists would half-apply the distillation.+ // Whether the gate has work to do is decided below (untrusted origin,+ // enforce only); resolving it here only moves the refusal earlier.+ const gate = resolveMarkdownNeutralizeModeForProcess();validate(input);// The SAME normaliser the trust classifier uses, so the identity this page@@ -351,10 +378,32 @@ export function distillSource(const createdAt = existed ? readCreatedAt(absPath, stamp) : stamp;const priorUpdatedAt = existed ? readUpdatedAt(absPath, stamp) : stamp;+ // Claim-text neutralization (t_c2ac4fc8, review M4): the claims are the+ // caller's text ABOUT the source, and an untrusted source makes them+ // third-party material - under enforce mode each claim's text passes+ // through the pure neutralizer before the bullets compose, so a planted+ // `[[wikilink]]` (or any other structure row) lands escaped while the+ // writer's own block citation after it composes live. The quote check+ // above already ran on the text the caller actually sent: verification+ // answers "does the source say this", which escaping would corrupt.+ // Off, shadow and the trusted lane leave every claim verbatim.+ let pageClaims = checked.claims;+ let neutralized: FrontmatterMap = {};+ if (origin.trust === INTAKE_TRUST.untrusted && gate === MARKDOWN_NEUTRALIZE_MODE.enforce) {+ const kinds = new Set<MarkdownStructureKind>();+ pageClaims = checked.claims.map((claim) => {+ const neutral = neutralizeMarkdown(claim.text);+ if (!neutral.changed) return claim;+ for (const kind of neutral.kinds) kinds.add(kind);+ return { ...claim, text: neutral.text };+ });+ neutralized = neutralizedMarkersFrontmatter([...kinds].toSorted());+ }+const claimsSection = ["## Claims","",- ...checked.claims.map((c) => renderClaim(c, canonicalSource)),+ ...pageClaims.map((c) => renderClaim(c, canonicalSource)),].join("\n");// The rendered section ends in a newline; the join supplies the separation.const excerptSection = excerpt !== undefined ? renderExcerptSection(excerpt).trimEnd() : "";@@ -382,6 +431,10 @@ export function distillSource(// rather than ranking it beside the operator's own notes. A trusted// source adds nothing, keeping its page byte-identical to before....untrustedSourceFrontmatter(origin.trust),+ // Names the structure families enforce-mode neutralization removed from+ // the claim text, ON CHANGE ONLY - the same conditional-spread shape as+ // the marker above, so an unchanged page gains zero bytes.+ ...neutralized,// How much of the source the page holds; nothing for a local file, so// its page stays byte-identical to before....captureScopeFrontmatter(capture.scope),diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.tsindex 54bbd7f5..23b83fd0 100644--- a/src/core/brain/doctor-exits.ts+++ b/src/core/brain/doctor-exits.ts@@ -157,6 +157,19 @@ const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = ["visibility line, so no one command resolves the class without deciding for pages nobody " +"reviewed",},+ {+ // The planted-structure-rows audit (t_c2ac4fc8). The rows are+ // third-party text already in the vault; un-planting them means+ // rewriting content nobody here authored, which the audit refuses to+ // do and no single command can do for an operator.+ code: "planted-structure-rows",+ reason:+ "the rows are third-party text already written into the vault, and un-planting them means " ++ "rewriting or re-capturing content nobody here authored; the audit is read-only by " ++ "contract, and the enforce-mode gate prevents the next write rather than repairing the " ++ "last one, so the exit is the operator's decision to re-capture specific pages or to run " ++ "a later repair pass",+ },{code: "stale-lock",reason:diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 4f39ef9f..89c50f3c 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -52,6 +52,7 @@ import { activeBudgetPressureCheck } from "./doctor/active-budget-check.ts";import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./doctor/check.ts";import { inboxArchivableCheck } from "./doctor/inbox-archive-check.ts";import { privacyMarkerCheck } from "./doctor/privacy-marker-check.ts";+import { plantedRowsCheck } from "./doctor/planted-rows-check.ts";import { capturePatternCheck, configCheck, vaultIgnoreCheck } from "./doctor/config-checks.ts";import { entityRegistryCheck } from "./doctor/entity-checks.ts";import { brokenBacklinkCheck } from "./doctor/link-checks.ts";@@ -92,6 +93,7 @@ import { removedToolReferenceCheck } from "./doctor/removed-tool-checks.ts";import { makeStaleDependencyCheck } from "./doctor/stale-dependency-check.ts";import { auditStaleDependencies } from "./stale-dependency.ts";import { frozenVaultCheck } from "./doctor/frozen-check.ts";+import { gitTrackedStateCheck } from "./doctor/git-tracked-state-check.ts";import { secretsSyncExposureCheck } from "./doctor/secrets-sync-check.ts";import { logChainCheck } from "./doctor/log-chain-check.ts";import { checkSemanticHealth } from "./doctor/semantic-health-check.ts";@@ -213,8 +215,15 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([syncConflictLogCheck,frozenVaultCheck,secretsSyncExposureCheck,+ // The git-side twin of the sync-exposure check above: derived state+ // the vault scope ignores but git still carries (t_206562ae).+ gitTrackedStateCheck,inboxArchivableCheck,privacyMarkerCheck,+ // The write-time twin of the privacy-marker count: third-party text+ // that planted live structure (t_c2ac4fc8), audited with the same+ // grammar the neutralizer escapes with.+ plantedRowsCheck,logChainCheck,symlinkEscapeCheck,frontmatterUncertaintyProbe,diff --git a/src/core/brain/doctor/git-tracked-state-check.ts b/src/core/brain/doctor/git-tracked-state-check.tsnew file mode 100644index 00000000..6502ab21--- /dev/null+++ b/src/core/brain/doctor/git-tracked-state-check.ts@@ -0,0 +1,206 @@+/**+ * The doctor's git tracked-state row (t_206562ae, task B3).+ *+ * The gitignore guard seeded at brain init keeps derived runtime state+ * out of git FROM now on, but an operator who ran an earlier init (or+ * added the store by hand before the guard existed) may already have+ * committed it. Tracking is the one condition a `.gitignore` line cannot+ * repair, so it is measured directly and graded error.+ *+ * Two git facts, two commands, never `git status`:+ *+ * - TRACKING is measured with `git ls-files -z -- .open-second-brain`,+ * run vault-bounded. In a linked worktree `git status` omits ignored+ * files, so only ls-files answers "is this in the index" - the same+ * discipline `vault-dirty.ts` documents for its own gate.+ * - IGNORING is measured with `git check-ignore -q` exit discipline:+ * 0 = ignored, 1 = not ignored, any other exit (or a git that cannot+ * run at all) is a refusal to say, and the row stays silent.+ *+ * Fail-soft throughout: a vault that is not a worktree, a vault whose+ * store directory is absent, and a git that cannot answer are all+ * silence - the doctor never throws on the state of the operator's+ * VCS, and never edits anything. Findings:+ *+ * - any tracked path under the store → severity error, naming ONE+ * location-independent untrack command (`git -C '<vault>' rm -r+ * --cached -- .open-second-brain`, single-quoted) plus the exact+ * missing ignore line; the tracked paths are listed as capped+ * evidence, the remainder counted;+ * - present, untracked, unignored → severity warning, the only signal+ * a vault whose init ran before the guard (or without git) gets.+ *+ * The code resolves through `DIAGNOSTIC_SIGNALS` to `o2b brain init`:+ * the seeder is idempotent and merge-safe, so the ignore half of the+ * remediation is one command (the untracking is git's, named in the+ * finding because no verb performs it).+ */++import { execFileSync } from "node:child_process";+import { existsSync } from "node:fs";+import { join, resolve } from "node:path";++import { DERIVED_STORE_DIR } from "../path-constants.ts";+// The exact ignore line is the seeder's own constant, re-exported here+// for this module's test consumers: a remediation message that says+// "add the exact line" must quote the line the guard actually writes,+// not a second composition of it.+import { GITIGNORE_GUARD_IGNORE_LINE } from "../gitignore-guard.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";++/** Derived brain state git is already carrying. */+export const GIT_TRACKED_DERIVED_STATE_CODE = "git-tracked-derived-state";++/** How many tracked paths one finding names before it counts the rest. */+const NAMED_PATH_LIMIT = 5;++export { GITIGNORE_GUARD_IGNORE_LINE };++/** Git listings are bounded like every git read in the tree. */+const MAX_GIT_OUTPUT = 64 * 1024 * 1024;++/** The derived-store pathspec every listing is bounded by. */+const STORE_PATHSPEC = DERIVED_STORE_DIR;++/** True when `vault` sits inside a git worktree; false when git cannot say. */+function isInsideWorktree(vault: string): boolean {+ try {+ const inside = execFileSync("git", ["-C", vault, "rev-parse", "--is-inside-work-tree"], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ maxBuffer: MAX_GIT_OUTPUT,+ }).trim();+ return inside === "true";+ } catch {+ return false;+ }+}++/**+ * Every path under the derived store git carries in its index,+ * vault-relative with git's own forward slashes. `null` when git cannot+ * answer - which is silence here, never a guess.+ */+function trackedStorePaths(vault: string): ReadonlyArray<string> | null {+ try {+ const out = execFileSync("git", ["-C", vault, "ls-files", "-z", "--", STORE_PATHSPEC], {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "ignore"],+ maxBuffer: MAX_GIT_OUTPUT,+ });+ return out.split("\0").filter((p) => p.length > 0);+ } catch {+ return null;+ }+}++/**+ * `check-ignore -q` exit discipline (the `vault-dirty.ts` posture):+ * 0 = ignored, 1 = not ignored, anything else = refuse to say (`null`).+ */+function isIgnored(vault: string, path: string): boolean | null {+ try {+ execFileSync("git", ["-C", vault, "check-ignore", "-q", "--", path], {+ stdio: ["ignore", "ignore", "ignore"],+ });+ return true;+ } catch (err) {+ const status = (err as NodeJS.ErrnoException & { status?: number | null }).status;+ return status === 1 ? false : null;+ }+}++/** What git can measure about the derived store's git state. */+export interface DerivedStoreGitState {+ /** Store paths in the git index, vault-relative. */+ readonly tracked: ReadonlyArray<string>;+ /** Whether the store directory is covered by an ignore rule. */+ readonly ignored: boolean;+}++/**+ * Measure the store's git state, or `null` when the row must stay+ * silent: store directory absent, not a worktree, or a git that cannot+ * answer any of its questions.+ */+export function probeDerivedStoreGitState(vault: string): DerivedStoreGitState | null {+ if (!existsSync(join(vault, DERIVED_STORE_DIR))) return null;+ if (!isInsideWorktree(vault)) return null;+ const tracked = trackedStorePaths(vault);+ if (tracked === null) return null;+ const ignored = isIgnored(vault, STORE_PATHSPEC);+ if (ignored === null) return null;+ return { tracked, ignored };+}++/**+ * `value` wrapped in single quotes with embedded single quotes escaped+ * the shell-standard way (close, escaped quote, reopen): the command is+ * pasted verbatim, and double quotes would leave `$`, backticks and `\`+ * live in the vault path.+ */+function shellSingleQuoted(value: string): string {+ return `'${value.replaceAll("'", `'\\''`)}'`;+}++function trackedMessage(vault: string, tracked: ReadonlyArray<string>): string {+ // ONE complete, location-independent command: `rm -r` on the store+ // directory covers every tracked path (a real store tracks+ // brain.sqlite with -wal and -shm, audit shards and ledgers - far past+ // any per-path cap), and `-C <vault>` makes it runnable from any+ // directory, a parent repository's root included - vault-relative+ // pathspecs fatal there. Single-quoted, so the paste is inert. The+ // tracked paths below are EVIDENCE ONLY: quoted for readability, capped+ // with the remainder counted, never hidden.+ const command = `git -C ${shellSingleQuoted(resolve(vault))} rm -r --cached -- ${DERIVED_STORE_DIR}`;+ const evidence = tracked.slice(0, NAMED_PATH_LIMIT).map((p) => `"${p}"`);+ const remainder = tracked.length - evidence.length;+ return (+ `${tracked.length} path(s) under ${DERIVED_STORE_DIR}/ are tracked by git: derived runtime ` ++ "state (search database, checkpoints, ledgers, locks, secrets ciphertext) is in history and " ++ `every commit carries its churn. Untrack with ${command} (runnable from any directory)` ++ `${evidence.length > 0 ? `; the tracked paths: ${evidence.join(", ")}` : ""}` ++ `${remainder > 0 ? `, and ${remainder} more` : ""}; add the exact line ` ++ `${GITIGNORE_GUARD_IGNORE_LINE} to .gitignore at the vault root (o2b brain init seeds it ` ++ "idempotently); this check never edits anything"+ );+}++function unignoredMessage(): string {+ return (+ `the derived store ${DERIVED_STORE_DIR}/ is present but not git-ignored: the next ` ++ `\`git add -A\` commits the search database, checkpoints, ledgers and secrets ciphertext. ` ++ `Add the exact line ${GITIGNORE_GUARD_IGNORE_LINE} to .gitignore at the vault root ` ++ "(o2b brain init seeds it idempotently)"+ );+}++/** The git tracked-state row: fail-soft, read-only, silent when it cannot know. */+export const gitTrackedStateCheck: DoctorCheck = {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ const state = probeDerivedStoreGitState(ctx.vault);+ if (state === null) return;++ // Tracking dominates: an ignore line beside tracked paths changes+ // nothing about the history already committed.+ if (state.tracked.length > 0) {+ out.issues.push({+ severity: "error",+ code: GIT_TRACKED_DERIVED_STATE_CODE,+ path: ctx.vault,+ message: trackedMessage(ctx.vault, state.tracked),+ } satisfies DoctorIssue);+ return;+ }+ if (!state.ignored) {+ out.issues.push({+ severity: "warning",+ code: GIT_TRACKED_DERIVED_STATE_CODE,+ path: ctx.vault,+ message: unignoredMessage(),+ } satisfies DoctorIssue);+ }+ },+};diff --git a/src/core/brain/doctor/planted-rows-check.ts b/src/core/brain/doctor/planted-rows-check.tsnew file mode 100644index 00000000..af1f8fcb--- /dev/null+++ b/src/core/brain/doctor/planted-rows-check.ts@@ -0,0 +1,134 @@+/**+ * Planted structure rows in Brain pages (lane A,+ * trust-and-responsiveness-hardening, t_c2ac4fc8).+ *+ * The write-time neutralizer (`text/neutralize-markdown.ts`) keeps+ * caller text from planting wikilinks, `@osb` markers, ```osb fences and+ * ATX headings - under enforce mode, on the two seams it guards. It says+ * nothing about the vault's history or about the seams it does not+ * guard: every page captured or ingested before the gate existed, while+ * it is off, or written by a seam the gate does not cover (the+ * note-write tools), can carry rows the link graph, the marker scanners+ * and the section parsers treat as the vault's own structure. This check+ * is that audit: ONE warning carrying the count and the paths, silent+ * when there are none, read-only by contract.+ *+ * The population and the scan are the planner's+ * ({@link planPlantedRows}): the marker and osb-fence families scan+ * every readable page under `Brain/` (no Brain writer emits a live+ * marker line or osb fence, so one anywhere is planted), while the+ * wikilink and heading families stay keyed to the third-party+ * provenance lanes, whose structure the Brain's own writers render by+ * design elsewhere. On both populations the sections those writers+ * themselves render - a capture's marker-authorized `## Guidance`, a+ * source summary's `## Sources`/`## Premises`/link and derivation+ * sections, a quarantined entity page's writer H1 and provenance+ * citation, a distillation page's `## Claims`/`## Excerpt`/`## Sources`+ * sections - are excluded as the vault's own output, never reported.+ * The lane classification stays in the finding as+ * context: those pages are named first, and the message counts them. A+ * page the caller may not read is not named and does not move the count+ * (`ctx.readable`, the contract every other counting check follows), and+ * the same predicate rides into the planner so its staged-vs-published+ * dedupe can never drop a staged copy in favor of a twin this filter+ * would remove - that would leave the report with neither copy.+ *+ * Under the gate's `shadow` mode the finding says so, and says exactly+ * what enforce would and would not do: the guarded write seams (the+ * capture, the untrusted ingest's summary prose and entity names, the+ * untrusted distillation's claim text) would escape the rows they+ * rewrite on the next write of the same text, while the rows no guarded+ * seam rewrites leave only by a later repair pass - the honest preview+ * an operator needs before turning the mode on.+ */++import { planPlantedRows } from "../planted-rows.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE,+ resolveMarkdownNeutralizeModeForProcess,+ type MarkdownNeutralizeMode,+} from "../text/neutralize-markdown.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";++/** Pages carrying live structure-bearing markdown in third-party bodies. */+export const PLANTED_STRUCTURE_ROWS_CODE = "planted-structure-rows";++/** How many paths one finding names before it counts the rest. */+const NAMED_PATH_LIMIT = 5;++/**+ * The gate posture the finding's wording reflects. A misconfigured mode+ * value is refused loudly at every write seam; here it degrades to the+ * neutral wording rather than throwing - the doctor never throws.+ */+function gateModeForWording(): MarkdownNeutralizeMode {+ try {+ return resolveMarkdownNeutralizeModeForProcess();+ } catch {+ return MARKDOWN_NEUTRALIZE_MODE.off;+ }+}++export const plantedRowsCheck: DoctorCheck = {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ // The readability predicate rides into the planner: the staged-vs-+ // published dedupe must not drop a staged copy in favor of a+ // hash-equal twin this filter would remove, or both rows would+ // vanish from the report.+ const plan = planPlantedRows(ctx.vault, ctx.readable);+ const readable =+ ctx.readable === undefined ? plan.planted : plan.planted.filter((p) => ctx.readable!(p.path));+ if (readable.length === 0) return;++ // The third-party provenance lanes are named first: same rows, but+ // not equally expected, and the operator reads the paths top-down.+ const ordered = [...readable].toSorted((a, b) => {+ if (a.thirdParty !== b.thirdParty) return a.thirdParty ? -1 : 1;+ return a.path < b.path ? -1 : a.path > b.path ? 1 : 0;+ });+ const rows = readable.reduce((sum, page) => sum + page.count, 0);+ const named = ordered.slice(0, NAMED_PATH_LIMIT).map((page) => page.path);+ const remainderCount = readable.length - named.length;+ const remainder = remainderCount > 0 ? ` and ${remainderCount} more` : "";+ const laneCount = readable.reduce((n, page) => n + (page.thirdParty ? 1 : 0), 0);+ const laneClause =+ laneCount > 0+ ? `; ${laneCount} of the page(s) sit in the third-party lanes (brain-capture captures, ` ++ "brain-source summaries, untrusted-stamped pages, quarantined entities) and are named first"+ : "";+ const shadow =+ gateModeForWording() === MARKDOWN_NEUTRALIZE_MODE.shadow+ ? " The markdown neutralization gate is in shadow mode: switching it to enforce would " ++ "escape the rows a guarded write seam rewrites - the next capture, untrusted ingest " ++ "(summary prose and entity names) or untrusted distillation (claim text) - while " ++ "rows no guarded seam rewrites leave only by a later repair pass."+ : "";+ out.issues.push({+ severity: "warning",+ code: PLANTED_STRUCTURE_ROWS_CODE,+ path: ctx.vault,+ message:+ `${rows} live structure row(s) across ${readable.length} Brain page(s) ` ++ "(planted wikilinks, @osb markers, osb fences, ATX headings): " ++ `${named.join(", ")}${remainder}. The population splits by family: the marker and ` ++ "osb-fence families are scanned on every readable page under Brain/ - no Brain " ++ "writer emits a live marker line or an osb fence, so one anywhere in the derived " ++ "layer is planted - while the wikilink and heading families are scanned only on " ++ "the third-party provenance lanes, where caller text lands. On both populations " ++ "the sections the Brain writers themselves render are excluded, not reported: a " ++ "capture's marker-authorized ## Guidance section and a source summary's " ++ "## Sources, ## Premises, ## Entities and ## Connections to existing notes " ++ "citation sections, plus its ## Parts and ## Table derivation headings, are this " ++ "vault's own output - and so are a quarantined entity page's writer H1 and " ++ "provenance citation and a distillation page's ## Claims, ## Excerpt and ## " ++ "Sources sections" ++ laneClause ++ ". Nothing was changed by this check; rows a guarded write seam rewrites leave " ++ "by re-writing their text with the markdown neutralization gate in enforce " ++ "mode, and every row leaves by a later repair pass" ++ shadow,+ } satisfies DoctorIssue);+ },+};diff --git a/src/core/brain/doctor/removed-tool-checks.ts b/src/core/brain/doctor/removed-tool-checks.tsindex 9a56b011..79a37e3b 100644--- a/src/core/brain/doctor/removed-tool-checks.ts+++ b/src/core/brain/doctor/removed-tool-checks.ts@@ -39,7 +39,20 @@ const REMOVED_TOOL_MAX_WARNINGS = 50;/** Subsystem name the scan reports an unreadable path under. */const REMOVED_TOOL_SITE = "brain.doctor.removedToolReference";-/** Root instruction files the scan reads beside the Brain tree. */+/**+ * Root instruction files the sweep reads beside the Brain tree. An+ * EXISTENCE-loop scan list, not a precedence order (t_00b617b6 sweep):+ * each existing file is read once for removed-tool references, in this+ * order, for reporting only. `GEMINI.md` is absent here while the+ * instruction-file ceiling (`TRACKED_FILES`,+ * `src/core/brain/trust/instruction-file-ceiling.ts`) and the write-back+ * contract audit (`AGENT_INSTRUCTION_FILES`,+ * `src/core/brain/writeback-contract.ts`) both include it - whether the+ * omission is deliberate is an open question recorded here, never+ * answered by a silent unification. Which file an operative host actually+ * reads is a different question again, answered by+ * `HOST_INSTRUCTION_PRECEDENCE` in writeback-contract.ts, not by this list.+ */const ROOT_INSTRUCTION_FILES: ReadonlyArray<string> = Object.freeze(["CLAUDE.md", "AGENTS.md"]);/**diff --git a/src/core/brain/gitignore-guard.ts b/src/core/brain/gitignore-guard.tsnew file mode 100644index 00000000..ee22a5c6--- /dev/null+++ b/src/core/brain/gitignore-guard.ts@@ -0,0 +1,291 @@+/**+ * The `.gitignore` guard seeder (t_206562ae): one managed block in the+ * vault's `.gitignore` covering the derived store.+ *+ * `<vault>/.open-second-brain/` holds every piece of derived runtime+ * state this tool keeps for itself - brain.sqlite, the hook audit, the+ * secrets store, the maintenance lease and journals, the ingest+ * checkpoints, dead letters, the session ledgers, the watchdog fallback,+ * the self-heal state, the lockfiles and the bench runs. The vault scope+ * already excludes the directory (`DEFAULT_VAULT_IGNORE_PATHS`), but+ * nothing told git, so a fresh `o2b brain init` in a repository left+ * `brain.sqlite` visible to `git status`. This module seeds the git-side+ * guard: a managed block whose entry list starts as exactly one+ * vault-root-anchored line, `/.open-second-brain/`.+ *+ * Behaviour:+ *+ * - No `.gitignore` → one is created containing only the block.+ * - An existing file keeps every byte of its user content and gains+ * the block appended with one separating blank line (the+ * `insertManagedBlock` merge). A conforming block already present is+ * MERGED, never clobbered: its own entries survive and only the+ * missing guard entries are added. The MERGED content is re-checked+ * for a negation after the entry before anything is written, because+ * a merge that lands the entry inside an earlier block does not move+ * it past a later `!.open-second-brain` - and a hit refuses the+ * write like every other conflict.+ * - Exact-line membership is checked first, so a user who already+ * ignores the path - inside the block or beside it - yields a skip,+ * not a duplicate. The skip is only clean while no LATER line+ * negates the entry: git evaluates patterns in order and the last+ * match wins, so `!.open-second-brain` after the entry leaves the+ * store visible, and that surfaces as the same named conflict a+ * malformed block gets.+ * - A second run is a no-op: byte-equal file, `skipped`.+ * - Markers present but malformed (unpaired, doubled, inverted) surface+ * as a named conflict with warn-and-continue: nothing is written,+ * and the doctor's git tracked-state row reports the still-unprotected+ * state. Surgery on a block a human or another tool mangled is not a+ * decision for a seeder to make.+ * - A `.gitignore` that is itself a symbolic link - live or dangling -+ * is the same named conflict: every write this seeder makes is an+ * atomic rename over the path, which would silently replace the+ * operator's link with a regular file. The refusal names the link+ * target, writes nothing, and the doctor row reports the+ * still-unprotected store.+ * - CRLF files keep their line endings, inside the block too (the+ * managed-block editor detects and restores them).+ * - No git subprocess is ever spawned: git is asked only by the+ * doctor's `git-tracked-state` probe, which measures what actually+ * happened on disk.+ */++import { existsSync, lstatSync, readFileSync, readlinkSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import {+ DEFAULT_BEGIN_MARKER,+ DEFAULT_END_MARKER,+ extractManagedBlock,+ hasManagedBlock,+ insertManagedBlock,+ ManagedBlockError,+} from "../install/managed-block.ts";+import { DERIVED_STORE_DIR } from "./path-constants.ts";++/** Vault-relative name of the file this guard seeds. */+export const GITIGNORE_GUARD_FILE = ".gitignore";++/**+ * The identity of this guard's block, named in warnings and doctor+ * messages so an operator can tell which managed block a finding is+ * about. The markers themselves are the shared `install/managed-block.ts`+ * defaults - the same convention `o2b brain protect` uses - so every+ * block this tree writes parses with the one editor.+ */+export const GITIGNORE_GUARD_BLOCK_ID = "derived-brain-state";++/**+ * The seeded entry list: starts as exactly one vault-root-anchored+ * pattern. Anchored at the vault root (`/.open-second-brain/`, with+ * trailing slash) so a vault nested inside a larger repository ignores+ * its own store and not a sibling's, and one entry covers every Tier A+ * writer. The source-reading census in+ * `tests/core/brain/gitignore-guard.test.ts` pins the list and the+ * population it covers.+ */+export const GITIGNORE_GUARD_ENTRIES: ReadonlyArray<string> = Object.freeze([+ `/${DERIVED_STORE_DIR}/`,+]);++/**+ * The exact `.gitignore` line the seeded block carries: the entry list+ * joined, so a remediation message that names "the exact line" quotes+ * the same constant the seeder writes and the two cannot drift. The+ * census in `tests/core/brain/gitignore-guard.test.ts` pins the list at+ * exactly one entry, so the joined form IS one line.+ */+export const GITIGNORE_GUARD_IGNORE_LINE = GITIGNORE_GUARD_ENTRIES.join("\n");++/** What one seeding pass did to `<vault>/.gitignore`. */+export type GitignoreGuardStatus =+ | "created" // the file did not exist and was written with only the block+ | "updated" // an existing file gained the block (or the block gained entries)+ | "skipped" // every entry already present as an exact line; no bytes moved+ | "conflict"; // malformed markers, a later line negates the entry, or the file is a symlink; nothing written, warning emitted++export interface GitignoreGuardResult {+ readonly status: GitignoreGuardStatus;+ /** Vault-relative name of the file, always {@link GITIGNORE_GUARD_FILE}. */+ readonly file: string;+ /** The named conflict detail, present only when status is "conflict". */+ readonly detail?: string;+}++/** The exact block body for `entries`: markers around one entry per line. */+function blockBody(entries: ReadonlyArray<string>): string {+ return `${DEFAULT_BEGIN_MARKER}\n${entries.join("\n")}\n${DEFAULT_END_MARKER}\n`;+}++/**+ * A line that re-includes the derived store. Built from the directory+ * constant so the guard and its negation cannot drift apart, and+ * matched over the git-valid spellings of the negation:+ *+ * - `!.open-second-brain` and `!/.open-second-brain`, with or without+ * git's optional trailing slash;+ * - unescaped trailing whitespace, which git strips from a pattern+ * (only a backslash-escaped space is significant);+ * - the double-star-slash prefix, which matches zero or more+ * directories and so covers the vault root too.+ *+ * Everything else - escaped-dot spellings, character-class tricks - is+ * deliberately out of scope: the doctor's git-tracked-state row measures+ * what git actually did and is the authority for any spelling this+ * matcher cannot name.+ */+const NEGATED_ENTRY_RE = new RegExp(+ `^!(?:/?|\\*\\*/)${DERIVED_STORE_DIR.replaceAll(".", "\\.")}/?[ \\t]*$`,+);++/**+ * The first line after the LAST guard entry that negates it, or null.+ * git evaluates .gitignore patterns in order and the last match wins, so+ * only a negation AFTER the entry re-opens the store - one before it is+ * overridden and harmless.+ */+function negationAfterEntry(lines: ReadonlyArray<string>): string | null {+ let lastEntry = -1;+ for (let i = 0; i < lines.length; i += 1) {+ if (GITIGNORE_GUARD_ENTRIES.includes(lines[i]!)) lastEntry = i;+ }+ for (let i = lastEntry + 1; i < lines.length; i += 1) {+ if (NEGATED_ENTRY_RE.test(lines[i]!)) return lines[i]!;+ }+ return null;+}++/**+ * Seed the guard block into `<vault>/.gitignore`, merging with whatever+ * is already there. Idempotent and best-effort in the conflict case; the+ * only throws are genuine I/O errors reading or writing the file.+ */+export function ensureVaultGitignoreEntries(vault: string): GitignoreGuardResult {+ const file = join(vault, GITIGNORE_GUARD_FILE);++ // A symlinked .gitignore is refused, never written through or over:+ // every write below lands an atomic rename on `file`, and rename(2)+ // swaps the LINK itself for a regular file - an operator who manages+ // the vault .gitignore as a link into their dotfiles (or a shared+ // file) would lose the link with a clean `updated` (or, through the+ // created branch, a dangling link with `created`) reported as if+ // nothing happened. lstat does not follow the link, so it sees the+ // link itself in both the live and the dangling case, before either+ // branch; the doctor's git tracked-state row then reports the still-+ // unprotected store, the same as every other conflict.+ let linkTarget: string | null = null;+ try {+ if (lstatSync(file).isSymbolicLink()) linkTarget = readlinkSync(file);+ } catch {+ // No path at all (ENOENT and friends): the created branch below+ // owns that case. A stat here is not a read of protected bytes.+ }+ if (linkTarget !== null) return symlinkConflict(linkTarget, file);++ if (!existsSync(file)) {+ atomicWriteFileSync(file, blockBody(GITIGNORE_GUARD_ENTRIES));+ return { status: "created", file: GITIGNORE_GUARD_FILE };+ }++ const current = readFileSync(file, "utf8");++ // Exact-line membership first, over the CRLF-normalized whole file: a+ // user who already ignores the path anywhere in it gets a skip, never+ // a second (redundant) line.+ const lines = current.replace(/\r\n/g, "\n").split("\n");+ const present = new Set(lines);+ const missing = GITIGNORE_GUARD_ENTRIES.filter((entry) => !present.has(entry));+ if (missing.length === 0) {+ // The entry being present is not the whole story: git takes the LAST+ // matching pattern, so a later `!.open-second-brain` re-includes the+ // store and a clean skip here would be optimistic - the doctor's+ // tracked-state row would catch it, but the init report should not+ // wait to be corrected. Surface the same named conflict the+ // malformed-marker case gets; write nothing either way.+ const negation = negationAfterEntry(lines);+ if (negation !== null) {+ return conflict(`the guard entry is negated by the later line ${negation} `, file);+ }+ return { status: "skipped", file: GITIGNORE_GUARD_FILE };+ }++ try {+ // Merge, never clobber: a conforming block's own entries survive and+ // only the missing guard entries are added to it. Entries the user+ // already wrote elsewhere in the file are not duplicated into it. An+ // empty existing block contributes no lines - the empty string splits+ // to [""], which would open the merged block with a stray blank line.+ const blockEntries = hasManagedBlock(current) ? blockEntryLines(current) : [];+ const next = insertManagedBlock(current, [...blockEntries, ...missing].join("\n"));+ if (next === current) {+ return { status: "skipped", file: GITIGNORE_GUARD_FILE };+ }+ // The merge moving the entry INSIDE the block does not move it after+ // the file's other patterns: a negation later in the file still wins+ // under git's last-match rule, so a clean `updated` here could seed+ // an entry that protects nothing. The merged content is asked the+ // same question the exact-line skip asks, and a hit refuses the+ // write - the seeder's one conflict convention is warn-and-continue+ // with the file byte-identical, and this case keeps it.+ const negation = negationAfterEntry(next.replace(/\r\n/g, "\n").split("\n"));+ if (negation !== null) {+ return conflict(+ `the merged block would still be negated by the later line ${negation} `,+ file,+ );+ }+ atomicWriteFileSync(file, next);+ return { status: "updated", file: GITIGNORE_GUARD_FILE };+ } catch (err) {+ if (!(err instanceof ManagedBlockError)) throw err;+ const detail = err.message;+ process.stderr.write(+ `warning: could not seed the ${GITIGNORE_GUARD_BLOCK_ID} .gitignore block ` ++ `(derived brain state stays visible to git): ${file}: ${detail}\n`,+ );+ return { status: "conflict", file: GITIGNORE_GUARD_FILE, detail };+ }+}++/** The existing block's entry lines, [] for a block that holds none. */+function blockEntryLines(current: string): ReadonlyArray<string> {+ const body = extractManagedBlock(current) ?? "";+ return body.length === 0 ? [] : body.split("\n");+}++/**+ * Report the named negation conflict: warn on stderr, write nothing.+ * The one conflict convention this seeder has - malformed markers behave+ * the same way - and the init report's `guard.status` carries it to+ * machine readers while the doctor's tracked-state row reports the+ * still-unprotected store.+ */+function conflict(detail: string, file: string): GitignoreGuardResult {+ process.stderr.write(+ `warning: the ${GITIGNORE_GUARD_BLOCK_ID} .gitignore guard is negated ` ++ `(derived brain state stays visible to git): ${file}: ${detail}` ++ "(git last-match-wins: the derived store stays visible to git)\n",+ );+ return { status: "conflict", file: GITIGNORE_GUARD_FILE, detail };+}++/**+ * Report a symlinked `.gitignore`: warn on stderr, write nothing. Same+ * conflict convention as {@link conflict} - `status: "conflict"` with a+ * detail naming the link target - because the store stays unprotected+ * either way; only the reason differs. The warning mirrors the+ * malformed-marker wording ("could not seed"), since seeding is exactly+ * what did not happen.+ */+function symlinkConflict(target: string, file: string): GitignoreGuardResult {+ const detail =+ `the file is a symbolic link to ${target} - seeding would replace the link ` ++ "with a regular file, so nothing was written";+ process.stderr.write(+ `warning: could not seed the ${GITIGNORE_GUARD_BLOCK_ID} .gitignore block ` ++ `(derived brain state stays visible to git): ${file}: ${detail}\n`,+ );+ return { status: "conflict", file: GITIGNORE_GUARD_FILE, detail };+}diff --git a/src/core/brain/ingest/ingest.ts b/src/core/brain/ingest/ingest.tsindex 0a55c8e1..7378af4a 100644--- a/src/core/brain/ingest/ingest.ts+++ b/src/core/brain/ingest/ingest.ts@@ -110,6 +110,12 @@ import {stageForReview,} from "../pending/pending-lanes.ts";import type { WriteSubject } from "../write-disposition.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE,+ neutralizeMarkdown,+ neutralizedMarkersFrontmatter,+ resolveMarkdownNeutralizeModeForProcess,+} from "../text/neutralize-markdown.ts";/** Frontmatter `kind:` marker of an ingested source summary page. */export const BRAIN_SOURCE_KIND = "brain-source";@@ -341,6 +347,16 @@ export function ingestSource(// the one an absent page gets: its path is deterministic, so `created`// would otherwise tell the caller the page exists.const summaryPath = canonicalNotePath(relative(vault, absPath));+ // Write-time marker neutralization gate (t_c2ac4fc8), resolved beside the+ // disposition and BEFORE ANY FILESYSTEM EFFECT - the capture seam's+ // contract. A misconfigured mode is a misconfiguration of the process,+ // not a verdict about this source: refusing it after the intake has+ // written entity pages or the trusted archive has persisted its bytes+ // would half-apply an ingest, and it would do so on the TRUSTED lane+ // too, which never uses the gate at all. Whether the gate has work to do+ // is decided at the summary write below (untrusted summaries, enforce+ // only); resolving it here only moves the refusal earlier.+ const gate = resolveMarkdownNeutralizeModeForProcess();// Review disposition (write-side trust, Tasks 9 and 12), resolved BEFORE// the intake so a refusal lands before ANY write - no entity page, no// manifest row, no summary page. With no permissions document the ingest@@ -398,6 +414,32 @@ export function ingestSource(? readKeptFrontmatter(absPath, stamp): { createdAt: stamp };+ // Write-time marker neutralization (t_c2ac4fc8), keyed off PROVENANCE:+ // the summary prose about an untrusted source is the one caller-authored+ // half of this page, so under enforce mode it passes through the pure+ // neutralizer ONCE here - before either consumer of the page bytes runs+ // - so the Brain/pending staged copy and the published page carry the+ // same escaped bytes. Every section appended below is vault-authored+ // (the provenance and link sections, the derivation section) and never+ // passes through the neutralizer. Off and shadow leave the summary+ // byte-identical: shadow's preview is the doctor's planted-rows audit,+ // which recomputes the would-be rows from the vault's bytes on its own,+ // so a shadow-mode seam has nothing to run. The gate itself was resolved+ // at the top of this function, before any write: only the DECISION lives+ // here.+ const summaryText = input.summary.trim();+ let storedSummary = summaryText;+ let neutralized: FrontmatterMap = {};+ if (trust === INTAKE_TRUST.untrusted) {+ if (gate === MARKDOWN_NEUTRALIZE_MODE.enforce) {+ const neutralSummary = neutralizeMarkdown(summaryText);+ if (neutralSummary.changed) {+ storedSummary = neutralSummary.text;+ neutralized = neutralizedMarkersFrontmatter(neutralSummary.kinds);+ }+ }+ }+const meta: FrontmatterMap = {kind: BRAIN_SOURCE_KIND,source_path: canonicalSource,@@ -408,6 +450,10 @@ export function ingestSource(// reason rather than ranking it beside the operator's own notes. Trusted// sources add nothing, keeping their page byte-identical to before....untrustedSourceFrontmatter(trust),+ // Names the structure families enforce-mode neutralization removed from+ // the summary, ON CHANGE ONLY - the same conditional-spread shape as the+ // marker above, so an unchanged page gains zero bytes.+ ...neutralized,// Says how much of the source was captured when it is less than the// whole file; a full-local source adds nothing, for the same reason....captureScopeFrontmatter(captureScope),@@ -447,7 +493,7 @@ export function ingestSource(};const body = [- input.summary.trim(),+ storedSummary,renderProvenanceSection(provenance),renderLinkSection("Entities", allEntities),renderLinkSection("Connections to existing notes", connections),diff --git a/src/core/brain/init.ts b/src/core/brain/init.tsindex 4333748f..d6b10d12 100644--- a/src/core/brain/init.ts+++ b/src/core/brain/init.ts@@ -11,6 +11,13 @@* - `Brain/_brain.yaml` and `Brain/_BRAIN.md` are written on first* run; subsequent runs without `force` skip them. `force: true`* overwrites both.+ * - `<vault>/.gitignore` gains the derived-state guard block+ * (`/.open-second-brain/`) on first run, merged with any existing+ * content; later runs skip it when the entries are already present.+ * The guard is hygiene, not load-bearing: a conflict (malformed+ * managed-block markers, a later negating line) or a guard file that+ * cannot be read or written is warned about on stderr and carried in+ * the result's `guard` field while the bootstrap continues.* - Bootstrap refuses to run if the machine-level plugin config (the* one `o2b init` writes) is missing, since callers must register* the vault before any Brain operation. The error message names@@ -26,6 +33,11 @@ import { fileURLToPath } from "node:url";import { defaultConfigPath } from "../config.ts";import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";+import {+ ensureVaultGitignoreEntries,+ GITIGNORE_GUARD_FILE,+ type GitignoreGuardStatus,+} from "./gitignore-guard.ts";import {BRAIN_BASES_REL,BRAIN_ROOT_REL,@@ -299,6 +311,15 @@ export interface BootstrapBrainOptions {readonly starterPath?: string;}+/**+ * How the step 1c `.gitignore` guard seeding concluded. The four seeder+ * statuses, plus `failed` for the case the seeder cannot report itself:+ * the guard file could not be read or written at all (a chmod-denied or+ * mandatory-locked `.gitignore`, a `.gitignore` that is a directory, a+ * rename the platform refused).+ */+export type BrainInitGuardStatus = GitignoreGuardStatus | "failed";+export interface BootstrapBrainResult {/** Vault-relative paths newly written. */readonly created: ReadonlyArray<string>;@@ -306,6 +327,24 @@ export interface BootstrapBrainResult {readonly overwritten: ReadonlyArray<string>;/** Vault-relative paths left untouched because they already existed. */readonly skipped: ReadonlyArray<string>;+ /**+ * How step 1c — the `<vault>/.gitignore` derived-state guard — ended.+ * Always set on a returned result. `created`, `updated` and `skipped`+ * are the clean outcomes; `conflict` (malformed managed-block markers,+ * or a line negating the guard entry, whether the entry was already+ * present or would have landed in a merged block) and `failed` (the+ * file could not be read or written) mark a guard the operator must+ * look at, carry a `detail`, and come with a named warning on stderr.+ * Bootstrap CONTINUES in both cases — the guard is hygiene the+ * doctor's git-tracked-state row reports independently — and machine+ * readers use this field instead of parsing stderr to tell a clean+ * skip from an unresolved guard: the `o2b brain init` verb carries it+ * through to its `--json` payload and names it in the human output.+ */+ readonly guard: {+ readonly status: BrainInitGuardStatus;+ readonly detail?: string;+ };}/**@@ -363,6 +402,25 @@ export function bootstrapBrain(writeVaultIdentity(vault);if (!identityExisted) created.push(vaultRelative(identityPath, vault));+ // 1c. `<vault>/.gitignore` — the derived-state guard (t_206562ae).+ // Every derived runtime state lives under `.open-second-brain/`, so+ // one vault-root-anchored entry covers it; without the seed, a+ // fresh init in a git repository left brain.sqlite visible to `git+ // status`. The seeder merges a managed block and never clobbers+ // user content; a git repository is NOT required (a plain folder+ // gets the same seed, and git is never consulted here). A created+ // file reports as created; an existing file that gained the block+ // reports as overwritten (its bytes changed on disk); a clean skip+ // or a named conflict leaves the file untouched and reports as+ // skipped, with `result.guard` distinguishing the two. The step is+ // guarded, not load-bearing: a `.gitignore` that cannot be read or+ // written (chmod-denied, mandatory-locked, or a directory) warns on+ // stderr and degrades to `guard: { status: "failed" }` instead of+ // aborting — bailing here would leave the half-built tree below+ // unwritten for a hygiene guard the doctor's git-tracked-state row+ // reports independently (and in more detail).+ const guard = seedGitignoreGuard(vault, created, overwritten, skipped);+// 2. `_brain.yaml` — default config (with optional primary_agent).const brainYamlPath = brainConfigPath(vault);const brainYamlRel = vaultRelative(brainYamlPath, vault);@@ -412,7 +470,45 @@ export function bootstrapBrain(created.push(...starterResult.copied);}- return { created, overwritten, skipped };+ return { created, overwritten, skipped, guard };+}++/**+ * Step 1c: seed the `<vault>/.gitignore` derived-state guard, record the+ * file in the created/overwritten/skipped lists, and answer the guard+ * outcome the result carries. The guard is always answered — the seeder+ * deliberately propagates I/O errors, and here they stop being fatal:+ * report on stderr, degrade to `guard: { status: "failed" }`, continue.+ */+function seedGitignoreGuard(+ vault: string,+ created: string[],+ overwritten: string[],+ skipped: string[],+): BootstrapBrainResult["guard"] {+ try {+ const gitignore = ensureVaultGitignoreEntries(vault);+ if (gitignore.status === "created") {+ created.push(gitignore.file);+ } else if (gitignore.status === "updated") {+ overwritten.push(gitignore.file);+ } else {+ skipped.push(gitignore.file);+ }+ return {+ status: gitignore.status,+ ...(gitignore.detail !== undefined ? { detail: gitignore.detail } : {}),+ };+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ process.stderr.write(+ `warning: brain init could not seed the ${GITIGNORE_GUARD_FILE} derived-state guard ` ++ `(derived brain state stays visible to git; \`o2b brain doctor\` reports the row): ` ++ `${detail}\n`,+ );+ skipped.push(GITIGNORE_GUARD_FILE);+ return { status: "failed", detail };+ }}/**diff --git a/src/core/brain/intake/extract-intake.ts b/src/core/brain/intake/extract-intake.tsindex 4dd9430d..a69d1166 100644--- a/src/core/brain/intake/extract-intake.ts+++ b/src/core/brain/intake/extract-intake.ts@@ -31,6 +31,21 @@* records of what an untrusted source claimed rather than edits to what the* operator already holds.*+ * Markdown neutralization (t_c2ac4fc8, review M4): the entity page H1 is+ * composed FROM the third-party display name, and the aliases are+ * third-party strings stored beside it - on the untrusted lane those are+ * caller text the same way a summary's prose is, so under the+ * markdown-neutralization gate's enforce mode they pass through the pure+ * neutralizer before any page bytes compose. A name whose text plants a+ * `[[wikilink]]` (or any other structure row) then writes an H1 whose+ * sigils - the planted ones and, with them, the writer's own heading+ * sigil - are escaped, so the page's line grammars see no live row on it.+ * Identity is untouched: the frontmatter name and the id key on the raw+ * label, relations still resolve by it, and the escaped H1 is a rendering+ * of the record, not a different record. Off and shadow write verbatim;+ * the trusted lane never neutralizes (its names are the caller's writing+ * about the operator's own material).+ ** Disposition contract (write-side trust, Task 12): the CALLING lane resolves* the review disposition ONCE for the logical write this intake belongs to and* hands the verdict in through {@link IntakeOptions.disposition}. The arms:@@ -83,6 +98,11 @@ import {} from "../entities/canonical.ts";import { relateEntities, upsertEntity } from "../entities/registry.ts";import { renderProvenanceSection, type Provenance } from "../provenance/provenance.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE,+ neutralizeMarkdown,+ resolveMarkdownNeutralizeModeForProcess,+} from "../text/neutralize-markdown.ts";import { INTAKE_TRUST, type IntakeTrust } from "../trust/untrusted-provenance.ts";import {UNTRUSTED_ORIGIN,@@ -346,7 +366,23 @@ function remotelyReadable(vault: string): (rel: string) => boolean {}/**- * Intake a typed extraction into the entity registry. Validates the full+ * The H1 heading text this intake renders for an entity display name.+ * Verbatim unless `active` - the untrusted lane under the gate's enforce+ * mode - in which case the name passes through the neutralizer, and when+ * the NAME itself carries structure the whole composed H1 line (the+ * writer's heading sigil included) is escaped, so the page's line+ * grammars see no live row anywhere on it. Detection runs on the name+ * ALONE first: the writer's `# ` template is the writer's, and a clean+ * name must not lose its heading to it.+ */+function entityH1Name(displayName: string, active: boolean): string {+ if (!active) return displayName;+ if (!neutralizeMarkdown(displayName).changed) return displayName;+ return neutralizeMarkdown(`# ${displayName}`).text;+}++/**+ * Intake one typed extraction into the entity registry. Validates the full* payload first (throwing {@link IntakeValidationError} with no write on* failure), then upserts entities and applies relations idempotently.*/@@ -356,12 +392,27 @@ export function intakeExtraction(opts: IntakeOptions,): IntakeResult {validateIntake(intake);+ // The write-time markdown neutralization gate (t_c2ac4fc8, review M4),+ // resolved BEFORE ANY WRITE like every seam: a misconfigured mode is a+ // misconfiguration of the process, not a verdict about this extraction,+ // and refusing it after the first entity page exists would half-apply+ // the intake. Whether the gate has work to do is decided per entity+ // below (untrusted origin, enforce only); resolving it here only moves+ // the refusal earlier.+ const gate = resolveMarkdownNeutralizeModeForProcess();// Before any write, like the payload validation above: an intake that// cannot be classified must not leave half its entities behind.const origin = resolveIntakeOrigin(vault, opts.provenance, opts.readable);const provenanceSection = renderProvenanceSection(opts.provenance);const untrustedOrigin = origin.trust === INTAKE_TRUST.untrusted;+ // The lane the neutralizer answers to: an untrusted intake's entity+ // display text is third-party material the same way a summary's prose+ // is, so under enforce mode the name's H1 rendering and the aliases+ // pass through the pure neutralizer before any page bytes compose. The+ // frontmatter name and the identity key stay raw - the escaped H1 is a+ // rendering of the record, not a different record.+ const neutralizeActive = untrustedOrigin && gate === MARKDOWN_NEUTRALIZE_MODE.enforce;const entitiesCreated: string[] = [];const entitiesUpdated: string[] = [];@@ -383,16 +434,25 @@ export function intakeExtraction(// Stamp provenance into the body only when creating the page, so a later// mention of the same entity does not overwrite its first citation. The// registry decides whether this is a creation, in the lane it writes in;- // asking here would answer for the canonical lane only.+ // asking here would answer for the canonical lane only. The H1's name+ // text is the lane-neutralized rendering (review M4); the record's name+ // below stays raw.const bodyOnCreate = provenanceSection- ? `# ${entity.name.trim()}\n\n${provenanceSection}`+ ? `# ${entityH1Name(entity.name.trim(), neutralizeActive)}\n\n${provenanceSection}`: undefined;+ // Aliases are third-party strings stored beside the name; on the+ // neutralizing lane they are stored with their structure sigils+ // escaped, so no reader of the page extracts a link from one.+ const laneAliases =+ entity.aliases !== undefined && neutralizeActive+ ? entity.aliases.map((alias) => neutralizeMarkdown(alias).text)+ : entity.aliases;let res;try {res = upsertEntity(vault, {category,name: entity.name,- ...(entity.aliases !== undefined ? { aliases: entity.aliases } : {}),+ ...(laneAliases !== undefined ? { aliases: laneAliases } : {}),agent: opts.agent,now: opts.now,...(entity.confidence !== undefined ? { confidence: entity.confidence } : {}),diff --git a/src/core/brain/link-graph/parse-wikilink.ts b/src/core/brain/link-graph/parse-wikilink.tsindex 99d2776f..02b3c987 100644--- a/src/core/brain/link-graph/parse-wikilink.ts+++ b/src/core/brain/link-graph/parse-wikilink.ts@@ -29,7 +29,12 @@import { basename } from "node:path";-import { ANCHORED_WIKILINK_RE, RICH_WIKILINK_RE, maskCodeRegions } from "../wikilink.ts";+import {+ ANCHORED_WIKILINK_RE,+ RICH_WIKILINK_RE,+ isLiveWikilinkSpan,+ maskCodeRegions,+} from "../wikilink.ts";/*** Local regex for the rich extractor. Captures the full bracket@@ -167,7 +172,10 @@ export function parseWikilinkRich(value: string): WikilinkParse {* each through {@link parseWikilinkRich}.** Skips text inside fenced or inline code blocks (mirrors the- * masking pass in `extractWikilinks` from `vault.ts`). Media-extension+ * masking pass in `extractWikilinks` from `vault.ts`), and links whose+ * opening or closing bracket is backslash-escaped - the same+ * odd-backslash-run rule `extractWikilinks` applies, so an escaped+ * `[[body]]` is literal text and plants no backlink. Media-extension* targets (`.png`, `.pdf`, …) are dropped so an embed-style link* does not pollute the backlink index.*@@ -178,6 +186,7 @@ export function extractWikilinkRichBodies(content: string): ReadonlyArray<stringconst masked = maskCodeRegions(content, () => " ");const out: string[] = [];for (const m of masked.matchAll(RICH_WIKILINK_RE)) {+ if (!isLiveWikilinkSpan(masked, m.index!, m.index! + m[0].length)) continue;const body = m[1]!;// Drop embed-style media links - same filter as// `extractWikilinks` in `vault.ts`. The check inspects thediff --git a/src/core/brain/lint-consolidate.ts b/src/core/brain/lint-consolidate.tsindex b1a7a4aa..6378b670 100644--- a/src/core/brain/lint-consolidate.ts+++ b/src/core/brain/lint-consolidate.ts@@ -50,7 +50,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";import { parseFrontmatter } from "../vault.ts";-import { WIKILINK_TARGET_RE, isBrainArtifactId } from "./wikilink.ts";+import { WIKILINK_TARGET_RE, isBrainArtifactId, isLiveWikilinkSpan } from "./wikilink.ts";import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";import {PAGE_LIFECYCLE,@@ -194,26 +194,33 @@ function scanFileForMergedLinks(): { fixes: LintFix[]; unresolved: LintUnresolvedLink[]; rewritten: string } {const fixes: LintFix[] = [];const unresolved: LintUnresolvedLink[] = [];- const rewritten = raw.replace(WIKILINK_TARGET_RE, (match, target: string, suffix?: string) => {- const resolved = merge.resolve(target);- if (resolved.unresolvable !== null) {- unresolved.push({+ const rewritten = raw.replace(+ WIKILINK_TARGET_RE,+ (match: string, target: string, suffix: string | undefined, offset: number, whole: string) => {+ // A bracket behind an odd backslash run is escaped data and holds+ // no link (the rule every link reader applies), so a merged-link+ // convergence must not report, resolve or rewrite one.+ if (!isLiveWikilinkSpan(whole, offset, offset + match.length)) return match;+ const resolved = merge.resolve(target);+ if (resolved.unresolvable !== null) {+ unresolved.push({+ kind: LINT_CONSOLIDATE_KIND.mergedLink,+ path,+ target,+ reason: resolved.unresolvable,+ });+ return match;+ }+ if (resolved.canonical === null) return match;+ fixes.push({kind: LINT_CONSOLIDATE_KIND.mergedLink,path,- target,- reason: resolved.unresolvable,+ from: target,+ to: resolved.canonical,});- return match;- }- if (resolved.canonical === null) return match;- fixes.push({- kind: LINT_CONSOLIDATE_KIND.mergedLink,- path,- from: target,- to: resolved.canonical,- });- return `[[${resolved.canonical}${suffix ?? ""}]]`;- });+ return `[[${resolved.canonical}${suffix ?? ""}]]`;+ },+ );return { fixes, unresolved, rewritten };}diff --git a/src/core/brain/maintenance/collect.ts b/src/core/brain/maintenance/collect.tsindex bd79c501..e9cdf314 100644--- a/src/core/brain/maintenance/collect.ts+++ b/src/core/brain/maintenance/collect.ts@@ -57,6 +57,22 @@ export interface CollectMaintenanceActionsOptions {* scan refused.*/readonly onError?: (error: MaintenanceCollectError) => void;+ /**+ * Whether the caller may see an artifact reference - a page id, a+ * vault-relative path, or a wikilink-spelled one; the same grammar+ * `ArtifactRefView.visible` answers. Applied to the CANDIDATE INPUTS+ * before scoring and capping: a hidden canonical drops its whole dedup+ * row, a hidden duplicate stops counting toward a visible canonical's+ * title, a hidden demotion id and a rewrite naming a hidden page take+ * no ranked slot. Applied here rather than by the sinks after the call,+ * because the scorer caps at `topN` - post-hoc filtering let hidden+ * top-ranked candidates consume the cap and left a scoped caller with+ * fewer actions (or none) while visible lower-ranked ones existed, a+ * shortfall that itself hinted at withheld rows. Omitted, every+ * candidate is ranked and the output is byte-identical to the plain+ * call.+ */+ readonly visible?: (ref: string | null | undefined) => boolean;}/**@@ -87,6 +103,9 @@ export function collectMaintenanceActions(opts: CollectMaintenanceActionsOptions = {},): ReadonlyArray<ActionItem> {const onError = opts.onError ?? (() => {});+ // An omitted predicate sees everything: the fallback keeps an+ // unscoped call's output byte-identical to the pre-predicate shape.+ const visible = opts.visible ?? (() => true);let dedupCandidates: Array<{ canonicalId: string; secondaryCount: number }> = [];let staleByLifecycle: Array<{ id: string; ageDays: number }> = [];let brokenLinks: Array<{ path: string; from: string }> = [];@@ -94,18 +113,31 @@ export function collectMaintenanceActions(const dedup = collectSignal("dedup", onError, () => findDuplicateCandidates(vault));if (dedup !== undefined) {- dedupCandidates = dedup.candidates.map((c) => ({- canonicalId: c.canonical.id,- secondaryCount: c.secondaries.length,- }));+ dedupCandidates = dedup.candidates+ // A hidden canonical drops the whole row: its id is the row's+ // title and target, and re-pointing the merge at a visible+ // duplicate would invent a recommendation the scorer never made.+ .filter((c) => visible(c.canonical.id))+ .map((c) => ({+ canonicalId: c.canonical.id,+ // The count is the leak beside a visible canonical: a duplicate+ // the caller may not see contributes nothing to the title.+ secondaryCount: c.secondaries.filter((s) => visible(s.id)).length,+ }));}const lint = collectSignal("lint", onError, () => lintConsolidate(vault, { apply: false }));if (lint !== undefined) {- staleByLifecycle = lint.demotions.map((d) => ({- id: d.id,- ageDays: d.ageDays,- }));- brokenLinks = lint.fixes.map((f) => ({ path: f.path, from: f.from }));+ staleByLifecycle = lint.demotions+ .filter((d) => visible(d.id))+ .map((d) => ({+ id: d.id,+ ageDays: d.ageDays,+ }));+ brokenLinks = lint.fixes+ // A rewrite row names the file it edits and counts one link per+ // merged source: a hidden page in either position leaks through.+ .filter((f) => visible(f.path) && visible(f.from))+ .map((f) => ({ path: f.path, from: f.from }));}const footprint = collectSignal("token-footprint", onError, () => computeTokenFootprint(vault));if (footprint !== undefined) {diff --git a/src/core/brain/page-lint.ts b/src/core/brain/page-lint.tsindex 997e540a..b4edd6de 100644--- a/src/core/brain/page-lint.ts+++ b/src/core/brain/page-lint.ts@@ -123,7 +123,12 @@ import {containsProseIsoDate,findUndatedQuantities,} from "./undated-quantity.ts";-import { WIKILINK_TARGET_RE, isBrainArtifactId, normaliseWikilinkTarget } from "./wikilink.ts";+import {+ WIKILINK_TARGET_RE,+ isBrainArtifactId,+ isLiveWikilinkSpan,+ normaliseWikilinkTarget,+} from "./wikilink.ts";import { ARTIFACT_MAX_BYTES, validateArtifact } from "./write-session/validate.ts";/** The additive JSON key every write surface carries the report in. */@@ -407,11 +412,15 @@ function declaredSchemaType(meta: FrontmatterMap): string | null {* Every distinct wikilink target on the page, in first-appearance order.* Distinct rather than per-occurrence: a page that names one dead target* five times has one thing wrong with it, and five identical rows would- * spend the finding cap saying so.+ * spend the finding cap saying so. A bracket behind an odd backslash run+ * is escaped data and opens or closes no link - the same rule+ * `extractWikilinks` applies, so a `\[[literal]]` span raises no+ * broken-link row.*/function distinctLinkTargets(raw: string): ReadonlyArray<string> {const seen = new Set<string>();for (const match of raw.matchAll(WIKILINK_TARGET_RE)) {+ if (!isLiveWikilinkSpan(raw, match.index!, match.index! + match[0].length)) continue;const target = normaliseWikilinkTarget(match[1] ?? "");if (target !== "") seen.add(target);}diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.tsindex 0a8ad47c..072d92d6 100644--- a/src/core/brain/path-constants.ts+++ b/src/core/brain/path-constants.ts@@ -203,6 +203,21 @@ export const BRAIN_SNAPSHOT_EXCLUDED_ENTRIES: ReadonlyArray<string> = Object.fre*/export const DERIVED_STORE_DIR = ".open-second-brain";export const DERIVED_STORE_FILE = "brain.sqlite";++/**+ * The bench-harness runs directory, vault-relative:+ * `<vault>/.open-second-brain/bench-runs/`.+ *+ * Named beside the derived store it sits in (t_206562ae) because the+ * `.gitignore` guard seeded at brain init covers the store with ONE+ * vault-root-anchored entry, and a consumer spelling the runs dir+ * independently of that store is exactly how a writer ends up outside+ * the covered directory. `tests/core/brain/gitignore-guard.test.ts`+ * reads both this constant and the bench verb's source to keep the two+ * from drifting; the CLI still resolves the value against the working+ * directory, so `--runs-dir` behaves exactly as before.+ */+export const BENCH_RUNS_REL = posix.join(DERIVED_STORE_DIR, "bench-runs");/*** Where the runtime hooks append their one-line-per-decision audit trail,* one shard per ISO week.diff --git a/src/core/brain/planted-rows.ts b/src/core/brain/planted-rows.tsnew file mode 100644index 00000000..bce4f917--- /dev/null+++ b/src/core/brain/planted-rows.ts@@ -0,0 +1,573 @@+/**+ * The planted-rows audit planner (lane A, trust-and-responsiveness-hardening,+ * t_c2ac4fc8).+ *+ * The write-time neutralizer keeps third-party text from planting+ * structure; this planner reports the rows that are ALREADY planted - the+ * pages written before the gate existed or while it is off. It is the+ * pure half of the doctor's `planted-structure-rows` counting check (the+ * `planPrivacyMarkerRestamp` shape: planner module, one counting check),+ * so the finding, its count and what enforce mode would change cannot+ * drift apart: both this audit and the neutralizer read the one+ * detection grammar in `text/neutralize-markdown.ts`.+ *+ * The population is split the way authorship actually splits. For the+ * marker and osb-fence families it is EVERY readable page under `Brain/`:+ * no Brain writer ever emits a live `@osb` marker line or a live ```osb+ * fence (the consumed `@osb✓` sentinel is not detection), so a live one+ * anywhere in the derived layer is planted by construction - the same+ * structure the §9 vault scan would harvest into signals from any page+ * it walks. For the wikilink and atx-heading families it stays the+ * third-party lanes keyed off PROVENANCE, because the Brain's own+ * writers render those by design on pages outside the lanes - the+ * manual's section headings, the log's `[[Brain/log/...]]` refs, the+ * digests' links - and reporting them regardless of provenance would+ * report the vault's own structure as planted on every run.+ *+ * The provenance classification therefore also rides along as CONTEXT on+ * each finding ({@link PlantedRowsPage.thirdParty}), and the doctor names+ * lane pages first - a lane page and an operator note with the same rows+ * are equally live, but not equally expected.+ *+ * The scan over each page's body is the neutralizer's own detection, so+ * an inert excerpt inside a fenced code block counts nothing while a+ * planted ```osb fence line does. Staged copies under `Brain/pending/`+ * are deduplicated against their publish targets by content: the pending+ * directory holds a byte-verbatim copy of the page under review, so the+ * same rows would otherwise be reported twice. The dedupe answers to the+ * caller's readability when one is supplied: the consuming check filters+ * its rows by `ctx.readable` AFTER planning, so a hash-equal published+ * twin the caller may not read must never stand in for a readable staged+ * copy - the dedupe would drop the copy, the check would drop the twin,+ * and both would vanish from the report.+ *+ * The writers' own output is not planted, and the scan knows it. A+ * capture's trailing `## Guidance` section, a source summary's citation+ * and derivation sections (`## Sources`, `## Premises (level)`,+ * `## Entities`, `## Connections to existing notes`, `## Parts`,+ * `## Table`, `### Rows a-b`), a quarantined entity page's writer H1 and+ * provenance citation, and a distillation page's `## Claims`, `## Excerpt`+ * and `## Sources` sections are shapes THIS vault rendered on its lane+ * pages - without the exclusion a clean capture carrying guidance, a+ * clean ingest carrying its citations, a clean untrusted intake carrying+ * the entity H1 or a clean distillation reports the vault's own writer as+ * planted. The exclusion is a static list keyed by page kind and section+ * heading ({@link WRITER_AUTHORED_SECTIONS}), never a whole-page pass,+ * and the capture heading only counts as the writer's when the+ * `capture_guidance` frontmatter marker authorizes it.+ *+ * Authorship follows what the writer actually rendered, not the heading+ * text alone. The citation, link and derivation sections render only+ * AFTER the writer's own `## Sources` heading - the writer's prose+ * boundary, since caller text occupies only the leading prose region of+ * these pages - so an occurrence before that boundary is a caller+ * quotation and stays planted even when the writer rendered its own+ * occurrence later, and a section the writer did not render at all is+ * never exempt (a summary quoting `## Entities` over planted bullets+ * while the extraction named no entities reports). A fenced `## Sources`+ * line never bounds anything: the boundary is the last one the section+ * readers render as a heading. The entity H1 exemption covers the+ * writer's heading sigil only - the name content is caller text, so a+ * wikilink planted inside the name counts. A distillation claim bullet's+ * writer citation is exempt only where its target ties to the page's own+ * `source_path` frontmatter; the claim TEXT around it is caller content+ * and every other wikilink on the line stays planted.+ *+ * Read-only by contract: nothing here writes, and a page that cannot be+ * read between the walk and the body scan is skipped rather than thrown+ * - the doctor never throws.+ */++import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";+import { listVaultPages, parseFrontmatter } from "../vault.ts";+import { vaultRelative } from "../path-safety.ts";+import { BRAIN_PENDING_REL, isUnderBrainRoot } from "./path-constants.ts";+import { MAINTENANCE_LANE_REACH } from "../graph/transport-reach.ts";+import { hasUntrustedSourceMarker } from "./trust/untrusted-provenance.ts";+import { BRAIN_CAPTURE_KIND } from "./capture/capture-note.ts";+import { BRAIN_SOURCE_KIND } from "./ingest/ingest.ts";+import { BRAIN_DISTILLATION_KIND } from "./distill/claim.ts";+import { BRAIN_ENTITY_KIND, BRAIN_ENTITY_STATUS } from "./entities/types.ts";+import { PROVENANCE_LEVELS } from "./provenance/provenance.ts";+import { fencedLineMask } from "./source-links.ts";+import {+ MARKDOWN_STRUCTURE_KIND,+ detectMarkdownStructure,+ type MarkdownStructureKind,+ type MarkdownStructureMatch,+} from "./text/neutralize-markdown.ts";+import type { FrontmatterMap, VaultPage } from "../types.ts";++/** Where the review queue holds staged copies, `/`-separated and vault-relative. */+const PENDING_DIR = `${BRAIN_PENDING_REL}/`;++/** One page whose body carries live structure rows. */+export interface PlantedRowsPage {+ /** Vault-relative path with `/` separators. */+ readonly path: string;+ /** The structure families planted in the body, sorted, unique. */+ readonly kinds: ReadonlyArray<MarkdownStructureKind>;+ /** How many live rows the fence-masked scan found. */+ readonly count: number;+ /**+ * True when the page sits in a third-party provenance lane (a capture,+ * a source summary, an untrusted-stamped page, a quarantined entity) -+ * the lanes the enforce-mode seams neutralize. Context for the finding,+ * not the population filter: every Brain page is scanned.+ */+ readonly thirdParty: boolean;+}++export interface PlantedRowsPlan {+ /** Pages the population selector admitted. */+ readonly scanned: number;+ /** Pages whose body carries live structure, sorted by path. */+ readonly planted: ReadonlyArray<PlantedRowsPage>;+}++/** A tolerant status read: the scalar as written, trimmed and lowered. */+function entityStatus(meta: FrontmatterMap): string {+ const raw = meta["status"];+ return typeof raw === "string" ? raw.trim().toLowerCase() : "";+}++/** Does this page belong to a lane that receives third-party text? */+function inThirdPartyLane(meta: FrontmatterMap): boolean {+ const kind = typeof meta["kind"] === "string" ? meta["kind"] : "";+ if (kind === BRAIN_CAPTURE_KIND) return true;+ if (kind === BRAIN_SOURCE_KIND) return true;+ if (hasUntrustedSourceMarker(meta)) return true;+ return kind === BRAIN_ENTITY_KIND && entityStatus(meta) === BRAIN_ENTITY_STATUS.quarantine;+}++/**+ * The families no Brain writer ever authors - a live row is planted+ * wherever it sits, so these scan every readable Brain page. The+ * wikilink and heading families are excluded because the Brain's own+ * writers render them by design outside the third-party lanes (see the+ * module docblock); there the lane key IS the authorship signal.+ */+const ALWAYS_PLANTED_KINDS: ReadonlySet<MarkdownStructureKind> = new Set([+ MARKDOWN_STRUCTURE_KIND.osbInline,+ MARKDOWN_STRUCTURE_KIND.osbFence,+]);++/** Heading of the body section the capture contract renders for guidance (capture-note.ts). */+const CAPTURE_GUIDANCE_HEADING = "## Guidance";++/**+ * Frontmatter field authorizing that section (capture-note.ts's+ * `GUIDANCE_MARKER_FIELD`): the writer sets it exactly when IT rendered+ * the heading, which is what keeps a caller's quoted `## Guidance` on+ * the planted side of the line.+ */+const CAPTURE_GUIDANCE_MARKER = "capture_guidance";++/**+ * One writer-rendered section shape: the heading line that opens it and+ * how much of what follows is the writer's too.+ */+interface WriterSectionRule {+ /** The exact heading line the writer renders (a trailing CR is tolerated). */+ readonly heading: string;+ /** Match headings that BEGIN with this text (the ranged `### Rows a-b` shape). */+ readonly prefix?: boolean;+ /** Also mask the `- ` bullet lines under the heading (the `- [[id]]` citation rows). */+ readonly bullets?: boolean;+ /** The section is the writer's only when this frontmatter field is set true. */+ readonly requiresMarker?: string;+ /**+ * Only the LAST occurrence of the heading in the body is the writer's.+ * True for the headings each writer renders once: caller text occupies+ * only the leading prose region of these pages, so an earlier+ * occurrence is a caller quotation and stays planted.+ */+ readonly trailingOnly?: boolean;+ /**+ * The occurrence counts as the writer's only when it sits AFTER the+ * writer's own `## Sources` citation heading - the writer's prose+ * boundary. The citation, link and derivation sections render only+ * after that heading (ingest.ts composes caller prose first, then the+ * provenance and link sections), so an occurrence before the boundary+ * is a caller quotation and stays planted EVEN when the writer rendered+ * its own occurrence of the same heading later, and a section the+ * writer did not render at all is never exempt. Absent from the body+ * entirely, the `## Sources` heading bounds nothing and every+ * after-boundary rule exempts nothing (fail closed toward reporting).+ */+ readonly afterBoundary?: boolean;+ /**+ * The `- ` bullet lines under the heading are the writer's ONLY where a+ * live wikilink on them targets the page's own value of this frontmatter+ * field (the writer's `([[source#^block]])` block citation, whose target+ * is the cited source exactly or with a `#` block suffix). The claim+ * TEXT around that citation is caller content: any other wikilink on the+ * line stays planted, so a claim bullet is reported per wikilink rather+ * than masked per line.+ */+ readonly bulletsTiedToSource?: string;+}++/**+ * The section shapes the Brain's own writers render on third-party lane+ * pages, keyed by frontmatter `kind` - the pure exclusion list that keeps+ * this audit from reporting the vault's own writer as planted.+ *+ * - `brain-capture` renders ONE section, the trailing+ * {@link CAPTURE_GUIDANCE_HEADING}, and only under its marker+ * (capture-note.ts). The guidance CONTENT is caller text (the+ * neutralizer's business at write time), so only the heading line is+ * the writer's.+ * - `brain-source` composes every summary page as caller prose plus+ * rendered sections (ingest.ts): the provenance citation sections+ * (`## Sources`, `## Premises (<level>)` per provenance.ts, their+ * `- [[id]]` bullets the writer's own citation rows), the two link+ * sections, and the html/table derivation sections+ * (`## Parts` per extract-html.ts, `## Table` with one+ * `### Rows a-b` heading per group per table-note.ts - the writer+ * renders many, so every occurrence in the writer's own region is its+ * own). Every section but `## Sources` renders after it, so all of+ * them answer to the writer's prose boundary.+ * - `brain-entity` composes every quarantined entity page as the+ * writer's `# <name>` H1 plus the provenance citation+ * (extract-intake.ts bodyOnCreate over renderProvenanceSection): the+ * H1's heading sigil is the writer's template, its provenance+ * sections are the citation sections. The NAME content is caller+ * text - the H1 exemption covers the heading row only, and a+ * wikilink planted inside the name is reported.+ * - `brain-distillation` composes every page from its own sections+ * (distill-source.ts): `## Claims` (whose bullets carry caller claim+ * text plus the writer's source-tied block citation), the optional+ * `## Excerpt` heading (its content is fenced, inert), and the+ * `## Sources` provenance citation.+ *+ * Keyed by KIND, not by lane membership: an untrusted-stamped page whose+ * kind renders no such sections gets no exclusion, and a lane page keeps+ * its exclusions whether or not it is also untrusted-stamped.+ */+const WRITER_AUTHORED_SECTIONS: ReadonlyMap<string, readonly WriterSectionRule[]> = new Map([+ [+ BRAIN_CAPTURE_KIND,+ [+ {+ heading: CAPTURE_GUIDANCE_HEADING,+ requiresMarker: CAPTURE_GUIDANCE_MARKER,+ trailingOnly: true,+ },+ ],+ ],+ [+ BRAIN_SOURCE_KIND,+ [+ { heading: "## Sources", bullets: true, trailingOnly: true },+ ...PROVENANCE_LEVELS.map((level): WriterSectionRule => ({+ heading: `## Premises (${level})`,+ bullets: true,+ trailingOnly: true,+ afterBoundary: true,+ })),+ { heading: "## Entities", bullets: true, trailingOnly: true, afterBoundary: true },+ {+ heading: "## Connections to existing notes",+ bullets: true,+ trailingOnly: true,+ afterBoundary: true,+ },+ { heading: "## Parts", trailingOnly: true, afterBoundary: true },+ { heading: "## Table", trailingOnly: true, afterBoundary: true },+ { heading: "### Rows ", prefix: true, afterBoundary: true },+ ],+ ],+ [+ BRAIN_ENTITY_KIND,+ [+ { heading: "## Sources", bullets: true, trailingOnly: true },+ ...PROVENANCE_LEVELS.map((level): WriterSectionRule => ({+ heading: `## Premises (${level})`,+ bullets: true,+ trailingOnly: true,+ afterBoundary: true,+ })),+ ],+ ],+ [+ BRAIN_DISTILLATION_KIND,+ [+ // The writer's `## Claims` is the page's opening line; a claim text+ // can never reproduce it (claims are single `- ` bullet lines), and+ // an occurrence inside the fenced `## Excerpt` renders as no heading+ // at all - so every exact occurrence is the writer's or inert.+ { heading: "## Claims", bulletsTiedToSource: "source_path" },+ { heading: "## Excerpt" },+ { heading: "## Sources", bullets: true, trailingOnly: true },+ ],+ ],+]);++/** A frontmatter boolean in both spellings the reader produces (true and "true"). */+function frontmatterMarked(meta: FrontmatterMap, field: string): boolean {+ const value = meta[field];+ return value === true || value === "true";+}++/**+ * The writer's prose boundary on citation-section pages: the LAST+ * `## Sources` heading the section readers render as a heading. A fenced+ * occurrence (a quoted document's fence carrying the heading) bounds+ * nothing - it renders as no heading at all, so it must not move the+ * writer region into the caller's prose.+ */+const WRITER_BOUNDARY_HEADING = "## Sources";++/**+ * True when `text` is the writer's H1 template shape on an entity page:+ * the registry renders every entity body opening with `# <name>`.+ */+function isEntityH1(line: string): boolean {+ return line.startsWith("# ");+}++/**+ * Does the wikilink matched at `spanText` target the page's own source?+ * The writer's block citation renders `[[source#^block]]`, so the target+ * is the frontmatter source exactly or with a `#` block suffix; an alias+ * pipe is decoration on the same target.+ */+function wikilinkTiesToSource(spanText: string, source: string): boolean {+ const inner = spanText.slice(2, -2);+ const target = inner.split("|")[0] ?? "";+ const hash = target.indexOf("#");+ return (hash === -1 ? target : target.slice(0, hash)) === source;+}++/**+ * The writer-authored lines of `body` for the page's kind, with each+ * line's start offset, or `null` when the kind renders no writer+ * sections. Heading comparisons are exact (CR-tolerant); a bullet mask+ * runs from the heading past blank lines and stops at the first line+ * that is neither blank nor a `- ` item. `citationLines` names the `- `+ * lines where a source-tied wikilink is the writer's own citation+ * (masked per match, never per line - the claim text around the+ * citation is caller content).+ */+interface WriterMask {+ readonly masked: Set<number>;+ readonly lineStarts: number[];+ readonly citationLines: Set<number>;+}++function writerAuthoredLines(meta: FrontmatterMap, body: string): WriterMask | null {+ const kind = typeof meta["kind"] === "string" ? meta["kind"] : "";+ const rules = WRITER_AUTHORED_SECTIONS.get(kind);+ if (rules === undefined) return null;+ const lines = body.split("\n");+ const lineStarts: number[] = [];+ let offset = 0;+ for (const line of lines) {+ lineStarts.push(offset);+ offset += line.length + 1;+ }+ // The heading mask the section readers run: a heading inside a fence+ // renders as no heading, so a fenced occurrence neither bounds the+ // writer region nor needs masking (its lines are inert to every family+ // the section rules could otherwise over-mask).+ const fenced = fencedLineMask(lines.map((line) => line.replace(/\r$/, "")));+ const boundaryIndex = rules.some((rule) => rule.afterBoundary === true)+ ? lines.findLastIndex(+ (line, i) => !fenced[i] && line.replace(/\r$/, "") === WRITER_BOUNDARY_HEADING,+ )+ : -1;+ const masked = new Set<number>();+ const citationLines = new Set<number>();+ for (const rule of rules) {+ if (rule.requiresMarker !== undefined && !frontmatterMarked(meta, rule.requiresMarker)) {+ continue;+ }+ const at: number[] = [];+ for (let i = 0; i < lines.length; i++) {+ const text = lines[i]!.replace(/\r$/, "");+ const hit = rule.prefix === true ? text.startsWith(rule.heading) : text === rule.heading;+ if (hit) at.push(i);+ }+ if (at.length === 0) continue;+ const occurrences = rule.trailingOnly === true ? [at[at.length - 1]!] : at;+ for (const i of occurrences) {+ if (rule.afterBoundary === true && (boundaryIndex < 0 || i <= boundaryIndex)) continue;+ masked.add(i);+ if (rule.bullets !== true) continue;+ for (let j = i + 1; j < lines.length; j++) {+ const text = lines[j]!.replace(/\r$/, "");+ if (text === "") continue;+ if (text.startsWith("- ")) {+ masked.add(j);+ continue;+ }+ break;+ }+ }+ if (rule.bulletsTiedToSource === undefined) continue;+ const source = meta[rule.bulletsTiedToSource];+ if (typeof source !== "string" || source.length === 0) continue;+ // The `- ` bullet lines of THIS section: from the heading until the+ // next heading line. The claim text on them is caller content, so+ // they are never masked wholesale - the match-level tie check in+ // {@link excludeWriterAuthoredRows} keeps only the writer's citation.+ const sectionStart = at[0]!;+ for (let j = sectionStart + 1; j < lines.length; j++) {+ const text = lines[j]!.replace(/\r$/, "");+ if (text.startsWith("#")) break;+ if (text.startsWith("- ")) citationLines.add(j);+ }+ }+ return { masked, lineStarts, citationLines };+}++/**+ * Drop the writer-authored rows from `matches`: a row whose span starts+ * on a writer-rendered line is this vault's own output, not planted+ * structure. `matches` arrive sorted by start offset, so one forward+ * line walk answers every row. Two per-match exemptions ride beside the+ * line mask, for the shapes whose lines carry caller content too: an+ * entity page's H1 line exempts the writer's heading sigil only (the+ * name content is caller text), and a distillation claim bullet exempts+ * the writer's source-tied citation only (the claim text around it is+ * caller content).+ */+function excludeWriterAuthoredRows(+ meta: FrontmatterMap,+ body: string,+ matches: ReadonlyArray<MarkdownStructureMatch>,+): ReadonlyArray<MarkdownStructureMatch> {+ const mask = writerAuthoredLines(meta, body);+ if (mask === null) return matches;+ const { masked, lineStarts, citationLines } = mask;+ const kind = typeof meta["kind"] === "string" ? meta["kind"] : "";+ const sourcePath =+ typeof meta["source_path"] === "string" ? (meta["source_path"] as string) : undefined;+ const entityH1 =+ kind === BRAIN_ENTITY_KIND && isEntityH1((body.split("\n")[0] ?? "").replace(/\r$/, ""));+ const live: MarkdownStructureMatch[] = [];+ let line = 0;+ for (const match of matches) {+ while (line + 1 < lineStarts.length && lineStarts[line + 1]! <= match.start) line++;+ if (masked.has(line)) continue;+ if (entityH1 && line === 0 && match.kind === MARKDOWN_STRUCTURE_KIND.heading) continue;+ if (+ citationLines.has(line) &&+ match.kind === MARKDOWN_STRUCTURE_KIND.wikilink &&+ sourcePath !== undefined &&+ wikilinkTiesToSource(body.slice(match.start, match.end), sourcePath)+ ) {+ continue;+ }+ live.push(match);+ }+ return live;+}++/**+ * Scan every readable Brain page for live structure rows. Pure over the+ * vault's bytes: nothing is written, nothing is mutated, and the result+ * is deterministic for a given vault state (paths sorted, kinds sorted).+ *+ * `readable` is the CALLER's readability over vault-relative paths (the+ * doctor's `ctx.readable`), and it is NOT a population filter here - the+ * consuming check applies it to the report after planning. It informs+ * one decision only: which published pages may stand in for a staged+ * copy in the dedupe. The planner hashes with filesystem access while+ * the check filters by this predicate, so without it a readable staged+ * copy deduped against a hash-equal twin the caller may not read would+ * leave the report with neither row.+ */+export function planPlantedRows(+ vault: string,+ readable?: (rel: string) => boolean,+): PlantedRowsPlan {+ const selected = listVaultPages(vault, { reach: MAINTENANCE_LANE_REACH }).filter((page) =>+ isUnderBrainRoot(vaultRelative(page.path, vault)),+ );++ const isStaged = (page: VaultPage): boolean =>+ vaultRelative(page.path, vault).startsWith(PENDING_DIR);++ // Scan FIRST, dedupe after. Deduping before the scan trades report+ // completeness for one skipped parse: the scan of a staged page whose+ // twin survives is wasted work at worst, while a twin that later+ // leaves the report (the check's readable filter) would take the+ // staged copy's rows with it if the copy had already been dropped.+ const hits: { entry: PlantedRowsPage; page: VaultPage }[] = [];+ for (const page of selected) {+ let body: string;+ try {+ [, body] = parseFrontmatter(page.path);+ } catch {+ // Vanished or unreadable between the walk and the read: a page the+ // audit cannot scan is a page it does not name, never a throw.+ continue;+ }+ const matches = detectMarkdownStructure(body);+ const lane = inThirdPartyLane(page.metadata);+ const scoped = lane ? matches : matches.filter((m) => ALWAYS_PLANTED_KINDS.has(m.kind));+ const live = excludeWriterAuthoredRows(page.metadata, body, scoped);+ if (live.length === 0) continue;+ hits.push({+ entry: {+ path: vaultRelative(page.path, vault),+ kinds: [...new Set(live.map((m) => m.kind))].toSorted(),+ count: live.length,+ thirdParty: lane,+ },+ page,+ });+ }++ // Staged-vs-published dedupe: a Brain/pending copy is the publish+ // target's bytes verbatim, so when a staged page's content equals a+ // published page's content the publish target is the report and the+ // staged copy is dropped - but ONLY when the twin actually reports.+ // A twin the caller may not read is filtered out of the report by the+ // consuming check, so its hash must not stand in for anything: the+ // readable staged copy is the one that must be reported. An UNDEFINED+ // hash - a page that could not be read between the scan and the hash -+ // never enters the set and never matches: two unreadable pages are not+ // the same page, and a staged copy the audit cannot hash is reported,+ // never silently dropped.+ //+ // The hash is memoized by path: only pages that reported are hashed at+ // all (a page with no rows never meets a dedupe question), and each of+ // those is read for hashing exactly once, however the two passes below+ // consult it - the walk and the body scan already read every page, so+ // this keeps the audit's synchronous reads per reported page at three+ // and per skipped page at two, instead of hashing the whole population+ // whenever a staged copy exists.+ const hashMemo = new Map<string, string | undefined>();+ const hashOf = (absPath: string): string | undefined => {+ if (!hashMemo.has(absPath)) hashMemo.set(absPath, contentHash(absPath));+ return hashMemo.get(absPath);+ };+ const publishedReportedHashes = new Set<string>();+ for (const hit of hits) {+ if (isStaged(hit.page)) continue;+ if (readable !== undefined && !readable(hit.entry.path)) continue;+ const hash = hashOf(hit.page.path);+ if (hash !== undefined) publishedReportedHashes.add(hash);+ }+ const planted = hits+ .filter((hit) => {+ if (!isStaged(hit.page)) return true;+ const stagedHash = hashOf(hit.page.path);+ return stagedHash === undefined || !publishedReportedHashes.has(stagedHash);+ })+ .map((hit) => hit.entry);+ planted.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ return { scanned: selected.length, planted };+}++function contentHash(absPath: string): string | undefined {+ try {+ return createHash("sha256").update(readFileSync(absPath)).digest("hex");+ } catch {+ return undefined;+ }+}diff --git a/src/core/brain/secrets/crypto.ts b/src/core/brain/secrets/crypto.tsindex f72fef3d..8a820be5 100644--- a/src/core/brain/secrets/crypto.ts+++ b/src/core/brain/secrets/crypto.ts@@ -60,10 +60,19 @@ const KEY_BYTES = 32;const SYNC_EXCLUSION_CONTENT = "*\n!.gitignore\n";/**- * Drop the exclusion marker into `dir`, once, best-effort. Nothing in- * src ever writes a `.gitignore` elsewhere (every other reference in the- * tree is a reader), so this file IS the guarantee that the keyfile and- * the ciphertext do not ride a git commit to another machine.+ * Drop the exclusion marker into `dir`, once, best-effort. Beside the+ * vault root, the only `.gitignore` writers in src are this marker and+ * the vault-level managed block seeded by `ensureVaultGitignoreEntries`+ * in `../gitignore-guard.ts` - both deliberate and named here so the+ * guarantee cannot silently rot: this marker stays separate because the+ * secrets directory can pre-date brain init (an operator may store a+ * secret long before the first `o2b brain init`). One further writer+ * exists by design outside that pair: `ensureBackupRootIgnored` in+ * `../../trust.ts` writes its own `.gitignore` into the `.o2b-backups/`+ * root, covering the backups it owns, not Brain state. This marker and+ * that seeder are the whole guarantee that the keyfile and the+ * ciphertext do not ride a git commit to another machine; every other+ * reference in the tree is a reader.*/function ensureSyncExclusionMarker(dir: string): void {const marker = join(dir, ".gitignore");diff --git a/src/core/brain/source-links.ts b/src/core/brain/source-links.tsindex 56697c01..bf4e9a98 100644--- a/src/core/brain/source-links.ts+++ b/src/core/brain/source-links.ts@@ -12,6 +12,7 @@*/import type { FrontmatterMap } from "../types.ts";+import { isLiveWikilinkSpan } from "./wikilink.ts";/** Heading of the canonical provenance section (`provenance.ts`). */const SOURCES_HEADING_RE = /^##\s+Sources\s*$/;@@ -51,8 +52,12 @@ function closesFence(line: string, opener: string): boolean {* opens a fence and never closes it cannot hide the structure that follows.* Two linear passes at most: the single pass that pairs fences, then the* unmarking of the one span that can be left open.+ *+ * Exported because the write-time neutralizer's heading family must answer+ * "is this line fenced?" with the exact walk the section readers run - a+ * fourth private copy of the shape is one tilde away from disagreeing.*/-function fencedLineMask(lines: ReadonlyArray<string>): boolean[] {+export function fencedLineMask(lines: ReadonlyArray<string>): boolean[] {const mask = Array.from({ length: lines.length }, () => false);let fence: string | null = null;let openedAt = 0;@@ -116,7 +121,13 @@ export function sourcesSectionTargets(body: string): ReadonlyArray<string> {inSection = false;continue;}- for (const match of line.matchAll(WIKILINK_RE)) targets.push(wikilinkTarget(match[0]));+ for (const match of line.matchAll(WIKILINK_RE)) {+ // A bracket behind an odd backslash run is escaped data and opens+ // or closes no link - the same rule `extractWikilinks` and the+ // neutralizer's detector apply - so an escaped span cites nothing.+ if (!isLiveWikilinkSpan(line, match.index!, match.index! + match[0].length)) continue;+ targets.push(wikilinkTarget(match[0]));+ }}return targets;}diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.tsindex 72578ea5..978693e9 100644--- a/src/core/brain/sync-lockfile.ts+++ b/src/core/brain/sync-lockfile.ts@@ -66,12 +66,15 @@ import {constants as fsConstants,fstatSync,lstatSync,+ readFileSync,mkdirSync,openSync,readdirSync,unlinkSync,writeSync,} from "node:fs";+import { randomUUID } from "node:crypto";+import { appendFileSync } from "node:fs";import { basename, dirname, join } from "node:path";import { BRAIN_ROOT_REL, DERIVED_STORE_DIR } from "./path-constants.ts";@@ -91,23 +94,30 @@ const LOCK_SUFFIX = ".lock";/*** The file a holder created: device and inode as exact bigints. `null` when- * the platform reports no inode (some network and FAT volumes answer 0),- * where ownership cannot be told apart and release falls back to removing- * the name.+ * the platform reports no inode (some network and FAT volumes answer 0).*/type LockIdentity = { readonly dev: bigint; readonly ino: bigint } | null;+/**+ * The body this holder wrote into its lock file: the unique token that+ * decides ownership when a POSIX filesystem hands a freed inode straight+ * back to the next create. Device and inode alone cannot tell a reused+ * identity apart, so release reads the stamp back and compares prefixes.+ * Empty on Windows, where ownership stays the device-and-inode check.+ */+type LockHolder = { readonly identity: LockIdentity; readonly token: string };+// Held locks and the file each holder created, tracked at module scope so the// exit hook can clean up.-const heldLocks = new Map<string, LockIdentity>();+const heldLocks = new Map<string, LockHolder>();let exitHookInstalled = false;function ensureExitHook(): void {if (exitHookInstalled) return;exitHookInstalled = true;process.on("exit", () => {- for (const [lockPath, identity] of heldLocks) {- if (ownsLockName(lockPath, identity)) {+ for (const [lockPath, holder] of heldLocks) {+ if (ownsLockName(lockPath, holder.identity, holder.token)) {try {unlinkSync(lockPath);} catch {@@ -131,13 +141,39 @@ function identityOf(fd: number): LockIdentity {/*** Whether `lockPath` still names the file this holder created. A missing name- * is not owned (nothing to remove); an unknown identity is presumed owned, the- * behaviour before ownership was tracked.+ * is not owned (nothing to remove). The device and inode must match, and the+ * body must still open with this holder's token: a filesystem that reuses a+ * freed inode for the next holder's create answers the same identity for a+ * file this holder no longer owns, and only the stamp tells them apart. On a+ * volume without inodes the token alone decides.*/-function ownsLockName(lockPath: string, identity: LockIdentity): boolean {+function ownsLockName(lockPath: string, identity: LockIdentity, token: string): boolean {+ let body: Buffer | null = null;+ try {+ body = readFileSync(lockPath);+ } catch {+ // A body that cannot be read (Windows holds a just-written file+ // briefly against readers) cannot be told from another holder's:+ // fall back to the device-and-inode check alone, the behaviour+ // before ownership tokens.+ body = null;+ }+ if (body !== null && token !== "") {+ // The stamp answers for the whole file: a matching token is owned,+ // a foreign one (a reused identity, a takeover survivor) is not. A+ // waiter mark that raced the stamp's own write clobbers the token's+ // first byte, so a body that still carries this holder's unique+ // token line is owned all the same; a foreign body cannot carry it.+ if (body.subarray(0, Buffer.byteLength(token, "utf8")).equals(Buffer.from(token, "utf8"))) {+ return true;+ }+ const uuidLine = Buffer.from(`\n${token.split("\n")[1] ?? ""}\n`, "utf8");+ return uuidLine.byteLength > 2 && body.includes(uuidLine);+ }try {const st = lstatSync(lockPath, { bigint: true });- return identity === null || (st.dev === identity.dev && st.ino === identity.ino);+ if (identity === null) return true;+ return st.dev === identity.dev && st.ino === identity.ino;} catch {return false;}@@ -230,16 +266,25 @@ export function acquireLockSync(target: string): LockHandle {const identity = identityOf(fd);- // Stamp pid + timestamp into the lock body. The contents are- // purely diagnostic - the doctor surface reads them when reporting- // stale locks. Failure to write is non-fatal: the lock semantics- // come from the exclusive create, not from the body.+ // Stamp pid, a unique holder token and the timestamp into the lock+ // body. On POSIX the token decides ownership at release: a filesystem+ // there can hand a freed inode straight back to the next holder's+ // create, and only the stamp tells the files apart (the doctor+ // surface reads the rest when reporting stale locks). Windows keeps+ // the device-and-inode check alone: its delete-pending windows make+ // a just-written body unreliable to read back, and its volumes+ // allocate fresh identities for recreated files, where the reuse+ // race has never been observed. A failed write leaves no token and+ // release falls back to the same check.let stampBytes = 0;+ let token: string | null =+ process.platform === "win32" ? null : `${process.pid}\n${randomUUID()}`;try {- const stamp = Buffer.from(`${process.pid}\n${new Date().toISOString()}\n`, "utf8");+ const stamp = Buffer.from(`${token}\n${new Date().toISOString()}\n`, "utf8");stampBytes = writeSync(fd, stamp, 0, stamp.byteLength);} catch {- // ignore; diagnostic-only payload+ // ignore; the body cannot be trusted as an ownership marker+ token = null;} finally {try {closeSync(fd);@@ -248,7 +293,11 @@ export function acquireLockSync(target: string): LockHandle {}}- heldLocks.set(lockPath, identity);+ const holder: LockHolder =+ token !== null && stampBytes >= Buffer.byteLength(token, "utf8")+ ? { identity, token }+ : { identity, token: "" };+ heldLocks.set(lockPath, holder);let released = false;return {path: lockPath,@@ -257,10 +306,10 @@ export function acquireLockSync(target: string): LockHandle {released = true;// A newer handle in this process may have re-registered the path; its// registration is the one the exit sweep must still see.- if (heldLocks.get(lockPath) === identity) heldLocks.delete(lockPath);+ if (heldLocks.get(lockPath) === holder) heldLocks.delete(lockPath);// The name no longer holds this holder's file: whoever holds it now// keeps it. Removing it would admit a second holder beside them.- if (!ownsLockName(lockPath, identity)) return;+ if (!ownsLockName(lockPath, holder.identity, holder.token)) return;// Anything past our own stamp was appended by a waiter (see// `markWaiting`): someone is queued for this lock, so a re-acquire from// this process steps back first. Best-effort, like the stamp itself.@@ -587,6 +636,12 @@ function waiterSleepMs(waitedMs: number): number {/** Upper bound on the bytes waiters append to one lock file. */const WAITER_MARK_LIMIT = 4_096;+/**+ * Below this size a lock body is still mid-stamp (pid, token line,+ * timestamp and separators never fit in less), and a waiter mark at+ * its end would land inside the token: leave such a file unmarked.+ */+const MIN_STAMP_BYTES = 48;const WAITER_MARK = Buffer.from("w", "utf8");/** Read-write, never create, and never follow a symlink where the platform can refuse one. */const MARK_OPEN_FLAGS = fsConstants.O_RDWR | (fsConstants.O_NOFOLLOW ?? 0);@@ -607,6 +662,10 @@ function markWaiting(lockPath: string): void {// one name. A symlink or hard link planted at the lock path (a synced// vault can carry one) must not turn the mark into a write elsewhere.if (!stat.isFile() || stat.nlink !== 1) return;+ // A body still inside its own stamp write (a waiter can open the+ // name in the microseconds before the holder's stamp lands) is left+ // alone: an early mark would write over the holder token position.+ if (stat.size < MIN_STAMP_BYTES) return;if (stat.size < WAITER_MARK_LIMIT) {writeSync(fd, WAITER_MARK, 0, WAITER_MARK.byteLength, stat.size);}diff --git a/src/core/brain/text/neutralize-markdown.ts b/src/core/brain/text/neutralize-markdown.tsnew file mode 100644index 00000000..868c33d2--- /dev/null+++ b/src/core/brain/text/neutralize-markdown.ts@@ -0,0 +1,710 @@+/**+ * Write-time neutralizer for structure-bearing markdown (lane A,+ * trust-and-responsiveness-hardening, t_c2ac4fc8).+ *+ * Third-party text written into the vault can plant structure the Brain+ * then treats as its own: a `[[wikilink]]` joins the link graph, an+ * `@osb` line joins the marker scanners, a ```osb fence plants a block+ * marker, and an ATX heading plants a semantic section the section+ * parsers read back. The read-time payload neutralizer+ * (`untrusted-source.ts`) and the ingest trust lane defend reads; nothing+ * defended writes. This module is the write-time leg: it escapes the+ * sigils of planted structure so the text keeps reading verbatim while+ * every line-grammar detector in src/core stops matching.+ *+ * ## Doctrine+ *+ * - **Structure only, never vocabulary.** Detection keys on grammar a+ * parser consumes, one family per consumer grammar, and on no word+ * list: wikilinks (`wikilink.ts` regex family), `@osb` inline+ * markers (the `inline.ts` parser itself, so "would a scanner parse+ * this" has exactly one answer), ```osb fence lines (the+ * `discoverMarkers` fence walk) and ATX headings (the CommonMark+ * opening shape, which covers the semantic headings and the log+ * heading). Task checkboxes, markdown links, reference definitions+ * and tags are deliberately out of the set.+ * - **Escape, never delete, never invisible characters.** One uniform+ * mechanism: a backslash before each sigil of a detected span+ * (brackets in wikilinks, `@` on marker lines, backticks on fence+ * lines, the `#` run on headings). CommonMark renders a backslash+ * before ASCII punctuation as the literal character, so the text+ * stays readable and the bytes stay honest; no HTML entities, no+ * zero-width anything.+ * - **Fence-aware, per consumer grammar.** Every family is masked by the+ * fence model the readers of that family actually run, because the+ * grammars disagree about what a fence even is: the marker scanner+ * (`inline.ts`) knows exactly-3-backtick lines and nothing else, the+ * section readers (`source-links.ts` `fencedLineMask`, shared with the+ * block resolver) know 3-or-more backtick or tilde runs, the search+ * chunker (`chunker.ts` `readCodeBlock`) closes any fence on the first+ * line starting with the same three-character mark, and the link+ * readers share {@link maskCodeRegions}. Masking an `@osb` row with the+ * one model and scanning it with the other is how a planted marker+ * inside a tilde fence would slip through: detection answers+ * "would MY consumer parse this" for each family separately.+ * - **Escape-aware detectors.** A sigil preceded by an odd backslash+ * run is data the caller already escaped, not structure; it is never+ * re-escaped. (Line-anchored families get this for free: `\@osb` and+ * `\#\#` fail the anchor.)+ * - **Line breaks normalized first.** The enforce-mode walk folds CRLF+ * to `\n` and a lone CR, NEL (U+0085), U+2028 and U+2029 to `\n`+ * before detection, and records the rewrite as the `line-break` kind:+ * CommonMark, Obsidian and `/m`-regex readers end lines on those+ * characters while the `\n`-splitting detectors do not, so an+ * unfolded `x\r# Planted` renders a heading no family would see.+ * - **Idempotent by construction.** Escaping a fence line dissolves the+ * fence, which can expose previously masked interior text - so+ * {@link neutralizeMarkdown} re-detects its own output until the+ * detector finds nothing left (bounded by+ * {@link NEUTRALIZE_FIXPOINT_STEPS}). The walk terminates because+ * each round only inserts backslashes before sigils that lacked an+ * odd run - a backslashed sigil fails the same detection on the next+ * pass (the odd-run rule, and the line anchors), so no sigil is ever+ * escaped twice, and escaping cannot CREATE a sigil: a backslash+ * before a sigil never starts a line the way `@osb`, `#` or ` ``` `+ * must. A round can only ever EXPOSE sigils that were already in the+ * text (a dissolved fence's interior), so the walk visits each sigil+ * at most once and the bound is a safety net, never reached. The exit+ * condition IS the doctrine: the output no longer matches the+ * detector, therefore `neutralize(neutralize(x))` is byte-identical+ * to `neutralize(x)`. Should the bound ever run out with live+ * structure still detected - an input the walk cannot converge on -+ * the walk fails CLOSED with a {@link MarkdownNeutralizeFixpointError}+ * instead of returning those bytes as if they were neutralized: the+ * bound guards against the impossible by refusing it, not by+ * shipping it.+ *+ * ## One detection grammar, two consumers+ *+ * {@link detectMarkdownStructure} is the shared layer: the writer+ * ({@link neutralizeMarkdown}) escapes the spans it reports, and the+ * doctor's planted-rows planner counts them - so the finding, its count+ * and what enforce mode would change cannot drift apart.+ *+ * The gate ({@link resolveMarkdownNeutralizeMode}) is pure and defaults+ * to `off`, where the seams do not call this module at all and every+ * write stays byte-identical to before it existed.+ */++import {+ isLiveWikilinkSpan,+ maskCodeRegions,+ precededByOddBackslashRun,+ WIKILINK_TARGET_RE,+} from "../wikilink.ts";+import { parseInlineMarker } from "../inline.ts";+import { fencedLineMask } from "../source-links.ts";+import { envOrConfig } from "../../validate.ts";+import type { FrontmatterMap } from "../../types.ts";+import { discoverConfig } from "../../config.ts";++// ----- The shared detection grammar -----------------------------------------++/** The structure families the neutralizer escapes and the auditor counts,+ * plus the line-break token: the enforce-mode walk also folds unusual line+ * separators to `\n` before detection and records that rewrite here, so the+ * `neutralized_markers` provenance names every way the output departed from+ * the input. The auditor counts only the structure families - the+ * line-break token never appears in {@link detectMarkdownStructure} output. */+export const MARKDOWN_STRUCTURE_KIND = Object.freeze({+ wikilink: "wikilink",+ osbInline: "osb-inline",+ osbFence: "osb-fence",+ heading: "atx-heading",+ lineBreak: "line-break",+} as const);++/** One {@link MARKDOWN_STRUCTURE_KIND} token. */+export type MarkdownStructureKind =+ (typeof MARKDOWN_STRUCTURE_KIND)[keyof typeof MARKDOWN_STRUCTURE_KIND];++/** One planted structure row: a span of `text` whose sigils are live. */+export interface MarkdownStructureMatch {+ readonly kind: MarkdownStructureKind;+ /** Inclusive start offset of the sigil span, in code units of `text`. */+ readonly start: number;+ /** Exclusive end offset of the sigil span. */+ readonly end: number;+}++/**+ * The ```osb fence-open shape `discoverMarkers` walks: exactly three backticks,+ * a plain info string, end of line. The marker grammar never learned+ * about longer runs or tilde fences, and this module does not teach it -+ * "would a marker scanner consume this" is the question the osb-fence+ * family answers.+ */+const OSB_FENCE_OPEN_RE = /^```([A-Za-z0-9_-]*)\s*$/;++/** The CommonMark ATX opening shape, widened to the union of consumer grammars: any+ * indentation (the section readers and the log reader disagree about how much a+ * heading may carry, so the detector under-cuts none of them), a `#` run of 1-6,+ * then a space, the CR of a CRLF body, or the line end. */+const ATX_HEADING_RE = /^[ \t]*(#{1,6})(?:[ \t\r]|$)/;++/** The fence marker both grammars are built from. */+const BACKTICK = "`";++/** One physical line and its start offset in the scanned text. */+interface Line {+ readonly text: string;+ readonly start: number;+}++function splitLines(text: string): Line[] {+ const out: Line[] = [];+ let start = 0;+ for (;;) {+ const nl = text.indexOf("\n", start);+ if (nl === -1) {+ out.push({ text: text.slice(start), start });+ return out;+ }+ out.push({ text: text.slice(start, nl), start });+ start = nl + 1;+ }+}++/** Length of the backtick run starting at `s[0]` (`s` is a pre-trimmed line head). */+function backtickRun(s: string): number {+ let n = 0;+ while (n < s.length && s[n] === BACKTICK) n++;+ return n;+}++/**+ * The ```osb fence lines plus the body mask, found by the same walk+ * `discoverMarkers` runs: an open fence line per {@link OSB_FENCE_OPEN_RE}+ * consumes lines until a line whose trimmed form starts with three backticks+ * (or the end of text), and an `osb`-info block contributes its open and+ * close fence lines. This is the marker grammar's ENTIRE fence concept -+ * exactly-3-backtick boundaries and nothing else: a tilde fence or a+ * 4-backtick fence fences nothing for the scanner, so the rows inside are+ * live and the mask must not cover them, while an unterminated fence+ * consumes the rest of the text and the mask must cover that.+ */+interface MarkerFenceStructure {+ /** The osb fence boundary-line sigil spans, in document order. */+ readonly spans: MarkdownStructureMatch[];+ /** True for body lines the marker scanner consumes as fenced (not parsed). */+ readonly bodyMasked: boolean[];+}++function markerFenceStructure(lines: ReadonlyArray<Line>): MarkerFenceStructure {+ const spans: MarkdownStructureMatch[] = [];+ const bodyMasked = Array.from({ length: lines.length }, () => false);+ let i = 0;+ while (i < lines.length) {+ const line = lines[i]!;+ const open = OSB_FENCE_OPEN_RE.exec(line.text.trim());+ if (open === null) {+ i++;+ continue;+ }+ const isOsb = (open[1] ?? "") === "osb";+ if (isOsb) {+ const indent = line.text.length - line.text.trimStart().length;+ spans.push({ kind: "osb-fence", start: line.start + indent, end: line.start + indent + 3 });+ }+ i++;+ while (i < lines.length) {+ const inner = lines[i]!;+ if (inner.text.trim().startsWith("```")) {+ if (isOsb) {+ const indent = inner.text.length - inner.text.trimStart().length;+ const run = backtickRun(inner.text.trimStart());+ spans.push({+ kind: "osb-fence",+ start: inner.start + indent,+ end: inner.start + indent + run,+ });+ }+ i++;+ break;+ }+ bodyMasked[i] = true;+ i++;+ }+ }+ return { spans, bodyMasked };+}++/** The sigil span of a line's leading `@` when the line parses as a marker. */+function inlineMarkerMatch(line: Line, lineNo: number): MarkdownStructureMatch | null {+ if (parseInlineMarker(line.text, lineNo + 1) === null) return null;+ const at = line.text.length - line.text.trimStart().length;+ return { kind: "osb-inline", start: line.start + at, end: line.start + at + 1 };+}++/**+ * The search chunker's code-block walk (`chunker.ts` `FENCE_RE` ++ * `readCodeBlock`), mirrored line for line: a block opens on a line whose+ * RAW form starts with three backticks or tildes (the chunker tests the+ * untrimmed line) and closes on the first later line whose TRIMMED form+ * starts with the same three-character mark - info string or not - and an+ * unclosed block runs to end of text. This is deliberately NOT+ * {@link fencedLineMask}'s rule: the chunker is pinned by+ * `CHUNKER_VERSION` (changing how it reads a page forces a full vault+ * re-chunk), so the detector carries the chunker's shape as its own+ * second heading mask rather than the chunker carrying the section+ * readers'.+ */+const CHUNKER_FENCE_OPEN_RE = /^(?:```|~~~)/;++function chunkerCodeBlockMask(lines: ReadonlyArray<Line>): boolean[] {+ const mask = Array.from({ length: lines.length }, () => false);+ let i = 0;+ while (i < lines.length) {+ if (!CHUNKER_FENCE_OPEN_RE.test(lines[i]!.text)) {+ i++;+ continue;+ }+ const mark = lines[i]!.text.trim().startsWith("```") ? "```" : "~~~";+ mask[i] = true;+ i++;+ while (i < lines.length) {+ mask[i] = true;+ const closed = lines[i]!.text.trim().startsWith(mark);+ i++;+ if (closed) break;+ }+ }+ return mask;+}++/**+ * Every planted structure row in `text`, left to right. Each family is+ * masked by the fence model its own readers run, because "is this row+ * inert?" has one answer per consumer grammar and they do not agree:+ *+ * - the osb-inline and osb-fence families answer to the marker scanner+ * (`inline.ts`): its exactly-3-backtick boundary walk is the only+ * fencing that exists there, so a planted marker inside a tilde fence+ * or a 4-backtick fence is live and gets reported;+ * - the atx-heading family answers to TWO fence grammars: the section+ * readers (`source-links.ts` `fencedLineMask`, shared with the block+ * resolver; a 3-or-more backtick or tilde fence closes only on a run+ * at least as long carrying nothing but whitespace, and an+ * unterminated fence fences nothing) and the search chunker+ * (`chunker.ts` `readCodeBlock`, which closes ANY fence on the first+ * later line whose trimmed form starts with the same three-character+ * mark, info string or not). A heading is escaped when EITHER grammar+ * leaves it live - the chunker's shorter-close rule exposes a heading+ * after a ``` line inside a ```` fence, which masking with+ * `fencedLineMask` alone left unescaped and attributable as a chunk+ * `headingPath`;+ * - the wikilink family answers to the link readers (`vault.ts`+ * `extractWikilinks`, page-lint) and runs the readers' own recipe:+ * code regions (fences and inline spans) are masked out of the scan+ * view first, then the multi-line-tolerant {@link WIKILINK_TARGET_RE}+ * shape and {@link isLiveWikilinkSpan} run on that view, so a+ * `[[...\n...]]` pair across a line break is detected exactly when+ * they would extract it. The mask is length-preserving, so every+ * match offset in the view is the same offset in the raw text and the+ * brackets the readers can see are exactly the brackets this scan+ * sees - a `[[target|`code`]]` span whose brackets sit outside the+ * region is reported (and escaped) even though the raw span overlaps+ * the region, which is the hole a raw-text scan with a region-overlap+ * test left open: the readers still extracted the live target from+ * their own masked view.+ *+ * Fence lines for the osb family are boundaries rather than masked+ * content. Pure and linear in the length of the text.+ */+export function detectMarkdownStructure(text: string): ReadonlyArray<MarkdownStructureMatch> {+ const lines = splitLines(text);+ const fence = markerFenceStructure(lines);+ const matches: MarkdownStructureMatch[] = [...fence.spans];+ // The wikilink family keys on the multi-line-tolerant shape its readers+ // run (`vault.ts` extractWikilinks, page-lint) over the same masked view+ // those readers match on. The fill preserves length, so match offsets+ // are raw-text offsets; the bracket-span match set itself is identical+ // under any space fill, because a code region contributes no bracket+ // characters in either view.+ const masked = maskCodeRegions(text, (region) => " ".repeat(region.length));+ for (const m of masked.matchAll(WIKILINK_TARGET_RE)) {+ const start = m.index;+ const end = start + m[0].length;+ if (!isLiveWikilinkSpan(masked, start, end)) continue;+ matches.push({ kind: "wikilink", start, end });+ }+ const headingMasked = fencedLineMask(lines.map((line) => line.text));+ const chunkerMasked = chunkerCodeBlockMask(lines);+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ // The heading escapes unless BOTH fence grammars mask the line: the+ // family's consumers disagree about where a fence ends (see the+ // family bullet above), and a line either consumer treats as+ // fence-open but the other does not is live for the latter.+ if (!headingMasked[i] || !chunkerMasked[i]) {+ const heading = ATX_HEADING_RE.exec(line.text);+ if (heading !== null) {+ const runStart = line.start + heading[0].indexOf("#");+ const start = runStart;+ const end = runStart + heading[1]!.length;+ matches.push({ kind: "atx-heading", start, end });+ }+ }+ if (fence.bodyMasked[i]) continue;+ const marker = inlineMarkerMatch(line, i);+ if (marker !== null) matches.push(marker);+ }+ return matches.toSorted((a, b) => a.start - b.start || a.end - b.end);+}++// ----- The neutralizer ------------------------------------------------------++/**+ * The line-separator normalization the enforce-mode walk runs before+ * detection: `\r\n` folds to `\n`, and a lone CR, NEL (U+0085), LINE+ * SEPARATOR (U+2028) or PARAGRAPH SEPARATOR (U+2029) becomes `\n`. These+ * are the characters CommonMark, Obsidian and every `/m`-regex line reader+ * treat as a line end while the `\n`-splitting detectors - OSB's own line+ * readers included - do not, so a planted row hiding behind one (`x\r#+ * Planted` renders a heading) would otherwise pass detection untouched.+ * One pass, and the output carries none of the separators, so the rewrite+ * is inherently idempotent.+ */+const LINE_BREAK_NORMALIZE_RE = /\r\n?|[\u0085\u2028\u2029]/g;++function normalizeLineBreaks(text: string): { text: string; changed: boolean } {+ const normalized = text.replace(LINE_BREAK_NORMALIZE_RE, "\n");+ return normalized === text ? { text, changed: false } : { text: normalized, changed: true };+}++/**+ * How many detect-and-escape rounds {@link neutralizeMarkdown} may run+ * before it refuses: two rounds are the deep case (round one escapes an+ * ```osb fence's boundary lines, the escape dissolves the fence for the+ * line-grammar consumers, and round two escapes the interior the dissolve+ * exposed), and no round can create a sigil or escape one twice (see the+ * doctrine block above), so the walk converges and the bound is a safety+ * net honest input never reaches. The post-condition is asserted, not+ * assumed: a bound exhausted with the output's own detection still+ * non-empty is a {@link MarkdownNeutralizeFixpointError}, never a+ * `changed: true` carrying live structure.+ */+const NEUTRALIZE_FIXPOINT_STEPS = 8;++/**+ * Backslash-escape the minimal sigil characters of one detected span.+ * The heading, marker and fence spans are pure sigil runs (`#`s, the+ * `@`, backticks) so every character escapes; a wikilink span covers its+ * whole `[[target]]` body, of which only the brackets are sigils - the+ * target stays verbatim, and a bracket the caller already escaped (an odd+ * backslash run before it, e.g. the closing `]` of `[[a\]]`) is data the+ * same rule the span's opening pair was held to, and is left alone. Each+ * bracket's run is read against the span as detected, so the backslashes+ * this pass inserts never make a later bracket look escaped.+ */+function escapeSigils(span: string, kind: MarkdownStructureKind): string {+ if (kind !== MARKDOWN_STRUCTURE_KIND.wikilink) {+ return [...span].map((ch) => `\\${ch}`).join("");+ }+ let out = "";+ for (let i = 0; i < span.length; i++) {+ const ch = span[i]!;+ if ((ch === "[" || ch === "]") && !precededByOddBackslashRun(span, i)) out += `\\${ch}`;+ else out += ch;+ }+ return out;+}++function escapeRound(+ context: string,+ text: string,+): { text: string; kinds: ReadonlyArray<MarkdownStructureKind> } | null {+ // Detection runs over the exact bytes the page's scanners see before+ // `text`; only spans reaching past the context are this call's business+ // (see {@link NeutralizeMarkdownOptions.precedingContext}).+ const stitched = context + text;+ const matches = detectMarkdownStructure(stitched).filter((m) => m.end > context.length);+ if (matches.length === 0) return null;+ let out = "";+ let last = context.length;+ const kinds = new Set<MarkdownStructureKind>();+ for (const m of matches) {+ const start = Math.max(m.start, context.length);+ if (start < last) continue; // by construction disjoint; a guard, not a contract+ out += text.slice(last - context.length, start - context.length);+ out += escapeSigils(stitched.slice(start, m.end), m.kind);+ last = m.end;+ kinds.add(m.kind);+ }+ out += text.slice(last - context.length);+ return { text: out, kinds: [...kinds].toSorted() };+}++/** What {@link neutralizeMarkdown} returns. */+export interface NeutralizedMarkdown {+ /** The text with planted structure escaped; byte-identical input when `changed` is false. */+ readonly text: string;+ /** Whether any structure was found and escaped, or line separators were rewritten. */+ readonly changed: boolean;+ /**+ * The families that were neutralized plus the `line-break` token when+ * unusual line separators were folded, sorted, unique; empty when+ * unchanged.+ */+ readonly kinds: ReadonlyArray<MarkdownStructureKind>;+}++const UNCHANGED: NeutralizedMarkdown = Object.freeze({+ text: "",+ changed: false,+ kinds: Object.freeze([]),+});++/** Optional inputs of {@link neutralizeMarkdown}. */+export interface NeutralizeMarkdownOptions {+ /**+ * The bytes rendered before `text` on the same page, verbatim: an+ * already-neutralized caller half plus whatever renderer-authored+ * separator and heading the writer placed between the halves (the+ * capture seam passes the neutralized body, the blank-line separator+ * and its own `## Guidance` heading).+ *+ * The seam needs this because a rendered page is ONE text to every+ * scanner: a fence the preceding half opens and `text`'s own bytes close+ * (or leave open) has combined-page meaning that neither half's+ * standalone scan can see - the split-fence hole, where a planted marker+ * live on the combined page scanned clean in both halves. The three+ * fence models the families answer to also disagree about what a fence+ * even is, and the boundary state differs per model in ways a boolean+ * cannot carry (an unterminated fence masks the rest of the page for the+ * marker scanner while fencing nothing for the section readers unless a+ * later fence closes it). So no state is summarized: detection runs over+ * `precedingContext + text` - the exact bytes the page's scanners see+ * ahead of `text` - and only spans reaching past the context are+ * escaped, which makes the half's verdict agree with the combined page's+ * in both directions.+ *+ * Skipping the context's own rows is safe by construction: caller+ * context is the output of an earlier neutralize call, whose detection+ * is empty (the fixpoint exit), and renderer-authored rows are the+ * writer's, never this call's business. No span can straddle the+ * boundary when the context carries the writer heading - the wikilink+ * target grammar stops at its `#`, and every other family is+ * line-anchored - so each escaped span lies wholly in `text`; a custom+ * context that let one straddle would have only its `text`-side sigils+ * escaped and fail closed at the fixpoint bound rather than ship a+ * half-escaped span.+ */+ readonly precedingContext?: string;+}++/**+ * Escape the structure-bearing markdown in third-party text.+ *+ * Unusual line separators (a lone CR, NEL, U+2028, U+2029 - and CRLF) are+ * folded to `\n` first and the fold is recorded as the `line-break` kind:+ * the line-grammar consumers these families answer to disagree about what+ * ends a line, and the fold removes the disagreement before detection. The+ * gate puts every call under `enforce`, so the other two modes stay+ * byte-identical by never reaching this function.+ *+ * Returns the input unchanged - `changed: false`, identical bytes, zero+ * added bytes - when nothing was found to normalize or escape, which is+ * the shape of the overwhelming majority of caller text. When structure+ * was found, each detected span's sigils are backslash-escaped (see the+ * module docblock for the doctrine) and {@link kinds} names every family+ * that was neutralized (plus `line-break` when separators were folded),+ * for the seams' conditional provenance key.+ *+ * The walk is bounded by {@link NEUTRALIZE_FIXPOINT_STEPS} and FAILS+ * CLOSED: a bound exhausted with live structure still detected throws+ * {@link MarkdownNeutralizeFixpointError} rather than returning the exact+ * bytes this module exists to neutralize (see+ * {@link neutralizeMarkdownWithBound}).+ */+export function neutralizeMarkdown(+ text: string,+ options: NeutralizeMarkdownOptions = {},+): NeutralizedMarkdown {+ return neutralizeMarkdownWithBound(text, NEUTRALIZE_FIXPOINT_STEPS, options);+}++/**+ * {@link neutralizeMarkdown} with the fixpoint bound made explicit -+ * `maxRounds` is the highest step index the detect-and-escape loop may+ * reach, so `0` still runs the one round that decides "nothing to do"+ * versus "escape once". Exported as the seam that lets tests force the+ * bound low (the production bound is a safety net that honest input+ * cannot reach); callers in the vault lanes use+ * {@link neutralizeMarkdown} and its settled bound.+ *+ * The post-condition is the doctrine's exit condition: the returned text+ * no longer matches {@link detectMarkdownStructure} on the spans that+ * reach past {@link NeutralizeMarkdownOptions.precedingContext} (the+ * context's own rows are skipped by construction, see there). If the+ * bound runs out with detection still finding such spans, the walk did+ * not converge and returning `changed: true` would ship live structure as+ * if it were neutralized - so the refusal is thrown, by name+ * ({@link MarkdownNeutralizeFixpointError}), and the caller's write dies+ * before any bytes are persisted.+ */+export function neutralizeMarkdownWithBound(+ text: string,+ maxRounds: number,+ options: NeutralizeMarkdownOptions = {},+): NeutralizedMarkdown {+ const context = options.precedingContext ?? "";+ // Unusual line separators fold to `\n` before any detection: the+ // line-grammar consumers the families answer to disagree about what ends+ // a line, and the fold puts `text` on the `\n`-only view every detector+ // here scans. The context is prior neutralizer output (see+ // {@link NeutralizeMarkdownOptions.precedingContext}), so it is already+ // folded and needs no second pass.+ const folded = normalizeLineBreaks(text);+ let current = folded.text;+ let kinds = new Set<MarkdownStructureKind>();+ if (folded.changed) kinds.add(MARKDOWN_STRUCTURE_KIND.lineBreak);+ for (let step = 0; step <= maxRounds; step++) {+ const round = escapeRound(context, current);+ if (round === null) break;+ current = round.text;+ for (const kind of round.kinds) kinds.add(kind);+ }+ if (kinds.size === 0) {+ return { text, changed: false, kinds: UNCHANGED.kinds };+ }+ const remaining = detectMarkdownStructure(context + current).filter(+ (m) => m.end > context.length,+ );+ if (remaining.length > 0) {+ throw new MarkdownNeutralizeFixpointError(+ `markdown neutralization did not reach its fixpoint within ` ++ `${maxRounds + 1} detect-and-escape round(s): ` ++ `${remaining.length} planted structure span(s) would remain in the output`,+ );+ }+ return Object.freeze({+ text: current,+ changed: true,+ kinds: Object.freeze([...kinds].toSorted()),+ });+}++/**+ * Refusal raised when {@link neutralizeMarkdown}'s fixpoint bound ran out+ * with live structure still detected - the fail-closed posture for the+ * safety net honest input never reaches (see the doctrine block: the exit+ * condition IS an empty detection, so anything else is a refusal, never a+ * silently under-neutralized write).+ */+export class MarkdownNeutralizeFixpointError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "MarkdownNeutralizeFixpointError";+ }+}++// ----- The provenance record ------------------------------------------------++/**+ * Frontmatter key recording the structure families an enforce-mode write+ * neutralized (and the `line-break` rewrite, when separators were folded).+ * A page carrying it says "these bytes are not what the caller sent" - the+ * audit trail for the one mode that edits content - and a write that+ * changed nothing adds nothing, keeping the untouched shape byte-identical+ * to before the gate existed.+ */+export const MARKDOWN_NEUTRALIZED_FRONTMATTER_KEY = "neutralized_markers";++/**+ * The frontmatter fragment a seam merges when neutralization changed+ * bytes: the key naming the neutralized kinds, sorted. An empty kind set+ * adds NOTHING - the `untrustedSourceFrontmatter` conditional-spread+ * precedent, so an unchanged body gains zero bytes.+ */+export function neutralizedMarkersFrontmatter(+ kinds: ReadonlyArray<MarkdownStructureKind>,+): FrontmatterMap {+ return kinds.length === 0 ? {} : { [MARKDOWN_NEUTRALIZED_FRONTMATTER_KEY]: [...kinds] };+}++// ----- The gate -------------------------------------------------------------++/**+ * The resolved posture of the write-time neutralization gate:+ * - `off` - the seams never invoke the neutralizer; every write+ * stays byte-identical to a build without this module,+ * - `shadow` - byte-identical to `off` at the seams. Shadow has no+ * work to do there: the doctor's planted-rows audit+ * recomputes the would-be rows from the vault's bytes on+ * its own and reads this mode only for its wording, so a+ * seam call under shadow would compute an answer nobody+ * consumes,+ * - `enforce` - the seams write neutralized bytes.+ */+export const MARKDOWN_NEUTRALIZE_MODE = Object.freeze({+ off: "off",+ shadow: "shadow",+ enforce: "enforce",+} as const);++export type MarkdownNeutralizeMode =+ (typeof MARKDOWN_NEUTRALIZE_MODE)[keyof typeof MARKDOWN_NEUTRALIZE_MODE];++/** Environment variable for the markdown neutralization gate mode. */+export const MARKDOWN_NEUTRALIZE_MODE_ENV = "OPEN_SECOND_BRAIN_MARKDOWN_NEUTRALIZE_MODE";++/** Machine-config key for the markdown neutralization gate mode. */+export const MARKDOWN_NEUTRALIZE_MODE_CONFIG = "markdown_neutralize_mode";++/** True when `value` is one of the three mode tokens. */+export function isMarkdownNeutralizeMode(value: string): value is MarkdownNeutralizeMode {+ return (Object.values(MARKDOWN_NEUTRALIZE_MODE) as string[]).includes(value);+}++/** Refusal raised for a gate mode value that is not in the vocabulary. */+export class MarkdownNeutralizeModeError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "MarkdownNeutralizeModeError";+ }+}++/**+ * Resolve the gate's mode: an explicit mode key wins (env over machine+ * config; an invalid value is a misconfiguration refused with a+ * {@link MarkdownNeutralizeModeError} naming the key actually in force -+ * never silently defaulted); with neither set the default is `off`, the+ * posture every write had before the gate existed. The+ * `resolveSearchTrustGateMode` shape minus the legacy boolean: this gate+ * never had one. Reads only its arguments.+ */+export function resolveMarkdownNeutralizeMode(input: {+ readonly env?: NodeJS.ProcessEnv;+ readonly config?: Readonly<Record<string, string>>;+}): MarkdownNeutralizeMode {+ const env = input.env ?? {};+ const config = input.config ?? {};+ const raw = envOrConfig(+ env,+ config,+ MARKDOWN_NEUTRALIZE_MODE_ENV,+ MARKDOWN_NEUTRALIZE_MODE_CONFIG,+ );+ if (raw !== null) {+ if (isMarkdownNeutralizeMode(raw)) return raw;+ const inForce = env[MARKDOWN_NEUTRALIZE_MODE_ENV]+ ? MARKDOWN_NEUTRALIZE_MODE_ENV+ : MARKDOWN_NEUTRALIZE_MODE_CONFIG;+ throw new MarkdownNeutralizeModeError(+ `${inForce} must be 'off', 'shadow' or 'enforce', got '${raw}'`,+ );+ }+ return MARKDOWN_NEUTRALIZE_MODE.off;+}++/**+ * Resolve the gate's mode the way the write seams do: the live process+ * env over the machine config at its default discovery path. The one+ * impure wrapper, so the capture and ingest seams cannot drift about+ * where the inputs come from; tests drive the pure+ * {@link resolveMarkdownNeutralizeMode} instead.+ */+export function resolveMarkdownNeutralizeModeForProcess(): MarkdownNeutralizeMode {+ return resolveMarkdownNeutralizeMode({ env: process.env, config: discoverConfig().data });+}diff --git a/src/core/brain/trust/instruction-file-ceiling.ts b/src/core/brain/trust/instruction-file-ceiling.tsindex 9af39a4e..18b23c07 100644--- a/src/core/brain/trust/instruction-file-ceiling.ts+++ b/src/core/brain/trust/instruction-file-ceiling.ts@@ -12,6 +12,23 @@* existence, not by pattern. Files that are not present return no* warning. Empty files return no warning either (zero is not above* any non-negative ceiling).+ *+ * This is an EXISTENCE loop, not a precedence order (t_00b617b6 sweep):+ * it asks which of the known instruction files exist and how long each+ * runs, and the order here (CLAUDE.md first) is only warning reporting+ * order - no host is claimed to read these in this sequence. The+ * reading-order question, which file an operative host actually reads,+ * belongs to `HOST_INSTRUCTION_PRECEDENCE` beside `AGENT_INSTRUCTION_FILES`+ * in `src/core/brain/writeback-contract.ts`. The tree carries exactly the+ * three instruction-file lists (this existence loop, the write-back+ * contract audit's candidate list, and `ROOT_INSTRUCTION_FILES` in+ * `src/core/brain/doctor/removed-tool-checks.ts`) plus that one precedence+ * table referencing them; they cross-reference instead of unifying, so no+ * fourth divergent list appears. Open question, recorded rather than+ * resolved: whether gemini-cli reads `GEMINI.md` at all is name-implied+ * only (see the precedence table's docblock), and this list includes it+ * where the removed-tool sweep's list omits it - possibly deliberate,+ * to be answered behaviorally as a follow-up, never by a silent merge.*/import { existsSync, readFileSync, statSync } from "node:fs";diff --git a/src/core/brain/trust/operator-summary.ts b/src/core/brain/trust/operator-summary.tsindex 6b0bce90..6253a151 100644--- a/src/core/brain/trust/operator-summary.ts+++ b/src/core/brain/trust/operator-summary.ts@@ -120,6 +120,16 @@ export interface BuildOperatorSummaryOptions {* action is ranked.*/readonly keepAction?: (action: ActionItem) => boolean;+ /**+ * Whether the caller may see an artifact reference - a page id, a+ * vault-relative path, or a wikilink-spelled one. Threaded into the+ * maintenance collector so it applies to the candidate inputs BEFORE+ * the scorer caps: a hidden top-ranked action takes no slot a visible+ * one could fill, and a dedup count excludes hidden secondaries.+ * Omitted, every candidate is ranked. `keepAction` stays as the+ * per-row filter beside it.+ */+ readonly visibleRef?: (ref: string | null | undefined) => boolean;/*** Whether the caller may see a verification-delta entry. The entries* and their summary counts - and the trust verdict over them - are@@ -157,6 +167,7 @@ export function buildOperatorSummary(opts.keepAction,collectErrors,opts.readable !== undefined,+ opts.visibleRef,);const trust = computeTrustVerdict({@@ -349,6 +360,7 @@ function safeTopActions(keepAction: BuildOperatorSummaryOptions["keepAction"],collectErrors: { scan: MaintenanceCollectSignal; message: string }[],restricted: boolean,+ visibleRef?: BuildOperatorSummaryOptions["visibleRef"],): ReadonlyArray<ActionItem> {try {const all = collectMaintenanceActions(vault, {@@ -358,6 +370,11 @@ function safeTopActions(const shown = restricted ? closedCollectError(e) : e;collectErrors.push({ scan: shown.signal, message: shown.message });},+ // Candidate-level visibility, before the scorer caps: the same+ // predicate brain_doctor's suggested_actions and the digest's+ // actions ask, so the sinks cannot disagree about what a scoped+ // caller is shown.+ ...(visibleRef !== undefined ? { visible: visibleRef } : {}),});const kept = keepAction === undefined ? all : all.filter(keepAction);return Object.freeze(kept.slice(0, Math.max(0, topN)));diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.tsindex 1bee9962..7643b3c5 100644--- a/src/core/brain/wikilink.ts+++ b/src/core/brain/wikilink.ts@@ -79,6 +79,48 @@ export const ANCHORED_WIKILINK_RE = /^\[\[([^\]]+)\]\]/;/** Whole-string wikilink form; body in one capture. */export const EXACT_WIKILINK_RE = /^\[\[([^\]]+)\]\]$/;+/**+ * Whether the character at `index` is preceded by an ODD run of+ * backslashes - the CommonMark shape of "already escaped by the author":+ * `\[` renders as a literal `[`, so a sigil behind an odd run is data the+ * caller already escaped, never structure. The one rule both halves of the+ * wikilink family read: the neutralizer's detector skips such sigils (and+ * never re-escapes them), and every link reader treats the bracket behind+ * one as inert text.+ *+ * Pure and linear in the run length. Shared from here rather than copied+ * so the detector's skip and the readers' skip cannot drift into two+ * grammars.+ */+export function precededByOddBackslashRun(s: string, index: number): boolean {+ let n = 0;+ let i = index - 1;+ while (i >= 0 && s[i] === "\\") {+ n++;+ i--;+ }+ return n % 2 === 1;+}++/**+ * Whether the `[[...]]` regex match spanning `[start, end)` in `text`+ * opens AND closes on live brackets: an opening or closing bracket+ * preceded by an odd backslash run is escaped data, and opens or closes+ * no link. `end - 2` must be the first `]` of the match's closing `]]`,+ * which every pattern in this module's family guarantees.+ *+ * The link readers apply this to each of their matches so they agree with+ * the neutralizer's detector by construction: a span the detector leaves+ * (an escaped `[[`) extracts as nothing, and a span it escapes can never+ * leave extractable structure behind. `text` is whatever string the+ * reader ran its regex over - code-masked or raw - so the run check reads+ * the same bytes the match did.+ */+export function isLiveWikilinkSpan(text: string, start: number, end: number): boolean {+ if (precededByOddBackslashRun(text, start)) return false;+ return !precededByOddBackslashRun(text, end - 2);+}+/** The two characters a fence is built from. */const BACKTICK = "`";const TILDE = "~";diff --git a/src/core/brain/writeback-contract.ts b/src/core/brain/writeback-contract.tsindex 17da6487..f0b8c6ca 100644--- a/src/core/brain/writeback-contract.ts+++ b/src/core/brain/writeback-contract.ts@@ -40,6 +40,31 @@* of scope: a check that silently reads through a link would audit a file* the agent instruction surface does not contain.*+ * Shadowing (t_00b617b6): the candidates are audited in isolation, but a+ * host reads exactly ONE of them - its entry in+ * {@link HOST_INSTRUCTION_PRECEDENCE}. A workspace where the file a host+ * reads carries no managed block while another candidate carries it is+ * shadowed: the operative host never sees the contract no matter how+ * conforming the other file is. {@link resolveShadowedInstructionContracts}+ * resolves that from the audit rows alone - pure, no I/O, no writes - and+ * the doctor-readiness probe grades each triple as a `fail`.+ *+ * One exception keeps the resolution honest about what a host actually+ * sees: a file whose `@` import line names the contract file renders+ * it - managed block included - into the surface the host reads. Claude+ * Code's memory-import syntax is an `@` at a word boundary followed by a+ * path - mid-line and list-item included - Gemini CLI documents the+ * `@./file.md` spelling, and a CLAUDE.md that only says `@AGENTS.md`+ * beside a conforming AGENTS.md is the common real setup; claiming a+ * shadow there fails `o2b doctor --readiness` for a workspace whose+ * operative host sees the gate. {@link auditWritebackContractFile}+ * therefore records the workspace-relative paths such lines reference+ * ({@link referencedImportPaths}, matched over a code-masked view -+ * imports inside code spans or fences are not imports - with `~/`,+ * absolute and workspace-escaping paths refused), and the resolver skips+ * the shadow triple when the preferred file imports a path that resolves+ * to the contract file.+ ** Findings are the closed {@link WRITEBACK_CONTRACT_FINDING} vocabulary:* `conforming`, `malformed-block`, `missing-clauses` (a block is present* and was measured - pass/fail material), `missing-block` (the file@@ -50,7 +75,7 @@*/import { lstatSync, readFileSync } from "node:fs";-import { join } from "node:path";+import { basename, dirname, join, resolve } from "node:path";import {DEFAULT_BEGIN_MARKER,@@ -59,6 +84,7 @@ import {hasManagedBlock,} from "../install/managed-block.ts";import { MARKER_WRITEBACK_GUARDRAIL } from "./marker-writeback.ts";+import { maskCodeRegions } from "./wikilink.ts";// ----- Constants ------------------------------------------------------------@@ -75,6 +101,50 @@ export const AGENT_INSTRUCTION_FILES: ReadonlyArray<string> = Object.freeze(["GEMINI.md",]);+/**+ * Host family to the ordered agent-instruction files the host reads at a+ * workspace root, first existing entry wins per host (t_00b617b6). This is+ * the PRECEDENCE table - which file an operative host actually reads - and+ * is deliberately a different shape from {@link AGENT_INSTRUCTION_FILES},+ * which is the existence-loop list this audit walks. The installer lane+ * (sibling card t_af5e252f) is expected to share this definition, which is+ * why each value is an ordered list even where the repo today names only+ * one file per host.+ *+ * Evidence, entry by entry:+ *+ * - `claude-code` reads `CLAUDE.md` - REPO-CITED,+ * `docs/cross-project-pointer.md:15`.+ * - `codex`, `cursor`, `aider` read `AGENTS.md` - REPO-CITED,+ * `docs/cross-project-pointer.md:16-17` ("Codex, Cursor, Aider, and+ * other tools that follow the `agents.md` convention").+ * - `opencode` reads `AGENTS.md` - REPO-CITED,+ * `docs/brainstorm/opencode-native-integration/variants.md` ("opencode+ * reads AGENTS.md natively").+ * - `gemini-cli` reads `GEMINI.md` - NAME-IMPLIED ONLY. No repo document+ * states it (the cross-project pointer predates the Gemini entry), and+ * upstream `context.fileName` can rename the surface. Recorded as the+ * open question the instruction-file-ceiling and removed-tool-sweep+ * docblocks carry; the finding vocabulary stays honest because a+ * shadow is claimed only from files this tree actually audited.+ *+ * There is no claude-code INSTALL target (the adapters write MCP configs+ * only), so "which host is operative here" cannot be derived from an+ * install manifest - detection keys on which candidate files co-exist plus+ * this table, never on manifests.+ */+export const HOST_INSTRUCTION_PRECEDENCE = Object.freeze({+ "claude-code": Object.freeze(["CLAUDE.md"]),+ codex: Object.freeze(["AGENTS.md"]),+ cursor: Object.freeze(["AGENTS.md"]),+ opencode: Object.freeze(["AGENTS.md"]),+ aider: Object.freeze(["AGENTS.md"]),+ "gemini-cli": Object.freeze(["GEMINI.md"]),+} as const);++/** Closed union over {@link HOST_INSTRUCTION_PRECEDENCE} keys. */+export type HostInstructionName = keyof typeof HOST_INSTRUCTION_PRECEDENCE;+/*** Recovery clause an audit carries when the block is missing or broken.* It names the surface to add and the markers that delimit it; nothing@@ -149,6 +219,15 @@ export interface WritebackContractFileAudit {readonly detail: string;/** Labels of the unmet contract clauses; empty unless `missing-clauses`. */readonly missing: ReadonlyArray<string>;+ /**+ * Workspace-relative import paths the file's `@`-style import lines+ * reference, in first-appearance order, deduplicated (see+ * {@link referencedImportPaths} for exactly what is matched and what+ * is refused). Empty unless the file was actually read: the refused+ * findings (`absent`, `symlink`, `unreadable`) measured no content, so+ * they claim no imports.+ */+ readonly imports: ReadonlyArray<string>;}// ----- Pure contract --------------------------------------------------------@@ -188,6 +267,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileAfinding: WRITEBACK_CONTRACT_FINDING.absent,detail: `${path} does not exist - nothing installed is not a contract violation`,missing: [],+ imports: [],};}return {@@ -195,6 +275,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileAfinding: WRITEBACK_CONTRACT_FINDING.unreadable,detail: `${path} could not be stat'ed: ${reason(err)}`,missing: [],+ imports: [],};}if (stat.isSymbolicLink()) {@@ -205,6 +286,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileA`${path} is a symbolic link - the audit refuses to read through symlinks, ` +"so the contract is unmeasured",missing: [],+ imports: [],};}let content: string;@@ -216,8 +298,10 @@ export function auditWritebackContractFile(path: string): WritebackContractFileAfinding: WRITEBACK_CONTRACT_FINDING.unreadable,detail: `${path} could not be read: ${reason(err)}`,missing: [],+ imports: [],};}+ const imports = referencedImportPaths(content);const body = hasManagedBlock(content) ? extractManagedBlock(content) : null;if (body === null) {if (!carriesMarkerLine(content)) {@@ -229,6 +313,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileA`managed block is not installed, so the write gate is not graded; ` +WRITEBACK_CONTRACT_RECOVERY,missing: [],+ imports,};}// A marker is there but not as one ordered pair (a lone, repeated or@@ -241,6 +326,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileA`${path} carries an Open Second Brain managed-block marker but no well-formed ` +`block - broken same-turn atomic-fact write gate; ${WRITEBACK_CONTRACT_RECOVERY}`,missing: [],+ imports,};}const missing = missingWritebackGateClauses(body);@@ -252,6 +338,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileA`${path} managed block is missing ${missing.join(", ")} - incomplete ` +`same-turn atomic-fact write gate; ${WRITEBACK_CONTRACT_RECOVERY}`,missing,+ imports,};}return {@@ -261,6 +348,7 @@ export function auditWritebackContractFile(path: string): WritebackContractFileA`${path} carries the managed block and the same-turn atomic-fact write gate ` +`(${WRITEBACK_CONTRACT_REQUIREMENTS.length} clauses verified)`,missing: [],+ imports,};}@@ -272,6 +360,80 @@ function carriesMarkerLine(content: string): boolean {.some((line) => line === DEFAULT_BEGIN_MARKER || line === DEFAULT_END_MARKER);}+/**+ * The workspace-relative import paths `content`'s `@`-style import lines+ * reference - the host memory-import shapes this tree implements, matched+ * over a code-masked view of the text:+ *+ * - code regions (inline spans and fenced blocks, `maskCodeRegions`)+ * are masked with a length-preserving fill BEFORE matching: no host+ * evaluates an import inside code, so a fenced `@AGENTS.md` renders+ * as literal text and must record nothing;+ * - the `@` must sit at a word boundary but ANYWHERE on the line -+ * Claude Code accepts mid-line and list-item imports and Gemini CLI+ * documents `@./file.md`, so a line-start-only basename match would+ * false-fail the documented spellings; an `@` preceded by a word+ * character (email) or another `@` is not an import;+ * - what follows is one path-shaped token (`A-Za-z0-9._~/-`, greedy)+ * ending at whitespace or end of line - `@AGENTS.md.bak` records+ * `AGENTS.md.bak` (never equal to a candidate path), and+ * `@docs/AGENTS.md` records `docs/AGENTS.md` (a different workspace+ * file than a root candidate);+ * - a leading `./` is stripped (`@./AGENTS.md` names the same file as+ * `@AGENTS.md`), while `~/...`, absolute paths and any token whose+ * normalized form escapes the workspace (`..` past the root) are+ * REFUSED outright and record nothing: such an import does not+ * render a workspace file, so it excuses nothing - a deliberate,+ * documented refusal kept conservative, because a lookalike that+ * suppressed a shadow would hide a live gate.+ *+ * CRLF line endings are normalized before the per-line match. Pure; used+ * by {@link auditWritebackContractFile} so the shadow resolver can tell a+ * host that renders the contract file through an import from one that+ * never sees it (the resolver resolves each recorded token against the+ * workspace directory and compares to the contract path).+ */++/** The path-shaped token grammar one `@` import may carry. */+const IMPORT_TOKEN_RE = /(?<![A-Za-z0-9@])@([A-Za-z0-9._~/-]+)(?=\s|$)/g;++export function referencedImportPaths(content: string): ReadonlyArray<string> {+ // Length-preserving fill: line structure (and CRLFs) survive intact.+ const masked = maskCodeRegions(content, (region) => " ".repeat(region.length));+ const found: string[] = [];+ for (const line of masked.replace(/\r\n/g, "\n").split("\n")) {+ for (const match of line.matchAll(IMPORT_TOKEN_RE)) {+ const token = normalizeImportToken(match[1]!);+ if (token === null) continue;+ if (!found.includes(token)) found.push(token);+ }+ }+ return Object.freeze(found);+}++/**+ * Normalize one matched import token, or `null` when the reference is+ * refused: leading `./` prefixes are stripped, then any path that leaves+ * the workspace - `~`, an absolute path, or more `..` than the token has+ * directory depth - is refused (documented; see+ * {@link referencedImportPaths}). Pure string math, no I/O.+ */+function normalizeImportToken(token: string): string | null {+ const stripped = token.replace(/^(?:\.\/)+/, "");+ if (stripped.length === 0) return null;+ if (stripped.startsWith("~") || stripped.startsWith("/")) return null;+ let depth = 0;+ for (const segment of stripped.split("/")) {+ if (segment === "..") {+ depth -= 1;+ if (depth < 0) return null; // escapes the workspace+ } else if (segment !== "." && segment !== "") {+ depth += 1;+ }+ }+ return stripped;+}+// ----- Workspace audit ------------------------------------------------------/**@@ -302,3 +464,106 @@ function reason(err: unknown): string {const message = err instanceof Error ? err.message : String(err);return message.replace(/\s+/g, " ").trim();}++// ----- Shadow resolution (t_00b617b6) ---------------------------------------++/**+ * One host reading a contract-free instruction file while another+ * workspace candidate carries the write-back contract: the operative host+ * never sees the gate. Pure data - resolved from audit rows, never from+ * the filesystem.+ */+export interface WritebackContractShadow {+ /** The host family whose preferred file misses the contract. */+ readonly host: HostInstructionName;+ /** Absolute path of the file the host reads, without the managed block. */+ readonly readsPath: string;+ /** Absolute path of another candidate that carries the contract. */+ readonly contractPath: string;+ /**+ * The {@link WRITEBACK_CONTRACT_FINDING} of the contract side - what the+ * advice on such a row depends on: a `conforming` contract file is a+ * contract worth copying, while `malformed-block` or `missing-clauses`+ * means the block the row points at is itself broken.+ */+ readonly contractFinding: WritebackContractFinding;+}++/**+ * The findings that prove a file CARRIES the managed block, in any state:+ * conforming, or installed-then-broken (`malformed-block`,+ * `missing-clauses`). A block that is present is evidence a host is being+ * shadowed away from, whatever its condition; `missing-block` is the one+ * present-file finding that does not carry it, and `absent`, `symlink`,+ * `unreadable` never measured a block at all.+ */+const BLOCK_BEARING_FINDINGS: ReadonlySet<WritebackContractFinding> = new Set([+ WRITEBACK_CONTRACT_FINDING.conforming,+ WRITEBACK_CONTRACT_FINDING.malformedBlock,+ WRITEBACK_CONTRACT_FINDING.missingClauses,+]);++/**+ * Resolve which hosts the workspace's contract placement shadows, PURELY+ * over the per-candidate audits (as {@link auditWorkspaceWritebackContract}+ * produces them): no reads, no lstats, no writes - synthetic audits of+ * paths that exist nowhere resolve exactly like audited ones.+ *+ * A host is shadowed when its preferred candidate - the first entry of its+ * {@link HOST_INSTRUCTION_PRECEDENCE} list that exists - is a file WITHOUT+ * the managed block while another candidate carries the block in any state.+ * A host whose preferred file is absent reads nothing and is not shadowed;+ * a host whose preferred file carries the block is not shadowed even when+ * a peer carries a better-formed one; a symlink or unreadable preferred+ * file is refused evidence, so no shadow is claimed from it (whether a+ * link between candidates should be admitted as evidence is a recorded+ * open question, not decided here). Nor is a host shadowed when its+ * preferred file - however block-free itself - imports the contract file+ * through a `@` line: the host renders that import into the surface it+ * reads, managed block included, so the gate is seen (the audits'+ * `imports` rows, {@link referencedImportPaths}; each recorded token is+ * resolved against the workspace directory and compared to the contract+ * file's path - the documented spellings (`@./AGENTS.md`, mid-line,+ * list item) match, while refused tokens (`~/`, absolute,+ * workspace-escaping) and tokens resolving to some OTHER workspace file+ * excuse nothing). The contract side is+ * the first block-bearing candidate in the audits' given order - the+ * candidate list's priority order for a workspace audit.+ */+export function resolveShadowedInstructionContracts(+ audits: ReadonlyArray<WritebackContractFileAudit>,+): ReadonlyArray<WritebackContractShadow> {+ const contract = audits.find((audit) => BLOCK_BEARING_FINDINGS.has(audit.finding));+ if (contract === undefined) return Object.freeze([]);+ const byName = new Map<string, WritebackContractFileAudit>();+ for (const audit of audits) byName.set(basename(audit.path), audit);+ const shadows: WritebackContractShadow[] = [];+ for (const [host, files] of Object.entries(HOST_INSTRUCTION_PRECEDENCE)) {+ const preferred = files+ .map((name) => byName.get(name))+ .find((audit) => audit !== undefined && audit.finding !== WRITEBACK_CONTRACT_FINDING.absent);+ if (preferred === undefined) continue;+ if (preferred.finding !== WRITEBACK_CONTRACT_FINDING.missingBlock) continue;+ // The host renders its preferred file's `@` imports into the surface+ // it reads: an import RESOLVING to the contract file carries the+ // block through, so there is no shadow to claim. Tokens are resolved+ // against the workspace - the directory the candidates sit in - so+ // `@./AGENTS.md`, a mid-line `@AGENTS.md` and a list-item+ // `- @AGENTS.md` all match, while a refused token (`~/`, absolute,+ // workspace-escaping) or one resolving to another workspace file+ // (`docs/AGENTS.md`) excuses nothing.+ const workspace = dirname(preferred.path);+ if (preferred.imports.some((token) => resolve(workspace, token) === resolve(contract.path))) {+ continue;+ }+ shadows.push(+ Object.freeze({+ host: host as HostInstructionName,+ readsPath: preferred.path,+ contractPath: contract.path,+ contractFinding: contract.finding,+ }),+ );+ }+ return Object.freeze(shadows);+}diff --git a/src/core/doctor-readiness.ts b/src/core/doctor-readiness.tsindex 971de553..db908e3f 100644--- a/src/core/doctor-readiness.ts+++ b/src/core/doctor-readiness.ts@@ -77,7 +77,10 @@* guardrail's own vocabulary, and the symlink refusal - lives in* `brain/writeback-contract.ts`, whose docblock is the settled marker* contract an installed block must satisfy. No repair or installer is- * built here, so a file without the block is skipped, not failed.+ * built here, so a file without the block is skipped, not failed. Since+ * t_00b617b6 the probe also grades placement shadowing: a host reading a+ * contract-free file while another candidate carries the contract is a+ * proved `fail`, because the operative host never sees the gate.*/import { readFileSync } from "node:fs";@@ -120,8 +123,11 @@ import { looksLikeServerEntry } from "./install/adapters/opencode.ts";import {AGENT_INSTRUCTION_FILES,WRITEBACK_CONTRACT_FINDING,+ WRITEBACK_CONTRACT_RECOVERY,auditWorkspaceWritebackContract,+ resolveShadowedInstructionContracts,type WritebackContractFinding,+ type WritebackContractShadow,} from "./brain/writeback-contract.ts";import type { InstallEnv, ManifestEntry } from "./install/types.ts";@@ -1713,6 +1719,33 @@ function statusForContractFinding(finding: WritebackContractFinding): ReadinessS}}+/**+ * The detail of one placement-shadow row (t_00b617b6): the file the host+ * reads, the host by name, the file that carries the contract, and the+ * same read-only recovery clause the per-file rows carry - adding the+ * block to the file the host reads is content-editing, so the probe+ * offers recovery prose, never a command that writes.+ *+ * The contract side's condition is the row's advice, so it is worded from+ * the triple's own finding: a `conforming` contract file "carries the+ * write-back contract" and copying its block is the right move, while any+ * block-bearing-but-broken finding (`malformed-block`, `missing-clauses`)+ * "carries a broken managed block" - following that file verbatim would+ * copy a broken block, and the row must not say otherwise.+ */+function writebackShadowRowDetail(shadow: WritebackContractShadow): string {+ const carries =+ shadow.contractFinding === WRITEBACK_CONTRACT_FINDING.conforming+ ? "carries the write-back contract"+ : "carries a broken managed block";+ return (+ `${shadow.readsPath} is the instruction file the ${shadow.host} host reads, but it ` ++ `carries no Open Second Brain managed block while ${shadow.contractPath} ${carries} - ` ++ `the operative host never sees the same-turn atomic-fact write ` ++ `gate; ${WRITEBACK_CONTRACT_RECOVERY}`+ );+}+/*** Does the vault's workspace agent-instruction file(s) carry the same-turn* atomic-fact memory write gate? Reads the candidates@@ -1738,6 +1771,18 @@ function statusForContractFinding(finding: WritebackContractFinding): ReadinessS* while one conforming file among absent peers passes: the absent* candidates did not participate, and the census in the detail says so* rather than hiding them.+ *+ * Placement shadowing (t_00b617b6) grades beside the per-file rows: a host+ * whose preferred file (`HOST_INSTRUCTION_PRECEDENCE` in+ * `brain/writeback-contract.ts`) carries no managed block while another+ * candidate carries the contract is a proved fault of the surface - the+ * operative host never sees the gate, however conforming the file it does+ * not read is. Each shadow triple becomes one `fail` row keyed by the file+ * the host reads, naming the host, both files and the read-only recovery+ * clause; shadow-free multi-file workspaces and absent-only workspaces+ * grade exactly as before. Shadow rows enter the census and the worst-of+ * aggregate like any other row, which is why the fail header counts+ * findings, not files.*/export async function probeWritebackContract(opts: ReadinessOptions): Promise<ReadinessVerdict> {const workspace = opts.vault;@@ -1747,10 +1792,16 @@ export async function probeWritebackContract(opts: ReadinessOptions): Promise<Restatus: statusForContractFinding(audit.finding),detail: audit.detail,}));- const counts = countByStatus(rows.map((row) => row.status));+ const shadowRows = resolveShadowedInstructionContracts(audits).map((shadow) => ({+ path: shadow.readsPath,+ status: READINESS_STATUS.fail,+ detail: writebackShadowRowDetail(shadow),+ }));+ const graded = [...rows, ...shadowRows];+ const counts = countByStatus(graded.map((row) => row.status));// Worst rows lead the detail; toSorted is stable, so within one bucket// the candidate list's priority order stands.- const ordered = rows.toSorted((a, b) => readinessRank(a.status) - readinessRank(b.status));+ const ordered = graded.toSorted((a, b) => readinessRank(a.status) - readinessRank(b.status));const rowText = ordered.map((row) => `${row.path}: ${row.detail}`).join("; ");const census =`(${counts.pass} pass, ${counts.fail} fail, ` +@@ -1758,7 +1809,7 @@ export async function probeWritebackContract(opts: ReadinessOptions): Promise<Reif (counts.fail > 0) {return {status: READINESS_STATUS.fail,- detail: `${counts.fail} agent-instruction file(s) fail the write-back contract ${census}: ${rowText}`,+ detail: `${counts.fail} agent-instruction finding(s) fail the write-back contract ${census}: ${rowText}`,};}if (counts.unknown > 0) {diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.tsindex 05703961..fa1f1f18 100644--- a/src/core/state/surfaces.ts+++ b/src/core/state/surfaces.ts@@ -1202,11 +1202,18 @@ export const STATE_SURFACE_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new M"nothing",],[- "src/cli/brain/verbs/bench.ts",- "its `.open-second-brain/bench-runs` default is resolved against the WORKING DIRECTORY, not " +- "against a vault, so it is not an in-vault surface at all. It is already enumerated as the " +- "`bench_run_artifacts` row of `OUT_OF_VAULT_STATE`, which is the population that owns " +- "locations outside the vault",+ "src/core/brain/gitignore-guard.ts",+ "the git-side guard seeder (t_206562ae): it writes the vault-root `.gitignore`, which " ++ "sits OUTSIDE the store directory, and only names the directory inside the ignore rule " ++ "(`/.open-second-brain/`). A rule telling git to look away creates no state in the " ++ "directory it covers, and the file it writes is the operator's own",+ ],+ [+ "src/core/brain/doctor/git-tracked-state-check.ts",+ "the doctor probe asks git ABOUT the store directory (`git ls-files` for tracking, " ++ "`git check-ignore` for the guard) and writes nothing anywhere. A check that measures " ++ "git's view of the directory creates no state in it - the finding it emits names git's " ++ "own `rm --cached` as the remedy",],]);diff --git a/src/core/vault.ts b/src/core/vault.tsindex da29696e..99f0da4f 100644--- a/src/core/vault.ts+++ b/src/core/vault.ts@@ -50,7 +50,7 @@ import { createHash } from "node:crypto";import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";import { dirname, join, relative } from "node:path";-import { WIKILINK_TARGET_RE, maskCodeRegions } from "./brain/wikilink.ts";+import { WIKILINK_TARGET_RE, isLiveWikilinkSpan, maskCodeRegions } from "./brain/wikilink.ts";import {FileAlreadyExistsError,atomicCreateFileSyncExclusive,@@ -569,13 +569,17 @@ export function slugify(value: string): string {/*** Extract unique `[[wikilink]]` targets from Markdown content. Skips media- * file extensions and links inside fenced or inline code blocks.+ * file extensions, links inside fenced or inline code blocks, and links+ * whose opening or closing bracket is backslash-escaped (an odd backslash+ * run before it - the same rule the neutralizer's detector applies, so a+ * `\[[literal]]` span is data here too and never joins the link graph).*/export function extractWikilinks(content: string): string[] {const masked = maskCodeRegions(content, () => " ");const seen = new Set<string>();const result: string[] = [];for (const m of masked.matchAll(WIKILINK_TARGET_RE)) {+ if (!isLiveWikilinkSpan(masked, m.index!, m.index! + m[0].length)) continue;const target = m[1]!;const dot = target.lastIndexOf(".");const ext = dot >= 0 ? target.slice(dot).toLowerCase() : "";diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex c45cc629..d78b4475 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -567,6 +567,7 @@ async function toolBrainMaintenance(export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_labels",+ kind: "write",description:"Controlled-vocabulary labels from the schema pack: assign (fail-closed, one value per dimension; labels frontmatter plus a label entity), remove, show. suggest: read-only advisory suggestions from the optional labels decision-model use (available: false when off); it never assigns.",inputSchema: {@@ -595,6 +596,7 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_tiers",+ kind: "write",description:"Frontmatter tier guard: check lists staged identity-field hand-edits the index post-pass detected, restore (apply=true required) writes the expected value back into the file, accept adopts the hand-edit as the new snapshot baseline. Nothing auto-resolves.",inputSchema: {@@ -617,6 +619,7 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_secrets",+ kind: "write",description:"Capability-gated secret custody, agent-facing subset: list stored secret metadata (never values) or run an allowlisted command with the secret injected as its declared env var - output comes back redacted. Storing and removing secrets stays on the operator's CLI (o2b brain secret).",inputSchema: {@@ -639,6 +642,7 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_maintenance",+ kind: "write",description:"Quiet-window, lease-guarded maintenance lane: run executes dream, reindex, bridges, clusters, relink and declared custom:<name> tasks behind window, busy, pressure, capacity and streak gates; status renders lease and journal. Reindex embeds only with config maintenance_embeddings.",inputSchema: {diff --git a/src/mcp/brain/analytics-tools.ts b/src/mcp/brain/analytics-tools.tsindex fdef66f0..874bddf6 100644--- a/src/mcp/brain/analytics-tools.ts+++ b/src/mcp/brain/analytics-tools.ts@@ -328,7 +328,7 @@ async function toolBrainAnalytics(args: Record<string, unknown>,): Promise<unknown> {// attention_flows requires an `operation`; the consolidated surface- // defaults it to the read-only `list` so `{view}` alone is valid.+ // defaults it to `list` so `{view}` alone is valid.const withDefaults = args["view"] === "attention_flows" ? { operation: "list", ...args } : args;return localizeEnvelope(ctx, await dispatchByView(ANALYTICS_VIEW_HANDLERS, ctx, withDefaults));}@@ -336,9 +336,16 @@ async function toolBrainAnalytics(export const ANALYTICS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_analytics",+ // Write-mode-dominant (tool-contract.ts), not "read": every+ // attention_flows operation lists the flow recipes first, and+ // `listAttentionFlows` seeds `Brain/attention-flows/open-loops.md`+ // through `ensureDefaultAttentionFlows` (mkdir + frontmatter write,+ // under the vault-identity write guard) whenever the vault lacks it.+ // A fresh vault therefore gets files written by a "read" view.+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:- "Read-only Brain analytics, one tool for every lens: view=timeline (event history), attention_flows, belief_evolution, concept_synthesis, or dedup (exact-hash ingest dedup trend). Replaces the per-lens analytics tools.",+ "Brain analytics, one tool for every lens: view=timeline (event history), attention_flows (seeds its default recipe when missing), belief_evolution, concept_synthesis, or dedup (exact-hash ingest dedup trend). Replaces the per-lens analytics tools.",inputSchema: {type: "object",properties: {diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.tsindex b1b15a1e..854ce764 100644--- a/src/mcp/brain/brief-tools.ts+++ b/src/mcp/brain/brief-tools.ts@@ -28,16 +28,13 @@ import {} from "../../core/brain/temporal/period-common.ts";import { selectEvents } from "../../core/brain/temporal/select-events.ts";import type { TimelineIndex } from "../../core/brain/temporal/types.ts";-import {- readerRefView,- type ArtifactRef,- type ArtifactRefView,-} from "../../core/brain/artifact-ref-view.ts";+import { type ArtifactRef, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";import { PREF_ID_PREFIX } from "../../core/brain/dream-plan.ts";import { buildTodayDashboard } from "../../core/brain/today-dashboard.ts";import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";import { buildWeeklySynthesis } from "../../core/brain/temporal/weekly-brief.ts";import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";+import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";import { renderDigest, type DigestFormat } from "../../core/brain/digest.ts";import { dream } from "../../core/brain/dream.ts";import {@@ -56,7 +53,7 @@ import { captureReportDelta } from "../../core/brain/report-snapshot.ts";import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";-import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";import { eventAtReach, eventsAtReach, recordRefs, requestRefView } from "./reach-events.ts";import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";@@ -211,9 +208,20 @@ async function toolBrainDigest(// window even when the caller omitted `until`.const effectiveUntil = until ?? new Date();const agentScope = coerceAgentScope(ctx, args, true);- // Below local reach the digest is rendered for this reader: a record it- // cannot read is absent from every row and count.+ // The digest is rendered for this reader whenever any rule is live: a+ // record below the caller's reach, or withheld by the enforced ownership+ // scope, is absent from every row and count. Passing the predicate+ // whenever it would withhold anything - rather than only below local+ // reach - is the view the `osb://digest/latest` resource renders the+ // same caller with, so the agent summary, the backlink counts and the+ // connection health cannot count the events and records those sections+ // beside them already withhold. With no rule live the predicate is+ // absent and the render stays byte-identical to the unfiltered one.const restricted = contextReach(ctx) !== TRANSPORT_REACH.local;+ // The enforced ownership scope (null unless+ // `integrity.owner_scope_delivery` is `fail` with a resolved identity)+ // decides the snapshot boundary below, beside the reach.+ const enforcedScope = resolveOwnerScopeDelivery(ctx.vault, agentScope).enforcedScope;const renderFor = (renderFormat: DigestFormat, readable?: (rel: string) => boolean) =>renderDigest(ctx.vault, {...(since ? { since } : {}),@@ -223,7 +231,7 @@ async function toolBrainDigest(...(agentScope !== undefined ? { agentScope } : {}),...(readable !== undefined ? { readable } : {}),});- const result = renderFor(format, restricted ? readableAtContextReach(ctx) : undefined);+ const result = renderFor(format, readableAtContextReachOrUndefined(ctx));const envelope: Record<string, unknown> = {format,@@ -232,8 +240,12 @@ async function toolBrainDigest(};// The snapshot is the vault's own run-over-run record, diffed over the// digest every record feeds, so a reader below local reach neither- // takes one nor is shown the delta.- if (restricted) return envelope;+ // takes one nor is shown the delta. The same holds for a caller the+ // enforced ownership scope narrows: its render is one owner's slice of+ // the vault, and persisting that slice under the shared date key would+ // hand the next caller a delta whose key paths were computed against+ // it - key paths naming artifact ids that caller was never shown.+ if (restricted || enforcedScope !== null) return envelope;// Snapshot the structured summary, not the rendered string: render// a JSON digest for the snapshot regardless of the caller's format// so the run-over-run diff keys on data.@@ -261,10 +273,19 @@ async function toolBrainDigest(// ----- brain_query ---------------------------------------------------------/**- * The rows of a daily or weekly envelope a reader at this request's- * reach may see, or `null` at local reach, where the envelope is the- * builder's own (the digest precedent: a reader below local reach is- * shown only what it may read, and takes no report snapshot).+ * The rows of a daily or weekly envelope this request may see, or+ * `null` when no rule is live - local reach with the ownership gate off -+ * and the envelope is the builder's own (the digest precedent: a reader+ * below local reach is shown only what it may read, and takes no report+ * snapshot).+ *+ * Two rules are asked, through the one adapter the digest's actions rows+ * use: the enforced ownership rule (`gatedOwnerScopeView`, live only+ * under `integrity.owner_scope_delivery: fail` with a resolved identity)+ * and the request's reach-and-readability view. Local reach no longer+ * short-circuits past the ownership rule - an enforced identity on the+ * operator's own transport is exactly the caller that gate exists to+ * scope, and its envelope was otherwise the builder's unfiltered own.** Status transitions, retirements and contradictions are dropped when a* record they name is withheld. Source pointers are deduplicated@@ -272,15 +293,21 @@ async function toolBrainDigest(* the window's events the reader may see: an artifact cited only by* evidence on a withheld preference is absent. The counts* (`events_by_kind`, `vault_delta`) are recomputed from the same- * selection, so a withheld record moves no count either.+ * selection, so a withheld record moves no count either. Because a live+ * rule means the envelope is one caller's slice, no report snapshot is+ * taken for it - the shared date key must not hold one caller's slice+ * for the next caller's delta to diff against.*/function periodRowsAtReach(ctx: ServerContext,index: TimelineIndex,window: { readonly since: string; readonly until: string },): PeriodRowsView | null {- if (contextReach(ctx) === TRANSPORT_REACH.local) return null;- const refs = readerRefView(ctx.vault, readableAtContextReach(ctx));+ const refs = everyArtifactRefView(+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ requestRefView(ctx),+ );+ if (refs.filtersNothing) return null;const events = eventsAtReach(refs, selectEvents(index, window));return {refs,@@ -350,7 +377,9 @@ async function toolBrainDailyBrief(source_pointers: atReach?.sourcePointers ?? brief.sourcePointers,generated_at: brief.generatedAt,};- // Below local reach no snapshot is taken and no delta reported.+ // When any rule is live - below local reach, or an enforced owner+ // scope - the envelope is this caller's slice: no snapshot is taken+ // under the shared date key and no delta is reported.if (atReach !== null) return envelope;// Dual-output: persist a machine snapshot and report the run-over-run// delta when report snapshots are enabled.@@ -402,7 +431,9 @@ async function toolBrainWeeklySynthesis(source_pointers: atReach?.sourcePointers ?? synth.sourcePointers,generated_at: synth.generatedAt,};- // Below local reach no snapshot is taken and no delta reported.+ // When any rule is live - below local reach, or an enforced owner+ // scope - the envelope is this caller's slice: no snapshot is taken+ // under the shared date key and no delta is reported.if (atReach !== null) return envelope;const delta = captureReportDelta(ctx.vault,@@ -546,6 +577,12 @@ async function toolBrainOperatorSummary(: {keepIssue: (issue: DoctorIssueNaming) => view.row(...doctorIssueRefs(ctx.vault, issue)),keepAction: (action: ActionItem) => view.row(action.target),+ // Candidate-level visibility for the maintenance collector:+ // applied before the scorer caps, so a hidden top-ranked+ // action takes no slot a visible one could fill - the same+ // question brain_doctor's suggested_actions and the digest's+ // actions ask over the same collector output.+ visibleRef: view.visible,keepVerification: (entry: VerificationDeltaEntry) =>view.row(...recordRefs(entry.id), entry.path),}),@@ -638,20 +675,19 @@ const BRIEF_VIEW_HANDLERS: Readonly<});/**- * The views whose builders thread `agent_scope` through to the ownership- * predicate. `agent_scope` is declared once for the whole tool, so the- * other five would ACCEPT the argument and discard it - handing a caller- * who asked to be isolated another owner's preference ids- * (`weekly.retired[].prefId`, `weekly.statusTransitions[].prefId`,- * `operator`'s ranked actions) while believing it was scoped. Silently- * ignoring an argument a tool accepts is this wave's anti-pattern, so the- * views that cannot honour it REFUSE it instead- * (context-integrity-gates, A6).+ * The views that accept an explicit `agent_scope` argument.*- * Threading it through the remaining five is the better end state; it- * needs an ownership predicate inside `weekly-brief`, `monthly-review`,- * `daily-brief`, `operator-summary` and `today-dashboard`, which is a- * change to those builders rather than to this dispatcher.+ * EVERY view in this dispatcher narrows to the caller's server-resolved+ * identity under `integrity.owner_scope_delivery: fail`, whether or not+ * it takes the argument: `morning` and `digest` thread the scope through+ * their builders; `daily` and `weekly` ask the enforced rule per row+ * through `periodRowsAtReach`; `monthly` and `today` through the+ * request's reference view; `operator` through the doctor/action view it+ * composes. The set below therefore answers a narrower question: where+ * the argument itself is accepted. It is declared once for the whole+ * tool, so a view that cannot honour it must not silently discard it -+ * the other five REFUSE it (`context-integrity-gates`, A6) and stay+ * scoped by the identity instead.*/const AGENT_SCOPE_VIEWS: ReadonlySet<string> = new Set(["morning", "digest"]);@@ -672,7 +708,8 @@ async function toolBrainBrief(throw new MCPError(INVALID_PARAMS,`brain_brief view=${view} cannot honour '${AGENT_SCOPE_ARG_NAME}'; ` +- `owner scoping is supported by view=${[...AGENT_SCOPE_VIEWS].join(", view=")}`,+ `an explicit scope is accepted by view=${[...AGENT_SCOPE_VIEWS].join(", view=")}; ` ++ `every view is already scoped by the server-resolved identity`,);}return localizeEnvelope(ctx, await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args, onProgress));@@ -681,9 +718,16 @@ async function toolBrainBrief(export const BRIEF_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_brief",+ // Write-mode-dominant (tool-contract.ts), not "read": view=digest+ // persists the window's structured snapshot under `Brain/reports/`+ // through `captureReportDelta` when report snapshots are enabled, so+ // the next digest run can diff against it. The write is opt-in and+ // skipped for restricted or scope-narrowed callers, but an opt-in+ // durable write still classifies the whole tool `write`.+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:- "Read-only Brain summary, one tool for every window: view=morning, daily, weekly, monthly, operator (maintenance dashboard), digest (activity window), or today (operator dashboard: due obligations, one-off pledges, open loops, recent activity, totals). Replaces the per-window brief tools.",+ "Brain summary, one tool for every window: view=morning, daily, weekly, monthly, operator (maintenance dashboard), digest (activity window + report snapshot), or today (operator dashboard: due obligations, one-off pledges, open loops, recent activity, totals). Replaces the per-window brief tools.",inputSchema: {type: "object",properties: {diff --git a/src/mcp/brain/calendar-tools.ts b/src/mcp/brain/calendar-tools.tsindex 7c8ff5c1..00f1d497 100644--- a/src/mcp/brain/calendar-tools.ts+++ b/src/mcp/brain/calendar-tools.ts@@ -222,6 +222,7 @@ function toolBrainAgenda(export const CALENDAR_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_obligation",+ kind: "write",description:"Recurring obligations under Brain/obligations/ with a deterministic cadence-driven next-due date: add, done (advances next_due one interval), list (optionally overdue-only), show, remove. Cadences: daily/weekly/biweekly/monthly/quarterly/yearly/every-<N>-days.",inputSchema: {@@ -269,6 +270,7 @@ export const CALENDAR_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_agenda",+ kind: "read",description:"Deterministic agenda synthesis over caller-provided calendar events (the Brain never calls a calendar API): overlap conflicts, free focus blocks (optionally clipped to a workday window), and events organised outside the operator's email domain(s). Pure analysis, no vault writes.",inputSchema: {diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.tsindex d9025dc9..5e15f156 100644--- a/src/mcp/brain/context-tools.ts+++ b/src/mcp/brain/context-tools.ts@@ -347,11 +347,16 @@ const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {};/**- * Read-only pull-bootstrap of `Brain/active.md` + the active-preference- * counts. Built for runtimes that have no `SessionStart` hook (Cursor,- * Aider, raw Claude API): one tool call gives the agent the same- * shortcut card the SessionStart-aware runtimes get injected- * automatically.+ * Pull-bootstrap of `Brain/active.md` + the active-preference counts.+ * Built for runtimes that have no `SessionStart` hook (Cursor, Aider,+ * raw Claude API): one tool call gives the agent the same shortcut card+ * the SessionStart-aware runtimes get injected automatically.+ *+ * Not a pure read: the bootstrap path calls `regenerateActive`, which+ * writes `Brain/active.md` whenever the on-disk body is absent or+ * stale, so the tool classifies `write` (write-mode-dominant,+ * `tool-contract.ts`) and the stdio transport never runs two bootstrap+ * calls beside each other on the concurrent read path.** Behaviour matrix:* - Brain/ absent → present:false, zero counts, and content@@ -361,9 +366,9 @@ const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {* such file either).* - Brain/ present, active.md absent → call regenerateActive (idempotent)* and read the regenerated file.- * - Brain/ present, active.md fresh → idempotent regenerate is a no-op- * rewrite; the on-disk body is- * returned verbatim.+ * - Brain/ present, active.md fresh → idempotent regenerate leaves an+ * equal body on disk; the on-disk+ * body is returned verbatim.*/async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {const dirs = brainDirs(ctx.vault);@@ -771,6 +776,7 @@ const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> =export const CONTEXT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_write_session",+ kind: "write",description:"Provider-agnostic Brain write sessions (artifact and decision-panel kinds): open returns a generation prompt, submit validates the text, only clean artifacts commit. Correction loop, retry cap, collision guard, optional operator review. The calling agent generates; the Brain never does.",inputSchema: {@@ -837,6 +843,7 @@ export const CONTEXT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_pinned_context",+ kind: "write",description:"Read, write, append, or clear the transient current-task scratchpad at `Brain/pinned.md`. Use for facts that should survive context rotation but should not become permanent preferences. Pass `operations` to apply an ordered batch atomically (all-or-nothing).",inputSchema: {@@ -880,8 +887,14 @@ export const CONTEXT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_context",+ // Write-mode-dominant (tool-contract.ts), not "read": the bootstrap+ // path calls `regenerateActive`, which writes the shared+ // `Brain/active.md` whenever the body is absent or stale. A read+ // classification would let concurrent session starts regenerate that+ // one shared file beside each other on the stdio read path.+ kind: "write",description:- "Pull the current Brain/active.md body, pinned current-task context, and active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Read-only.",+ "Pull the current Brain/active.md body, pinned current-task context, and active-preference counts. Use at session start when SessionStart hook is unavailable (Cursor, Aider, raw Claude API). Regenerates Brain/active.md when absent or stale.",inputSchema: {type: "object",properties: {},diff --git a/src/mcp/brain/decisions-tools.ts b/src/mcp/brain/decisions-tools.tsindex f0d56933..3f260525 100644--- a/src/mcp/brain/decisions-tools.ts+++ b/src/mcp/brain/decisions-tools.ts@@ -405,6 +405,7 @@ async function toolBrainDecision(export const DECISIONS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Decision tool. record captures a decision note (chosen, assumption, review date); outcome backfills it; rate rates it; show, list, compare and similar read past ones; history reads receipts; recall resurfaces a rated one; open parks a question with its options; resolve picks one; discard closes it.",inputSchema: {diff --git a/src/mcp/brain/derive-tools.ts b/src/mcp/brain/derive-tools.tsindex ab78fd48..8136e12c 100644--- a/src/mcp/brain/derive-tools.ts+++ b/src/mcp/brain/derive-tools.ts@@ -56,6 +56,7 @@ async function toolBrainDeriveFact(export const DERIVE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Commit a derived fact (a conclusion the agent reasoned from premises) as an unconfirmed preference with premise provenance. Supply `slug`, `topic`, `principle`, `premises` (ids), and `level` (deduced/inferred). OSB validates each premise exists. Opt-in: requires guardrails.derived_fact_synthesis.",inputSchema: {diff --git a/src/mcp/brain/design-note-tools.ts b/src/mcp/brain/design-note-tools.tsindex e2925795..17882ba2 100644--- a/src/mcp/brain/design-note-tools.ts+++ b/src/mcp/brain/design-note-tools.ts@@ -82,6 +82,7 @@ async function toolBrainDesignNote(export const DESIGN_NOTE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"One-shot design note; runs no model. Without `note` it grounds the topic in the vault's tensions, decisions and truth projections and returns one needs-llm-step envelope, naming any store the vault holds nothing in. With `note` it commits under Brain/decisions/; not one recommendation refuses.",inputSchema: {diff --git a/src/mcp/brain/distill-tools.ts b/src/mcp/brain/distill-tools.tsindex 6e67a405..1c9bcdfe 100644--- a/src/mcp/brain/distill-tools.ts+++ b/src/mcp/brain/distill-tools.ts@@ -127,6 +127,7 @@ function distillWithQuoteCode(export const DISTILL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",// The guarantee is stated here, in the idiom `brain_intake_entities` uses:// a caller choosing a tool reads this, and a write that quarantines what it// just wrote must say so where the choice is made.diff --git a/src/mcp/brain/entity-tools.ts b/src/mcp/brain/entity-tools.tsindex 3a0e267f..b917e2fd 100644--- a/src/mcp/brain/entity-tools.ts+++ b/src/mcp/brain/entity-tools.ts@@ -125,6 +125,7 @@ async function toolBrainSwitchVault(export const ENTITY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_entity",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Look up (view: get) or list (view: list) canonical entities from the Brain/entities/ registry. Aliases resolve to the canonical record. Read-only; writes go through the o2b CLI.",@@ -159,6 +160,7 @@ export const ENTITY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_switch_vault",+ kind: "write",description:"Activate a named vault profile (from the profiles registry). Updates the active pointer; the change takes effect on the next server launch - the running server keeps its already-resolved vault.",inputSchema: {diff --git a/src/mcp/brain/extract-tools.ts b/src/mcp/brain/extract-tools.tsindex dcbe6f45..94b78797 100644--- a/src/mcp/brain/extract-tools.ts+++ b/src/mcp/brain/extract-tools.ts@@ -166,6 +166,7 @@ async function toolBrainExtractSignals(export const EXTRACT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Mine taste signals from an imported session's USER turns; runs no model. Omit `items` for the plan; with `items` commit, and a barren commit records a tombstone. Barren sessions skip as 'mining_tombstone'; `force` re-mines once. Refuses caps, floors, repeats.",inputSchema: {diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 77e9e44a..c054766b 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -1147,6 +1147,7 @@ async function toolBrainExpire(export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_feedback",+ kind: "write",description:"Record one Brain taste signal in `Brain/inbox/sig-*.md`. With `force_confirmed: true`, create the preference directly (skips the dream trial window).",inputSchema: {@@ -1212,6 +1213,7 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_dream",+ kind: "write",description:"Deterministic learning pass over `Brain/inbox/`. action=run (default) promotes inline; the staged lifecycle persists a reviewable bundle: stage -> validate -> apply (or discard), plus list and retriage. Typically scheduled via cron.",inputSchema: {@@ -1282,6 +1284,7 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_apply_evidence",+ kind: "write",description:"Record whether an active preference was applied, violated, or marked outdated against a freshly-produced durable artifact. Appends one event to `Brain/log/<today>.md`. A single `outdated` event triggers retire on the next dream pass.",inputSchema: {@@ -1324,6 +1327,7 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_note",+ kind: "write",description:"Append one narrative-milestone line (release shipped, PR merged, fact discovered) to today's Brain log under the `note` event kind. Use when neither brain_feedback nor brain_apply_evidence fits.",inputSchema: {@@ -1346,6 +1350,7 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_observed_use",+ kind: "write",description:"Record session-end observed-use verdicts (USED/IGNORED/CONTRADICTED) per injected memory. The host supplies structured verdicts; the kernel stores and aggregates them into the observed-reuse recall-ranking signal (no LLM).",inputSchema: {@@ -1380,6 +1385,7 @@ export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: EXPIRE_TOOL,+ kind: "write",description:"Set, change or clear the expiration_date of one signal or preference, by id. An expired memory is filtered out of default reads and never deleted or moved. Clearing is the explicit word 'none'.",inputSchema: {diff --git a/src/mcp/brain/generation-tools.ts b/src/mcp/brain/generation-tools.tsindex 6bb98854..37b64c57 100644--- a/src/mcp/brain/generation-tools.ts+++ b/src/mcp/brain/generation-tools.ts@@ -225,6 +225,7 @@ function sourceRefArgs(raw: unknown): ReadonlyArray<ContinuitySourceRef> {export const GENERATION_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:"Inbound, opt-in LLM generation tracing; the kernel never calls an LLM. action=record posts a generation's usage for a handoff, gated default-off via enable or generation_trace_enabled, storing prompt_hash + token counts only, never the prompt. action=list/summary read and join to memory paths.",diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.tsindex 9140fe28..4a7d0248 100644--- a/src/mcp/brain/health-tools.ts+++ b/src/mcp/brain/health-tools.ts@@ -224,10 +224,16 @@ async function toolBrainDoctor(// v0.10.15: ranked maintenance actions surfaced as a parallel// signal to errors/warnings. The list is independent of `strict`// because nothing here downgrades the `ok` flag - actions are- // suggestions, not invariant violations.+ // suggestions, not invariant violations. The view's predicate is+ // threaded INTO the collector, so hidden candidates are dropped+ // before the scorer caps: a hidden top-ranked action takes no slot+ // a visible one could fill.suggested_actions: view.keep(- collectMaintenanceActions(ctx.vault, { onError: (e) => collectErrors.push(e) }),+ collectMaintenanceActions(ctx.vault, {+ onError: (e) => collectErrors.push(e),+ visible: view.visible,+ }),(a) => [a.target],).map((a) => ({@@ -440,6 +446,7 @@ async function toolBrainStatus(export const HEALTH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_doctor",+ kind: "write",description:"Validate `Brain/` invariants (status-vs-folder, frontmatter, duplicate ids, ISO, log headers). Read-only by default; `repair` previews safe fixes (WAL gaps, orphaned references) with a per-file diff; `repair`+`apply` applies them as machine consent (`caller-apply` in each fix's event).",inputSchema: {@@ -472,6 +479,7 @@ export const HEALTH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_health",+ kind: "read",description:"Semantic-health report: contradictory confirmed preferences (opposite sign, same subject), recurring concepts with no dedicated preference, stale evidence, and preference-confirmation bursts (batch inflation). Per-domain findings plus a clean/watch/investigate verdict. Read-only.",inputSchema: {@@ -490,6 +498,7 @@ export const HEALTH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_status",+ kind: "read",description:"Unified operator status snapshot: composes doctor, semantic health, hygiene, stale scan, review candidates, active profile, and state-file health. Every problem carries the exact next command to run; a healthy vault reports all-clear. Read-only.",inputSchema: {diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.tsindex b18f9947..e23632a7 100644--- a/src/mcp/brain/hygiene-tools.ts+++ b/src/mcp/brain/hygiene-tools.ts@@ -444,6 +444,7 @@ async function toolBrainHygiene(export const HYGIENE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_hygiene",+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:"Memory hygiene. `scan`: contested truth slots, near-duplicate preferences, stale or orphaned pages, low-usefulness candidates, knowledge resting on url-only sources. `apply`: run selected finding ids. `refresh`: recompile stale pages. `archive_get`: archived source bytes by hash, local only.",diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex a16cab43..7b9e074a 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -783,6 +783,7 @@ async function toolBrainIngestBatchPlan(export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Ingest one text-bearing source into the brain. Supply `source_path` (vault path or URL), a `summary`, the extracted `entities`, and optional `relations`. OSB creates/updates entity pages and a per-source summary page that backlinks the source and lists its connections. Idempotent; no model, no OCR.",inputSchema: {@@ -859,6 +860,7 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: SEARCH_TOOL,+ kind: "read",description:"Find every Brain page derived from one EXACT source file (`source_file`: a vault path or URL): the ingest summary page, session-derived signals, `[[source]]` provenance wikilinks, and preferences folded from those signals. Read-only; each entry flags deletable vs protected mention.",inputSchema: {@@ -882,6 +884,7 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: DELETE_TOOL,+ kind: "write",description:"Remove everything derived from one EXACT source file. DRY-RUN BY DEFAULT: no `confirm` reports the blast radius, deletes nothing. `confirm` deletes derived entries + ingest index artifacts (shared/aggregate pages only reported); originals outside Brain/ only with `include_originals`. Auditable.",inputSchema: {@@ -922,6 +925,7 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: BATCH_PLAN_TOOL,+ kind: "write",description:"Plan a folder ingest into bounded parallel batches. Walks `source_dir` for ingestible files, skips unchanged ones via the content-hash manifest, and packs the new/modified remainder into batches bounded by `max_batch_bytes`/`max_batch_files`. Read-only; the caller dispatches each batch.",inputSchema: {diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex 3f10c2ec..0c2ad3e8 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -1196,6 +1196,7 @@ function itemPathHidden(item: unknown, view: ArtifactRefView): boolean {export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_claims",+ kind: "write",description:"Claim-graph query (a projection over superseded_by / contradicts / valid_from / valid_until). operation: current (default) = truth now; at = truth at an instant; history = every claim incl. tombstoned; replaced = what replaced X; contests = what contests X; rebuild = rebuild the projection.",inputSchema: {@@ -1220,6 +1221,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_codegraph_report",+ kind: "read",description:"Read-only codegraph partner report: in-scope project, index state + counts, and Cargo.toml workspace members. When indexed, adds a non-blocking graph-health gate (index.health: dangling refs, self-loops, collapsed edges, cache-root mismatch) before labeling/import trust the graph. Never mutates.",inputSchema: {@@ -1232,6 +1234,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_foresight",+ kind: "read",description:"Forward-looking projection (Brain's only anticipatory surface): recurring routines coming due within the horizon via cadence arithmetic, recent open commitments, and open questions - deterministic, every item carries sources.",inputSchema: {@@ -1250,6 +1253,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_bridges",+ kind: "write",description:"Bridge discovery over the vec index: discover proposes links between embedding-near notes that share no edge (orphan-first, regenerates Brain/proposals/bridges.md, records a metric); accept writes one related wikilink into the source note; dismiss silences a pair; list reads the artifact back.",inputSchema: {@@ -1278,6 +1282,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_clusters",+ kind: "write",description:"Graph-wide community detection: run applies deterministic label propagation, materializes one note per community of size >= min_size under Brain/clusters/, removes stale notes, records a metric; list reads them back. Optional batch_size chunks work with isolated, reported per-batch failures.",inputSchema: {@@ -1304,6 +1309,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_moc_audit",+ kind: "read",description:"Per-MOC coverage audit. Given a hub note id, classifies its outbound cluster into well-covered / fragile / candidate-missing and surfaces a suggested-next candidate. MOC detection is purely structural (outbound link count + link density). Read-only.",inputSchema: {@@ -1321,6 +1327,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_deep_synthesis",+ kind: "write",description:"Topic-scoped deterministic dossier: matched notes, agreements, contradictions, stale claims, knowledge gaps (dangling wikilinks), plus per-finding causal context, decomposed confidence, and a visible evidence-loss ledger. Evidence assembly only. triggers=true enqueues findings.",inputSchema: {@@ -1352,6 +1359,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_diarize",+ kind: "read",description:"Subject profile for a registry entity: assembles its document set from the registry and sources, computes a deterministic stated-vs-evidenced gap (claims vs evidence frequency and recency), and emits a profile skeleton plus one needs-llm-step envelope. Read-only. Unknown entity errors.",inputSchema: {@@ -1376,6 +1384,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_idea_discovery",+ kind: "write",description:"Ranked next-direction candidates from the vault's open loops: unanswered open questions, orphan research notes (no inbound links), and aging unresolved inbox signals. Deterministic scoring; triggers=true enqueues the ranked ideas.",inputSchema: {@@ -1399,6 +1408,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_truth",+ kind: "write",description:"Entity claim ledger: ingest a claim, render current-truth slots, list conflicts, aggregate quantities, report collisions, window recall via the events operation, or commit grounded agent-stated claims via the state operation with per-claim anchoring verdicts.",inputSchema: {@@ -1485,6 +1495,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_dead_ends",+ kind: "write",description:"Negative-knowledge registry (Brain/dead-ends/): record one tried-and-failed approach with why it failed, or list the bounded active set so recall surfaces avoid-X alongside prefer-Y.",inputSchema: {diff --git a/src/mcp/brain/landscape-tools.ts b/src/mcp/brain/landscape-tools.tsindex 020eda59..f2ef6765 100644--- a/src/mcp/brain/landscape-tools.ts+++ b/src/mcp/brain/landscape-tools.ts@@ -28,6 +28,7 @@ async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknexport const LANDSCAPE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_mcp_landscape",+ kind: "read",description:"List the Model Context Protocol servers configured across the vault: each server's name, the config file that declares it, the packages it pulls, and the env-var NAMES it requires. Environment values are never read. Discovery is vault-relative. Read-only.",inputSchema: {diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.tsindex 32fffbba..3ffc8e72 100644--- a/src/mcp/brain/lifecycle-file-tools.ts+++ b/src/mcp/brain/lifecycle-file-tools.ts@@ -472,6 +472,7 @@ async function toolBrainScaffoldStub(export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"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: {@@ -526,6 +527,7 @@ export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze},{name: STUB_TOOL,+ kind: "write",description:"Unresolved wikilink targets. action: list reads them from the search index and refuses with a state and a next_command when that index is missing or partly resolved, rather than reporting zero; write materialises a stub for one target, its body linking back to the sources. Dry-run unless apply.",inputSchema: {diff --git a/src/mcp/brain/lifecycle-tools.ts b/src/mcp/brain/lifecycle-tools.tsindex 444a02d9..8e5aa0ce 100644--- a/src/mcp/brain/lifecycle-tools.ts+++ b/src/mcp/brain/lifecycle-tools.ts@@ -211,6 +211,7 @@ async function toolBrainLifecycle(export const LIFECYCLE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Cross-type lifecycle. action: tombstone marks a memory tombstoned in place; supersede links a successor; temporal-replace closes one fact and opens another at a shared instant; tip resolves a chain tip; curator slices observed-use verdicts; correct sweeps a correction, dry run by default.",inputSchema: {diff --git a/src/mcp/brain/memory-bridge-tools.ts b/src/mcp/brain/memory-bridge-tools.tsindex ea52a7fb..5a481b35 100644--- a/src/mcp/brain/memory-bridge-tools.ts+++ b/src/mcp/brain/memory-bridge-tools.ts@@ -111,6 +111,7 @@ const MEMORY_BRIDGE_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> =export const MEMORY_BRIDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_memory_bridge",+ kind: "write",description:"Host memory bridge: persist a Hermes built-in memory write (action add|replace, target memory|user) into the vault as a durable host_memory_write continuity record. Called by the provider on_memory_write hook; pass `operations` for an atomic batch.",inputSchema: {diff --git a/src/mcp/brain/ner-tools.ts b/src/mcp/brain/ner-tools.tsindex 2477372d..38e5c84d 100644--- a/src/mcp/brain/ner-tools.ts+++ b/src/mcp/brain/ner-tools.ts@@ -64,6 +64,7 @@ async function toolBrainIntakeEntities(export const NER_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Intake entities the agent extracted from note text into the entity registry (this server runs no model). Supply `entities` (category, name, optional aliases), the `source` they came from, and optional typed `relations`. Entities are quarantined unless the source names a file that exists.",inputSchema: {diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.tsindex 608fbdf7..cfd7bef9 100644--- a/src/mcp/brain/notes-tools.ts+++ b/src/mcp/brain/notes-tools.ts@@ -682,6 +682,7 @@ async function widenNearDuplicates(export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_create_note",+ kind: "write",description:"Create an actual vault note file (path + frontmatter + content), written atomically inside the vault. Distinct from brain_note, which only appends a log line. Refuses traversal, the Brain root, excluded paths, bad write bindings, default clobbering. An applied create claims a detached index refresh.",inputSchema: {@@ -732,6 +733,7 @@ export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_update_note",+ kind: "write",description:"Update an existing vault note: merge frontmatter keys and/or replace the body, atomically; a missing target is refused. Reuses the create-note safety envelope: traversal, the Brain root, excluded paths, bad write bindings. An applied update claims a detached index refresh.",inputSchema: {@@ -764,6 +766,7 @@ export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_append_note",+ kind: "write",description:"Append Markdown text to an existing vault note's body, written atomically. A missing target is refused. Reuses the create-note safety envelope: traversal, the Brain root, excluded paths, and writes outside the declared write binding are refused. An applied append claims a detached index refresh.",inputSchema: {diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex bdae296d..be967cd9 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -1334,6 +1334,7 @@ function anticipatoryAnswer(result: ReadAnticipatoryContextResult): Record<strinexport const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_context_pack",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Return the highest-tier, most recent vault slice under `max_tokens` - derived from the model context window when omitted, refused when nothing resolves. Ordered core → supporting → peripheral, newest first; stops when the next page would exceed the budget. Read-only.",@@ -1463,6 +1464,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_context_receipts",+ kind: "read",description:"List context receipt summaries, show one full receipt by id, or fold a window into a retrieval summary (distinct items, per-item injection frequency, token cost, observed use). Receipts are append-only continuity records emitted by opt-in injection callers. Read-only.",inputSchema: {@@ -1522,6 +1524,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_event_trace",+ kind: "read",description:"Join logged Brain events to their attached continuity records (recall telemetry, context receipts, generation reports) by shared correlation ids. Defaults to today. `total`/`trace_total` are exact once the walk exhausts; mid-walk they report the page's scan bound, never a silent cap. Read-only.",inputSchema: {@@ -1563,6 +1566,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_context_presets",+ kind: "read",description:"Show, suggest, or diff read-only context budget presets. Diagnostics only; never writes configuration.",inputSchema: {@@ -1605,6 +1609,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([// is bounded by its own per-entry / total character caps - now also// derived from the resolved context window when absent (t_a567cc12).name: "brain_pre_compress_pack",+ kind: "read",description:"Return a compact system-prompt addendum (top-K confirmed preferences plus the head of active.md) for a host to inject right before context compression. Char-budgeted: absent caps derive from the resolved model context window, so the addendum is bounded whenever a window resolves. Read-only.",inputSchema: {@@ -1666,6 +1671,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_pre_compact_extract",+ kind: "write",description:"Extract typed Decision/Commitment/Outcome/Rule/Open question records from bounded text into continuity storage.",inputSchema: {@@ -1711,6 +1717,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_anticipatory_context",+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:"Turn-specific context bundle kept warm by lifecycle hooks: the active context pack plus session-recall hits, keyed by the session's lineage root. Returns the warm cache inside the TTL or a live fallback, reporting `cache_state`. `refresh: true` forces a refresh first.",diff --git a/src/mcp/brain/pledge-tools.ts b/src/mcp/brain/pledge-tools.tsindex 1fe46f8f..9ccf0178 100644--- a/src/mcp/brain/pledge-tools.ts+++ b/src/mcp/brain/pledge-tools.ts@@ -366,6 +366,7 @@ async function toolBrainIntakePledges(export const PLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_pledge",+ kind: "write",description:"One-off pledges under Brain/pledges/ - a promise made in prose, with a due date, a cited source page and evidence quotes verified against that source at write time: add, fulfill (stamps the date), list (optionally overdue-only), show, remove (archives the page).",inputSchema: {@@ -442,6 +443,7 @@ export const PLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: INTAKE_TOOL,+ kind: "write",description:"Intake pledges extracted from a vault page; this server runs no model. Supply `source` plus typed `pledges` (title, due, evidence quotes from it, counterparty NAMES). Validated whole before any write; counterparty names anchor server-side, unanchored names reported not stored, repeats are no-ops.",inputSchema: {diff --git a/src/mcp/brain/procedure-tools.ts b/src/mcp/brain/procedure-tools.tsindex bc5f53d0..62f991d2 100644--- a/src/mcp/brain/procedure-tools.ts+++ b/src/mcp/brain/procedure-tools.ts@@ -331,6 +331,7 @@ async function toolBrainProceduralGraph(export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_skill_proposals",+ kind: "write",description:"Skill proposals: learn, list, accept, reject; recover abandoned accepts; usage counts; evidence against the outcome ledger. page_candidates gates mature vault pages (tier, lifecycle, confidence, reuse; skips ones a skill covers), one envelope each; page_draft stages the returned draft.",inputSchema: {@@ -426,6 +427,7 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_procedural_memory",+ kind: "write",description:"Reconcile/list procedural memory and update the usage + outcome sidecar (reconcile, list, mark_used, mark_outcome). list accepts ranked:true to order by validated success rate.",inputSchema: {@@ -462,6 +464,7 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_recurrence",+ kind: "write",description:"Inspect and update recurrence/support diagnostics (list, show, learn, forget, purge_source).",inputSchema: {@@ -492,6 +495,7 @@ export const PROCEDURE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_procedural_graph",+ kind: "write",description:"Rebuild/show procedural graph projection and prospective hint projection (rebuild, show, hints).",inputSchema: {diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.tsindex b4408c8b..32dfb6bf 100644--- a/src/mcp/brain/query-tools.ts+++ b/src/mcp/brain/query-tools.ts@@ -976,6 +976,7 @@ const BRAIN_QUERY_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_query",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Read-only lookup: one preference + its evidence trail, all artifacts under a topic, or every log event after a timestamp. Exactly one of `preference`, `topic`, `since` must be supplied.",@@ -1044,6 +1045,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_agent_query",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit; returns deterministic matched contributions plus a summary.",@@ -1088,6 +1090,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_writes",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"List recorded note writes (create, update, append, revert), newest first, with the agent, the device the log shard names, the target path and the content digest on each side. Filters by agent, device, path, op and time window. plan_revert returns the sealed plan for undoing them. Read-only.",@@ -1139,6 +1142,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_write_destinations",+ kind: "read",description:"One row per vault-relative destination the note-write and write-session events " +"name, with per-kind counts, contributing agents and devices, newest touch, and a " +@@ -1182,6 +1186,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_agent_diff",+ kind: "read",description:"Read-only comparison between source agents using the same provenance foundation as brain_agent_query. Supports browse, search, diff, and map modes.",inputSchema: {@@ -1227,6 +1232,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_backlinks",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"List inbound references to a Brain artifact id (preference, retired, or signal). Returns every source that points at the id via wikilink, in any preference/retired frontmatter field, body prose, signal source, or log payload. Read-only.",@@ -1246,6 +1252,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_audit",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Return a preference's full mutation audit trail (create / promote / update / retire / merge), oldest first, with agent, reason, and revisions. Accepts pref-/ret-/bare/wikilink ids. Read-only.",@@ -1265,6 +1272,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_sources",+ kind: "read",description:"Read-only dashboard of the brain's signals grouped by (agent, source_type) with active/processed and distinct-topic counts plus totals.",inputSchema: {@@ -1276,6 +1284,7 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_unlinked_mentions",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Raw-text mentions of a target's title / aliases not already inside `[[...]]`; walks Brain/preferences and Brain/retired. Boundaries are Unicode-aware and language-agnostic. `total` is exact once the walk exhausts; mid-walk it reports the page's scan bound, never a silent cap. Read-only.",diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.tsindex 2d1a7f8f..c7b83f34 100644--- a/src/mcp/brain/recall-tools.ts+++ b/src/mcp/brain/recall-tools.ts@@ -1233,6 +1233,7 @@ function expandPayload(export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_benchmark",+ kind: "read",description:"Recall-quality benchmark: score the vault's live hybrid recall against a fixed dataset ({queries: [{id, query, expected: [paths]}]}) - hit@k and MRR per query and aggregate - and record one recall_benchmark metric so quality is chartable over time.",inputSchema: {@@ -1254,6 +1255,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_tune",+ kind: "write",description:"Opt-in self-tuning recall: run grid-evaluates bounded parameters (pool multiplier, traversal depth, learned weights, expansion) against a benchmark dataset and persists the winner to Brain/search/tuning.json; status shows the validated state; reset deletes it. Search honors it only when enabled.",inputSchema: {@@ -1275,6 +1277,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_recall_telemetry",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"List recall telemetry records or summarize recall coverage and gaps; cost folds write volume against reads per period; dead_weight reports in-scope pages no recall ever surfaced, hidden pages dropped before totals, dead list capped (limit; default 50, max 500). Opt-in emit; read-only.",@@ -1352,6 +1355,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_route_metrics",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Route-level MCP latency: list mcp_route_latency records or summarize per-tool latency (count, errors, min/avg/max, p50/p95/p99, per-stage count/avg/p95) slowest-first. Emitted only when mcp_route_metrics_enabled is on; payload-safe (tool, scope, status, duration, arg keys, stage names). Read-only.",@@ -1393,6 +1397,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_retrieval_plan",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Shadow-only retrieval planner for a question: composes query intent/weights, summary-surface route, context-pack density allocation, token-impact ledger, and route p95 latency into a strategy, token-budget allocation, graph-expansion advice, reliability, and a marginal-value stop. Read-only.",@@ -1418,6 +1423,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_token_impact",+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:"Durable value-of-memory ledger. `record`: a pack's tokenizer-exact prompt-token delta (baseline−packed; method exact|fallback) + optional modeled inference-avoidance. `outcome` calibrates the model. `summary` keeps EXACT separate from MODELED; `list` reads samples. Gated write; payload-safe.",@@ -1494,6 +1500,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_context_pack_outcome",+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:"Context-pack outcome loop. `post` records an outcome row for a carried sample id — first-pass/repair/retry counters plus three SEPARATE token signals (exact, modeled, observed) — calibrates the token-impact ledger, and records the kernel's on-disk evidence. `list`/`summary` read rows. Gated.",@@ -1603,6 +1610,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_knowledge_gaps",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Cross-query demand gaps: aggregate the persisted recall demand log into recurring queries the vault answers poorly, ranked by frequency × (1 − IDF-weighted coverage). Read-only; log written only by opt-in recall telemetry.",@@ -1631,6 +1639,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_session_grep",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Search imported session recall raw turns and summary nodes, bounded by an optional time window (since/before). With operation=coverage, runs the coverage-first thread selection instead: facets fanned out under the topic budget, selected under char_budget, returned chronologically with diagnostics.",@@ -1698,6 +1707,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_session_describe",+ kind: "read",description:"Describe counts and summary depths for an imported session recall DAG. With topics, also render the adaptive topic-budget report the coverage operation fans out under.",inputSchema: {@@ -1717,6 +1727,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_session_expand",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Expand a session recall raw or summary node to immediate sources and paginated exact raw turn content. With payload instead of id, page the exact content behind an [payload: osb-payload://<sha256> chars=N] placeholder.",diff --git a/src/mcp/brain/receipt-tools.ts b/src/mcp/brain/receipt-tools.tsindex a96fb6ef..98ccd824 100644--- a/src/mcp/brain/receipt-tools.ts+++ b/src/mcp/brain/receipt-tools.ts@@ -185,6 +185,7 @@ async function toolBrainReceipts(export const RECEIPT_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_receipts",+ kind: "write",previewBudget: MCP_PREVIEW_BUDGET,description:"Receipt compaction. `scan` (default) inventories both ledgers read-only; `compact` folds " +diff --git a/src/mcp/brain/research-tools.ts b/src/mcp/brain/research-tools.tsindex 01e84473..db691f30 100644--- a/src/mcp/brain/research-tools.ts+++ b/src/mcp/brain/research-tools.ts@@ -56,6 +56,7 @@ async function toolBrainResearchReport(export const RESEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Write a dated, cited research report. Supply `title`, consulted `sources`, and `findings` (each citing its source). OSB rejects uncited findings, then writes one report page per date+title (idempotent). OSB runs no model.",inputSchema: {diff --git a/src/mcp/brain/review-tools.ts b/src/mcp/brain/review-tools.tsindex fb8733af..e9465c13 100644--- a/src/mcp/brain/review-tools.ts+++ b/src/mcp/brain/review-tools.ts@@ -250,6 +250,7 @@ async function toolBrainStaleScan(export const REVIEW_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_intent_review",+ kind: "read",description:"Read-only pre-dream intent review over active signal clusters. Returns each topic's decision, signal count, risk band, risk score, and reasons without mutating files.",inputSchema: {@@ -267,6 +268,7 @@ export const REVIEW_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_retention",+ kind: "read",description:"Recommendation-only lifecycle review over retired preferences and processed signals. Returns keep/improve/park/prune candidates and never deletes or moves artifacts.",inputSchema: {@@ -284,6 +286,7 @@ export const REVIEW_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_review_candidates",+ kind: "read",description:"Read-only preview of the next `brain_dream` pass: would_create / would_promote / would_retire / would_supersede, clusters below threshold, gated retires, intent reviews, and opt-in retire_siblings (lexical or stored-vector pairs; tier status in retire_siblings_semantic). Mutates nothing.",inputSchema: {@@ -301,6 +304,7 @@ export const REVIEW_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_stale_scan",+ kind: "read",description:"Structural staleness report: preferences, signals, and Brain/log files inactive longer than the configured `temporal:` thresholds (stale_pref_days / stale_signal_days / stale_log_days). Read-only.",inputSchema: {diff --git a/src/mcp/brain/storage-tools.ts b/src/mcp/brain/storage-tools.tsindex 4445c6dd..172b193f 100644--- a/src/mcp/brain/storage-tools.ts+++ b/src/mcp/brain/storage-tools.ts@@ -155,6 +155,7 @@ async function toolBrainStorage(export const STORAGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_storage",+ kind: "read",description:"Storage report: per-surface byte census (measured or refused by name), the growth forecast against the cap with its tier, and the usage sample this invocation records. Below local reach the census is not taken: measured: false, reason named. Read-only over vault content; appends one usage sample.",inputSchema: {diff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.tsindex feac8795..22ca4e0c 100644--- a/src/mcp/brain/synthesis-tools.ts+++ b/src/mcp/brain/synthesis-tools.ts@@ -369,6 +369,7 @@ function positiveIntArg(args: Record<string, unknown>, name: string): number | uexport const SYNTHESIS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: SUMMARY_TOOL,+ kind: "write",description:"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 (optionally one session). Append-only, deduped; an all-empty digest is rejected.",inputSchema: {@@ -422,6 +423,7 @@ export const SYNTHESIS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: CHECKPOINT_TOOL,+ kind: "write",description:"Batch-save a whole session's signals + a decisions/learnings/next_steps summary + optional diary in one idempotent round-trip, keyed by session_id. A same-content retry dedupes; a different-content retry is payload_mismatch. Items needing review return in `partial` (status 'mixed'), never dropped.",inputSchema: {@@ -474,6 +476,7 @@ export const SYNTHESIS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: LINEAGE_TOOL,+ kind: "read",description:"Read-only provenance tracer: how a derived artifact was reached, as an observation -> synthesis -> conclusion graph. A ctn_ id walks the sourceRefs graph; a pref-/ret- id adapts belief-evolution. Cycle-guarded, depth-bounded; an unknown id errors.",inputSchema: {@@ -497,6 +500,7 @@ export const SYNTHESIS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: HISTORY_TOOL,+ kind: "read",description:"Decompose a note's git history into episodic phases, split when the gap between commits exceeds gap_hours (default 72) - deterministic and language-agnostic. Each phase carries subjects, dates, authors. Missing repo: available=false; no commits: zero phases. Read-only.",inputSchema: {diff --git a/src/mcp/brain/tension-tools.ts b/src/mcp/brain/tension-tools.tsindex 420e10c4..bafa0a90 100644--- a/src/mcp/brain/tension-tools.ts+++ b/src/mcp/brain/tension-tools.ts@@ -193,6 +193,7 @@ async function toolBrainTension(export const TENSION_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: TOOL,+ kind: "write",description:"Persisted-contradiction (tension) lifecycle. detect persists contradictions from notes.read_paths as open tensions (idempotent); list/show read; confirm, dismiss, resolve transition. verify: read-only advisory verdict from the optional tension decision-model use; never changes a tension.",inputSchema: {diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.tsindex 0a135de5..f3c6a8ee 100644--- a/src/mcp/brain/workspace-tools.ts+++ b/src/mcp/brain/workspace-tools.ts@@ -290,6 +290,7 @@ function toolBrainTrigger(export const WORKSPACE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_intention",+ kind: "write",description:"Scoped current-intention chains under Brain/intentions/: set updates a workstream's now-document (prior text lands in its history trail), show/list read, move retires the chain into history/.",inputSchema: {@@ -321,6 +322,7 @@ export const WORKSPACE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_trigger",+ kind: "write",description:// Within the registry guard's tool-description ceiling (290 of the// 300 characters), which is why the wording is this tight: thediff --git a/src/mcp/brain/write-batch-tools.ts b/src/mcp/brain/write-batch-tools.tsindex 63603925..c3e7751b 100644--- a/src/mcp/brain/write-batch-tools.ts+++ b/src/mcp/brain/write-batch-tools.ts@@ -308,6 +308,7 @@ async function toolBrainWriteBatch(export const WRITE_BATCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_write_batch",+ kind: "write",description:"Apply an ordered batch of Brain write operations atomically. Ops: create_note, update_note, append_note, apply_evidence, append_log_line. Validated first; the first invalid op aborts with a typed error naming its index and nothing is written. Note ops honour the declared write binding.",inputSchema: {diff --git a/src/mcp/hydrate-tool.ts b/src/mcp/hydrate-tool.tsindex 291bc8d3..4d99d92b 100644--- a/src/mcp/hydrate-tool.ts+++ b/src/mcp/hydrate-tool.ts@@ -32,6 +32,7 @@ export const TOOL_HYDRATE_NAME = "tool_hydrate";export function buildHydrateTool(getTable: () => ReadonlyArray<ToolDefinition>): ToolDefinition {return {name: TOOL_HYDRATE_NAME,+ kind: "read",description:"Two-pass tool discovery: no arguments returns the compact tool catalog (name, one-line description, group); names returns full schemas for the requested tools. Hidden tools stay callable via tools/call.",inputSchema: {diff --git a/src/mcp/resources.ts b/src/mcp/resources.tsindex 6875ed5a..7d2cebe5 100644--- a/src/mcp/resources.ts+++ b/src/mcp/resources.ts@@ -394,6 +394,12 @@ function readDigestLatest(ctx: ResourceContext, uri: string, view: RequestView):const rendered = renderDigest(ctx.vault, {format: "markdown",...(view.refs.filtersNothing ? {} : { readable: view.refs.visible }),+ // Ownership is pushed into the render's SELECTION as well as its+ // row filter, the way `readActive` does: `view.refs` already+ // carries the rule on the filter side, and the digest's+ // vault-wide sections (the maintenance actions) are scoped by the+ // render itself rather than by which rows an id happens to name.+ ...(view.ownerScope !== null ? { agentScope: view.ownerScope } : {}),});return {uri,diff --git a/src/mcp/schema-tools.ts b/src/mcp/schema-tools.tsindex 1127d97c..d76210a8 100644--- a/src/mcp/schema-tools.ts+++ b/src/mcp/schema-tools.ts@@ -102,6 +102,7 @@ function toolSchemaInspect(export const SCHEMA_TOOLS: ReadonlyArray<ToolDefinition> = [{name: "schema_inspect",+ kind: "read",previewBudget: MCP_PREVIEW_BUDGET,description:"Read-only Brain schema inspection, one tool for every view: graph, lint, stats, orphans, explain_type (needs token), active_pack, or packs. Replaces the per-view schema read tools.",@@ -122,6 +123,7 @@ export const SCHEMA_TOOLS: ReadonlyArray<ToolDefinition> = [},{name: "schema_apply_mutations",+ kind: "write",description:"Apply an atomic batch of schema mutations to Brain/_brain.yaml and write an audit record. With dry_run, returns the pack that would result and its diff instead, writing nothing.",inputSchema: {diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 4c0a632b..60512dff 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -1,11 +1,12 @@/*** MCP tool registry slice for Brain Search.*- * Exposes `brain_search` (read-only, agent-facing) and the- * `search.*` enrichment used by `second_brain_status`. Index management- * verbs (`index`, `reindex`, `check`) are intentionally NOT exposed- * over MCP — they are operator business, never agent business- * (design doc §3, principle 5).+ * Exposes `brain_search` (agent-facing; write-classified - it persists+ * ranking-state ledgers under `Brain/search/`, see the kind comment at+ * the definition) and the `search.*` enrichment used by+ * `second_brain_status`. Index management verbs (`index`, `reindex`,+ * `check`) are intentionally NOT exposed over MCP — they are operator+ * business, never agent business (design doc §3, principle 5).** Anchored in docs/plans/2026-05-16-brain-search-design.md §9.*/@@ -1913,6 +1914,7 @@ async function toolBrainSearchExpand(export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_recall_feedback",+ kind: "write",description:"Record explicit recall feedback (up/down) for one search result. Feeds the deterministic learned-weight fold; events land under Brain/search/feedback/.",inputSchema: RECALL_FEEDBACK_INPUT_SCHEMA,@@ -1921,6 +1923,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_recall_gate",+ kind: "read",description:"Classify whether recall should run. Diagnostics only; does not search. Pass `scores` AND `match_quality` together for an adequacy verdict; either alone is INVALID_PARAMS (see `dependentRequired`). A measurement decides the verdict: below-floor quality answers retrieve false. `admit` echoes it.",inputSchema: RECALL_GATE_INPUT_SCHEMA,@@ -1929,8 +1932,18 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_search",+ // Write-mode-dominant (tool-contract.ts), not "read". The handler's+ // writes are ranking STATE, not accepted-loss telemetry appends:+ // `reinforce` persists boost events the fold reads back+ // (`recordReinforce` -> Brain/search/reinforce/), access recording is+ // default-on and writes activation events plus the derived state+ // (`recordAccessEvent` -> Brain/search/activation/), and under the+ // telemetry opt-in the recall-telemetry and query-demand ledgers+ // append. All of these feed later searches' behaviour, so they fail+ // the fail-soft-appends carve-out and gate the write path.+ kind: "write",description:- "Full-text search across the vault. Optional semantic layer when configured. Read-only. When a query misses, consult brain_recall_gate before widening recall: it classifies whether widening is warranted.",+ "Full-text search across the vault. Optional semantic layer when configured. Persists access events and opt-in reinforce/telemetry ledgers under Brain/search/. When a query misses, consult brain_recall_gate before widening recall: it classifies whether widening is warranted.",inputSchema: SEARCH_INPUT_SCHEMA,outputSchema: SEARCH_OUTPUT_SCHEMA,previewBudget: MCP_PREVIEW_BUDGET,@@ -1938,6 +1951,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_search_expand",+ kind: "read",description:"Progressive disclosure layers 2 + 3: drill a brain_search card (by chunk_id) into the fuller note and the paginated raw chunk transcript. Read-only; reuses the existing index.",inputSchema: SEARCH_EXPAND_INPUT_SCHEMA,@@ -1947,6 +1961,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_eval",+ kind: "read",description:"Score retrieval quality over a dataset against the active vault: hit@k, MRR, answer-containment@k, source-utilization, citation-depth, source warnings. Read-only.",inputSchema: EVAL_INPUT_SCHEMA,@@ -1956,6 +1971,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},{name: "brain_file_context",+ kind: "read",description:"Given a file path, surface prior vault work that mentions it (decisions, bug notes, refactor history) by querying the index with terms derived from the path. A size gate skips trivial files. Read-only; no LLM.",inputSchema: FILE_CONTEXT_INPUT_SCHEMA,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 534524a1..e3df862e 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -286,6 +286,32 @@ export class MCPServer {return toolResult(tool, await this.invokeToolHandler(tool, args, undefined, undefined));}+ /**+ * Whether this request must run behind the stdio transport's write+ * gate rather than on the concurrent read path.+ *+ * Everything that is not a `tools/call` is a read. A `tools/call` is a+ * write when its tool's `kind` is `write` - and every failure to KNOW+ * is a write too, because the gate only ever costs serialization while+ * guessing "read" could run a mutator beside another dispatch: a+ * malformed `params`, an unknown tool name (refused shortly, but never+ * parallelized), and a definition that carries no `kind` (a hand-built+ * one that cast the field away) all take the gate. No argument is ever+ * inspected: classification is per tool, never per call. This consults+ * the registry only - it performs none of the work `handleRequest`+ * will redo, and transport code may call it before dispatching.+ */+ classifiesWrite(request: JsonRpcRequest): boolean {+ if (request.method !== "tools/call") return false;+ const name = (request.params as { readonly name?: unknown } | null | undefined)?.["name"];+ if (typeof name !== "string") return true;+ try {+ return findTool(this.tools, name).kind !== "read";+ } catch {+ return true;+ }+ }+/*** Single seam through which every tool handler runs, for both the CLI* bridge (`callTool`) and the JSON-RPC `tools/call` path. With routediff --git a/src/mcp/skill-tools.ts b/src/mcp/skill-tools.tsindex c6b894a7..c703fec2 100644--- a/src/mcp/skill-tools.ts+++ b/src/mcp/skill-tools.ts@@ -212,6 +212,7 @@ function toolSkillsAttach(export const SKILL_TOOLS: ReadonlyArray<ToolDefinition> = [{name: "list_skills",+ kind: "read",description:"List agent skills shipped with Open Second Brain (and vault-local Brain/skills/) with one-line descriptions. Each entry carries a shadowed array naming the same-named skill directories it overrode, empty when discovery found none. Read-only.",inputSchema: {@@ -224,6 +225,7 @@ export const SKILL_TOOLS: ReadonlyArray<ToolDefinition> = [},{name: "get_skill",+ kind: "read",description:"Fetch a skill's SKILL.md content by name; optional file_path reads an auxiliary file inside the same skill directory. An offer_id from skills_attach is echoed back on the result; a malformed one is refused, never dropped. Read-only.",inputSchema: {@@ -250,6 +252,7 @@ export const SKILL_TOOLS: ReadonlyArray<ToolDefinition> = [},{name: "skills_attach",+ kind: "read",description:"Score skills against the turn text; returns a char-budgeted block of relevant summaries and the offer_id to cite on get_skill (null when none). Candidates without a discriminating term are dropped. Usage-ordered when skills_attach_usage_ordering is on. enabled:false unless skill_auto_attach is set.",inputSchema: {diff --git a/src/mcp/stdio.ts b/src/mcp/stdio.tsindex 045d0a0e..8fee7908 100644--- a/src/mcp/stdio.ts+++ b/src/mcp/stdio.ts@@ -10,8 +10,10 @@* disposition and killed the process wherever it happened to be, which* for a `tools/call` is mid-dispatch with no frame written. It now shares* the HTTP transport's register (`./drain.ts`): a drain stops the loop at- * a request boundary, waits for the one request that can be in flight,- * and only then closes the reader. Nothing here handles a signal - that+ * a request boundary and waits for every request it has accepted - under+ * the bounded parallel reads that can be several at once, and including a+ * write still parked behind them - and only then closes the reader.+ * Nothing here handles a signal - that* belongs to the CLI, which owns the process (`src/cli/mcp-drain.ts`).*/@@ -19,7 +21,7 @@ import { createInterface } from "node:readline";import type { Readable, Writable } from "node:stream";import { MCPServer, type MCPServerOptions, type MCPServerRuntimeOptions } from "./server.ts";-import { errorResponse, type JsonRpcResponse } from "./server.ts";+import { errorResponse, internalErrorResponse, type JsonRpcResponse } from "./server.ts";import { INVALID_REQUEST, PARSE_ERROR, type JsonRpcNotification } from "./protocol.ts";import { RequestDrain, resolveDrainDeadlineMs, type DrainOutcome } from "./drain.ts";import { ORIGIN_CHANNEL, setOriginChannel } from "../core/origin-channel.ts";@@ -69,6 +71,63 @@ export interface ServeStdioOptions {readonly drainDeadlineMs?: number;/** Called once the loop is live, with the handle that shuts it down. */readonly onStart?: (handle: StdioTransportHandle) => void;+ /**+ * Dispatch against this server instead of the one the loop builds.+ *+ * The loop still claims the origin channel, reads the stream and+ * writes every frame; a caller passing a server owns everything else+ * about it - its `sendNotification` wiring and its reach (tests, which+ * need handlers they can hold and release). Production callers leave+ * this unset: the built server is how the transport facts get set+ * after the caller's options, and no production caller can supply a+ * server that carries them.+ */+ readonly server?: MCPServer;+}++/**+ * How many read-classified requests the production loop keeps in flight+ * at once.+ *+ * A constant, not a knob: the number exists to bound this process's+ * concurrent SQLite read connections and its share of the event loop+ * under one slow read, and four answers that for every host this+ * transport runs on. The loop backpressures at the cap - it does not+ * read another line until a slot frees - so the bound holds by+ * construction, not by cooperation. Writes never consume a slot: they+ * run alone behind the write gate below.+ */+export const STDIO_READ_CONCURRENCY = 4;++/**+ * The in-loop write gate: a FIFO async mutex every write-classified+ * dispatch passes through.+ *+ * Dispatch-only by design rule: the gate lives HERE, in the transport+ * loop, never inside a core handler - `brain_write_batch` composes write+ * kernels, so a lower-level lock would self-block the one caller that+ * most needs writes to work. One write runs at a time (FIFO, in arrival+ * order), and - because the same loop is the only reader - the loop does+ * not read another line until the write it dispatched has settled, so no+ * read starts beside a running write either; the gate's dispatch body+ * additionally waits for the reads already in flight to settle first.+ * Cross-request frame order is thereby surrendered in one direction+ * only: reads may complete and be written out of arrival order, which is+ * JSON-RPC-legal, while every write keeps its arrival order and runs+ * exclusively. Clients correlate out-of-order responses by id and+ * interleaved progress by progress token.+ */+class WriteGate {+ #tail: Promise<void> = Promise.resolve();++ run(body: () => Promise<void>): Promise<void> {+ const run = this.#tail.then(body);+ this.#tail = run.then(+ () => undefined,+ () => undefined,+ );+ return run;+ }}/**@@ -78,6 +137,15 @@ export interface ServeStdioOptions {* JSON-RPC request. Invalid JSON yields a `-32700` parse-error response;* batch requests (an array at the top level) yield a `-32600` invalid-request* response, matching the 2025-06-18 spec which removed batch support.+ *+ * Reads (everything `MCPServer.classifiesWrite` declines) are dispatched+ * without being awaited, up to {@link STDIO_READ_CONCURRENCY} in flight;+ * the loop backpressures on a free slot before reading further lines.+ * Writes run one at a time through {@link WriteGate}. Every response is+ * written inside its own drain window: a read is tracked from its+ * dispatch, a write from its ACCEPTANCE - before it parks behind the+ * gate - so a drain that starts while the write is parked waits for it,+ * and no request is marked finished before its answer frame is queued.*/export async function serveStdio(ctx: MCPServerOptions,@@ -98,15 +166,18 @@ export async function serveStdio(// asked for - which is what lets a `tools/call` carrying a progress// token be answered with live notifications instead of a refusal. Set// after the caller's options so a transport fact cannot be overridden- // by a runtime option.- const server = new MCPServer(ctx, {- ...runtimeOpts,- sendNotification: (notification) => writeFrame(stdout, notification),- // A transport fact, so it is set after the caller's options for the- // same reason `sendNotification` is: a runtime option must not be- // able to claim a reach this transport did not establish.- reach: STDIO_TRANSPORT_REACH,- });+ // by a runtime option. The test-supplyable `ioOpts.server` bypasses+ // this constructor on purpose; see its docblock.+ const server =+ ioOpts.server ??+ new MCPServer(ctx, {+ ...runtimeOpts,+ sendNotification: (notification) => writeFrame(stdout, notification),+ // A transport fact, so it is set after the caller's options for the+ // same reason `sendNotification` is: a runtime option must not be+ // able to claim a reach this transport did not establish.+ reach: STDIO_TRANSPORT_REACH,+ });const rl = createInterface({ input: stdin, crlfDelay: Infinity });const drain = new RequestDrain();@@ -118,57 +189,183 @@ export async function serveStdio(// The wait comes first and the reader is closed after it: closing// the interface while a `tools/call` is still running would end the// loop before its response frame was written, which is the stdio- // shape of the truncated HTTP response this unit removes.+ // shape of the truncated HTTP response this unit removes. The+ // register holds every dispatched request - parallel reads included+ // - so this wait covers the whole in-flight set.const outcome = await drain.drain(deadlineMs);rl.close();return outcome;},});- for await (const rawLine of rl) {- // Stopped accepting. A line that arrives after a drain has started is- // left unread rather than answered with an error frame: the client is- // being disconnected either way, and a half-served shutdown that- // replies to some requests and not others is harder to reason about- // than one that stops cleanly at a request boundary.- if (drain.draining) break;- const line = rawLine.trim();- if (!line) continue;- let request: unknown;+ // One dispatch, read or write alike: the response write stays INSIDE+ // the tracked window, so a request is never marked finished before its+ // frame is queued (the drain could otherwise end the loop between the+ // dispatch and the answer). The window's `finish` is handed in rather+ // than opened here because the two paths open it at different moments:+ // a read at its dispatch, a WRITE at its acceptance - before it parks+ // behind the gate - so a drain that starts while the write is parked+ // already sees it (see dispatchWrite).+ const dispatch = async (request: Record<string, unknown>, finish: () => void): Promise<void> => {try {- request = JSON.parse(line);- } catch (exc) {- writeFrame(- stdout,- errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`),- );- continue;- }- if (Array.isArray(request)) {- writeFrame(- stdout,- errorResponse(- null,- INVALID_REQUEST,- "batch requests are not supported by the 2025-06-18 spec",- ),- );- continue;- }- if (typeof request !== "object" || request === null) {- writeFrame(stdout, errorResponse(null, INVALID_REQUEST, "request must be an object"));- continue;- }- // The response write is INSIDE the tracked window: a request marked- // finished before its frame is queued lets a drain end the loop- // between the dispatch and the answer.- const finish = drain.begin(requestLabel(request as Record<string, unknown>));- try {- const response = await server.handleRequest(request as Record<string, unknown>);+ const response = await server.handleRequest(request);if (response !== null) writeFrame(stdout, response);+ } catch (exc) {+ // A dispatch failure still answers its id. An unanswered request is+ // worse than a failed one - the caller waits for a correlation that+ // never arrives - so the catch frames the error here rather than+ // letting the rejection escape into the bookkeeping below. The+ // dispatcher's own INTERNAL_ERROR builder, the same framing the+ // HTTP catch-all uses: the prose goes through the redactor for this+ // transport's reach, and the code comes from the classifier. A+ // NOTIFICATION has no id to answer, so it gets no frame: the+ // dispatcher itself returns null for a failed notification rather+ // than an `id: null` error, and this catch-all mirrors that instead+ // of writing a response to a frame that was never a request.+ if ("id" in request) {+ writeFrame(stdout, internalErrorResponse(request["id"], exc, server.vault, server.reach));+ }} finally {finish();}+ };++ // The read path. `readsInFlight` is the slot count; the loop is the+ // only reader, so the single-waiter `slotFreed` release is enough.+ const readPromises = new Set<Promise<void>>();+ let readsInFlight = 0;+ let slotFreed: (() => void) | null = null;+ const dispatchRead = (request: Record<string, unknown>): void => {+ // Swallowed ONCE, here, and every hook below derived from the+ // swallow. Deriving the bookkeeping from the RAW promise - a bare+ // `void run.finally(...)` beside a swallowed `run` - creates a SECOND+ // promise that rejects when `run` does, and voiding it leaves an+ // unhandled rejection the runtime kills the process for, while the+ // request it belongs to never sees an error frame. The set holds the+ // settled twin, so every `Promise.all` over it (the write gate's+ // wait, this loop's exit barrier) stays rejection-free by+ // construction.+ const run = dispatch(request, drain.begin(requestLabel(request))).then(+ () => undefined,+ () => undefined,+ );+ readPromises.add(run);+ readsInFlight++;+ void run.finally(() => {+ readsInFlight--;+ readPromises.delete(run);+ slotFreed?.();+ slotFreed = null;+ });+ };++ // The write path. The loop awaits each write, so one write is in+ // flight at a time and no further line is read until it settles; the+ // gate is the FIFO order, and its body first waits out the reads that+ // were already running when the write arrived.+ const writeGate = new WriteGate();+ const writePromises = new Set<Promise<void>>();+ const dispatchWrite = (request: Record<string, unknown>): Promise<void> => {+ // The drain window opens at ACCEPTANCE, not when the write finally+ // dispatches. A write that arrives while reads are in flight parks in+ // the gate body below until they settle, and a write left unregistered+ // through that park was invisible to a drain: a SIGTERM in the window+ // watched the reads empty the register, resolved `drained`, and the+ // CLI exited - leaving the write to run afterward, its mutation landed+ // with no response ever delivered. Begun here, the write holds the+ // drain open from the moment the loop accepted it and is named in a+ // deadline report that beats it; `finish` is idempotent, and the+ // window closes when the response frame is written, inside `dispatch`.+ const finish = drain.begin(requestLabel(request));+ // Swallowed once, for the same reason the read path swallows: the+ // gate body can only settle cleanly when every promise it waits on+ // does, and the loop awaits this twin - a rejection here would fall+ // out of the `for await` and kill the loop a framed error already+ // answered for.+ const run = writeGate+ .run(async () => {+ while (readPromises.size > 0) {+ await Promise.all(readPromises);+ }+ await dispatch(request, finish);+ })+ .then(+ () => undefined,+ () => undefined,+ );+ writePromises.add(run);+ void run.finally(() => {+ writePromises.delete(run);+ });+ return run;+ };++ // EOF, a drain break and `rl.close()` all leave this loop only after+ // every dispatched request has settled: the exit hooks that run after+ // `serveStdio` returns (the search store WAL checkpoint, the+ // sync-lockfile unlink) must never run under floating handlers.+ try {+ readLoop: for await (const rawLine of rl) {+ // Stopped accepting. A line that arrives after a drain has started+ // is left unread rather than answered with an error frame: the+ // client is being disconnected either way, and a half-served+ // shutdown that replies to some requests and not others is harder+ // to reason about than one that stops cleanly at a request+ // boundary.+ if (drain.draining) break;+ const line = rawLine.trim();+ if (!line) continue;+ let request: unknown;+ try {+ request = JSON.parse(line);+ } catch (exc) {+ writeFrame(+ stdout,+ errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`),+ );+ continue;+ }+ if (Array.isArray(request)) {+ writeFrame(+ stdout,+ errorResponse(+ null,+ INVALID_REQUEST,+ "batch requests are not supported by the 2025-06-18 spec",+ ),+ );+ continue;+ }+ if (typeof request !== "object" || request === null) {+ writeFrame(stdout, errorResponse(null, INVALID_REQUEST, "request must be an object"));+ continue;+ }+ const record = request as Record<string, unknown>;+ if (server.classifiesWrite(record)) {+ // oxlint-disable-next-line no-await-in-loop -- the await IS the write gate: no new line is read while a write runs+ await dispatchWrite(record);+ } else {+ while (readsInFlight >= STDIO_READ_CONCURRENCY) {+ // oxlint-disable-next-line no-await-in-loop -- backpressure: hold at the cap before reading further lines+ await new Promise<void>((resolve) => {+ slotFreed = resolve;+ });+ // The park sits between the drain-break check above and the+ // dispatch below, so the boundary is re-checked once it is+ // over: this line was read BEFORE the drain began, but it was+ // held behind a full cap, and dispatching it after the drain+ // resolved would serve it outside the drain's wait - past+ // `rl.close()`, where the client may have stopped reading. So+ // it is left unread, under the same rule the check at the top+ // of the loop states: a line that arrives after a drain has+ // started is not answered.+ if (drain.draining) break readLoop;+ }+ dispatchRead(record);+ }+ }+ } finally {+ await Promise.all([...readPromises, ...writePromises]);}return 0;}@@ -255,11 +452,13 @@ export async function serveStdioFromString(out.push(frameLine(errorResponse(null, INVALID_REQUEST, "request must be an object")));continue;}- // Sequential on purpose, and not a candidate for `Promise.all`: the- // frames this loop collects are ordered, and a request that emits- // progress must have its notifications land between its predecessor's- // response and its own. Running the calls in parallel would shuffle- // them.+ // Sequential on purpose, and not because the transport serializes -+ // the production loop does not. This harness collects its frames+ // positionally: a test that writes "initialize, then tools/call"+ // reads the answers back by index, and running the calls in parallel+ // would shuffle collected frames whose whole meaning is their+ // position. Concurrency semantics belong to {@link serveStdio} and+ // its suite; this loop stays the deterministic harness.// oxlint-disable-next-line no-await-in-loopconst response = await server.handleRequest(request as Record<string, unknown>);if (response !== null) out.push(frameLine(response));diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.tsindex 77e23c8c..ca998388 100644--- a/src/mcp/tool-contract.ts+++ b/src/mcp/tool-contract.ts@@ -204,11 +204,56 @@ export interface ServerContext {readonly ruleScope?: RuleScopeSources;}+/**+ * The dispatch class of one tool: does any operation it can run mutate+ * durable vault state?+ *+ * Distinct from `ToolCeilingKind` (`src/core/runtime/host-facts.ts`),+ * which classifies a HOST's published tool ceiling - same member name,+ * unrelated fact.+ *+ * The rule is write-mode-dominant: a tool that CAN write is `write`,+ * decided per operation family at registration, never per arguments at+ * dispatch - no args parsing ever re-classifies a call. A dual-capability+ * tool (`brain_watchdog` remediate, `brain_lifecycle` apply,+ * `brain_dream`, `brain_receipts` fold) is `write` because of its write+ * half. Fail-soft observability appends (metrics ledger samples, opt-in+ * context receipts, route-latency records) do NOT make a tool `write`:+ * the stdio transport runs reads concurrently and accepts losing a+ * fail-open telemetry append under `ELOCKED` rather than serializing the+ * read path (see `src/mcp/stdio.ts`).+ *+ * The field never reaches the wire: the `tools/list` projection+ * (`MCPServer.handleToolsList`) picks its advertised fields explicitly,+ * and `tests/mcp/mcp.test.ts` pins that exact key set.+ */+export const TOOL_KIND = Object.freeze({+ /** Every operation the tool runs is a read or fail-soft telemetry. */+ read: "read",+ /** At least one operation the tool can run mutates durable state. */+ write: "write",+} as const);++/** Closed union over {@link TOOL_KIND}. */+export type ToolKind = (typeof TOOL_KIND)[keyof typeof TOOL_KIND];+export interface ToolDefinition {readonly name: string;readonly description: string;readonly inputSchema: Record<string, unknown>;readonly outputSchema?: OutputSchema;+ /**+ * The dispatch class of this tool ({@link TOOL_KIND}): `read` when+ * every operation it can run is a read or fail-soft telemetry,+ * `write` when any operation can mutate durable vault state -+ * write-mode-dominant, decided here at registration and never from+ * arguments at dispatch. Required so the partition is stated where the+ * tool is defined; the stdio transport treats an absent value as+ * `write` (fail-closed) so a hand-built definition that casts the+ * field away can only ever lose serialization, never safety. Metadata+ * only: it never reaches the `tools/list` wire payload.+ */+ readonly kind: ToolKind;/*** Optional MCP preview budget in characters (v0.18.0). When set and* the serialized result exceeds it, the JSON-RPC `tools/call` pathdiff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 692dcbc4..01fe3055 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -453,10 +453,13 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {export { REMOVED_TOOLS };// The set is named after the original payload (mutating writers). As-// of v0.10.10 it also hosts `brain_context`, a *reader* tool that has-// to be always-loaded to be useful at session start. Renaming the-// MCP server itself is deferred — see-// `docs/plans/2026-05-20-v0.10.10-design.md` §12.+// of v0.10.10 it also hosts `brain_context`, which has to be+// always-loaded to be useful at session start. It was admitted here as+// "a reader tool" back then, but its handler regenerates the shared+// `Brain/active.md`, so under the write-mode-dominant concurrency kind+// (`tool-contract.ts`) it is a writer too and the set name now+// describes it exactly. Renaming the MCP server itself is deferred —+// see `docs/plans/2026-05-20-v0.10.10-design.md` §12.const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set(["brain_apply_evidence","brain_context",@@ -478,6 +481,7 @@ export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefiniticonst all: ToolDefinition[] = [{name: CAPABILITY_DIAGNOSTIC_TOOL,+ kind: "read",description:"Report runtime MCP tool availability and withheld-tool reasons for this server process.",inputSchema: {@@ -490,6 +494,7 @@ export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefiniti},{name: "second_brain_status",+ kind: "read",description: "Report Open Second Brain configuration and vault status.",inputSchema: {type: "object",@@ -507,6 +512,7 @@ export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefiniti},{name: "second_brain_query",+ kind: "read",description: "List vault pages with optional title substring filter.",inputSchema: {type: "object",@@ -536,6 +542,7 @@ export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefiniti...SEARCH_TOOLS,{name: "vault_health",+ kind: "read",description:"Run vault, config, and plugin manifest health checks, and report every state surface in the vault with its path, reachability, and the override that placed it.",inputSchema: {@@ -552,6 +559,7 @@ export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefiniti},{name: "brain_artifact_get",+ kind: "read",description:"Fetch the full payload of a previously preview-truncated tool result by its artifact_id. Read-only.",inputSchema: {diff --git a/src/mcp/watchdog-tools.ts b/src/mcp/watchdog-tools.tsindex a4e238c2..d239115b 100644--- a/src/mcp/watchdog-tools.ts+++ b/src/mcp/watchdog-tools.ts@@ -5,6 +5,7 @@ import type { ToolDefinition } from "./tool-contract.ts";export const WATCHDOG_TOOLS: ReadonlyArray<ToolDefinition> = [{name: "brain_watchdog",+ kind: "write",description:"Probe Brain health and return safe recovery recommendations. Read-only unless remediate=true, which only creates missing Brain directories.",inputSchema: {diff --git a/src/mcp/wiring-tools.ts b/src/mcp/wiring-tools.tsindex ed3fa3c1..a2537933 100644--- a/src/mcp/wiring-tools.ts+++ b/src/mcp/wiring-tools.ts@@ -215,6 +215,7 @@ function toolWiring(ctx: ServerContext, args: Record<string, unknown>): unknownexport const WIRING_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: WIRING_TOOL_NAME,+ kind: "read",// Under the 300-character registry cap: the path policy and the// per-view field tables are long-form guidance, and `registry-guard.ts`// states that those belong in docs/mcp.md rather than in a schema everydiff --git a/tests/core/architecture/state-surface-census.test.ts b/tests/core/architecture/state-surface-census.test.tsindex 262d1918..f1d2546b 100644--- a/tests/core/architecture/state-surface-census.test.ts+++ b/tests/core/architecture/state-surface-census.test.ts@@ -86,7 +86,14 @@ const STORE_DIR_IDENTIFIER = "DERIVED_STORE_DIR";// state beside it as census surfaces, and writes nothing.// 26 -> 27: the pending mining surveys join the population with their row// (v1.86.1 review fixes), the same join the session mining ledger made.-const SWEPT_POPULATION_SIZE = 27;+// 27 -> 28, net, from the trust-and-responsiveness-hardening wave: the+// gitignore guard and its doctor tracked-state probe join the population,+// excused (one seeds the vault `.gitignore` that covers the directory, one+// probes git's view of it; neither creates state inside it), while the bench+// verb LEFT the population - its runs dir was hoisted to `BENCH_RUNS_REL` in+// `path-constants.ts`, so it no longer spells the directory - taking its now+// stale exclusion with it.+const SWEPT_POPULATION_SIZE = 28;/** Declared surfaces today. Pinned for the same reason. */// 50: the source-archives row (answer-trust Task C1) joins the population,diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex ec7d4c05..dad2f8b8 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -1536,8 +1536,14 @@ const DIRECT_WRITE_ROWS = 86;* and its manifest sidecar (`src/core/brain/host-memory-promotions.ts`)* commits `Brain/.imports/host-memory-promotions.json` through the same* helper - both under the apply arm only, the dry run writes nothing.+ *+ * 132 -> 133, from the trust-and-responsiveness-hardening wave: the+ * gitignore guard (`src/core/brain/gitignore-guard.ts`) commits the seeded+ * vault `.gitignore` through the shared atomic writer - git configuration at+ * the vault root, created or merged at brain init, never a page under+ * `Brain/`.*/-const SHARED_HELPER_ROWS = 132;+const SHARED_HELPER_ROWS = 133;// ----- Origin-channel coverage boundary (Unit C) ----------------------------@@ -1704,8 +1710,11 @@ const UNSTAMPED_DIRECT_ROWS = 85;* continuity promote verb and its promotion manifest both commit through* the shared atomic writer, and a ledger readback stamps no origin* channel - the pages it lands are vault pages, not channel records.+ * 128 -> 129 is the gitignore guard (trust-and-responsiveness-hardening):+ * the `.gitignore` it seeds is git configuration at the vault root,+ * carrying no origin channel - no record family of Unit C names it.*/-const UNSTAMPED_SHARED_ROWS = 128;+const UNSTAMPED_SHARED_ROWS = 129;describe("in-vault write-site census", () => {test("every direct-fs write site carries a written exclusion", () => {diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.tsindex fd319b80..def8e61c 100644--- a/tests/core/brain.doctor.test.ts+++ b/tests/core/brain.doctor.test.ts@@ -29,6 +29,7 @@ import { writePreference } from "../../src/core/brain/preference.ts";import { writeSignal } from "../../src/core/brain/signal.ts";import { runDoctor } from "../../src/core/brain/doctor.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { writeCaptureNote } from "../../src/core/brain/capture/capture-note.ts";let tmp: string;@@ -904,3 +905,44 @@ describe("corrupted principle frontmatter", () => {expect(res.warnings.filter((w) => w.code === "principle-corrupted")).toEqual([]);});});++// ---------------------------------------------------------------------------+// Registry order for the planted-structure-rows audit (t_c2ac4fc8, lane A).+// The order of DOCTOR_CHECKS is the order findings are reported in, which is+// a report contract: the planted-rows check sits immediately after the+// privacy-marker check, and a vault tripping both reports them in that order.+// ---------------------------------------------------------------------------++describe("doctor registry order: planted-structure-rows after privacy-marker-unstamped", () => {+ test("a vault tripping both checks reports the privacy marker finding first", () => {+ // Privacy marker: an informal reservation with no visibility declaration.+ atomicWriteFileSync(+ join(tmp, "Brain", "reserved.md"),+ ["---", "kind: note", "access: private", "---", "", "a private note", ""].join("\n"),+ );+ // Planted rows: a capture page carrying live structure.+ writeCaptureNote(tmp, {+ body: "quotes [[planted-note]] inline",+ provenance: { source: "telegram", sender: "1", capturedAt: "2026-09-01T08:00:00Z" },+ });+ const res = runDoctor(tmp);+ const privacyIndex = res.warnings.findIndex((w) => w.code === "privacy-marker-unstamped");+ const plantedIndex = res.warnings.findIndex((w) => w.code === "planted-structure-rows");+ expect(privacyIndex).toBeGreaterThanOrEqual(0);+ expect(plantedIndex).toBeGreaterThan(privacyIndex);+ });++ test("the planted-rows audit is silent on a clean vault", () => {+ writePreference(tmp, {+ slug: "clean-order",+ topic: "clean-order",+ principle: "Keep the registry order honest.",+ created_at: "2026-09-01T08:00:00Z",+ unconfirmed_until: "2026-09-15T08:00:00Z",+ status: "unconfirmed",+ evidenced_by: [],+ });+ const res = runDoctor(tmp);+ expect(res.warnings.filter((w) => w.code === "planted-structure-rows")).toEqual([]);+ });+});diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.tsindex 88a403a4..b534dc19 100644--- a/tests/core/brain.init.test.ts+++ b/tests/core/brain.init.test.ts@@ -14,6 +14,13 @@ import { join, posix } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { brainDirs } from "../../src/core/brain/paths.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";+import { runDoctor } from "../../src/core/brain/doctor.ts";+import {+ GITIGNORE_GUARD_IGNORE_LINE,+ GIT_TRACKED_DERIVED_STATE_CODE,+} from "../../src/core/brain/doctor/git-tracked-state-check.ts";+import { DEFAULT_BEGIN_MARKER, DEFAULT_END_MARKER } from "../../src/core/install/managed-block.ts";+import { cmdBrainInit } from "../../src/cli/brain/verbs/init.ts";// Shared temp scratch for both vault and machine-config directories.// Tests that need to assert the "missing machine config" path can@@ -38,6 +45,41 @@ afterEach(() => {rmSync(configHome, { recursive: true, force: true });});+/** Run `fn`, capturing everything it writes to stderr; restore afterwards. */+function captureStderr(fn: () => unknown): { stderr: string } {+ const original = process.stderr.write.bind(process.stderr);+ let captured = "";+ process.stderr.write = ((chunk: string | Uint8Array): boolean => {+ captured += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");+ return true;+ }) as typeof process.stderr.write;+ try {+ fn();+ } finally {+ process.stderr.write = original;+ }+ return { stderr: captured };+}++/**+ * Run the init verb in-process, capturing stdout. The verb's docblock+ * promises machine readers `result.guard` instead of stderr parsing;+ * the CLI tests below hold the verb's OWN output to that promise.+ */+async function runBrainInitCli(argv: string[]): Promise<{ code: number; stdout: string }> {+ let stdout = "";+ const originalWrite = process.stdout.write.bind(process.stdout);+ process.stdout.write = ((chunk: string | Uint8Array): boolean => {+ stdout += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");+ return true;+ }) as typeof process.stdout.write;+ try {+ return { code: await cmdBrainInit(argv), stdout };+ } finally {+ process.stdout.write = originalWrite;+ }+}+describe("bootstrapBrain — empty vault", () => {test("creates every Brain directory and the three managed files", () => {const result = bootstrapBrain(vault, { configPath });@@ -61,12 +103,16 @@ describe("bootstrapBrain — empty vault", () => {// (context-integrity-gates, Unit J).expect(existsSync(join(vault, "Brain", "vault-id.json"))).toBe(true);- // Counts: seven created (vault-id.json, _brain.yaml, _BRAIN.md, and- // the four Brain/bases/*.base view definitions stamped at init),- // none overwritten, none skipped.- expect(result.created.length).toBe(7);+ // Counts: eight created (vault-id.json, _brain.yaml, _BRAIN.md, the+ // four Brain/bases/*.base view definitions stamped at init, and the+ // seeded .gitignore guard), none overwritten, none skipped.+ expect(result.created.length).toBe(8);+ expect(result.created).toContain(".gitignore");expect(result.overwritten.length).toBe(0);expect(result.skipped.length).toBe(0);+ // The guard outcome is carried structurally, so machine readers can+ // tell a clean seed from an unresolved one without parsing stderr.+ expect(result.guard).toEqual({ status: "created" });// _brain.yaml byte-equals the default constant.expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(@@ -138,7 +184,12 @@ describe("bootstrapBrain — force overwrite", () => {expect(result.overwritten).toContain(posix.join("Brain", "_brain.yaml"));expect(result.overwritten).toContain(posix.join("Brain", "_BRAIN.md"));- expect(result.skipped.length).toBe(0);+ // The gitignore guard does not take part in force: a managed block+ // merge never rewrites over the operator's file, so the second run+ // leaves it in skipped (t_206562ae) — a CLEAN skip, reflected in the+ // guard outcome.+ expect(result.skipped).toEqual([".gitignore"]);+ expect(result.guard?.status).toBe("skipped");expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(DEFAULT_BRAIN_CONFIG_YAML,@@ -274,3 +325,304 @@ describe("bootstrapBrain — Bases view definitions", () => {expect(readFileSync(stomped, "utf8")).toContain('file.inFolder("Brain/log")');});});++describe("bootstrapBrain — gitignore guard (t_206562ae)", () => {+ /**+ * `git` in the vault; git is on PATH everywhere this suite runs. A+ * fixture command that fails must fail the test it sets up: this helper+ * used to drop the exit code, so a no-op `git commit` left+ * `porcelain()` asserting an empty repository and the guard was+ * "proven" by a measurement that never happened. Same posture as the+ * degradation suite's helper below.+ */+ function git(...args: string[]): void {+ const run = Bun.spawnSync(["git", ...args], { cwd: vault, stdout: "pipe", stderr: "pipe" });+ if (run.exitCode !== 0) {+ throw new Error(`git ${args.join(" ")} failed: ${run.stderr.toString()}`);+ }+ }++ function porcelain(): string {+ return Bun.spawnSync(["git", "status", "--porcelain"], {+ cwd: vault,+ stdout: "pipe",+ stderr: "ignore",+ })+ .stdout.toString()+ .replace(/\r\n/g, "\n");+ }++ test("the git helper refuses a failing git command instead of passing silently", () => {+ // Before `git init` the vault is not a repository, so this invocation+ // exits non-zero. The helper must surface that: a fixture whose setup+ // commands silently no-op would leave `porcelain()` asserting an empty+ // repository - "no dirt" because nothing was ever committed - and the+ // guard would be proven by a measurement that never happened.+ expect(() => git("status", "--porcelain")).toThrow(/git status --porcelain failed/);+ });++ test("fresh init seeds the guard block beside the identity stamp", () => {+ const result = bootstrapBrain(vault, { configPath });+ const content = readFileSync(join(vault, ".gitignore"), "utf8");+ expect(result.created).toContain(".gitignore");+ expect(content).toContain(DEFAULT_BEGIN_MARKER);+ expect(content).toContain("/.open-second-brain/");+ expect(content).toContain(DEFAULT_END_MARKER);+ });++ test("derived runtime state created after init never shows as git dirt", () => {+ // A real repository: init, then commit the vault as the operator+ // would, then let the runtime create the derived store. Without the+ // seeded guard the store shows as untracked dirt here. Several git+ // subprocesses deep - an explicit timeout keeps hosted Windows+ // runners clear of the 5s default; commit.gpgsign=false keeps a+ // machine with commit.gpgsign=true from failing for unrelated+ // reasons.+ bootstrapBrain(vault, { configPath });+ git("init");+ git("add", "-A");+ git(+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "-m",+ "vault",+ );+ expect(porcelain()).toBe("");++ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "bytes", "utf8");+ expect(porcelain()).toBe("");+ expect(existsSync(join(vault, ".open-second-brain", "brain.sqlite"))).toBe(true);+ }, 20000);++ test("a second init reports no creations and stays byte-identical on .gitignore", () => {+ bootstrapBrain(vault, { configPath });+ const before = readFileSync(join(vault, ".gitignore"), "utf8");+ const second = bootstrapBrain(vault, { configPath });+ expect(second.created).not.toContain(".gitignore");+ expect(second.created.length).toBe(0);+ expect(readFileSync(join(vault, ".gitignore"), "utf8")).toBe(before);+ });++ test("a pre-existing user .gitignore survives init byte-preserved outside the block", () => {+ const user = "# my patterns\n*.tmp\n.obsidian/workspace.json\n";+ writeFileSync(join(vault, ".gitignore"), user, "utf8");+ const result = bootstrapBrain(vault, { configPath });+ const content = readFileSync(join(vault, ".gitignore"), "utf8");+ expect(content.startsWith(user)).toBe(true);+ expect(content).toContain(DEFAULT_BEGIN_MARKER);+ expect(result.created).not.toContain(".gitignore");+ });++ test("init into a non-git folder succeeds identically — no git dependency at init", () => {+ // The default fixtures here are plain temp dirs (no git), so this is+ // the non-git path: the seeder runs, git is never consulted, and the+ // result reports the created .gitignore like any other step.+ const result = bootstrapBrain(vault, { configPath });+ expect(result.created).toContain(".gitignore");+ expect(existsSync(join(vault, ".gitignore"))).toBe(true);+ });+});++describe("bootstrapBrain — gitignore guard degradation (warn-and-continue)", () => {+ /** `git` in the vault; git is on PATH everywhere this suite runs. */+ function git(...args: string[]): void {+ const run = Bun.spawnSync(["git", ...args], { cwd: vault, stdout: "pipe", stderr: "pipe" });+ if (run.exitCode !== 0) {+ throw new Error(`git ${args.join(" ")} failed: ${run.stderr.toString()}`);+ }+ }++ test("a directory .gitignore cannot abort the bootstrap: warn, report skipped, continue", () => {+ // A chmod-denied, mandatory-locked or directory .gitignore used to+ // kill init midway — after the Brain dirs and the identity stamp+ // were written, before _brain.yaml existed: a half-bootstrapped+ // vault, taken down by a hygiene write the doctor reports anyway.+ mkdirSync(join(vault, ".gitignore"), { recursive: true });++ let result!: ReturnType<typeof bootstrapBrain>;+ const { stderr } = captureStderr(() => {+ result = bootstrapBrain(vault, { configPath });+ });++ // The bootstrap completed: the managed files below the guard exist.+ expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);+ expect(existsSync(join(vault, "Brain", "_BRAIN.md"))).toBe(true);++ // The result names the guard failure: the file is skipped and the+ // guard outcome is "failed" with a detail, not a clean skip.+ expect(result.skipped).toContain(".gitignore");+ expect(result.created).not.toContain(".gitignore");+ expect(result.guard?.status).toBe("failed");+ expect(typeof result.guard?.detail).toBe("string");+ expect((result.guard?.detail ?? "").length).toBeGreaterThan(0);++ // ...and the degradation is visible on stderr, named.+ expect(stderr).toMatch(/warning:/);+ expect(stderr).toContain(".gitignore");+ });++ test("a malformed managed block reports a named conflict, not a plain skip", () => {+ // Nothing is written and the seeder warns, but the result used to+ // say plain `skipped` — indistinguishable from "already covered".+ const broken = "# mine\n# >>> open-second-brain managed >>>\n*.tmp\n";+ writeFileSync(join(vault, ".gitignore"), broken, "utf8");++ let result!: ReturnType<typeof bootstrapBrain>;+ const { stderr } = captureStderr(() => {+ result = bootstrapBrain(vault, { configPath });+ });++ // Bootstrap continued past the guard.+ expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);+ // The file is exactly as the operator left it and reports as skipped...+ expect(readFileSync(join(vault, ".gitignore"), "utf8")).toBe(broken);+ expect(result.skipped).toContain(".gitignore");+ expect(result.created).not.toContain(".gitignore");+ expect(result.overwritten).not.toContain(".gitignore");+ // ...but the guard outcome distinguishes the conflict from a clean+ // skip, for stderr readers and machine readers alike.+ expect(result.guard?.status).toBe("conflict");+ expect(typeof result.guard?.detail).toBe("string");+ expect((result.guard?.detail ?? "").length).toBeGreaterThan(0);+ expect(stderr).toMatch(/warning:/);+ expect(stderr).toContain("derived-brain-state");+ });++ test("a hostile .gitignore that negates the entry after it is a conflict, not a clean skip", () => {+ // git last-match-wins: the entry is present, so the seeder's+ // exact-line check used to report a clean skip while the store was+ // NOT ignored. The init report carries the conflict instead.+ const hostile = "/.open-second-brain/\n*.tmp\n!.open-second-brain\n";+ writeFileSync(join(vault, ".gitignore"), hostile, "utf8");++ let result!: ReturnType<typeof bootstrapBrain>;+ captureStderr(() => {+ result = bootstrapBrain(vault, { configPath });+ });++ // Bootstrap continued; nothing was written to the operator's file.+ expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);+ expect(readFileSync(join(vault, ".gitignore"), "utf8")).toBe(hostile);+ expect(result.skipped).toContain(".gitignore");+ expect(result.created).not.toContain(".gitignore");+ expect(result.overwritten).not.toContain(".gitignore");+ expect(result.guard?.status).toBe("conflict");+ expect(result.guard?.detail).toContain("!.open-second-brain");+ });++ test("a conforming block that a later negation defeats reports the conflict, not a clean update", () => {+ // The merge would land the entry INSIDE the earlier block while the+ // negation after it still wins under git's last-match rule, so the+ // seeder must refuse the write - and the init report must say the+ // guard did not resolve instead of claiming a seeded block.+ const hostile = `${DEFAULT_BEGIN_MARKER}\n*.log\n${DEFAULT_END_MARKER}\n!.open-second-brain\n`;+ writeFileSync(join(vault, ".gitignore"), hostile, "utf8");++ let result!: ReturnType<typeof bootstrapBrain>;+ captureStderr(() => {+ result = bootstrapBrain(vault, { configPath });+ });++ // Bootstrap continued past the guard; the operator's file is+ // byte-identical and the store stays unprotected - reported.+ expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);+ expect(readFileSync(join(vault, ".gitignore"), "utf8")).toBe(hostile);+ expect(result.skipped).toContain(".gitignore");+ expect(result.created).not.toContain(".gitignore");+ expect(result.overwritten).not.toContain(".gitignore");+ expect(result.guard?.status).toBe("conflict");+ expect(result.guard?.detail).toContain("!.open-second-brain");+ });++ test("the doctor's tracked-state row reports the state a failed guard left behind", () => {+ // Init degraded past the unwritable guard; the protection the guard+ // would have seeded is genuinely absent, and the doctor's row is the+ // thing that says so — exactly what the step's docblock claims.+ mkdirSync(join(vault, ".gitignore"), { recursive: true });+ captureStderr(() => bootstrapBrain(vault, { configPath }));++ git("init");+ git(+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "add",+ "-A",+ );+ git(+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "-m",+ "vault",+ );+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "bytes", "utf8");++ const report = runDoctor(vault);+ const rows = report.warnings.filter((i) => i.code === GIT_TRACKED_DERIVED_STATE_CODE);+ expect(rows).toHaveLength(1);+ expect(rows[0]!.message).toContain(GITIGNORE_GUARD_IGNORE_LINE);+ }, 20000);+});++describe("brain init CLI — the guard outcome on both output streams", () => {+ test("--json carries guard.status = conflict for a defeated block fixture", async () => {+ // A conflict used to render in JSON as a plain skipped .gitignore -+ // indistinguishable from a clean "already covered" skip.+ const hostile = `${DEFAULT_BEGIN_MARKER}\n*.log\n${DEFAULT_END_MARKER}\n!.open-second-brain\n`;+ writeFileSync(join(vault, ".gitignore"), hostile, "utf8");++ const { code, stdout } = await runBrainInitCli([+ "--vault",+ vault,+ "--config",+ configPath,+ "--json",+ ]);+ expect(code).toBe(0);+ const payload = JSON.parse(stdout) as {+ guard?: { status?: string; detail?: string };+ skipped?: string[];+ };+ expect(payload.guard?.status).toBe("conflict");+ expect(payload.guard?.detail).toContain("!.open-second-brain");+ expect(payload.skipped).toContain(".gitignore");+ });++ test("--json carries the guard outcome for a clean run too", async () => {+ const { code, stdout } = await runBrainInitCli([+ "--vault",+ vault,+ "--config",+ configPath,+ "--json",+ ]);+ expect(code).toBe(0);+ const payload = JSON.parse(stdout) as { guard?: { status?: string } };+ expect(payload.guard?.status).toBe("created");+ });++ test("the human output names the guard outcome for a conflict fixture", async () => {+ const hostile = `${DEFAULT_BEGIN_MARKER}\n*.log\n${DEFAULT_END_MARKER}\n!.open-second-brain\n`;+ writeFileSync(join(vault, ".gitignore"), hostile, "utf8");++ const { code, stdout } = await runBrainInitCli(["--vault", vault, "--config", configPath]);+ expect(code).toBe(0);+ expect(stdout).toContain("guard: conflict");+ expect(stdout).toContain("!.open-second-brain");+ });+});diff --git a/tests/core/brain/backlinks-anchor-alias.test.ts b/tests/core/brain/backlinks-anchor-alias.test.tsindex 33d4a97d..0ad32c13 100644--- a/tests/core/brain/backlinks-anchor-alias.test.ts+++ b/tests/core/brain/backlinks-anchor-alias.test.ts@@ -234,4 +234,25 @@ describe("buildBacklinkIndex - alias resolution", () => {expect(sourceKind).toBe("preference");expect(field).toBe("body");});++ test("an escaped bracket in a body plants no backlink", () => {+ // `\[[pref-target]]` is literal text by the odd-backslash-run rule+ // every link reader applies, so it joins no link graph.+ writeFileSync(+ join(vault, "Brain", "preferences", "pref-esc.md"),+ [+ "---",+ "kind: preference",+ "topic: e",+ "_status: confirmed",+ "principle: x",+ "---",+ "",+ "Quotes \\[[pref-target]] and [[pref-target\\]] verbatim.",+ ].join("\n"),+ );+ const idx = buildBacklinkIndex(vault);+ expect(idx.has("pref-target")).toBe(false);+ expect(idx.has("pref-target\\")).toBe(false);+ });});diff --git a/tests/core/brain/capture/capture-note.test.ts b/tests/core/brain/capture/capture-note.test.tsindex 430f2bbe..ea9e20d1 100644--- a/tests/core/brain/capture/capture-note.test.ts+++ b/tests/core/brain/capture/capture-note.test.ts@@ -356,3 +356,245 @@ describe("writeCaptureNote — declared page_types vocabulary (t_151a564c)", ()expect(read.provenance.capturedAt).toBe("2026-07-19T12:00:00Z");});});++// ---------------------------------------------------------------------------+// Write-time marker neutralization (t_c2ac4fc8, lane A3). The capture seam+// neutralizes caller text under the gate's enforce mode and records the+// neutralized kinds in a conditional frontmatter key; off and shadow write+// byte-identical output.+// ---------------------------------------------------------------------------++import { createHash } from "node:crypto";+import { discoverMarkers } from "../../../../src/core/brain/inline.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE_ENV,+ MarkdownNeutralizeModeError,+ detectMarkdownStructure,+} from "../../../../src/core/brain/text/neutralize-markdown.ts";+import { BRAIN_CAPTURES_REL } from "../../../../src/core/brain/paths.ts";++/** Set the gate mode env twin for one test, restoring it afterwards. */+function withGateMode(mode: string, run: () => void): void {+ const saved = process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = mode;+ try {+ run();+ } finally {+ if (saved === undefined) delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ else process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = saved;+ }+}++/**+ * The id a fresh-vault capture of this text derives (captureBaseId's+ * contract: sha256 over source, sender, the TRIMMED body and the optional+ * guidance, first 8 hex; prefix `cap-<date>` keeps the date's dashes).+ */+function expectedId(body: string, guidance: string | null): string {+ const hash = createHash("sha256")+ .update(+ `telegram\u0000` ++ `12345\u0000` ++ `${body.trim()}` ++ (guidance === null ? "" : `\u0000${guidance}`),+ "utf8",+ )+ .digest("hex")+ .slice(0, 8);+ return `cap-2026-07-19-120000-${hash}`;+}++const MARKER_BODY = [+ "## Quoted",+ "",+ "see [[pref-target]] and [[pref-other|The Other]]",+ "",+ "@osb set note=[[x]] field=a value=b",+].join("\n");++test("gate off: a body full of live markers persists byte-identical to the legacy shape", () => {+ const note = writeCaptureNote(vault, { body: MARKER_BODY, provenance: prov() });+ const id = expectedId(MARKER_BODY, null);+ expect(note.id).toBe(id);+ expect(readFileSync(join(vault, note.path), "utf8")).toBe(+ [+ "---",+ "kind: brain-capture",+ `id: ${id}`,+ "capture_source: telegram",+ "capture_sender: 12345",+ 'captured_at: "2026-07-19T12:00:00Z"',+ "tags: [brain, brain/capture]",+ "---",+ "",+ MARKER_BODY,+ ].join("\n") + "\n",+ );+});++test("gate shadow: bytes are unchanged and no provenance key is written", () => {+ withGateMode("shadow", () => {+ const note = writeCaptureNote(vault, { body: MARKER_BODY, provenance: prov() });+ const id = expectedId(MARKER_BODY, null);+ expect(readFileSync(join(vault, note.path), "utf8")).toBe(+ [+ "---",+ "kind: brain-capture",+ `id: ${id}`,+ "capture_source: telegram",+ "capture_sender: 12345",+ 'captured_at: "2026-07-19T12:00:00Z"',+ "tags: [brain, brain/capture]",+ "---",+ "",+ MARKER_BODY,+ "",+ ].join("\n"),+ );+ });+});++test("gate enforce: planted markers are inert on disk and the kinds are recorded", () => {+ withGateMode("enforce", () => {+ const note = writeCaptureNote(vault, { body: MARKER_BODY, provenance: prov() });+ const raw = readFileSync(join(vault, note.path), "utf8");+ // The stored body is the post-neutralize text: no live structure per a+ // fence-masked scan of the persisted bytes.+ expect(detectMarkdownStructure(raw)).toEqual([]);+ expect(raw).toContain("\\[\\[pref-target\\]\\]");+ expect(raw).toContain("\\[\\[pref-other|The Other\\]\\]");+ expect(raw).toContain("\\#\\# Quoted");+ expect(raw).toContain("\\@osb set note=");+ // The conditional provenance key names the neutralized kinds, sorted.+ expect(raw).toContain("neutralized_markers: [atx-heading, osb-inline, wikilink]");+ // The reader hands back what was persisted, rendered as literal text.+ const read = readCaptureNote(vault, note.id)!;+ expect(read.body).toContain("\\[\\[pref-target\\]\\]");+ // Identity follows the persisted bytes.+ expect(note.id).toBe(expectedId(read.body, read.guidance));+ });+});++test("gate enforce: the guidance tail is neutralized and the writer's own split still works", () => {+ withGateMode("enforce", () => {+ const note = writeCaptureNote(vault, {+ body: "quotes a document\n\n## Guidance\n\nthe quoted fake section",+ guidance: "route to [[pref-sink]]",+ provenance: prov(),+ });+ const raw = readFileSync(join(vault, note.path), "utf8");+ // The caller-authored halves are inert; the page's ONE live heading+ // is the writer's own renderer-authored section heading.+ expect(raw).toContain("\\#\\# Guidance");+ expect(raw).toContain("\n\n## Guidance\n\n");+ expect(raw).toContain("route to \\[\\[pref-sink\\]\\]");+ expect(raw).toContain("neutralized_markers: [atx-heading, wikilink]");+ const read = readCaptureNote(vault, note.id)!;+ expect(detectMarkdownStructure(read.body)).toEqual([]);+ expect(detectMarkdownStructure(read.guidance!)).toEqual([]);+ // The split fires on the writer-set marker and never on the escaped one.+ expect(read.body).toBe("quotes a document\n\n\\#\\# Guidance\n\nthe quoted fake section");+ expect(read.guidance).toBe("route to \\[\\[pref-sink\\]\\]");+ });+});++test("gate enforce: a fence split across the body-guidance boundary cannot plant a live marker", () => {+ withGateMode("enforce", () => {+ // The reviewer's concrete fixture: the body's trailing fence opens an+ // unterminated fence the guidance's own fence line closes on the+ // rendered page, which left the planted marker LIVE for every marker+ // scanner while both halves scanned clean on their own.+ const note = writeCaptureNote(vault, {+ body: "x\n```",+ guidance: "```\n@osb feedback negative topic=t principle=p",+ provenance: prov(),+ });+ const raw = readFileSync(join(vault, note.path), "utf8");+ // The rendered page bytes carry no live marker ...+ expect(discoverMarkers(raw)).toHaveLength(0);+ expect(raw).toContain("\\@osb feedback negative topic=t principle=p");+ // ... and the conditional provenance key names what was escaped.+ expect(raw).toContain("neutralized_markers: [osb-inline]");+ // The writer's own heading is never escaped: only the caller halves pass+ // through the neutralizer.+ expect(raw).toContain("\n\n## Guidance\n\n");+ const read = readCaptureNote(vault, note.id)!;+ expect(read.body).toBe("x\n```");+ expect(read.guidance).toBe("```\n\\@osb feedback negative topic=t principle=p");+ });+});++test("gate enforce: a marker the split fence masks on the page stays untouched in both halves", () => {+ withGateMode("enforce", () => {+ // Consistency direction: the body's fence never closes, so the combined+ // page's scanner parses nothing from the guidance - the fence masks the+ // marker there just as it masks it in the threaded half, and the write+ // stays byte-identical with no provenance key.+ const note = writeCaptureNote(vault, {+ body: "x\n```",+ guidance: "@osb feedback negative topic=t principle=p",+ provenance: prov(),+ });+ const raw = readFileSync(join(vault, note.path), "utf8");+ expect(discoverMarkers(raw)).toHaveLength(0);+ expect(raw).toContain("\n@osb feedback negative topic=t principle=p");+ expect(rawHasNeutralizedKey(join(vault, note.path))).toBe(false);+ });+});++test("gate enforce: a clean body gains zero bytes", () => {+ withGateMode("enforce", () => {+ const note = writeCaptureNote(vault, { body: "capture a thought", provenance: prov() });+ const id = expectedId("capture a thought", null);+ expect(readFileSync(join(vault, note.path), "utf8")).toBe(+ [+ "---",+ "kind: brain-capture",+ `id: ${id}`,+ "capture_source: telegram",+ "capture_sender: 12345",+ 'captured_at: "2026-07-19T12:00:00Z"',+ "tags: [brain, brain/capture]",+ "---",+ "",+ "capture a thought",+ "",+ ].join("\n"),+ );+ expect(rawHasNeutralizedKey(join(vault, note.path))).toBe(false);+ });+});++function rawHasNeutralizedKey(path: string): boolean {+ return readFileSync(path, "utf8").includes("neutralized_markers:");+}++test("gate enforce: re-capture of the same text under a stable gate is idempotent", () => {+ withGateMode("enforce", () => {+ const first = writeCaptureNote(vault, { body: MARKER_BODY, provenance: prov() });+ const second = writeCaptureNote(vault, { body: MARKER_BODY, provenance: prov() });+ // Same text, same provenance, same gate: the same derived stem - the+ // allocator's exclusive-create suffix is the only difference.+ expect(second.id.startsWith(`${first.id}-`)).toBe(true);+ const firstRaw = readFileSync(join(vault, first.path), "utf8");+ const secondRaw = readFileSync(join(vault, second.path), "utf8");+ expect(secondRaw).toBe(firstRaw.replace(`id: ${first.id}`, `id: ${second.id}`));+ });+});++test("a misconfigured gate mode is refused before any filesystem effect", () => {+ withGateMode("sometimes", () => {+ expect(() =>+ writeCaptureNote(vault, { body: "capture a thought", provenance: prov() }),+ ).toThrow(MarkdownNeutralizeModeError);+ expect(existsSync(join(vault, "Brain", "captures"))).toBe(false);+ });+});++test("the staging area is where neutralized captures land", () => {+ withGateMode("enforce", () => {+ const note = writeCaptureNote(vault, { body: MARKER_BODY, provenance: prov() });+ expect(note.path.startsWith(`${BRAIN_CAPTURES_REL}/`)).toBe(true);+ expect(note.staged).toBe(true);+ });+});diff --git a/tests/core/brain/digest-actions.test.ts b/tests/core/brain/digest-actions.test.tsindex 122e3a5b..4717b299 100644--- a/tests/core/brain/digest-actions.test.ts+++ b/tests/core/brain/digest-actions.test.ts@@ -11,6 +11,10 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { renderDigest } from "../../../src/core/brain/digest.ts";+import { brainConfigPath } from "../../../src/core/brain/paths.ts";+import { appendLogEvent } from "../../../src/core/brain/log.ts";+import { BRAIN_LOG_EVENT_KIND } from "../../../src/core/brain/types.ts";+import { GATE_MODE } from "../../../src/core/integrity/stamp.ts";// A forwarding mock over the dedup scan (the claim-provenance precedent):// inert unless this file's failing-scan test turns it on, so the mocks@@ -206,3 +210,367 @@ describe("brain_digest actions surface", () => {expect(payload.actions[0]!.impact).toBeGreaterThan(0);});});++/**+ * The actions list is collected vault-wide, so it can name a preference+ * every section beside it withholds under+ * `integrity.owner_scope_delivery: fail`. These rows pin the same+ * isolation the other digest sections already honour: another owner's+ * stale page is absent from `actions` on every format, while an action+ * whose target the caller may see still appears (no over-filtering),+ * and a scope requested without the gate changes nothing.+ */+function setGate(mode: string | null): void {+ const body = mode === null ? "" : `integrity:\n owner_scope_delivery: ${mode}\n`;+ writeFileSync(brainConfigPath(vault), `schema_version: 1\n${body}`);+}++/** The digest JSON payload's ranked `actions` array. */+function actionsOf(content: string): ReadonlyArray<{ target?: string }> {+ return (JSON.parse(content) as { actions: ReadonlyArray<{ target?: string }> }).actions;+}++describe("digest actions honor the caller's agent scope", () => {+ const OURS = "our-stale-page";+ const THEIRS = "their-stale-page";+ /** Old enough to be past the stale-stable cap on any run date. */+ const OLD = "2024-01-01T00:00:00Z";++ function seedTwoOwnerStalePages(): void {+ for (const [slug, owner] of [+ [OURS, undefined],+ [THEIRS, "agent-a"],+ ] as const) {+ writePref(slug, {+ topic: slug,+ principle: `principle for ${slug}`,+ status: "unconfirmed",+ created_at: OLD,+ unconfirmed_until: "2024-06-01T00:00:00Z",+ ...(owner !== undefined ? { owner } : {}),+ });+ }+ }++ test("under fail, another owner's stale page is absent from actions and the caller's own still appear", () => {+ seedTwoOwnerStalePages();+ setGate(GATE_MODE.fail);++ const json = renderDigest(vault, {+ format: "json",+ since: new Date(OLD),+ until: new Date("2024-01-02T00:00:00Z"),+ agentScope: "agent-b",+ });+ const payload = JSON.parse(json.content) as {+ actions: Array<{ id: string; category: string; title: string; target?: string }>;+ };+ expect(payload.actions.some((a) => a.target === `pref-${THEIRS}`)).toBe(false);+ expect(json.content).not.toContain(THEIRS);+ // No over-filtering: the action whose target the caller may see is+ // still ranked, category and target intact.+ expect(+ payload.actions.some((a) => a.category === "lifecycle" && a.target === `pref-${OURS}`),+ ).toBe(true);++ // The markdown renderer draws from the same filtered rows.+ const md = renderDigest(vault, {+ format: "markdown",+ since: new Date(OLD),+ until: new Date("2024-01-02T00:00:00Z"),+ agentScope: "agent-b",+ });+ expect(md.content).toContain("## Actions");+ expect(md.content).toContain(`pref-${OURS}`);+ expect(md.content).not.toContain(THEIRS);++ // Its own owner still sees the maintenance suggestion.+ const asOwner = renderDigest(vault, {+ format: "json",+ since: new Date(OLD),+ until: new Date("2024-01-02T00:00:00Z"),+ agentScope: "agent-a",+ });+ expect(asOwner.content).toContain(THEIRS);+ });++ test("a scope requested under off or warn changes no action", () => {+ seedTwoOwnerStalePages();+ const unscoped = renderDigest(vault, {+ format: "json",+ since: new Date(OLD),+ until: new Date("2024-01-02T00:00:00Z"),+ });+ const baseline = JSON.parse(unscoped.content).actions;+ // The fixture really does rank both pages, so the comparison below+ // is not an agreement over an empty list.+ expect(baseline.some((a: { target?: string }) => a.target === `pref-${THEIRS}`)).toBe(true);+ expect(baseline.some((a: { target?: string }) => a.target === `pref-${OURS}`)).toBe(true);++ for (const mode of [GATE_MODE.off, GATE_MODE.warn]) {+ setGate(mode);+ const scoped = renderDigest(vault, {+ format: "json",+ since: new Date(OLD),+ until: new Date("2024-01-02T00:00:00Z"),+ agentScope: "agent-b",+ });+ expect(JSON.parse(scoped.content).actions).toEqual(baseline);+ }+ });+});++/**+ * The digest passes its composed visibility view INTO the maintenance+ * collector, so the predicate is applied to the candidate inputs before+ * scoring and capping. Before, the collector capped at the default ten+ * and the scope filtered afterwards: another owner's top-ranked rows+ * took slots and were dropped, leaving a scoped caller with fewer than+ * ten actions (or none) while visible lower-ranked ones existed - and a+ * shortfall that itself hinted at withheld rows.+ */+describe("digest actions are visibility-filtered before they are capped", () => {+ /** Old enough to make impact strictly larger than the OURS pages'. */+ const ANCIENT = "2020-01-01T00:00:00Z";+ const OLDER = "2024-01-01T00:00:00Z";++ function seedRankedStalePages(): void {+ for (let i = 0; i < 12; i += 1) {+ writePref(`theirs-${i}`, {+ topic: `theirs-${i}`,+ principle: `principle theirs ${i}`,+ created_at: ANCIENT,+ owner: "agent-a",+ });+ }+ for (let i = 0; i < 10; i += 1) {+ writePref(`ours-${i}`, {+ topic: `ours-${i}`,+ principle: `principle ours ${i}`,+ created_at: OLDER,+ });+ }+ }++ test("a scoped caller sees exactly topN rows, all visible, when hidden rows outrank them", () => {+ seedRankedStalePages();+ setGate(GATE_MODE.fail);++ const scoped = actionsOf(+ renderDigest(vault, {+ format: "json",+ since: new Date(OLDER),+ until: new Date("2024-01-02T00:00:00Z"),+ agentScope: "agent-b",+ }).content,+ );+ expect(scoped).toHaveLength(10);+ for (const action of scoped) expect(action.target).not.toContain("theirs");++ // Unscoped, the hidden rows still rank exactly as before the+ // predicate existed: the cap is filled by the top-ranked hidden+ // pages, so the caller who asked for nothing sees no change.+ const unscoped = actionsOf(+ renderDigest(vault, {+ format: "json",+ since: new Date(OLDER),+ until: new Date("2024-01-02T00:00:00Z"),+ }).content,+ );+ expect(unscoped).toHaveLength(10);+ for (const action of unscoped) expect(action.target).toContain("pref-theirs-");++ // And a scope requested without the gate still changes nothing.+ setGate(GATE_MODE.off);+ const off = actionsOf(+ renderDigest(vault, {+ format: "json",+ since: new Date(OLDER),+ until: new Date("2024-01-02T00:00:00Z"),+ agentScope: "agent-b",+ }).content,+ );+ expect(JSON.stringify(off)).toBe(JSON.stringify(unscoped));+ });++ test("a dedup row's secondary count excludes secondaries the caller may not see", () => {+ // The count is the leak: "Merge 2 duplicate(s)" tells a caller a+ // second page they may not see exists. Owner scope cannot produce a+ // mixed group (per-scope keying never groups pages across owners),+ // but the reach half of the composed view can: one duplicate is+ // unreadable at this caller's reach, its sibling canonical is not.+ writePref("canonical", {+ topic: "shared-topic",+ principle: "the shared principle",+ created_at: "2025-01-01T00:00:00Z",+ });+ writePref("dup-visible", {+ topic: "shared-topic",+ principle: "the shared principle",+ created_at: "2025-02-01T00:00:00Z",+ });+ writePref("dup-hidden", {+ topic: "shared-topic",+ principle: "the shared principle",+ created_at: "2025-03-01T00:00:00Z",+ });++ const scopedJson = renderDigest(vault, {+ format: "json",+ since: new Date("2025-04-01T00:00:00Z"),+ until: new Date("2025-04-02T00:00:00Z"),+ readable: (rel) => !rel.includes("dup-hidden"),+ });+ const scoped = actionsOf(scopedJson.content);+ const dedup = scoped.find((a) => (a as { category?: string }).category === "dedup");+ expect(dedup).toBeDefined();+ expect((dedup as { title?: string }).title).toBe("Merge 1 duplicate(s) into pref-canonical");+ expect(scopedJson.content).not.toContain("dup-hidden");++ // A caller at full reach still counts both duplicates.+ const unscoped = actionsOf(+ renderDigest(vault, {+ format: "json",+ since: new Date("2025-04-01T00:00:00Z"),+ until: new Date("2025-04-02T00:00:00Z"),+ }).content,+ );+ const openDedup = unscoped.find((a) => (a as { category?: string }).category === "dedup");+ expect((openDedup as { title?: string }).title).toBe(+ "Merge 2 duplicate(s) into pref-canonical",+ );+ });+});++/**+ * The confidence-shift and contradiction rows are parsed from dream log+ * lines, so the log-level filter reads the whole line as one reference+ * and cannot resolve the preference it names; the parsed id is what+ * carries the row. Those ids resolve through the Brain id-directories,+ * so the rows are judged by the same composed view the actions are kept+ * through: under `integrity.owner_scope_delivery: fail` another owner's+ * shift or contradiction is absent with its pref id, counts and+ * description, while the caller's own rows still render, and a scope+ * requested without the gate changes nothing.+ */+describe("digest confidence shifts and contradictions honor the caller's agent scope", () => {+ const OURS = "shared";+ const THEIRS = "owned-by-a";+ const DREAM_AT = "2026-05-24T12:00:00.000Z";+ const SINCE = new Date("2026-05-24T00:00:00Z");+ const UNTIL = new Date("2026-05-25T00:00:00Z");++ function seedShifts(): void {+ writePref(OURS, {+ topic: OURS,+ principle: `principle for ${OURS}`,+ status: "confirmed",+ created_at: "2026-05-01T00:00:00Z",+ confirmed_at: "2026-05-02T00:00:00Z",+ });+ writePref(THEIRS, {+ topic: THEIRS,+ principle: `principle for ${THEIRS}`,+ status: "confirmed",+ created_at: "2026-05-01T00:00:00Z",+ confirmed_at: "2026-05-02T00:00:00Z",+ owner: "agent-a",+ });+ appendLogEvent(+ vault,+ {+ timestamp: DREAM_AT,+ eventType: BRAIN_LOG_EVENT_KIND.dream,+ body: {+ run_id: "run-shifts",+ confidence_shifts: [+ `[[pref-${THEIRS}]] high -> medium (applied: 11, violated: 0)`,+ `[[pref-${OURS}]] low -> high (applied: 3, violated: 1)`,+ ],+ contradictions: [+ `[[pref-${THEIRS}]] contradicts the logged behaviour (topic: ${OURS})`,+ `[[pref-${OURS}]] conflicts with the recorded evidence`,+ ],+ },+ },+ { deviceId: "" },+ );+ }++ interface ShiftRow {+ readonly id: string;+ readonly applied_count: number | null;+ }+ interface ContradictionRow {+ readonly id: string;+ readonly description: string;+ }++ function rows(content: string): {+ shifts: ReadonlyArray<ShiftRow>;+ contradictions: ReadonlyArray<ContradictionRow>;+ } {+ const payload = JSON.parse(content) as {+ confidence_shifts: ReadonlyArray<ShiftRow>;+ contradictions: ReadonlyArray<ContradictionRow>;+ };+ return { shifts: payload.confidence_shifts, contradictions: payload.contradictions };+ }++ test("under fail, another owner's shift and contradiction rows are absent and the caller's own render", () => {+ seedShifts();+ setGate(GATE_MODE.fail);++ const json = renderDigest(vault, {+ format: "json",+ since: SINCE,+ until: UNTIL,+ agentScope: "agent-b",+ });+ const scoped = rows(json.content);+ expect(scoped.shifts.map((r) => r.id)).toEqual([`pref-${OURS}`]);+ expect(scoped.contradictions.map((r) => r.id)).toEqual([`pref-${OURS}`]);+ // The description of a withheld contradiction is raw log prose; none+ // of it travels either.+ expect(json.content).not.toContain(THEIRS);+ expect(json.content).not.toContain("contradicts the logged behaviour");+ // No over-filtering: the caller's own rows keep their counts and text.+ expect(scoped.shifts[0]).toMatchObject({ applied_count: 3 });+ expect(scoped.contradictions[0]!.description).toContain("conflicts with the recorded evidence");++ // Its own owner still reads both rows.+ const asOwner = renderDigest(vault, {+ format: "json",+ since: SINCE,+ until: UNTIL,+ agentScope: "agent-a",+ });+ const owned = rows(asOwner.content);+ expect(owned.shifts.map((r) => r.id)).toEqual([`pref-${THEIRS}`, `pref-${OURS}`]);+ expect(owned.contradictions.map((r) => r.id)).toEqual([`pref-${THEIRS}`, `pref-${OURS}`]);+ });++ test("a scope requested under off or warn changes no shift or contradiction row", () => {+ seedShifts();+ const unscoped = rows(+ renderDigest(vault, { format: "json", since: SINCE, until: UNTIL }).content,+ );+ // The fixture really does carry both owners' rows on both lists.+ expect(unscoped.shifts.map((r) => r.id)).toEqual([`pref-${THEIRS}`, `pref-${OURS}`]);+ expect(unscoped.contradictions.map((r) => r.id)).toEqual([`pref-${THEIRS}`, `pref-${OURS}`]);++ for (const mode of [GATE_MODE.off, GATE_MODE.warn]) {+ setGate(mode);+ const scoped = rows(+ renderDigest(vault, {+ format: "json",+ since: SINCE,+ until: UNTIL,+ agentScope: "agent-b",+ }).content,+ );+ expect(scoped.shifts).toEqual(unscoped.shifts);+ expect(scoped.contradictions).toEqual(unscoped.contradictions);+ }+ });+});diff --git a/tests/core/brain/distill/distill-source-trust.test.ts b/tests/core/brain/distill/distill-source-trust.test.tsindex f041a948..95196e2f 100644--- a/tests/core/brain/distill/distill-source-trust.test.ts+++ b/tests/core/brain/distill/distill-source-trust.test.ts@@ -55,6 +55,11 @@ import {type DistillSourceResult,} from "../../../../src/core/brain/distill/distill-source.ts";import { hashFile } from "../../../../src/core/brain/ingest/content-manifest.ts";+import { planPlantedRows } from "../../../../src/core/brain/planted-rows.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE_ENV,+ MarkdownNeutralizeModeError,+} from "../../../../src/core/brain/text/neutralize-markdown.ts";import {SOURCE_HASH_MAX_BYTES,SourceTrustError,@@ -308,3 +313,131 @@ describe("distillSource - a trusted page is what it was, plus what was added", (expect(md.replace(added, "")).toBe(BEFORE_THIS_UNIT.replace("HASH", hashFile(abs)));});});++/**+ * Claim-text neutralization on the untrusted distill lane (review M4): the+ * claims are caller text composed into the page verbatim, so a planted+ * `[[...]]` in a claim stayed live on the quarantined page even under+ * enforce - the summary seam neutralized, the distill seam did not.+ */++/** Run `run` with the gate mode env twin set, restoring it afterwards. */+function withGateMode(mode: string, run: () => void): void {+ const saved = process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = mode;+ try {+ run();+ } finally {+ if (saved === undefined) delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ else process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = saved;+ }+}++function pageBody(res: DistillSourceResult): string {+ return parseFrontmatter(join(vault, res.distillationPath))[1];+}++describe("distillSource - claim neutralization on the untrusted lane", () => {+ const URL_SOURCE = "https://example.test/claims";+ const PLANTED_CLAIM = "The [[planted]] claim";++ test("enforce escapes planted structure in claim text; the writer citation stays live", () => {+ withGateMode("enforce", () => {+ const res = distillSource(+ vault,+ { sourcePath: URL_SOURCE, claims: [{ text: PLANTED_CLAIM, block: "abc" }] },+ { agent: "claude", now: NOW },+ );+ const body = pageBody(res);+ // The caller's claim text is escaped; the writer's own block citation+ // after it is not.+ expect(body).toContain(+ "- The \\[\\[planted\\]\\] claim ([[https://example.test/claims#^abc]])",+ );+ // The conditional provenance key names what changed, on change only.+ expect(pageMeta(res)["neutralized_markers"]).toEqual(["wikilink"]);+ // The page is silent for the planted-rows audit: the Claims, Excerpt+ // and Sources sections and the source-tied citation are the writer's.+ expect(planPlantedRows(vault).planted.map((p) => p.path)).not.toContain(res.distillationPath);+ });+ });++ test("quote verification runs on the claim text the caller sent", () => {+ withGateMode("enforce", () => {+ // A URL source with an admitted excerpt is untrusted AND quotable:+ // the excerpt is the evidence the spans are checked against.+ const res = distillSource(+ vault,+ {+ sourcePath: URL_SOURCE,+ claims: [{ text: 'The "sky is blue" [[planted]] today' }],+ excerpt: "The sky is blue today",+ },+ { agent: "claude", now: NOW },+ );+ // The verified quote is counted against the ORIGINAL text; only the+ // planted link's sigils are escaped on the page.+ expect(res.quotes?.verified_in_source).toBe(1);+ const body = pageBody(res);+ expect(body).toContain('- The "sky is blue" \\[\\[planted\\]\\] today');+ // The scanner hands the frontmatter scalar back as written ("1").+ expect(pageMeta(res)["quotes_verified"]).toBe("1");+ });+ });++ test("gate off stores the claim text verbatim and the audit reports the planted row", () => {+ const res = distillSource(+ vault,+ { sourcePath: URL_SOURCE, claims: [{ text: PLANTED_CLAIM, block: "abc" }] },+ { agent: "claude", now: NOW },+ );+ const body = pageBody(res);+ expect(body).toContain("- The [[planted]] claim ([[https://example.test/claims#^abc]])");+ expect(pageMeta(res)["neutralized_markers"]).toBeUndefined();+ const planted = planPlantedRows(vault).planted.find((p) => p.path === res.distillationPath);+ expect(planted).toBeDefined();+ expect(planted!.kinds).toEqual(["wikilink"]);+ expect(planted!.count).toBe(1);+ });++ test("shadow stores the claim text verbatim", () => {+ withGateMode("shadow", () => {+ const res = distillSource(+ vault,+ { sourcePath: URL_SOURCE, claims: [{ text: PLANTED_CLAIM }] },+ { agent: "claude", now: NOW },+ );+ expect(pageBody(res)).toContain("- The [[planted]] claim");+ expect(pageMeta(res)["neutralized_markers"]).toBeUndefined();+ });+ });++ test("a trusted source's claims stay verbatim under enforce", () => {+ withGateMode("enforce", () => {+ seed(SOURCE);+ const res = distillSource(+ vault,+ { sourcePath: SOURCE, claims: [{ text: PLANTED_CLAIM }] },+ { agent: "claude", now: NOW },+ );+ expect(res.trust).toBe(INTAKE_TRUST.trusted);+ // Neutralization keys off provenance: the claims about the operator's+ // own file are the caller's writing about trusted material.+ expect(pageBody(res)).toContain("- The [[planted]] claim");+ expect(pageMeta(res)["neutralized_markers"]).toBeUndefined();+ });+ });++ test("an invalid gate mode refuses before any write", () => {+ expect(() =>+ withGateMode("yes", () =>+ distillSource(+ vault,+ { sourcePath: URL_SOURCE, claims: [{ text: "A claim" }] },+ { agent: "claude", now: NOW },+ ),+ ),+ ).toThrow(MarkdownNeutralizeModeError);+ expect(distillationPages()).toEqual([]);+ });+});diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.tsindex 0d833f0c..c2129a5c 100644--- a/tests/core/brain/doctor-exit-census.test.ts+++ b/tests/core/brain/doctor-exit-census.test.ts@@ -63,6 +63,7 @@ import { dirname, join } from "node:path";import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";import { PRIVACY_MARKER_UNSTAMPED_CODE } from "../../../src/core/brain/doctor/privacy-marker-check.ts";+import { PLANTED_STRUCTURE_ROWS_CODE } from "../../../src/core/brain/doctor/planted-rows-check.ts";import {DOCTOR_EXIT_EXCLUSIONS,doctorExitReason,@@ -191,6 +192,7 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = ["entity-label-malformed","entity-quote-variant-collision","freshen-failing",+ "git-tracked-derived-state","inbox-archivable","log-chain-broken","low-evidence-confirmed",@@ -357,6 +359,16 @@ describe("the classification is readable at runtime, not only by this test", ()expect(doctorExitReason("not-a-doctor-code")).toBeNull();});+ test("the planted structure rows finding publishes its no-command reason", () => {+ // The audit is read-only by contract, so the doctor names the reason+ // rather than an unconditional exit. Pinned by NAME: the code is read+ // from the check module, not retyped here.+ const reason = doctorExitReason(PLANTED_STRUCTURE_ROWS_CODE);+ expect(reason).toBe(DOCTOR_EXIT_EXCLUSIONS.get(PLANTED_STRUCTURE_ROWS_CODE)!);+ expect(reason!.trim().length).toBeGreaterThanOrEqual(MIN_REASON_LENGTH);+ expect(reason).not.toContain("o2b");+ });+test("the informal privacy marker finding publishes its no-command reason", () => {// The restamp is preview-first by contract, so the doctor names the// reason rather than an unconditional exit. Pinned by NAME: the code isdiff --git a/tests/core/brain/doctor/git-tracked-state-check.test.ts b/tests/core/brain/doctor/git-tracked-state-check.test.tsnew file mode 100644index 00000000..796fce87--- /dev/null+++ b/tests/core/brain/doctor/git-tracked-state-check.test.ts@@ -0,0 +1,313 @@+/**+ * The doctor's git tracked-state row (t_206562ae, task B3), against real+ * temporary git repositories - the `sync-exposure.test.ts` shape, with+ * `git init` instead of `.stfolder`.+ *+ * Tracking is measured ONLY by `git ls-files`, never inferred from+ * status: the tracked-and-ignored fixture below is the pin. Ignoring is+ * measured ONLY by `check-ignore` exit discipline. The check is silent+ * when the store is absent, in a non-git folder, or when git cannot+ * answer, and it never edits anything.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runDoctor } from "../../../../src/core/brain/doctor.ts";+import {+ GITIGNORE_GUARD_IGNORE_LINE,+ GIT_TRACKED_DERIVED_STATE_CODE,+ gitTrackedStateCheck,+ probeDerivedStoreGitState,+} from "../../../../src/core/brain/doctor/git-tracked-state-check.ts";+import { ensureVaultGitignoreEntries } from "../../../../src/core/brain/gitignore-guard.ts";+import type { DoctorIssue } from "../../../../src/core/brain/types.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-git-tracked-state-"));+ vault = join(tmp, "vault");+ // The Brain layer fixtures the doctor's pass expects, per the+ // secrets-sync fixture shape.+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {+ mkdirSync(join(vault, "Brain", d), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** `git` in the vault; git is on PATH everywhere this suite runs. */+function git(cwd: string, ...args: string[]): void {+ const run = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe" });+ if (run.exitCode !== 0) {+ throw new Error(`git ${args.join(" ")} failed: ${run.stderr.toString()}`);+ }+}++/**+ * A real repository around the vault, with its content committed.+ * `commit.gpgsign=false` keeps a machine whose global config signs+ * commits from failing these fixtures for unrelated reasons.+ */+function gitRepoWithCommit(): void {+ git(vault, "init");+ git(vault, "-c", "[email protected]", "-c", "user.name=o2b", "add", "-A");+ git(+ vault,+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "-m",+ "vault",+ );+}++function withStore(): void {+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ writeFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "sqlite-bytes", "utf8");+}++function findingsOf(severity: "error" | "warning"): ReadonlyArray<DoctorIssue> {+ const report = runDoctor(vault);+ return (severity === "error" ? report.errors : report.warnings).filter(+ (i) => i.code === GIT_TRACKED_DERIVED_STATE_CODE,+ );+}++describe("the git tracked-state doctor check", () => {+ test("is silent when the vault is not a git worktree", () => {+ withStore();+ expect(findingsOf("error")).toHaveLength(0);+ expect(findingsOf("warning")).toHaveLength(0);+ });++ test("is silent when the derived store directory is absent", () => {+ gitRepoWithCommit();+ expect(findingsOf("error")).toHaveLength(0);+ expect(findingsOf("warning")).toHaveLength(0);+ }, 20000);++ test("errors when the store is committed, naming one vault-bounded untrack command and the ignore line", () => {+ withStore();+ gitRepoWithCommit();+ const errors = findingsOf("error");+ expect(errors).toHaveLength(1);+ const message = errors[0]!.message;+ // One complete command, vault-bounded with -C, targeting the whole+ // directory: it untracks every tracked path no matter how many there+ // are, and it runs from any directory - a parent repository's root+ // included.+ expect(message).toContain(`git -C '${vault}' rm -r --cached -- .open-second-brain`);+ expect(message).toContain(GITIGNORE_GUARD_IGNORE_LINE);+ expect(message).toContain("never edits");+ }, 20000);++ test("names the complete untrack command once and keeps the path list as evidence, counting the rest", () => {+ // The cap is honest about evidence, not about the remediation: the+ // named command covers every tracked path via `-r` on the directory,+ // and the five quoted paths below it are evidence only - a real+ // store tracks brain.sqlite with -wal/-shm, audit shards, ledgers.+ withStore();+ for (let i = 0; i < 6; i += 1) {+ writeFileSync(join(vault, ".open-second-brain", `shard-${i}.sqlite`), "bytes", "utf8");+ }+ writeFileSync(join(vault, ".open-second-brain", "my db.sqlite"), "bytes", "utf8");+ gitRepoWithCommit();++ const message = findingsOf("error")[0]!.message;+ expect(message.match(/git -C /g)).toHaveLength(1);+ expect(message).toContain('".open-second-brain/my db.sqlite"');+ expect(message).toContain('".open-second-brain/shard-2.sqlite"');+ expect(message).toContain("and 3 more");+ }, 20000);++ test("errors even when the tracked store is ALSO ignored - tracking is measured, not inferred", () => {+ withStore();+ gitRepoWithCommit();+ // The ignore line arrives AFTER the commit: the path stays in the+ // index (only untracking removes it from there) and `git status`+ // would never show it again. ls-files must.+ writeFileSync(join(vault, ".gitignore"), `${GITIGNORE_GUARD_IGNORE_LINE}\n`);+ const errors = findingsOf("error");+ expect(errors).toHaveLength(1);+ expect(errors[0]!.severity).toBe("error");+ }, 20000);++ test("warns (not errors) for a present-but-unignored untracked store", () => {+ // The repository is committed BEFORE the store exists, so the store+ // is genuinely untracked: exactly the vault an init ran in without+ // git knowing.+ gitRepoWithCommit();+ withStore();+ const errors = findingsOf("error");+ expect(errors).toHaveLength(0);+ const warnings = findingsOf("warning");+ expect(warnings).toHaveLength(1);+ expect(warnings[0]!.message).toContain(GITIGNORE_GUARD_IGNORE_LINE);+ }, 20000);++ test("is silent after the full remediation: untrack plus the seeded ignore line", () => {+ withStore();+ gitRepoWithCommit();+ git(+ vault,+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "rm",+ "-r",+ "--cached",+ ".open-second-brain/brain.sqlite",+ );+ expect(ensureVaultGitignoreEntries(vault).status).toBe("created");+ git(vault, "-c", "[email protected]", "-c", "user.name=o2b", "add", "-A");+ git(+ vault,+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "-m",+ "untrack derived state",+ );+ expect(findingsOf("error")).toHaveLength(0);+ expect(findingsOf("warning")).toHaveLength(0);+ }, 20000);++ test("in a vault nested in a bigger repo, the named command untracks from the repo root", () => {+ // The tracked paths are vault-relative (`git -C <vault> ls-files`),+ // so per-path `git rm` commands fatal'd from the repository root -+ // exactly where an operator of a nested vault runs git. The one+ // command the message names is vault-bounded and runs anywhere.+ const nested = join(tmp, "nested");+ vault = join(nested, "vault");+ for (const d of [+ "Brain/preferences",+ "Brain/retired",+ "Brain/inbox",+ "Brain/processed",+ "Brain/log",+ ]) {+ mkdirSync(join(vault, d), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ withStore();+ writeFileSync(join(vault, ".open-second-brain", "ledger.sqlite"), "bytes", "utf8");+ // The repo root is `tmp`; only the nested vault's store is tracked.+ git(tmp, "init");+ git(tmp, "-c", "[email protected]", "-c", "user.name=o2b", "add", "-A");+ git(+ tmp,+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "-m",+ "repo",+ );+ const errors = findingsOf("error");+ expect(errors).toHaveLength(1);+ const message = errors[0]!.message;+ expect(message).toContain(`git -C '${vault}' rm -r --cached -- .open-second-brain`);+ expect(message).toContain('".open-second-brain/ledger.sqlite"');+ // Run exactly the command the message names, from the repository+ // root, then seed the guard and recommit: the row goes silent.+ git(+ tmp,+ "-c",+ "[email protected]",+ "-C",+ vault,+ "rm",+ "-r",+ "--cached",+ "--",+ ".open-second-brain",+ );+ expect(ensureVaultGitignoreEntries(vault).status).toBe("created");+ git(tmp, "-c", "[email protected]", "-c", "user.name=o2b", "add", "-A");+ git(+ tmp,+ "-c",+ "[email protected]",+ "-c",+ "user.name=o2b",+ "-c",+ "commit.gpgsign=false",+ "commit",+ "-m",+ "untrack the nested vault's derived state",+ );+ expect(findingsOf("error")).toHaveLength(0);+ expect(findingsOf("warning")).toHaveLength(0);+ }, 20000);++ test("never edits anything", () => {+ withStore();+ gitRepoWithCommit();+ const storeBefore = readFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "utf8");+ runDoctor(vault);+ expect(readFileSync(join(vault, ".open-second-brain", "brain.sqlite"), "utf8")).toBe(+ storeBefore,+ );+ expect(existsSync(join(vault, ".gitignore"))).toBe(false);+ }, 20000);+});++describe("the probe underneath the check", () => {+ test("a git that cannot answer is silence, not a finding", () => {+ withStore();+ gitRepoWithCommit();+ const savedPath = process.env.PATH;+ try {+ // An empty PATH: execFileSync("git") cannot resolve, every git+ // call in the probe fails, and the probe refuses to guess.+ process.env.PATH = tmp;+ const probe = probeDerivedStoreGitState(vault);+ expect(probe).toBeNull();+ const out = { issues: [] as DoctorIssue[], uncertain: [] };+ expect(() => gitTrackedStateCheck.run(probeContext(), out)).not.toThrow();+ expect(out.issues).toHaveLength(0);+ } finally {+ if (savedPath === undefined) delete process.env.PATH;+ else process.env.PATH = savedPath;+ }+ }, 20000);++ test("the check is failSoft", () => {+ expect(gitTrackedStateCheck.failSoft).toBe(true);+ });+});++/** A minimal context: the check reads nothing but `vault`. */+function probeContext(): Parameters<typeof gitTrackedStateCheck.run>[0] {+ return {+ vault,+ now: new Date(0),+ config: undefined,+ dbPath: undefined,+ configPath: undefined,+ knownBasenames: new Set(),+ idIndex: new Map(),+ preferences: [],+ logs: [],+ };+}diff --git a/tests/core/brain/doctor/planted-rows-check.test.ts b/tests/core/brain/doctor/planted-rows-check.test.tsnew file mode 100644index 00000000..2d9d6aea--- /dev/null+++ b/tests/core/brain/doctor/planted-rows-check.test.ts@@ -0,0 +1,617 @@+/**+ * The planted-structure-rows doctor audit (t_c2ac4fc8, lane A5).+ *+ * The doctor leg of the write-time neutralization: a read-only counting+ * check over the pages third-party text was written into, sharing the+ * detection grammar with the neutralizer itself, so the finding, its+ * count and what enforce mode would change cannot drift apart. Mirrors+ * the privacy-marker check's shape: one warning, count and capped named+ * paths, `ctx.readable` filtering, silent when there is nothing to+ * report, never mutating and never throwing.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ chmodSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { runDoctor } from "../../../../src/core/brain/doctor.ts";+import {+ PLANTED_STRUCTURE_ROWS_CODE,+ plantedRowsCheck,+} from "../../../../src/core/brain/doctor/planted-rows-check.ts";+import { planPlantedRows } from "../../../../src/core/brain/planted-rows.ts";+import { writeCaptureNote } from "../../../../src/core/brain/capture/capture-note.ts";+import { intakeExtraction } from "../../../../src/core/brain/intake/extract-intake.ts";+import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";+import { distillSource } from "../../../../src/core/brain/distill/distill-source.ts";+import { MARKDOWN_NEUTRALIZE_MODE_ENV } from "../../../../src/core/brain/text/neutralize-markdown.ts";+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";+import type {+ DoctorCheckContext,+ DoctorFindings,+} from "../../../../src/core/brain/doctor/check.ts";++let vault: string;++const NOW = new Date("2026-08-01T10:00:00Z");++function prov(source = "telegram"): { source: string; sender: string; capturedAt: string } {+ return { source, sender: "12345", capturedAt: "2026-08-01T10:00:00Z" };+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-planted-rows-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++/** The one planted-structure-rows warning of a run, if any. */+function plantedWarning(v: string) {+ return runDoctor(v).warnings.find((w) => w.code === PLANTED_STRUCTURE_ROWS_CODE);+}++/** A DoctorCheckContext over `v`, with an optional readability predicate. */+function checkContext(v: string, readable?: (rel: string) => boolean): DoctorCheckContext {+ return {+ vault: v,+ now: NOW,+ config: undefined,+ dbPath: undefined,+ configPath: undefined,+ ...(readable !== undefined ? { readable } : {}),+ knownBasenames: new Set<string>(),+ idIndex: new Map<string, string[]>(),+ preferences: [],+ logs: [],+ };+}++function runCheck(v: string, readable?: (rel: string) => boolean): DoctorFindings {+ const findings: DoctorFindings = { issues: [], uncertain: [] };+ plantedRowsCheck.run(checkContext(v, readable), findings);+ return findings;+}++function writePlainPage(rel: string, frontmatter: string, body: string): string {+ const abs = join(vault, ...rel.split("/"));+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, `---\n${frontmatter}\n---\n\n${body}\n`, "utf8");+ return rel;+}++/** Every file under `v` as [vault-relative path, bytes], sorted - a mutation detector. */+function snapshot(v: string): Array<[string, string]> {+ const out: Array<[string, string]> = [];+ for (const rel of readdirSync(v, { recursive: true }) as string[]) {+ const abs = join(v, rel);+ try {+ out.push([rel.replaceAll("\\", "/"), readFileSync(abs, "utf8")]);+ } catch {+ // a directory entry: readdirSync(recursive) lists those too+ }+ }+ return out.toSorted((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));+}++const PLANTED_BODY = "quotes [[planted-note]] and a\n\n## Planted Heading\n";++describe("plantedRowsCheck (the counting check)", () => {+ test("silent when nothing is planted", () => {+ writeCaptureNote(vault, { body: "a clean capture", provenance: prov() });+ expect(plantedWarning(vault)).toBeUndefined();+ });++ test("one warning counting planted pages, naming capped paths", () => {+ for (let i = 0; i < 7; i++) {+ writeCaptureNote(vault, {+ body: `capture ${i} [[planted-${i}]]`,+ provenance: prov(),+ });+ }+ const warning = plantedWarning(vault);+ expect(warning).toBeDefined();+ expect(warning!.severity).toBe("warning");+ expect(warning!.message).toContain("7 Brain page(s)");+ // The five named paths are distinct rows, all staged captures of this+ // same-second batch, with the remainder counted after the cap.+ const namedPaths = warning!.message.match(/Brain\/captures\/cap-\S+?\.md/g) ?? [];+ expect(namedPaths).toHaveLength(5);+ expect(new Set(namedPaths).size).toBe(5);+ for (const path of namedPaths) {+ expect(path).toMatch(/^Brain\/captures\/cap-2026-08-01-100000-/);+ }+ expect(warning!.message).toContain("and 2 more");+ // The paths are vault-relative: the vault root itself is never named.+ expect(warning!.message).not.toContain(vault);+ });++ test("a page the caller may not read is neither named nor counted", () => {+ writeCaptureNote(vault, { body: "visible [[a]]", provenance: prov() });+ const hidden = writeCaptureNote(vault, { body: "hidden [[b]]", provenance: prov("other") });+ const findings = runCheck(vault, (rel) => rel !== hidden.path);+ expect(findings.issues).toHaveLength(1);+ expect(findings.issues[0]!.message).not.toContain(hidden.path);+ expect(findings.issues[0]!.message).toContain("1 Brain page(s)");+ });++ test("a staged copy identical to its publish target is counted once", () => {+ const note = writeCaptureNote(vault, { body: "once [[a]]", provenance: prov() });+ const publishedAbs = join(vault, note.path);+ const stagedDir = join(vault, "Brain", "pending", "ingest");+ mkdirSync(stagedDir, { recursive: true });+ writeFileSync(join(stagedDir, "ing-2026-08-01-x.md"), readFileSync(publishedAbs, "utf8"));+ const findings = runCheck(vault);+ expect(findings.issues).toHaveLength(1);+ expect(findings.issues[0]!.message).toContain("1 Brain page(s)");+ expect(findings.issues[0]!.message).toContain(note.path);+ expect(findings.issues[0]!.message).not.toContain("Brain/pending/ingest");+ });++ test("a capture's own guidance section is writer output, not planted", () => {+ // The writer renders the trailing ## Guidance heading itself+ // (capture-note.ts) under the capture_guidance marker; on this+ // third-party lane the heading is a live atx row like any other, so+ // without the writer-section exclusion a CLEAN capture reported its+ // own writer as planted.+ writeCaptureNote(vault, {+ body: "a clean capture",+ provenance: prov(),+ guidance: "file this under projects after reading",+ });+ expect(plantedWarning(vault)).toBeUndefined();+ });++ test("an extra planted row beside a writer section is still exactly that row", () => {+ // The exclusion covers the writer's ## Guidance heading, nothing+ // else: planted rows in the caller's body count, and the writer's+ // own heading does not.+ writeCaptureNote(vault, {+ body: "note [[planted-link]]\n\n## Planted Heading\n",+ provenance: prov(),+ guidance: "file this",+ });+ const warning = plantedWarning(vault)!;+ expect(warning.message).toContain("2 live structure row(s) across 1 Brain page(s)");+ });++ test("a Guidance heading no marker authorizes is still planted", () => {+ // The writer renders ## Guidance only when it set capture_guidance;+ // an unmarked capture carrying the heading is quoting caller text+ // (people quote documents), and the split is exactly what the marker+ // authorizes.+ writePlainPage(+ "Brain/captures/cap-unmarked.md",+ "kind: brain-capture",+ "quoted material\n\n## Guidance\n\n[[planted-link]]",+ );+ const page = planPlantedRows(vault).planted.find(+ (p) => p.path === "Brain/captures/cap-unmarked.md",+ );+ expect(page).toBeDefined();+ expect(page!.kinds).toEqual(["atx-heading", "wikilink"]);+ });++ test("a source summary's own citation sections are writer output, not planted", () => {+ // ingest.ts composes every summary page as prose plus the rendered+ // provenance and link sections; the `## Sources` heading and its+ // `- [[id]]` bullets are the writer's citation rows, so a clean+ // ingest must report none of them.+ const sections = [+ "## Sources",+ "",+ "- [[cap-2026-08-01-100000-ab12cd34]]",+ "",+ "## Premises (stated)",+ "",+ "- [[fact-one]]",+ "",+ "## Entities",+ "",+ "- [[entity-one]]",+ "",+ "## Connections to existing notes",+ "",+ "- [[note-one]]",+ ].join("\n");+ writePlainPage(+ "Brain/sources/s.md",+ "kind: brain-source\nsource_path: notes/a.md",+ `summary of the source\n\n${sections}`,+ );+ expect(planPlantedRows(vault).planted).toEqual([]);+ // Every provenance level is a writer-rendered heading spelling. The+ // writer renders Premises only AFTER its own ## Sources citation+ // (renderProvenanceSection emits Sources first), so the fixture carries+ // the citation a real summary page always has.+ writePlainPage(+ "Brain/sources/s2.md",+ "kind: brain-source\nsource_path: notes/b.md",+ "summary\n\n## Sources\n\n- [[cap-2026-08-01-100000-ab12cd34]]\n\n## Premises (inferred)\n\n- [[fact-two]]",+ );+ expect(planPlantedRows(vault).planted).toEqual([]);+ });++ test("the derivation headings a summary writer renders are not planted either", () => {+ // The html and table extractors append their own sections to the+ // same summary page (extract-html.ts `## Parts`, table-note.ts+ // `## Table` with one `### Rows a-b` heading per group); those+ // headings are writer-rendered like the citation sections.+ const derivation = [+ "## Parts",+ "",+ "```parts",+ "h1 Title | lines 0-3",+ "```",+ "",+ "## Table",+ "",+ "```table",+ "a | b",+ "1 | 2",+ "```",+ "",+ "### Rows 0-1",+ "",+ "```table",+ "a | b",+ "1 | 2",+ "```",+ "",+ "Rendered 2 of 2 rows.",+ ].join("\n");+ writePlainPage(+ "Brain/sources/t.md",+ "kind: brain-source\nsource_path: data/t.csv",+ `summary of the table\n\n## Sources\n\n- [[cap-2026-08-01-100000-ab12cd34]]\n\n${derivation}`,+ );+ expect(planPlantedRows(vault).planted).toEqual([]);+ });++ test("an extra planted row in the summary prose is still exactly that row", () => {+ const sections = ["## Sources", "", "- [[cap-one]]"].join("\n");+ writePlainPage(+ "Brain/sources/s.md",+ "kind: brain-source\nsource_path: notes/a.md",+ `caller [[planted-link]] prose\n\n## Planted Heading\n\n${sections}`,+ );+ const warning = plantedWarning(vault)!;+ expect(warning.message).toContain("2 live structure row(s) across 1 Brain page(s)");+ });++ test("a quarantined entity page's writer sections are writer output, not planted", () => {+ // The registry composes every quarantined entity page as the writer's+ // `# <name>` H1 plus the provenance citation (`## Sources` with its+ // `- [[source]]` bullet, renderProvenanceSection) - review H2: without+ // the brain-entity writer rules a CLEAN untrusted ingest reported its+ // own writer as planted, a permanent warning on any vault that ever+ // ingested an untrusted source.+ intakeExtraction(+ vault,+ { entities: [{ category: "person", name: "Alice Example" }], relations: [] },+ {+ agent: "claude",+ now: NOW,+ provenance: { level: "stated", sources: ["[[https://example.test/x]]"], premises: [] },+ },+ );+ const plan = planPlantedRows(vault);+ expect(plan.planted.find((p) => p.path.startsWith("Brain/entities/"))).toBeUndefined();+ });++ test("a planted name on an entity page is exactly that row beside the writer's sections", () => {+ // The writer's H1 shape (`# ` on the first body line) and its citation+ // sections are exempt; the NAME content is caller text, so a wikilink+ // planted inside it counts - the heading row on the same line does not.+ intakeExtraction(+ vault,+ {+ entities: [{ category: "person", name: "Alice [[evil-target]] Example" }],+ relations: [],+ },+ {+ agent: "claude",+ now: NOW,+ provenance: { level: "stated", sources: ["[[https://example.test/x]]"], premises: [] },+ },+ );+ const page = planPlantedRows(vault).planted.find((p) => p.path.startsWith("Brain/entities/"));+ expect(page).toBeDefined();+ expect(page!.kinds).toEqual(["wikilink"]);+ expect(page!.count).toBe(1);+ });++ test("a distillation page's writer sections are writer output, not planted", () => {+ // distill-source.ts composes every distillation page from its own+ // `## Claims`, `## Excerpt` and `## Sources` sections (review H2): a+ // clean untrusted distillation reported 4 planted rows of the writer's+ // own output.+ distillSource(+ vault,+ {+ sourcePath: "https://example.test/y",+ claims: [{ text: "The sky is blue" }],+ excerpt: "The sky is blue today",+ },+ { agent: "claude", now: NOW },+ );+ const plan = planPlantedRows(vault);+ expect(plan.planted.find((p) => p.path.startsWith("Brain/distillations/"))).toBeUndefined();+ });++ test("a planted claim is exactly that row beside the writer's block citation", () => {+ // The writer's claim-bullet citation `([[source#^block]])` ties to the+ // page's own source_path frontmatter and is exempt; a wikilink planted+ // in the caller's claim TEXT ties to nothing and counts.+ distillSource(+ vault,+ {+ sourcePath: "https://example.test/y",+ claims: [{ text: "The [[planted]] claim", block: "abc" }],+ },+ { agent: "claude", now: NOW },+ );+ const page = planPlantedRows(vault).planted.find((p) =>+ p.path.startsWith("Brain/distillations/"),+ );+ expect(page).toBeDefined();+ expect(page!.kinds).toEqual(["wikilink"]);+ expect(page!.count).toBe(1);+ });++ test("a quoted writer heading in the prose is planted when the writer rendered no such section", () => {+ // Review M1, reproduced end to end: the writer emits no ## Entities+ // section when the extraction named no entities (ingest.ts renders the+ // link sections only when non-empty), so a summary QUOTING the heading+ // is its last occurrence and its planted bullets used to be masked.+ const summary = [+ "Some prose about the source.",+ "",+ "## Entities",+ "",+ "- [[evil-target]]",+ "- [[another-planted]]",+ ].join("\n");+ const res = ingestSource(+ vault,+ {+ sourcePath: "https://example.test/z",+ summary,+ extraction: { entities: [], relations: [] },+ },+ { agent: "claude", now: NOW },+ );+ const page = planPlantedRows(vault).planted.find((p) => p.path === res.summaryPath);+ expect(page).toBeDefined();+ expect(page!.kinds).toEqual(["atx-heading", "wikilink"]);+ expect(page!.count).toBe(3);+ });++ test("a quoted section reports while the writer's own section after the citation stays exempt", () => {+ // The writer's sections all render after its ## Sources citation, so+ // that heading is the writer's prose boundary: an occurrence before it+ // is a caller quotation and counts, the writer's own occurrence after+ // it stays exempt.+ writePlainPage(+ "Brain/sources/q.md",+ "kind: brain-source\nsource_path: notes/a.md",+ [+ "prose",+ "",+ "## Entities",+ "",+ "- [[evil-target]]",+ "",+ "## Sources",+ "",+ "- [[cap-one]]",+ "",+ "## Entities",+ "",+ "- [[ent-real]]",+ ].join("\n"),+ );+ const page = planPlantedRows(vault).planted.find((p) => p.path === "Brain/sources/q.md");+ expect(page).toBeDefined();+ expect(page!.kinds).toEqual(["atx-heading", "wikilink"]);+ expect(page!.count).toBe(2);+ });++ test("a quoted ### Rows heading outside the writer's derivation region is planted", () => {+ // The ranged Rows headings are writer output only inside the writer's+ // own region (after its ## Sources citation); the prefix match no+ // longer exempts every occurrence anywhere in the body.+ writePlainPage(+ "Brain/sources/r.md",+ "kind: brain-source\nsource_path: data/t.csv",+ "prose\n\n### Rows 0-9\n\n[[planted]]\n\n## Sources\n\n- [[cap-one]]",+ );+ const page = planPlantedRows(vault).planted.find((p) => p.path === "Brain/sources/r.md");+ expect(page).toBeDefined();+ expect(page!.kinds).toEqual(["atx-heading", "wikilink"]);+ expect(page!.count).toBe(2);+ });++ test("a staged copy is reported when its published twin is unreadable to the caller", () => {+ // Dedupe runs inside the planner, which knows nothing of+ // ctx.readable; the check filters by it afterwards. A readable+ // staged page whose hash-equal twin the caller may not read must+ // still be reported - dropping the staged copy in favor of a twin+ // the check then filters out would make BOTH disappear.+ const note = writeCaptureNote(vault, { body: "twin [[a]]", provenance: prov() });+ const stagedRel = "Brain/pending/ingest/ing-2026-08-01-x.md";+ mkdirSync(dirname(join(vault, ...stagedRel.split("/"))), { recursive: true });+ writeFileSync(+ join(vault, ...stagedRel.split("/")),+ readFileSync(join(vault, ...note.path.split("/")), "utf8"),+ );+ const findings = runCheck(vault, (rel) => rel !== note.path);+ expect(findings.issues).toHaveLength(1);+ expect(findings.issues[0]!.message).toContain(stagedRel);+ expect(findings.issues[0]!.message).not.toContain(note.path);+ });++ test("the marker and fence families scan every readable Brain page; the rest stay lane-keyed", () => {+ // A planted @osb marker on a page NO Brain writer could have authored+ // it on is reported wherever it sits: the §9 vault scan would harvest+ // a live marker from any page it walks, and no Brain writer ever+ // emits one (only the consumed @osb✓ sentinel), so provenance gates+ // nothing for the marker and fence families.+ writePlainPage(+ "Brain/notes/note-x.md",+ "kind: note",+ "@osb feedback negative topic=t principle=p\n",+ );+ writePlainPage("Notes/plain.md", "kind: note", "@osb feedback negative topic=t principle=p\n");+ const plan = planPlantedRows(vault);+ const paths = plan.planted.map((p) => p.path);+ expect(paths).toEqual(["Brain/notes/note-x.md"]);+ expect(paths).not.toContain("Notes/plain.md");+ // Not a third-party lane: the classification rides along as context.+ expect(plan.planted[0]!.thirdParty).toBe(false);+ expect(plan.planted[0]!.kinds).toEqual(["osb-inline"]);+ // The wikilink and heading families stay keyed to the third-party+ // lanes: the Brain's own writers render those by design on pages+ // outside the lanes (the manual's section headings, the log's+ // [[Brain/log/...]] refs), so reporting them regardless of provenance+ // would report the vault's own structure as planted on every run.+ writePlainPage("Brain/notes/note-y.md", "kind: note", PLANTED_BODY);+ const laneKeyed = planPlantedRows(vault);+ expect(laneKeyed.planted.map((p) => p.path)).toEqual(["Brain/notes/note-x.md"]);+ // On a third-party lane page the same body IS a finding.+ writePlainPage(+ "Brain/sources/s.md",+ "kind: brain-source\nsource_path: x\nuntrusted_source: true",+ PLANTED_BODY,+ );+ const after = planPlantedRows(vault);+ const afterPaths = after.planted.map((p) => p.path);+ expect(afterPaths).toContain("Brain/sources/s.md");+ expect(after.planted.find((p) => p.path === "Brain/sources/s.md")!.thirdParty).toBe(true);+ expect(after.planted.find((p) => p.path === "Brain/sources/s.md")!.kinds).toEqual([+ "atx-heading",+ "wikilink",+ ]);+ // The Brain's own machinery is silent: a bootstrap vault's manual+ // carries designed headings and no marker family rows at all.+ expect(afterPaths).not.toContain("Brain/_BRAIN.md");+ });++ test("the finding names the population split and counts the third-party lanes", () => {+ writeCaptureNote(vault, { body: "third [[a]]", provenance: prov() });+ writePlainPage("Brain/notes/note-y.md", "kind: note", "@osb set note=n field=f value=v");+ const warning = plantedWarning(vault)!;+ expect(warning.message).toContain("Brain page(s)");+ // The population split, stated exactly as the planner applies it:+ // one family everywhere, the other only on the lanes, and the+ // writers' own sections excluded from both.+ expect(warning.message).toContain("The population splits by family");+ expect(warning.message).toContain(+ "marker and osb-fence families are scanned on every readable page under Brain/",+ );+ expect(warning.message).toContain(+ "wikilink and heading families are scanned only on the third-party provenance lanes",+ );+ expect(warning.message).toContain("excluded, not reported");+ expect(warning.message).toContain("1 of the page(s) sit in the third-party lanes");+ // Third-party pages are named before the rest: the provenance context.+ expect(warning.message.indexOf("Brain/captures/")).toBeLessThan(+ warning.message.indexOf("Brain/notes/"),+ );+ });++ test.skipIf(CHMOD_CANNOT_DENY)(+ "a publish twin the audit cannot hash does not drop its staged copy",+ () => {+ // The published twin goes unreadable between the walk (which admits+ // it) and the hash (which comes back undefined). An undefined hash+ // must match nothing - two unreadable pages are not the same page -+ // so the readable staged copy stays in the report.+ const note = writeCaptureNote(vault, { body: "once [[a]]", provenance: prov() });+ const stagedDir = join(vault, "Brain", "pending", "ingest");+ mkdirSync(stagedDir, { recursive: true });+ const stagedRel = "Brain/pending/ingest/ing-2026-08-01-x.md";+ writeFileSync(+ join(vault, ...stagedRel.split("/")),+ readFileSync(join(vault, note.path), "utf8"),+ );+ const publishedAbs = join(vault, ...note.path.split("/"));+ chmodSync(publishedAbs, 0o000);+ try {+ const findings = runCheck(vault);+ expect(findings.issues[0]!.message).toContain(stagedRel);+ } finally {+ chmodSync(publishedAbs, 0o644);+ }+ },+ );++ test("the body scan is fence-masked: inert code hides nothing in, planted fences count", () => {+ // A wikilink inside a python fence is inert; an osb block's fence+ // lines are live structure the marker scanners consume.+ writeCaptureNote(vault, {+ body: "```python\nx = '[[inert]]'\n```\n\nlive [[live-one]]\n",+ provenance: prov(),+ });+ const plan = planPlantedRows(vault);+ expect(plan.planted).toHaveLength(1);+ expect(plan.planted[0]!.count).toBe(1);+ expect(plan.planted[0]!.kinds).toEqual(["wikilink"]);+ writeCaptureNote(vault, {+ body: "```osb\nkind: set\nnote: n\nfield: a\nvalue: b\n```\n",+ provenance: prov(),+ });+ const fencePlan = planPlantedRows(vault);+ const fencePage = fencePlan.planted.find((p) => p.kinds.includes("osb-fence"));+ expect(fencePage).toBeDefined();+ expect(fencePage!.kinds).toEqual(["osb-fence"]);+ });++ test("the check never mutates and never throws over a NUL-byte page", () => {+ writeCaptureNote(vault, { body: "planted [[a]]", provenance: prov() });+ // A NUL byte in the body is ordinary text, not structure: detection+ // neither chokes on it nor counts it, and the page's live wikilink+ // row is reported exactly as it would be without the byte.+ writePlainPage("Brain/captures/corrupt.md", "kind: brain-capture", "body [[x]]\n\x00binary");+ const before = snapshot(vault);+ expect(() => runCheck(vault)).not.toThrow();+ expect(runCheck(vault).issues.length).toBeGreaterThanOrEqual(1);+ const nulPage = planPlantedRows(vault).planted.find(+ (p) => p.path === "Brain/captures/corrupt.md",+ );+ expect(nulPage).toBeDefined();+ expect(nulPage!.count).toBe(1);+ expect(nulPage!.kinds).toEqual(["wikilink"]);+ expect(snapshot(vault)).toEqual(before);+ });++ test("shadow mode adds the would-be-enforce wording; off does not", () => {+ const saved = process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ try {+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = "shadow";+ writeCaptureNote(vault, { body: "planted [[a]]", provenance: prov() });+ const shadowMessage = plantedWarning(vault)!.message;+ expect(shadowMessage).toContain("shadow");+ expect(shadowMessage).toContain("enforce");+ rmSync(join(vault, "Brain", "captures"), { recursive: true, force: true });+ delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ writeCaptureNote(vault, { body: "planted [[b]]", provenance: prov() });+ expect(plantedWarning(vault)!.message).not.toContain("shadow");+ } finally {+ if (saved === undefined) delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ else process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = saved;+ }+ });+});diff --git a/tests/core/brain/gitignore-guard.test.ts b/tests/core/brain/gitignore-guard.test.tsnew file mode 100644index 00000000..d15127cb--- /dev/null+++ b/tests/core/brain/gitignore-guard.test.ts@@ -0,0 +1,520 @@+/**+ * The vault `.gitignore` guard seeder (t_206562ae, task B1).+ *+ * `bootstrapBrain` seeds a managed block into `<vault>/.gitignore` whose+ * entry list starts as exactly one vault-root-anchored line,+ * `/.open-second-brain/` - one entry covering every Tier A derived-state+ * writer (brain.sqlite, hook-audit, secrets, maintenance sqlite and+ * journals, ingest checkpoints, dead-letters, session ledgers, watchdog+ * fallback, self-heal state, locks, bench runs). The seeder never shells+ * out to git and never touches bytes outside the block.+ *+ * The census at the bottom is the source-reading half (same discipline as+ * `tests/hooks/audit-root.test.ts` and the sync-lockfile lock-site+ * census): the entry covers the directory only while every derived-state+ * writer actually resolves under it, so the sweep pins the population.+ */++import { describe, expect, test } from "bun:test";+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ DEFAULT_BEGIN_MARKER,+ DEFAULT_END_MARKER,+} from "../../../src/core/install/managed-block.ts";+import {+ ensureVaultGitignoreEntries,+ GITIGNORE_GUARD_ENTRIES,+ GITIGNORE_GUARD_FILE,+} from "../../../src/core/brain/gitignore-guard.ts";+import { BENCH_RUNS_REL, DERIVED_STORE_DIR } from "../../../src/core/brain/path-constants.ts";++let vault: string;++function freshVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-gitignore-guard-"));+ return dir;+}++function gitignorePath(): string {+ return join(vault, GITIGNORE_GUARD_FILE);+}++function seededBlock(): string {+ return `${DEFAULT_BEGIN_MARKER}\n${GITIGNORE_GUARD_ENTRIES.join("\n")}\n${DEFAULT_END_MARKER}\n`;+}++/**+ * The git-valid spellings of a negating line the matcher must catch.+ * Beyond the two plain forms: a trailing slash, git's ignored unescaped+ * trailing whitespace, and the double-star-slash prefix that matches+ * zero or more directories (so it covers the vault root too). Spellings+ * OUTSIDE this list - escaped-dot spellings, character-class and+ * bracket-expression tricks - stay out of scope on purpose: the doctor's+ * git-tracked-state row measures what git actually did, and is the+ * authority for everything this matcher cannot name.+ */+const NEGATION_LINE_VARIANTS: ReadonlyArray<string> = [+ "!.open-second-brain",+ "!/.open-second-brain",+ "!.open-second-brain/",+ "!/.open-second-brain/",+ "!.open-second-brain ",+ "!**/.open-second-brain",+ "!**/.open-second-brain/",+];++describe("ensureVaultGitignoreEntries", () => {+ test("creates a .gitignore containing only the block when none exists", () => {+ vault = freshVault();+ try {+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("created");+ expect(result.file).toBe(GITIGNORE_GUARD_FILE);+ expect(existsSync(gitignorePath())).toBe(true);+ expect(readFileSync(gitignorePath(), "utf8")).toBe(seededBlock());+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("appends the block to an existing user .gitignore, byte-preserving user content", () => {+ vault = freshVault();+ try {+ const user = "# my patterns\n*.tmp\n.obsidian/workspace.json\n";+ writeFileSync(gitignorePath(), user, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("updated");+ const next = readFileSync(gitignorePath(), "utf8");+ expect(next.startsWith(user)).toBe(true);+ expect(next).toContain(DEFAULT_BEGIN_MARKER);+ expect(next).toContain(`/${DERIVED_STORE_DIR}/`);+ expect(next).toContain(DEFAULT_END_MARKER);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a second run is a no-op: byte-equal file, skipped", () => {+ vault = freshVault();+ try {+ ensureVaultGitignoreEntries(vault);+ const before = readFileSync(gitignorePath(), "utf8");+ const second = ensureVaultGitignoreEntries(vault);+ expect(second.status).toBe("skipped");+ expect(readFileSync(gitignorePath(), "utf8")).toBe(before);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a user line that already ignores the path yields a skip, not a duplicate", () => {+ vault = freshVault();+ try {+ const user = "*.tmp\n/.open-second-brain/\n";+ writeFileSync(gitignorePath(), user, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("skipped");+ expect(readFileSync(gitignorePath(), "utf8")).toBe(user);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("CRLF files keep their line endings in both the user content and the block", () => {+ vault = freshVault();+ try {+ writeFileSync(gitignorePath(), "# my patterns\r\n*.tmp\r\n", "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("updated");+ const next = readFileSync(gitignorePath(), "utf8");+ expect(next.startsWith("# my patterns\r\n*.tmp\r\n")).toBe(true);+ expect(next).toContain(`${DEFAULT_BEGIN_MARKER}\r\n`);+ expect(next).toContain(`/${DERIVED_STORE_DIR}/\r\n`);+ expect(next).toContain(`${DEFAULT_END_MARKER}\r\n`);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("an existing conforming block with extra entries merges without losing them", () => {+ vault = freshVault();+ try {+ const prior = `${DEFAULT_BEGIN_MARKER}\n*.log\n${DEFAULT_END_MARKER}\n`;+ writeFileSync(gitignorePath(), prior, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("updated");+ const next = readFileSync(gitignorePath(), "utf8");+ // The block survives as ONE block, its prior entries kept, ours added.+ expect(next.match(new RegExp(DEFAULT_BEGIN_MARKER, "g"))).toHaveLength(1);+ expect(next).toContain("*.log");+ expect(next).toContain(`/${DERIVED_STORE_DIR}/`);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("malformed existing markers surface the named conflict without writing", () => {+ vault = freshVault();+ try {+ const broken = "# mine\n# >>> open-second-brain managed >>>\n*.tmp\n";+ writeFileSync(gitignorePath(), broken, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("conflict");+ expect(result.detail).toBeTruthy();+ // Warn-and-continue: the file is exactly as the user left it.+ expect(readFileSync(gitignorePath(), "utf8")).toBe(broken);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("two begin markers are a conflict too", () => {+ vault = freshVault();+ try {+ const broken = `${DEFAULT_BEGIN_MARKER}\n${DEFAULT_END_MARKER}\n${DEFAULT_BEGIN_MARKER}\n`;+ writeFileSync(gitignorePath(), broken, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("conflict");+ expect(readFileSync(gitignorePath(), "utf8")).toBe(broken);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a later negating line turns the exact-line skip into a named conflict", () => {+ // git evaluates .gitignore patterns in order and the LAST match+ // wins: with `!.open-second-brain` after the entry the store is NOT+ // ignored, so reporting a clean skip here would be optimistic. The+ // doctor row catches it later; the init report itself must not lie.+ for (const negation of NEGATION_LINE_VARIANTS) {+ vault = freshVault();+ try {+ const hostile = `/.open-second-brain/\n*.tmp\n${negation}\n`;+ writeFileSync(gitignorePath(), hostile, "utf8");+ let result!: ReturnType<typeof ensureVaultGitignoreEntries>;+ const { stderr } = captureStderr(() => {+ result = ensureVaultGitignoreEntries(vault);+ });+ expect(result.status).toBe("conflict");+ expect(result.detail).toContain(negation.trim());+ // Warn-and-continue: the file is exactly as the user left it.+ expect(readFileSync(gitignorePath(), "utf8")).toBe(hostile);+ expect(stderr).toMatch(/warning:/);+ expect(stderr).toContain("derived-brain-state");+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ }+ });++ test("a conforming block that a later negation defeats is a conflict, not a clean update", () => {+ // The merge would land the entry INSIDE the earlier block, so the+ // negation after the block still wins under git's last-match rule:+ // a clean `updated` here would seed nothing effective while the+ // report claimed the guard moved.+ vault = freshVault();+ try {+ const hostile = `${DEFAULT_BEGIN_MARKER}\n*.log\n${DEFAULT_END_MARKER}\n!.open-second-brain\n`;+ writeFileSync(gitignorePath(), hostile, "utf8");+ let result!: ReturnType<typeof ensureVaultGitignoreEntries>;+ const { stderr } = captureStderr(() => {+ result = ensureVaultGitignoreEntries(vault);+ });+ expect(result.status).toBe("conflict");+ expect(result.detail).toContain("!.open-second-brain");+ // Warn-and-continue: the file is exactly as the user left it, and+ // the store stays unprotected - reported, never claimed as seeded.+ expect(readFileSync(gitignorePath(), "utf8")).toBe(hostile);+ expect(stderr).toMatch(/warning:/);+ expect(stderr).toContain("derived-brain-state");+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a negation BEFORE the block is overridden by the merged entry - a clean update", () => {+ // Last-match-wins favors the entry the merge adds, because it lands+ // after the negation inside the block.+ vault = freshVault();+ try {+ const user = `!.open-second-brain\n${DEFAULT_BEGIN_MARKER}\n*.log\n${DEFAULT_END_MARKER}\n`;+ writeFileSync(gitignorePath(), user, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("updated");+ const next = readFileSync(gitignorePath(), "utf8");+ expect(next).toContain(`/${DERIVED_STORE_DIR}/`);+ expect(next).toContain("*.log");+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("an existing empty block gains the entry without a stray blank line", () => {+ // Begin marker directly followed by end marker: the block body is+ // the empty string, and `"".split("\n")` yields [""], which used to+ // open the merged block with a blank line.+ vault = freshVault();+ try {+ writeFileSync(gitignorePath(), `${DEFAULT_BEGIN_MARKER}\n${DEFAULT_END_MARKER}\n`, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("updated");+ expect(readFileSync(gitignorePath(), "utf8")).toBe(+ `${DEFAULT_BEGIN_MARKER}\n/${DERIVED_STORE_DIR}/\n${DEFAULT_END_MARKER}\n`,+ );+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a negation BEFORE the entry is a clean skip - last-match-wins favors the entry", () => {+ vault = freshVault();+ try {+ const harmless = "!.open-second-brain\n/.open-second-brain/\n";+ writeFileSync(gitignorePath(), harmless, "utf8");+ const result = ensureVaultGitignoreEntries(vault);+ expect(result.status).toBe("skipped");+ expect(readFileSync(gitignorePath(), "utf8")).toBe(harmless);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a symlinked .gitignore is a conflict: the link is kept, the target untouched", () => {+ // An operator who manages the vault .gitignore as a link into their+ // dotfiles loses the link silently if the seeder writes: the atomic+ // write renames a regular file over the LINK path, and init would+ // report a clean `updated`. The seeder must refuse like every other+ // writer in this tree, naming the link target, and the doctor row+ // then reports the still-unprotected store.+ vault = freshVault();+ try {+ const target = join(vault, "dotfiles.gitignore");+ const user = "# my patterns\n";+ writeFileSync(target, user, "utf8");+ symlinkSync("dotfiles.gitignore", gitignorePath());+ let result!: ReturnType<typeof ensureVaultGitignoreEntries>;+ const { stderr } = captureStderr(() => {+ result = ensureVaultGitignoreEntries(vault);+ });+ expect(result.status).toBe("conflict");+ expect(result.detail).toContain("dotfiles.gitignore");+ expect(result.detail!.length).toBeGreaterThan(0);+ // The link is still a link, and the target holds exactly the+ // user's bytes - nothing was written anywhere.+ expect(lstatSync(gitignorePath()).isSymbolicLink()).toBe(true);+ expect(readFileSync(target, "utf8")).toBe(user);+ expect(stderr).toMatch(/warning:/);+ expect(stderr).toContain("derived-brain-state");+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a dangling .gitignore link is a conflict too, never replaced by a created file", () => {+ // existsSync is false through a dangling link, which used to route+ // the seeder into the created branch - renaming a regular file over+ // the link. The refusal must see the link itself, so the same+ // conflict applies and the (broken, but the operator's) link stays.+ vault = freshVault();+ try {+ symlinkSync("gone-target.gitignore", gitignorePath());+ let result!: ReturnType<typeof ensureVaultGitignoreEntries>;+ const { stderr } = captureStderr(() => {+ result = ensureVaultGitignoreEntries(vault);+ });+ expect(result.status).toBe("conflict");+ expect(result.detail).toContain("gone-target.gitignore");+ expect(lstatSync(gitignorePath()).isSymbolicLink()).toBe(true);+ expect(existsSync(gitignorePath())).toBe(false);+ expect(existsSync(join(vault, "gone-target.gitignore"))).toBe(false);+ expect(stderr).toMatch(/warning:/);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });+});++/** Run `fn`, capturing everything it writes to stderr; restore afterwards. */+function captureStderr(fn: () => unknown): { stderr: string } {+ const original = process.stderr.write.bind(process.stderr);+ let captured = "";+ process.stderr.write = ((chunk: string | Uint8Array): boolean => {+ captured += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");+ return true;+ }) as typeof process.stderr.write;+ try {+ fn();+ } finally {+ process.stderr.write = original;+ }+ return { stderr: captured };+}++// ----- Source-reading census ------------------------------------------------++/**+ * Every `src/` file that references the derived store, by constant or by+ * the directory's literal name (as a quoted path segment or a+ * slash-anchored pattern in a message). This is the population the+ * `/.open-second-brain/` entry has to cover.+ */+const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "src");++const DERIVED_STORE_REFERENCE_RE =+ /DERIVED_STORE_DIR|DERIVED_STORE_FILE|BENCH_RUNS_REL|"\.open-second-brain"|\/\.open-second-brain/;++function derivedStoreSites(): string[] {+ const out: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ walk(full);+ continue;+ }+ if (!entry.name.endsWith(".ts")) continue;+ if (DERIVED_STORE_REFERENCE_RE.test(readFileSync(full, "utf8"))) {+ out.push(full.slice(SRC.length + 1).replaceAll("\\", "/"));+ }+ }+ };+ walk(SRC);+ return out.toSorted();+}++/**+ * Declared derived-state sites, each with what its reference IS. A new+ * site fails the census until its author states what the reference is+ * here; a declared site whose reference disappears (a writer moved its+ * paths outside the covered directory) fails the membership assertion.+ */+const DECLARED_SITES: ReadonlyMap<string, string> = new Map([+ ["cli/bootstrap/receipt.ts", "bootstraps the bootstrap lockfile under the store"],+ ["cli/bootstrap/run.ts", "CLI bootstrap reporting that names the store"],+ ["cli/brain/help-text.ts", "help prose naming the store directory"],+ ["cli/brain/verbs/bench.ts", "bench runs default dir, composed from BENCH_RUNS_REL"],+ ["cli/brain/verbs/dead-letters.ts", "dead-letter listing prose naming the store"],+ [+ "core/brain/checkpoint-store.ts",+ "the shared checkpoint substrate under the store (ingest and session-import lanes)",+ ],+ ["core/brain/dead-letter.ts", "dead letters under the store"],+ ["core/brain/gitignore-guard.ts", "composes the seeded guard entry from the constant"],+ ["core/brain/init.ts", "bootstraps the seed; names the entry in its step 1c docblock"],+ [+ "core/brain/doctor/git-tracked-state-check.ts",+ "composes the ls-files pathspec and the guard ignore line from the constant",+ ],+ ["core/brain/ingest/checkpoint.ts", "ingest checkpoints under the store"],+ [+ "core/brain/ingest/content-manifest.ts",+ "ingest content manifest under the store, spelled as the private MACHINE_ARTIFACT_DIR beside its join",+ ],+ [+ "core/brain/inject-failopen.ts",+ "inject cache under the store, spelled as the private INJECT_CACHE_DIR beside its join",+ ],+ ["core/brain/maintenance/journal.ts", "maintenance journals under the store"],+ ["core/brain/maintenance/lease.ts", "maintenance lease sqlite under the store"],+ ["core/brain/path-constants.ts", "owns the directory name itself"],+ ["core/brain/paths.ts", "composes the hook-audit root under the store from the constant"],+ [+ "core/brain/protect.ts",+ "protect manifest under the store, spelled as the private MANIFEST_DIR beside its join",+ ],+ ["core/brain/recall-inject.ts", "recall injection reporting that names the store"],+ ["core/brain/secrets/store.ts", "secrets directory under the store, spelled as a join literal"],+ ["core/brain/secrets/token-store.ts", "token-store reporting that names the store"],+ ["core/brain/session-mining-ledger.ts", "session mining ledger under the store"],+ ["core/brain/session-mining-surveys.ts", "session mining surveys under the store"],+ ["core/brain/sessions/discover.ts", "session import ledger under the store"],+ ["core/brain/snapshot.ts", "snapshot recovery reaching the brain.sqlite file"],+ ["core/brain/storage/usage.ts", "storage census over the store"],+ ["core/brain/sync-lockfile.ts", "lock files under the store"],+ [+ "core/brain/temporal/weekly-brief.ts",+ "weekly brief EXCLUDES the store by directory name, it writes nothing there",+ ],+ ["core/brain/watchdog.ts", "watchdog audit fallback under the store"],+ ["core/derived-store-guard.ts", "the symlink guard over the store directory itself"],+ ["core/doctor-selftest.ts", "doctor self-test writing probe state under the store"],+ [+ "core/graph/mcp-config.ts",+ "MCP config SKIP_DIRS excludes the store by name, it writes nothing there",+ ],+ ["core/install/adapters/aider.ts", "aider adapter reporting that names the store"],+ [+ "core/install/adapters/aider-wrapper.ts",+ "aider context artifact under the store, spelled as a join literal",+ ],+ ["core/install/manifest.ts", "install lockfile under the store, spelled as a join literal"],+ ["core/maintenance/self-heal-upgrade-state.ts", "self-heal upgrade state under the store"],+ ["core/search/paths.ts", "composes the brain.sqlite path under the store from the constants"],+ ["core/state/surfaces.ts", "state surfaces census over the store"],+ [+ "core/vault-scope/defaults.ts",+ "DEFAULT_VAULT_IGNORE_PATHS excludes the store by name, it writes nothing there",+ ],+]);++describe("every derived-state site sits under the covered directory", () => {+ test("the sweep actually found the sites", () => {+ // A census over an empty set passes for the wrong reason.+ expect(derivedStoreSites().length).toBeGreaterThan(20);+ });++ test("no derived-state site is missing from the declared set", () => {+ const undeclared = derivedStoreSites().filter((rel) => !DECLARED_SITES.has(rel));+ expect(undeclared).toEqual([]);+ });++ test("every declared site still exists and still references the store", () => {+ const vanished = [...DECLARED_SITES.keys()].filter((rel) => {+ const path = join(SRC, rel);+ if (!existsSync(path)) return true;+ return !DERIVED_STORE_REFERENCE_RE.test(readFileSync(path, "utf8"));+ });+ expect(vanished).toEqual([]);+ });++ test("the bench runs dir is hoisted, not locally spelled", () => {+ // The default runs dir is named beside DERIVED_STORE_DIR so the+ // guard's single entry provably covers it (task B1).+ expect(BENCH_RUNS_REL).toBe(`${DERIVED_STORE_DIR}/bench-runs`);+ const bench = readFileSync(join(SRC, "cli", "brain", "verbs", "bench.ts"), "utf8");+ expect(bench).not.toContain('".open-second-brain"');+ expect(bench).toContain("BENCH_RUNS_REL");+ });+});++describe("the guard's entry list", () => {+ test("starts as exactly one vault-root-anchored entry naming the store", () => {+ expect([...GITIGNORE_GUARD_ENTRIES]).toEqual([`/${DERIVED_STORE_DIR}/`]);+ });++ test("seeding a fresh vault covers the derived store root", () => {+ vault = freshVault();+ try {+ mkdirSync(vault, { recursive: true });+ ensureVaultGitignoreEntries(vault);+ const content = readFileSync(gitignorePath(), "utf8");+ expect(content).toContain(`/${DERIVED_STORE_DIR}/`);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });+});diff --git a/tests/core/brain/ingest/ingest-marker-neutralize.test.ts b/tests/core/brain/ingest/ingest-marker-neutralize.test.tsnew file mode 100644index 00000000..6392cf5d--- /dev/null+++ b/tests/core/brain/ingest/ingest-marker-neutralize.test.ts@@ -0,0 +1,303 @@+/**+ * Write-time marker neutralization at the ingest seam (t_c2ac4fc8, lane A4).+ *+ * The summary prose is the calling agent's writing ABOUT a source; the+ * source it cites decides the lane. Under the markdown-neutralization+ * gate's enforce mode, an UNTRUSTED source's summary is neutralized once+ * at body assembly, so the staged copy and the published page carry the+ * same escaped bytes while every vault-authored section appended after+ * the summary stays live. Off, shadow and the trusted lane change+ * nothing.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join, relative } from "node:path";+import { tmpdir } from "node:os";++import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";+import { parseFrontmatter } from "../../../../src/core/vault.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE_ENV,+ MarkdownNeutralizeModeError,+ detectMarkdownStructure,+} from "../../../../src/core/brain/text/neutralize-markdown.ts";++let vault: string;+let configHome: string;++const NOW = new Date("2026-06-13T12:00:00Z");+const URL_SOURCE = "https://example.test/articles/a";+const LOCAL_SOURCE = "Articles/a.md";++/** A summary that plants one marker of every family the neutralizer escapes. */+const MARKER_SUMMARY = [+ "## Planted Heading",+ "",+ "quotes [[planted-note]] inline",+ "",+ "@osb set note=[[x]] field=a value=b",+ "",+ "```osb",+ "kind: set",+ "note: n",+ "field: a",+ "value: b",+ "```",+].join("\n");++/** Run `run` with the gate mode env twin set, restoring it afterwards. */+function withGateMode(mode: string, run: () => void): void {+ const saved = process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = mode;+ try {+ run();+ } finally {+ if (saved === undefined) delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ else process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = saved;+ }+}++/** Run `run` with the ingest review lane enabled (stage disposition). */+function withIngestReviewLane(run: () => void): void {+ const key = "OPEN_SECOND_BRAIN_WRITE_APPROVAL_INGEST_ENABLED";+ const saved = process.env[key];+ process.env[key] = "true";+ try {+ run();+ } finally {+ if (saved === undefined) delete process.env[key];+ else process.env[key] = saved;+ }+}++function input(sourcePath: string, summary: string) {+ return {+ sourcePath,+ summary,+ extraction: { entities: [{ category: "concept", name: "Alpha" }], relations: [] },+ };+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-ingest-neutralize-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-ingest-neutralize-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++/** The body of the summary page at `path` (everything after the frontmatter). */+function pageBody(path: string): string {+ const [, body] = parseFrontmatter(path);+ return body;+}++describe("ingestSource marker neutralization (enforce, untrusted)", () => {+ test("planted markers are inert on the published page; vault-authored sections stay live", () => {+ withGateMode("enforce", () => {+ const result = ingestSource(vault, input(URL_SOURCE, MARKER_SUMMARY), {+ agent: "claude",+ now: NOW,+ });+ const raw = readFileSync(join(vault, result.summaryPath), "utf8");+ // Every planted family escaped in the summary prose.+ expect(raw).toContain("\\#\\# Planted Heading");+ expect(raw).toContain("\\[\\[planted-note\\]\\]");+ expect(raw).toContain("\\@osb set note=");+ expect(raw).toContain("\\`\\`\\`osb");+ expect(raw).not.toContain("[[planted-note]]");+ // The conditional provenance key names every kind, sorted.+ expect(raw).toContain("neutralized_markers: [atx-heading, osb-fence, osb-inline, wikilink]");+ // Vault-authored sections are appended untouched: the Sources and+ // Entities link rows stay live, and their headings stay live.+ const body = pageBody(join(vault, result.summaryPath));+ expect(body).toContain("- [[https://example.test/articles/a]]");+ expect(body).toContain("## Entities");+ expect(body).toContain("- [[ent-concept-alpha]]");+ // The caller-authored half - the summary section, everything before+ // the renderer's own Sources heading - carries no live structure.+ const summarySection = body.slice(0, body.indexOf("\n\n## Sources\n\n"));+ expect(detectMarkdownStructure(summarySection)).toEqual([]);+ expect(body).toContain("## Sources");+ // The untrusted marker still rides the provenance merge.+ expect(raw).toContain("untrusted_source: true");+ });+ });++ test("the staged copy and the published page carry identical bytes", () => {+ withGateMode("enforce", () => {+ let stagedBytes: string | undefined;+ withIngestReviewLane(() => {+ const staged = ingestSource(vault, input(URL_SOURCE, MARKER_SUMMARY), {+ agent: "claude",+ now: NOW,+ });+ expect(staged.staged).toBe(true);+ const laneDir = join(vault, "Brain", "pending", "ingest");+ const entries = readdirSync(laneDir).filter((name) => name.endsWith(".md"));+ expect(entries).toHaveLength(1);+ stagedBytes = readFileSync(join(laneDir, entries[0]!), "utf8");+ // The staged copy is inert too.+ expect(stagedBytes).toContain("\\[\\[planted-note\\]\\]");+ expect(stagedBytes).not.toContain("[[planted-note]]");+ });+ // A separate vault, same input, lane off: the publish path.+ const publishVault = mkdtempSync(join(tmpdir(), "o2b-ingest-neutralize-pub-"));+ try {+ const cfg = mkdtempSync(join(tmpdir(), "o2b-ingest-neutralize-pub-cfg-"));+ atomicWriteFileSync(+ join(cfg, "config.yaml"),+ `vault: ${publishVault}\nagent_name: claude\n`,+ );+ bootstrapBrain(publishVault, { configPath: join(cfg, "config.yaml") });+ const published = ingestSource(publishVault, input(URL_SOURCE, MARKER_SUMMARY), {+ agent: "claude",+ now: NOW,+ });+ expect(stagedBytes).toBe(readFileSync(join(publishVault, published.summaryPath), "utf8"));+ rmSync(cfg, { recursive: true, force: true });+ } finally {+ rmSync(publishVault, { recursive: true, force: true });+ }+ });+ });++ test("a re-ingest of the published page never re-stages and stays idempotent", () => {+ withGateMode("enforce", () => {+ // No entities: what this pins is the neutralization, not the+ // connection section a second ingest legitimately grows (an entity+ // the first run created is a connection to prior material).+ const bare = {+ sourcePath: URL_SOURCE,+ summary: MARKER_SUMMARY,+ extraction: { entities: [], relations: [] },+ };+ const first = ingestSource(vault, bare, { agent: "claude", now: NOW });+ const rawBefore = readFileSync(join(vault, first.summaryPath), "utf8");+ // The second run arrives under the review lane: the page already+ // exists, so the review boundary (entry, not mutation) keeps it a+ // direct rewrite - and the recomputed bytes are identical, so it+ // skips entirely.+ withIngestReviewLane(() => {+ const second = ingestSource(vault, bare, { agent: "claude", now: NOW });+ expect(second.created).toBe(false);+ expect(second.staged).toBeUndefined();+ expect(existsPendingIngest(vault)).toBe(false);+ });+ expect(readFileSync(join(vault, first.summaryPath), "utf8")).toBe(rawBefore);+ });+ });+});++function existsPendingIngest(vault: string): boolean {+ const laneDir = join(vault, "Brain", "pending", "ingest");+ try {+ return readdirSync(laneDir).some((name) => name.endsWith(".md"));+ } catch {+ return false;+ }+}++/**+ * Every file under `root` as `[relative path, bytes]`, sorted - the whole+ * vault as data, so a "refused before any write" claim is asserted against+ * everything the seam could have touched (entity pages, the trusted+ * archive, the summary, manifest rows, log events) and not just the+ * surfaces the test author remembered.+ */+function vaultSnapshot(root: string): Array<[string, Buffer]> {+ const out: Array<[string, Buffer]> = [];+ const walk = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ )) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) walk(path);+ else out.push([relative(root, path), readFileSync(path)]);+ }+ };+ walk(root);+ return out;+}++describe("ingestSource gate misconfiguration refuses before any write", () => {+ test("an invalid gate mode throws and leaves the vault byte-identical", () => {+ // A trusted LOCAL source: the trusted lane is the one that also+ // captures the durable archive, so a half-applied ingest here is the+ // widest mess the old ordering could leave - entity pages and archived+ // bytes on disk, no summary page. The gate never has work to do on a+ // trusted ingest, but a misconfiguration is refused all the same,+ // before anything is written (the capture seam's contract).+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, LOCAL_SOURCE), "source bytes\n", "utf8");++ const before = vaultSnapshot(vault);+ expect(() =>+ withGateMode("yes", () => {+ ingestSource(vault, input(LOCAL_SOURCE, "plain summary"), { agent: "claude", now: NOW });+ }),+ ).toThrow(MarkdownNeutralizeModeError);+ // Zero writes: no entity page, no archive, no summary, no manifest+ // row, no log event - every path and every byte as before the call.+ expect(vaultSnapshot(vault)).toEqual(before);+ });+});++describe("ingestSource marker neutralization (byte-identity lanes)", () => {+ test("gate off and an untrusted source: the summary persists live, with no provenance key", () => {+ const result = ingestSource(vault, input(URL_SOURCE, MARKER_SUMMARY), {+ agent: "claude",+ now: NOW,+ });+ const body = pageBody(join(vault, result.summaryPath));+ expect(body).toContain("[[planted-note]]");+ expect(body).toContain("@osb set note=");+ expect(body).toContain("## Planted Heading");+ const [meta] = parseFrontmatter(join(vault, result.summaryPath));+ expect(meta["neutralized_markers"]).toBeUndefined();+ // The scanner hands the scalar back as written, so the marker can+ // arrive as the string "true" - the two-form check hasUntrustedSourceMarker makes.+ expect(meta["untrusted_source"] === true || meta["untrusted_source"] === "true").toBe(true);+ });++ test("gate shadow and an untrusted source: bytes are unchanged, no key", () => {+ withGateMode("shadow", () => {+ const result = ingestSource(vault, input(URL_SOURCE, MARKER_SUMMARY), {+ agent: "claude",+ now: NOW,+ });+ const body = pageBody(join(vault, result.summaryPath));+ expect(body).toContain("[[planted-note]]");+ const [meta] = parseFrontmatter(join(vault, result.summaryPath));+ expect(meta["neutralized_markers"]).toBeUndefined();+ });+ });++ test("gate enforce and a TRUSTED source: the summary persists live, with no key", () => {+ withGateMode("enforce", () => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, LOCAL_SOURCE), "bytes\n", "utf8");+ const result = ingestSource(vault, input(LOCAL_SOURCE, MARKER_SUMMARY), {+ agent: "claude",+ now: NOW,+ });+ const body = pageBody(join(vault, result.summaryPath));+ // Neutralization keys off provenance, not content: a vault file the+ // caller may read is the trusted lane, and its summary is the+ // caller's own writing about the operator's own material.+ expect(body).toContain("[[planted-note]]");+ expect(body).toContain("@osb set note=");+ const [meta] = parseFrontmatter(join(vault, result.summaryPath));+ expect(meta["neutralized_markers"]).toBeUndefined();+ expect(meta["untrusted_source"]).toBeUndefined();+ });+ });+});diff --git a/tests/core/brain/intake/extract-intake.test.ts b/tests/core/brain/intake/extract-intake.test.tsindex 4e44a4ca..963e1ebf 100644--- a/tests/core/brain/intake/extract-intake.test.ts+++ b/tests/core/brain/intake/extract-intake.test.ts@@ -12,7 +12,7 @@*/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";@@ -25,6 +25,12 @@ import {type ExtractionIntake,type IntakeOptions,} from "../../../../src/core/brain/intake/extract-intake.ts";+import { planPlantedRows } from "../../../../src/core/brain/planted-rows.ts";+import { parseFrontmatter, extractWikilinks } from "../../../../src/core/vault.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE_ENV,+ MarkdownNeutralizeModeError,+} from "../../../../src/core/brain/text/neutralize-markdown.ts";import type { Provenance } from "../../../../src/core/brain/provenance/provenance.ts";let vault: string;@@ -166,3 +172,130 @@ describe("intakeExtraction - validation refuses malformed payloads with no partiexpect(listEntities(vault)).toHaveLength(0);});});++/**+ * The untrusted intake's page bytes (review M4): the entity page H1 carries+ * the third-party display name verbatim, so a planted `[[...]]` in a name+ * stayed live there even under enforce - the summary was neutralized, the+ * entity pages it quarantined were not.+ */++/** Provenance citing a URL: no vault bytes, so the intake classifies untrusted. */+function untrustedOpts(agent: string): IntakeOptions {+ return {+ agent,+ now: NOW,+ provenance: { level: "stated", sources: ["[[https://example.test/w]]"], premises: [] },+ };+}++/** Run `run` with the gate mode env twin set, restoring it afterwards. */+function withGateMode(mode: string, run: () => void): void {+ const saved = process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = mode;+ try {+ run();+ } finally {+ if (saved === undefined) delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ else process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = saved;+ }+}++const PLANTED_NAME = "Alice [[evil-target]] Example";++function entityPage(id: string): { meta: Record<string, unknown>; body: string; raw: string } {+ const path = join(vault, "Brain", "entities", "person", `${id}.md`);+ const raw = readFileSync(path, "utf8");+ const [meta, body] = parseFrontmatter(path);+ return { meta, body, raw };+}++describe("intakeExtraction - markdown neutralization on the untrusted lane", () => {+ test("enforce escapes a planted name in the entity page H1 and the audit stays silent", () => {+ withGateMode("enforce", () => {+ const res = intakeExtraction(+ vault,+ {+ entities: [{ category: "person", name: PLANTED_NAME, aliases: ["Alice [[evil]]"] }],+ relations: [],+ },+ untrustedOpts("claude"),+ );+ const id = res.entitiesCreated[0]!;+ const page = entityPage(id);+ // The writer's H1 line carries the escaped form: the planted name's+ // sigils AND the writer's own heading sigil are escaped together, so+ // the page's link readers extract nothing from the name.+ expect(page.body).toContain("\\# Alice \\[\\[evil-target\\]\\] Example");+ expect(extractWikilinks(page.body)).toEqual(["https://example.test/w"]);+ // The alias is neutralized too: no live brackets in the stored value.+ expect(page.meta["aliases"]).toEqual(["Alice \\[\\[evil\\]\\]"]);+ // The quarantined page is silent for the planted-rows audit.+ const rel = `Brain/entities/person/${id}.md`;+ expect(planPlantedRows(vault).planted.filter((p) => p.path === rel)).toEqual([]);+ // Identity is untouched: the frontmatter name stays the third-party+ // record verbatim, and the id keys on it exactly as before (the+ // escaped H1 is a rendering of the record, not a different record).+ expect(page.meta["name"]).toBe(PLANTED_NAME);+ expect(id).toBe("ent-person-alice-evil-target-example");+ });+ });++ test("gate off leaves the untrusted name verbatim and the audit reports exactly the planted row", () => {+ const res = intakeExtraction(+ vault,+ { entities: [{ category: "person", name: PLANTED_NAME }], relations: [] },+ untrustedOpts("claude"),+ );+ const id = res.entitiesCreated[0]!;+ const page = entityPage(id);+ expect(page.body).toContain(`# ${PLANTED_NAME}`);+ expect(page.meta["aliases"]).toBeUndefined();+ const rel = `Brain/entities/person/${id}.md`;+ const planted = planPlantedRows(vault).planted.find((p) => p.path === rel);+ expect(planted).toBeDefined();+ expect(planted!.kinds).toEqual(["wikilink"]);+ expect(planted!.count).toBe(1);+ });++ test("shadow leaves the untrusted name verbatim", () => {+ withGateMode("shadow", () => {+ const res = intakeExtraction(+ vault,+ { entities: [{ category: "person", name: PLANTED_NAME }], relations: [] },+ untrustedOpts("claude"),+ );+ const page = entityPage(res.entitiesCreated[0]!);+ expect(page.body).toContain(`# ${PLANTED_NAME}`);+ });+ });++ test("a trusted intake's name stays verbatim under enforce", () => {+ withGateMode("enforce", () => {+ const res = intakeExtraction(+ vault,+ { entities: [{ category: "person", name: PLANTED_NAME }], relations: [] },+ opts("claude"),+ );+ const page = entityPage(res.entitiesCreated[0]!);+ // Neutralization keys off provenance: a vault file the caller may+ // read is the trusted lane, and the name is the caller's own writing+ // about the operator's own material.+ expect(page.body).toContain(`# ${PLANTED_NAME}`);+ expect(page.meta["status"]).toBe("active");+ });+ });++ test("an invalid gate mode refuses with no partial write", () => {+ expect(() =>+ withGateMode("yes", () =>+ intakeExtraction(+ vault,+ { entities: [{ category: "person", name: "Alice" }], relations: [] },+ untrustedOpts("claude"),+ ),+ ),+ ).toThrow(MarkdownNeutralizeModeError);+ expect(listEntities(vault)).toHaveLength(0);+ });+});diff --git a/tests/core/brain/link-graph/parse-wikilink.test.ts b/tests/core/brain/link-graph/parse-wikilink.test.tsindex 7cf1245b..11c637ae 100644--- a/tests/core/brain/link-graph/parse-wikilink.test.ts+++ b/tests/core/brain/link-graph/parse-wikilink.test.ts@@ -131,3 +131,24 @@ describe("extractWikilinkRichBodies - code masking", () => {}});});++describe("extractWikilinkRichBodies - escaped brackets", () => {+ // The same odd-backslash-run rule the neutralizer's detector applies:+ // a backslash-escaped bracket opens or closes no link, so an escaped+ // `[[target]]` in a body contributes no backlink edge.+ test("an escaped opening bracket opens no link", () => {+ expect(extractWikilinkRichBodies("\\[[a]]")).toEqual([]);+ });++ test("an escaped closing bracket closes no link", () => {+ expect(extractWikilinkRichBodies("[[a\\]]")).toEqual([]);+ });++ test("a link after an even backslash run stays live", () => {+ expect(extractWikilinkRichBodies("\\\\[[a]]")).toEqual(["a"]);+ });++ test("an escaped link beside a live one leaves only the live one", () => {+ expect(extractWikilinkRichBodies("\\[[a]] and [[b]]")).toEqual(["b"]);+ });+});diff --git a/tests/core/brain/lint-consolidate.test.ts b/tests/core/brain/lint-consolidate.test.tsindex 537348aa..c9d70e4d 100644--- a/tests/core/brain/lint-consolidate.test.ts+++ b/tests/core/brain/lint-consolidate.test.ts@@ -61,6 +61,20 @@ describe("lintConsolidate — fix-merged-link", () => {expect(content).toContain("[[pref-canon#section]]");});+ test("an escaped bracket names no link to converge", () => {+ // `\[[pref-dup]]` is literal text by the odd-backslash-run rule every+ // link reader applies; a merge over its target would mutate bytes+ // that hold no link, so the rewriter skips the span entirely.+ writePref("canon", { topic: "x", principle: "y" });+ writePref("dup", { topic: "x", principle: "y", merged_into: "pref-canon" });+ const path = join(vault, "Brain", "log", "2026-05-25.md");+ writeFileSync(path, "saw \\[[pref-dup]] today\n");++ const report = lintConsolidate(vault, { apply: true });+ expect(report.fixes).toEqual([]);+ expect(readFileSync(path, "utf8")).toBe("saw \\[[pref-dup]] today\n");+ });+test("a two-step merge converges in ONE pass", () => {// A -> B -> C. The single-hop merge map rewrote [[pref-a]] to// [[pref-b]], reported a `to` that was itself merged away, and neededdiff --git a/tests/core/brain/maintenance-collect.test.ts b/tests/core/brain/maintenance-collect.test.tsindex 9e852fa2..24dcc251 100644--- a/tests/core/brain/maintenance-collect.test.ts+++ b/tests/core/brain/maintenance-collect.test.ts@@ -80,6 +80,89 @@ describe("collectMaintenanceActions", () => {});});+/**+ * A visibility predicate threaded into the collector is applied to the+ * CANDIDATE INPUTS - dedup canonical and secondaries, demotion ids,+ * link paths - before scoring and capping. Ranked post-hoc filtering+ * (what every sink did before) let another owner's rows take ranked+ * slots and then dropped them, so a scoped caller got fewer than the+ * cap - and the shortfall itself hinted that withheld rows exist,+ * against the module's identical-to-absent convention.+ */+describe("collectMaintenanceActions — the visibility predicate applies before the cap", () => {+ test("hidden top-ranked candidates take no slot a visible one could fill", () => {+ // Twelve stale pages owned by another owner, older (so+ // higher-impact) than ten visible ones: post-hoc filtering left the+ // scoped caller with an empty list.+ for (let i = 0; i < 12; i += 1) writeStale(`theirs-${i}`, "2020-01-01T00:00:00Z", "agent-a");+ for (let i = 0; i < 10; i += 1) writeStale(`ours-${i}`, "2024-01-01T00:00:00Z");+ const actions = collectMaintenanceActions(vault, {+ visible: (ref) => !(ref ?? "").includes("theirs"),+ });+ expect(actions).toHaveLength(10);+ for (const action of actions) expect(action.target).not.toContain("theirs");+ });++ test("a dedup candidate counts only the secondaries the caller may see", () => {+ // Canonical is the oldest page; one of its two duplicates belongs to+ // another owner. The row survives with the VISIBLE count - the count+ // is what would disclose the hidden page's existence.+ writeStale("canonical", "2025-01-01T00:00:00Z", undefined, "shared", "the shared principle");+ writeStale("dup-visible", "2025-02-01T00:00:00Z", undefined, "shared", "the shared principle");+ writeStale("dup-hidden", "2025-03-01T00:00:00Z", "agent-a", "shared", "the shared principle");+ const actions = collectMaintenanceActions(vault, {+ visible: (ref) => !(ref ?? "").includes("hidden"),+ });+ const dedup = actions.find((a) => a.category === "dedup");+ expect(dedup).toBeDefined();+ expect(dedup!.title).toBe("Merge 1 duplicate(s) into pref-canonical");+ // The hidden duplicate's own row is gone too: its id would leak.+ expect(actions.some((a) => a.target === "pref-dup-hidden")).toBe(false);+ });++ test("omitting the predicate ranks every candidate, byte-identical to the plain call", () => {+ // The contract every unscoped caller keeps: passing nothing changes+ // nothing. Pinned as a byte comparison over the ranked list.+ writeStale("canonical", "2025-01-01T00:00:00Z");+ writeStale("dup", "2025-02-01T00:00:00Z");+ writeStale("lone", "2020-01-01T00:00:00Z", "agent-a");+ writeStale("other", "2024-01-01T00:00:00Z");++ const plain = collectMaintenanceActions(vault);+ const open = collectMaintenanceActions(vault, { visible: () => true });+ expect(JSON.stringify(open)).toBe(JSON.stringify(plain));+ expect(plain.length).toBeGreaterThan(0);+ expect(plain.some((a) => a.target === "pref-lone")).toBe(true);+ });+});++/**+ * A minimal stale-stable page: old enough to be a lint demotion+ * candidate on any run date. Topic and principle default to per-page+ * values so unrelated fixtures never group as dedup candidates.+ */+function writeStale(+ slug: string,+ createdAt: string,+ owner?: string,+ topic?: string,+ principle?: string,+): void {+ const lines = [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "tags: [brain, brain/preference]",+ `topic: ${topic ?? `topic-${slug}`}`,+ `principle: ${principle ?? `principle ${slug}`}`,+ `created_at: ${createdAt}`,+ "---",+ "",+ ];+ if (owner !== undefined) lines.splice(4, 0, `owner: ${owner}`);+ writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`), lines.join("\n"), "utf8");+}+function writePref(slug: string, principle: string, body: string): void {writeFileSync(join(vault, "Brain", "preferences", `pref-${slug}.md`),diff --git a/tests/core/brain/page-lint.test.ts b/tests/core/brain/page-lint.test.tsindex 08a5dc10..dc4a8e9c 100644--- a/tests/core/brain/page-lint.test.ts+++ b/tests/core/brain/page-lint.test.ts@@ -114,6 +114,20 @@ describe("lintWrittenPages - findings", () => {expect(report.truncated).toBe(false);});+ test("an escaped bracket opens no wikilink to lint", () => {+ // `\[[pref-ghost]]` is literal text by the same odd-backslash-run+ // rule every link reader applies; it names no target, so it raises+ // no broken-link row, while a link after an even run stays live.+ const escaped = writeNote("Notes/Escaped.md", "---\ntitle: E\n---\n\nsee \\[[pref-ghost]]\n");+ expect(lintWrittenPages(vault, [escaped], READ_ALL).findings).toEqual([]);+ const closed = writeNote("Notes/EscClose.md", "---\ntitle: C\n---\n\nsee [[pref-ghost\\]]\n");+ expect(lintWrittenPages(vault, [closed], READ_ALL).findings).toEqual([]);+ const live = writeNote("Notes/Live.md", "---\ntitle: L\n---\n\nsee \\\\[[pref-ghost]]\n");+ const report = lintWrittenPages(vault, [live], READ_ALL);+ expect(report.findings.length).toBe(1);+ expect(report.findings[0]).toMatchObject({ code: "broken-wikilink", path: "pref-ghost" });+ });+test("a link to a merged page names the FULLY resolved canonical target", () => {writePref("canon");writePref("mid", { merged_into: "pref-canon" });diff --git a/tests/core/brain/source-links.test.ts b/tests/core/brain/source-links.test.tsindex cc602645..57d2eb6a 100644--- a/tests/core/brain/source-links.test.ts+++ b/tests/core/brain/source-links.test.ts@@ -155,4 +155,13 @@ describe("sourcesSectionTargets", () => {"a.md",]);});++ test("an escaped bracket opens no source link", () => {+ // A backslash-escaped `[[` is literal text, so the row cites nothing+ // - the same odd-backslash-run rule the neutralizer's detector and+ // the other link readers apply.+ expect(sourcesSectionTargets("## Sources\n\n- \\[[a.md]]\n")).toEqual([]);+ expect(sourcesSectionTargets("## Sources\n\n- [[a.md\\]]\n")).toEqual([]);+ expect(sourcesSectionTargets("## Sources\n\n- \\[[a.md]] and [[b.md]]\n")).toEqual(["b.md"]);+ });});diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.tsindex c8179448..be4e3425 100644--- a/tests/core/brain/sync-lockfile.test.ts+++ b/tests/core/brain/sync-lockfile.test.ts@@ -14,14 +14,18 @@ import {readdirSync,readFileSync,rmSync,+ statSync,unlinkSync,utimesSync,writeFileSync,} from "node:fs";+import { randomUUID } from "node:crypto";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";+import { IS_WINDOWS } from "../../helpers/platform.ts";+import {acquireLockSync,acquireLockSyncWithRetry,@@ -126,6 +130,48 @@ describe("acquireLockSync", () => {}expect(existsSync(target + ".lock")).toBe(false);});+ test.skipIf(IS_WINDOWS)(+ "release keeps a reused-identity lock that carries a foreign holder token",+ () => {+ // A filesystem can hand a freed inode straight back to the next+ // create, so the lock file that answers this holder's device and+ // inode can be another holder's. Ownership is decided by the body's+ // holder token as well: overwriting the body in place keeps the+ // identity while replacing the holder, and the first release must+ // read the foreign stamp, judge the name not its own, and leave the+ // file in place.+ const target = join(tmpRoot, "pref-reused.md");+ const lockPath = target + ".lock";+ const first = acquireLockSync(target);+ const identity = statSync(lockPath, { bigint: true });+ writeFileSync(lockPath, `${process.pid}\n${randomUUID()}\n`);+ const reused = statSync(lockPath, { bigint: true });+ expect(reused.dev).toBe(identity.dev);+ expect(reused.ino).toBe(identity.ino);+ first.release();+ expect(existsSync(lockPath)).toBe(true);+ expect(() => acquireLockSync(target)).toThrow(/lock busy/);+ unlinkSync(lockPath);+ expect(existsSync(lockPath)).toBe(false);+ },+ );++ test("release unlinks a lock whose token's first byte lost to a racing waiter mark", () => {+ // A waiter that opened the name in the microseconds before the+ // holder's stamp landed writes its mark at position zero and+ // clobbers the token's first byte. The body still carries the+ // holder's unique token line, so the release must treat the file+ // as its own and remove it.+ const target = join(tmpRoot, "pref-clobbered.md");+ const lockPath = target + ".lock";+ const first = acquireLockSync(target);+ const before = readFileSync(lockPath, "utf8");+ writeFileSync(lockPath, `w${before.slice(1)}`);+ first.release();+ expect(existsSync(lockPath)).toBe(false);+ const again = acquireLockSync(target);+ again.release();+ });});describe("exit sweep after a stale handle's release", () => {diff --git a/tests/core/brain/text/neutralize-markdown.test.ts b/tests/core/brain/text/neutralize-markdown.test.tsnew file mode 100644index 00000000..e524a62c--- /dev/null+++ b/tests/core/brain/text/neutralize-markdown.test.ts@@ -0,0 +1,816 @@+/**+ * Tests for the pure write-time markdown neutralizer+ * (trust-and-responsiveness-hardening, t_c2ac4fc8, lane A1/A2).+ *+ * The neutralizer escapes structure-bearing markdown in third-party text:+ * wikilinks, `@osb` inline markers, ```osb fence lines and ATX headings.+ * Doctrine under test: structure-only detection (never vocabulary),+ * fence-awareness, escape-not-delete, idempotence by construction, and+ * zero bytes when nothing was detected.+ */++import { describe, expect, test } from "bun:test";++import { discoverMarkers } from "../../../../src/core/brain/inline.ts";+import { sourcesSectionTargets } from "../../../../src/core/brain/source-links.ts";+import {+ MARKDOWN_NEUTRALIZE_MODE,+ MARKDOWN_NEUTRALIZE_MODE_CONFIG,+ MARKDOWN_NEUTRALIZE_MODE_ENV,+ MarkdownNeutralizeFixpointError,+ MarkdownNeutralizeModeError,+ detectMarkdownStructure,+ neutralizeMarkdown,+ neutralizeMarkdownWithBound,+ resolveMarkdownNeutralizeMode,+ type MarkdownStructureKind,+} from "../../../../src/core/brain/text/neutralize-markdown.ts";+import { chunkMarkdown } from "../../../../src/core/search/chunker.ts";+import { extractWikilinkRichBodies } from "../../../../src/core/brain/link-graph/parse-wikilink.ts";+import { extractWikilinks } from "../../../../src/core/vault.ts";++/** The structure kinds one sample carries, as a set for order-free asserts. */+function kindsOf(...kinds: MarkdownStructureKind[]): MarkdownStructureKind[] {+ return [...new Set(kinds)].toSorted();+}++describe("neutralizeMarkdown: wikilinks", () => {+ test("escapes a plain wikilink", () => {+ const out = neutralizeMarkdown("see [[pref-foo]] now");+ expect(out.text).toBe("see \\[\\[pref-foo\\]\\] now");+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("wikilink"));+ });++ test("escapes an aliased wikilink without touching the alias body", () => {+ const out = neutralizeMarkdown("[[pref-foo|The Rule]]");+ expect(out.text).toBe("\\[\\[pref-foo|The Rule\\]\\]");+ expect(out.kinds).toEqual(kindsOf("wikilink"));+ });++ test("escapes every wikilink on a line", () => {+ const out = neutralizeMarkdown("- [[a]] and [[b|c]]");+ expect(out.text).toBe("- \\[\\[a\\]\\] and \\[\\[b|c\\]\\]");+ });++ test("leaves lone brackets alone", () => {+ const out = neutralizeMarkdown("an array literal like arr[0] and a [bracket]");+ expect(out.changed).toBe(false);+ expect(out.text).toBe("an array literal like arr[0] and a [bracket]");+ });++ test("escapes a wikilink whose target spans a newline (the link extractor's shape)", () => {+ // The link readers match over the whole text with the multi-line+ // -tolerant shape (`vault.ts` extractWikilinks, page-lint), so a+ // `[[...\n...]]` pair across a line break is a live link to them -+ // single-line detection reported nothing and left it planted.+ const src = "see [[pref-evil\nnote]] end";+ expect(extractWikilinks(src)).toEqual(["pref-evil\nnote"]);+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("wikilink"));+ expect(extractWikilinks(out.text)).toEqual([]);+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });++ test("an already-escaped closing bracket inside a wikilink is data: the span is not live", () => {+ // `[[a\]]`: the closing `]` carries an odd backslash run, so no link+ // reader extracts the span (isLiveWikilinkSpan fails on it) and no+ // consumer parses a link there - the detector applies the readers'+ // own live-span rule and leaves the bytes alone, adding zero bytes.+ // (The readers hold BOTH brackets to the rule, so the span is inert+ // even though its opening pair is unescaped.)+ const src = "[[a\\]]";+ expect(extractWikilinks(src)).toEqual([]);+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(false);+ expect(out.text).toBe(src);+ expect(extractWikilinks(out.text)).toEqual([]);+ expect(neutralizeMarkdown(out.text).changed).toBe(false);+ });+});++describe("neutralizeMarkdown: @osb inline markers", () => {+ test("escapes a valid inline marker at line start", () => {+ const line = '@osb feedback negative topic=mocking principle="don\'t mock DB"';+ const out = neutralizeMarkdown(line);+ expect(out.text).toBe(`\\${line}`);+ expect(out.kinds).toEqual(kindsOf("osb-inline"));+ });++ test("escapes an inline marker indented by spaces", () => {+ const line = " @osb feedback negative topic=t principle=p";+ const out = neutralizeMarkdown(line);+ expect(out.text).toBe(` \\${line.trimStart()}`);+ expect(out.kinds).toEqual(kindsOf("osb-inline"));+ });++ test("a marker inside a list row is not line-anchored; only its wikilink escapes", () => {+ // The marker scanners anchor on the trimmed line's first token, so a+ // `- @osb ...` row is not a live marker to them; the neutralizer keys+ // off the same grammar and escapes only the wikilink the link readers+ // would actually see.+ const out = neutralizeMarkdown("- @osb set note=[[x]] field=a value=b");+ expect(out.text).toBe("- @osb set note=\\[\\[x\\]\\] field=a value=b");+ expect(out.kinds).toEqual(kindsOf("wikilink"));+ });++ test("does not escape the processed sentinel form", () => {+ const line = "@osb✓ feedback negative topic=t principle=p";+ const out = neutralizeMarkdown(line);+ expect(out.changed).toBe(false);+ expect(out.text).toBe(line);+ });++ test("does not escape a non-marker word that merely starts with @osb", () => {+ const out = neutralizeMarkdown("@osbarbitrary is not a marker");+ expect(out.changed).toBe(false);+ });++ test("does not escape an unknown-kind attempt", () => {+ const out = neutralizeMarkdown("@osb wat topic=x principle=y");+ expect(out.changed).toBe(false);+ });++ test("does not escape a marker mentioned mid-line", () => {+ const out = neutralizeMarkdown("then I wrote @osb feedback negative topic=t principle=p");+ expect(out.changed).toBe(false);+ });+});++describe("neutralizeMarkdown: osb fenced blocks", () => {+ test("escapes the open and close fence lines of an osb block", () => {+ const src = [+ "```osb",+ "kind: feedback",+ "signal: negative",+ "topic: t",+ "principle: p",+ "```",+ "",+ ].join("\n");+ const out = neutralizeMarkdown(src);+ expect(out.text).toBe(+ [+ "\\`\\`\\`osb",+ "kind: feedback",+ "signal: negative",+ "topic: t",+ "principle: p",+ "\\`\\`\\`",+ "",+ ].join("\n"),+ );+ expect(out.kinds).toEqual(kindsOf("osb-fence"));+ });++ test("escapes the open fence line of an unterminated osb block", () => {+ const src = ["```osb", "kind: feedback", ""].join("\n");+ const out = neutralizeMarkdown(src);+ expect(out.text.startsWith("\\`\\`\\`osb\n")).toBe(true);+ expect(out.kinds).toEqual(kindsOf("osb-fence"));+ });++ test("leaves a non-osb fence and its content untouched", () => {+ const src = ["```python", 'x = "[[not-a-link]]"', "```", ""].join("\n");+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(false);+ expect(out.text).toBe(src);+ });++ test("leaves content inside inline code untouched", () => {+ const src = "use `[[pref-foo]]` verbatim";+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(false);+ expect(out.text).toBe(src);+ });+});++describe("neutralizeMarkdown: ATX headings", () => {+ test("escapes a semantic heading", () => {+ const out = neutralizeMarkdown("## Sources");+ expect(out.text).toBe("\\#\\# Sources");+ expect(out.kinds).toEqual(kindsOf("atx-heading"));+ });++ test("escapes a log heading", () => {+ const out = neutralizeMarkdown("## 12:34:56Z — reviewed");+ expect(out.text).toBe("\\#\\# 12:34:56Z — reviewed");+ });++ test("escapes a heading with a deeper hash run", () => {+ expect(neutralizeMarkdown("#### Parts").text).toBe("\\#\\#\\#\\# Parts");+ });++ test("escapes an ATX heading at any indentation", () => {+ // Deliberately broader than any single consumer's shape: the heading+ // readers disagree about how much indentation a heading may carry, and+ // the union the detector covers must not under-cut any of them.+ const out = neutralizeMarkdown(" ## End");+ expect(out.text).toBe(" \\#\\# End");+ expect(out.kinds).toEqual(kindsOf("atx-heading"));+ });++ test("escapes a heading whose only content after the hash run is a CRLF's CR", () => {+ // The line-grammar consumers split on `\n` and their heading shapes+ // accept `\s` (or any character) after the hash run, so `##\r` is a+ // heading to them; the trailing class must tolerate it. The CRLF+ // itself folds to LF before detection (the line-break normalization)+ // and the fold is recorded in the kinds.+ const out = neutralizeMarkdown("##\r\nbody\n");+ expect(out.text).toBe("\\#\\#\nbody\n");+ expect(out.kinds).toEqual(kindsOf("atx-heading", "line-break"));+ // The standalone detector still scans unfolded bytes (the doctor's+ // audit runs it on stored pages), so the CR tolerance stays load-bearing there.+ const detected = detectMarkdownStructure("##\r\nbody\n");+ expect(detected.map((m) => m.kind)).toEqual(["atx-heading"]);+ });++ test("does not escape a hashtag without a space", () => {+ expect(neutralizeMarkdown("#hashtag").changed).toBe(false);+ });++ test("does not escape a hash run deeper than six", () => {+ expect(neutralizeMarkdown("####### seven").changed).toBe(false);+ });++ test("does not escape a hash mid-line", () => {+ expect(neutralizeMarkdown("issue #42 is open").changed).toBe(false);+ });+});++describe("neutralizeMarkdown: unusual line breaks are normalized first", () => {+ // CommonMark, Obsidian and every `/m`-regex line reader treat a bare CR,+ // NEL (U+0085), LINE SEPARATOR (U+2028) and PARAGRAPH SEPARATOR (U+2029)+ // as line ends, while the `\n`-splitting detectors (and OSB's own line+ // readers) do not - so `x\r# Planted` renders a heading the detector+ // would never see. The enforce-mode walk folds all of them to `\n`+ // before detection and records the rewrite in the result kinds, so the+ // `neutralized_markers` provenance names it. The capture and untrusted+ // ingest seams invoke the neutralizer only under `enforce` (their gate+ // branches precede every call), so `off` and `shadow` stay byte-identical+ // - asserted at the seam level in the capture and ingest suites.+ test("a planted heading behind a bare CR is caught and escaped", () => {+ const out = neutralizeMarkdown("x\r# Planted\n");+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("atx-heading", "line-break"));+ expect(out.text).toBe("x\n\\# Planted\n");+ expect(detectMarkdownStructure(out.text)).toEqual([]);+ });++ test("a planted marker behind NEL (U+0085) is caught and escaped", () => {+ const out = neutralizeMarkdown("x\u0085@osb feedback positive topic=t principle=p");+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("osb-inline", "line-break"));+ expect(out.text).toBe("x\n\\@osb feedback positive topic=t principle=p");+ });++ test("a planted heading behind LINE SEPARATOR (U+2028) is caught and escaped", () => {+ const out = neutralizeMarkdown("x\u2028# Planted\n");+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("atx-heading", "line-break"));+ expect(out.text).toBe("x\n\\# Planted\n");+ });++ test("a planted heading behind PARAGRAPH SEPARATOR (U+2029) is caught and escaped", () => {+ const out = neutralizeMarkdown("x\u2029# Planted\n");+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("atx-heading", "line-break"));+ expect(out.text).toBe("x\n\\# Planted\n");+ });++ test("a CRLF body folds to LF and the rewrite is recorded even with no structure", () => {+ const src = "plain\r\nprose\r\n";+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("line-break"));+ expect(out.text).toBe("plain\nprose\n");+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });++ test("the normalized-and-escaped output is idempotent per separator", () => {+ for (const src of ["x\r# P\n", "x\u0085# P\n", "x\u2028# P\n", "x\u2029# P\n"]) {+ const once = neutralizeMarkdown(src);+ const twice = neutralizeMarkdown(once.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(once.text);+ }+ });+});++describe("neutralizeMarkdown: escape awareness and idempotence", () => {+ test("an already-escaped wikilink is data, not structure (odd backslash run)", () => {+ const src = "\\[[pref-foo]]";+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(false);+ expect(out.text).toBe(src);+ });++ test("a wikilink after an even backslash run is live and escaped", () => {+ const out = neutralizeMarkdown("\\\\[[pref-foo]]");+ expect(out.text).toBe("\\\\\\[\\[pref-foo\\]\\]");+ });++ test("already-escaped headings and markers are not re-escaped", () => {+ const src = "\\#\\# Sources\\n\\@osb set note=n field=f value=v";+ const out = neutralizeMarkdown(src.replace(/\\n/g, "\n"));+ expect(out.changed).toBe(false);+ });++ test("unchanged input returns the identical bytes with changed: false", () => {+ const src = "plain prose with no structure at all\n\nsecond line\n";+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(false);+ expect(out.text).toBe(src);+ expect(out.kinds).toEqual([]);+ });++ test("neutralize is idempotent on every sample in this file", () => {+ const samples = [+ "see [[pref-foo]] now",+ "[[pref-foo|The Rule]]",+ '@osb feedback negative topic=mocking principle="x"',+ "- @osb set note=[[x]] field=a value=b",+ "```osb\nkind: feedback\nsignal: negative\ntopic: t\nprinciple: p\n```\n",+ "```osb\nkind: feedback\n",+ "```osb\nkind: set\nnote: [[x]]\nfield: a\nvalue: b\n```\n",+ "## Sources\n\nsome [[link]] text\n",+ "## 12:34:56Z — reviewed\n- note: value\n",+ "```python\nx = '[[keep]]'\n```\n",+ "use `[[keep]]` verbatim",+ "\\[[already-escaped]]",+ "[[a\\]]",+ "see [[pref-evil\nnote]] end",+ " ## Indented heading\n",+ "##\r\nbody\n",+ "~~~\n@osb feedback negative topic=t principle=p\n~~~\n",+ "````\n@osb feedback negative topic=t principle=p\n````\n",+ "```osb\n## Planted\n@osb set note=n field=f value=v\n```\n",+ [+ "## Quoted document",+ "",+ "prose quoting [[a note]] and a heading below",+ "",+ "## Sources",+ "",+ "- [[source-id]]",+ "",+ "```osb",+ "kind: fact",+ "topic: t",+ "principle: p",+ "premise: q",+ "level: stated",+ "```",+ "",+ ].join("\n"),+ ];+ for (const src of samples) {+ const once = neutralizeMarkdown(src);+ const twice = neutralizeMarkdown(once.text);+ expect(twice.text).toBe(once.text);+ expect(twice.changed).toBe(false);+ }+ });++ test("introduces no characters beyond backslashes from the input", () => {+ const src = "## H\n\n[[a|b]]\n\n@osb set note=n field=f value=v\n```osb\nkind: set\n```\n";+ const out = neutralizeMarkdown(src);+ const allowed = new Set([...src, "\\"]);+ for (const ch of out.text) expect(allowed.has(ch)).toBe(true);+ });++ test("vault-authored shapes escape when fed through the caller-text entry point", () => {+ // The neutralizer is text-in, text-out: it cannot tell authorship. The+ // guarantee the seams make is that vault-authored sections never pass+ // through it; these two assertions pin what WOULD happen to the shapes+ // if a seam ever leaked them, so a silent leak is visible here.+ expect(neutralizeMarkdown("- [[some-id]]").text).toBe("- \\[\\[some-id\\]\\]");+ expect(neutralizeMarkdown("## Guidance").text).toBe("\\#\\# Guidance");+ });+});++describe("neutralizeMarkdown: wikilink reader parity (escaped brackets)", () => {+ // The detector and extractWikilinks must answer "is this a link?" with+ // ONE truth: whatever the detector leaves (already-escaped data) the+ // extractor must find inert, so an enforce-mode write can never leave+ // bytes that still join the link graph - and the doctor's planted-rows+ // audit, which runs the same detection, counts exactly the rows the+ // readers would have extracted.+ const adversarial = [+ "\\[[pref-evil]] see",+ "\\[[pref-evil\nnote]] see",+ "\\\\[[pref-evil]] see",+ "[[pref-evil\\]] see",+ "[[pref-evil\nnote\\]] see",+ ];++ test("neutralize output of adversarial escaped-bracket inputs extracts zero links", () => {+ for (const src of adversarial) {+ const out = neutralizeMarkdown(src);+ expect(extractWikilinks(out.text)).toEqual([]);+ }+ });++ test("an escaped multi-line wikilink is inert to both the detector and the extractor", () => {+ const src = "\\[[pref-evil\nnote]] see";+ expect(detectMarkdownStructure(src)).toEqual([]);+ expect(neutralizeMarkdown(src).changed).toBe(false);+ expect(extractWikilinks(src)).toEqual([]);+ });++ test("the idempotence fixpoint holds on the escaped-bracket inputs", () => {+ for (const src of adversarial) {+ const once = neutralizeMarkdown(src);+ const twice = neutralizeMarkdown(once.text);+ expect(twice.text).toBe(once.text);+ expect(twice.changed).toBe(false);+ }+ });+});++describe("neutralizeMarkdown: wikilinks spanning inline code (the readers' masked view)", () => {+ // The link readers do not scan the raw bytes: they first replace every+ // code region (fence or inline span) with a space and match on THAT+ // view, so a `[[target|`code`]]` span whose brackets sit outside the+ // region still extracts a live target from them. The detector must ask+ // the same question over the same view - masking code regions with a+ // length-preserving fill keeps every match offset identical to the raw+ // text - or a span the raw scan dismisses as "overlapping code" stays+ // live in the vault's link graph under `enforce`.+ test("a wikilink carrying an inline code span is caught and escaped, and extracts nothing", () => {+ const src = "Quoted thread: see [[Evil Page|`x`]] for details";+ expect(extractWikilinks(src)).toEqual(["Evil Page"]);+ expect(extractWikilinkRichBodies(src)).toEqual(["Evil Page| "]);+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("wikilink"));+ expect(out.text).toBe("Quoted thread: see \\[\\[Evil Page|`x`\\]\\] for details");+ expect(extractWikilinks(out.text)).toEqual([]);+ expect(extractWikilinkRichBodies(out.text)).toEqual([]);+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });++ test("a fenced wikilink whose brackets sit outside the fence's line grammar is still caught", () => {+ // Inline spans, not just fenced blocks: any code region the readers+ // mask must mask the detector's view identically - and nothing more.+ const src = "note [[a|`b`]] and `[[c]]` end";+ expect(extractWikilinks(src)).toEqual(["a"]);+ const out = neutralizeMarkdown(src);+ expect(out.text).toBe("note \\[\\[a|`b`\\]\\] and `[[c]]` end");+ expect(out.kinds).toEqual(kindsOf("wikilink"));+ expect(extractWikilinks(out.text)).toEqual([]);+ expect(extractWikilinkRichBodies(out.text)).toEqual([]);+ });++ test("the wikilink scan stays linear on link-and-backtick heavy pages (was quadratic)", () => {+ // One planted row per line: a live link followed by an inline code+ // span - the shape that made the old detector re-scan every code+ // region for every match (quadratic). Measured on this Bun build:+ // 1.4 MB of this shape took ~6.1 s with the region-overlap test and+ // ~20 ms with the masked-view scan; the bound below leaves two orders+ // of magnitude of headroom on the fixed cost while still failing on+ // the quadratic shape.+ const page =+ "- [[Brain/log/note-0000]] ran `bun test --grep smoke` and more prose here\n".repeat(19_000);+ expect(page.length).toBeGreaterThan(1_000_000);+ const t0 = performance.now();+ const matches = detectMarkdownStructure(page);+ const elapsed = performance.now() - t0;+ expect(matches).toHaveLength(19_000);+ expect(elapsed).toBeLessThan(2_000);+ });+});++describe("neutralizeMarkdown: the marker scanner's fence model", () => {+ test("a planted marker inside a tilde fence is live for the scanner and gets escaped", () => {+ // The marker grammar knows exactly one fence: an exactly-3-backtick line+ // (`inline.ts` FENCE_RE). A tilde fence is plain text to it, so the+ // planted marker inside is LIVE structure the scanner parses - and the+ // detector must say so, not mask it the way the wikilink readers'+ // codeRegions (which does know tildes) would.+ const src = "~~~\n@osb feedback negative topic=t principle=p\n~~~\n";+ expect(discoverMarkers(src)).toHaveLength(1);+ expect(detectMarkdownStructure(src).map((m) => m.kind)).toEqual(["osb-inline"]);+ const out = neutralizeMarkdown(src);+ expect(out.kinds).toEqual(kindsOf("osb-inline"));+ expect(out.text.split("\n")[1]).toBe("\\@osb feedback negative topic=t principle=p");+ expect(discoverMarkers(out.text)).toHaveLength(0);+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });++ test("a planted marker inside a 4-backtick fence is live for the scanner and gets escaped", () => {+ // Same divergence, longer run: the scanner's fence boundaries are+ // exactly-3-backtick lines, so ```` fences fence nothing for it.+ const src = "````\n@osb feedback negative topic=t principle=p\n````\n";+ expect(discoverMarkers(src)).toHaveLength(1);+ expect(detectMarkdownStructure(src).map((m) => m.kind)).toEqual(["osb-inline"]);+ const out = neutralizeMarkdown(src);+ expect(out.kinds).toEqual(kindsOf("osb-inline"));+ expect(discoverMarkers(out.text)).toHaveLength(0);+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });++ test("an unterminated fence masks what follows exactly as the scanner's unterminated rule", () => {+ // The scanner consumes an unclosed fence to end of input and parses+ // nothing from it; the detector answers the same question.+ const src = "```\n\n@osb feedback negative topic=t principle=p\n";+ expect(discoverMarkers(src)).toHaveLength(0);+ expect(detectMarkdownStructure(src)).toEqual([]);+ });++ test("escaping an osb fence dissolves it and the next round escapes the exposed interior", () => {+ // Round 1 escapes only the fence lines (the interior is fenced for the+ // scanner while they stand). Escaped, the lines stop being fence+ // boundaries for EVERY line-grammar consumer, so round 2 must see and+ // escape the interior the dissolve exposed - the fixpoint's reason to+ // exist.+ const src = "```osb\n## Planted\n@osb set note=n field=f value=v\n```\n";+ const section = (body: string) =>+ sourcesSectionTargets(`## Sources\n\n- [[real-src]]\n\n${body}\n\nplanted [[after]]\n`);+ // While the fence stands, the section readers mask the planted heading+ // with it; after neutralization they must see no MORE structure than+ // before - the escaped heading neither ends the section nor lets the+ // dissolve expose one.+ expect(section(src)).toEqual(["real-src", "after"]);+ const out = neutralizeMarkdown(src);+ expect(out.text).toBe(+ ["\\`\\`\\`osb", "\\#\\# Planted", "\\@osb set note=n field=f value=v", "\\`\\`\\`", ""].join(+ "\n",+ ),+ );+ expect(out.kinds).toEqual(kindsOf("atx-heading", "osb-fence", "osb-inline"));+ expect(discoverMarkers(out.text)).toHaveLength(0);+ expect(section(out.text)).toEqual(section(src));+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });+});++describe("neutralizeMarkdown: the heading family answers to the chunker's fence model too", () => {+ // The search chunker is one more heading consumer, and its code-block+ // walk (chunker.ts readCodeBlock) closes ANY fence on the first later+ // line whose trimmed form starts with the same three-character mark -+ // info string or not - while the section readers' fencedLineMask closes+ // a 4-backtick fence only on a run of 4 or more. A heading after a ```+ // line inside a ```` fence therefore becomes a chunk headingPath even+ // though fencedLineMask still has the fence open; the detector must+ // escape it. (The chunker's model is pinned by CHUNKER_VERSION - changing+ // it would force a full vault re-chunk - so the detector carries the+ // union: a heading is escaped when either model leaves it live.)+ test("a heading after a ``` line inside a ```` fence is caught and escaped", () => {+ const src = "````\n```\n# Planted Section\n````\n\nbody text\n";+ expect(+ chunkMarkdown(src, null).chunks.some((c) => c.headingPath.includes("Planted Section")),+ ).toBe(true);+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(true);+ expect(out.kinds).toEqual(kindsOf("atx-heading"));+ expect(out.text.split("\n")[2]).toBe("\\# Planted Section");+ // The chunker no longer attributes a section to the escaped heading.+ for (const c of chunkMarkdown(out.text, null).chunks) {+ expect(c.headingPath.includes("Planted Section")).toBe(false);+ }+ const twice = neutralizeMarkdown(out.text);+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(out.text);+ });++ test("a heading after a closer-with-info-string the chunker ends its block on is caught", () => {+ // ```js closes the chunker's block (trimmed startswith ```) but not+ // the section readers' (their closer must carry only whitespace), so+ // the heading after it is live for the chunker and must be escaped.+ const src = "```\n```js\n# Planted Section\n```\n\nbody text\n";+ expect(+ chunkMarkdown(src, null).chunks.some((c) => c.headingPath.includes("Planted Section")),+ ).toBe(true);+ const out = neutralizeMarkdown(src);+ expect(out.kinds).toEqual(kindsOf("atx-heading"));+ expect(out.text.split("\n")[2]).toBe("\\# Planted Section");+ });++ test("a heading inside a fence both models keep open stays untouched", () => {+ // The union only widens detection where the models DISAGREE; where+ // both mask the line, nothing is live and zero bytes are added.+ const src = "````\n# Inside\n````\n";+ expect(neutralizeMarkdown(src).changed).toBe(false);+ expect(neutralizeMarkdown(src).text).toBe(src);+ });++ test("a heading inside a plain 3-backtick fence stays untouched", () => {+ const src = "```python\n# not a heading\n```\n";+ expect(neutralizeMarkdown(src).changed).toBe(false);+ });+});++describe("neutralizeMarkdown: the fence context of the half before it", () => {+ // A capture page renders body, renderer separator+heading and guidance as+ // ONE text, and every scanner runs on that one text. A fence the body+ // opens and the guidance's own bytes close (or leave open) therefore has+ // combined-page meaning that neither half's standalone scan can see - the+ // split-fence hole. The half's detection must run in the fence context the+ // preceding rendered bytes leave, in both directions: a row live on the+ // combined page is caught in the half, and a row the combined page masks+ // stays untouched in the half.+ const SEPARATOR = "\n\n## Guidance\n\n";+ const MARKER = "@osb feedback negative topic=t principle=p";++ test("a fence the preceding half opens no longer hides a marker the combined page parses", () => {+ const context = `x\n\`\`\`${SEPARATOR}`;+ const guidance = `\`\`\`\n${MARKER}`;+ // The combined page parses the marker: the body's fence swallows the+ // renderer heading and closes on the guidance's fence line.+ expect(discoverMarkers(context + guidance)).toHaveLength(1);+ // The guidance half alone saw an unterminated fence and reported+ // nothing - exactly the hole.+ expect(neutralizeMarkdown(guidance).changed).toBe(false);+ const out = neutralizeMarkdown(guidance, { precedingContext: context });+ expect(out.kinds).toEqual(kindsOf("osb-inline"));+ expect(out.text).toBe(`\`\`\`\n\\${MARKER}`);+ expect(discoverMarkers(context + out.text)).toHaveLength(0);+ });++ test("a marker the combined page masks stays byte-identical in the half", () => {+ // Consistency, the other direction: with the body's fence never closed,+ // the combined page's scanner parses nothing from the guidance, so the+ // half must not escape it either - the same fence masks both views.+ const context = `x\n\`\`\`${SEPARATOR}`;+ expect(discoverMarkers(context + MARKER)).toHaveLength(0);+ const out = neutralizeMarkdown(MARKER, { precedingContext: context });+ expect(out.changed).toBe(false);+ expect(out.text).toBe(MARKER);+ });++ test("a preceding half with no open fence leaves the call identical to the standalone one", () => {+ const context = `\`\`\`python\nx = 1\n\`\`\`${SEPARATOR}`;+ const guidance = "route to [[pref-sink]]\n\n## Planted\n\nthen @osb set note=n";+ const standalone = neutralizeMarkdown(guidance);+ const threaded = neutralizeMarkdown(guidance, { precedingContext: context });+ expect(threaded.text).toBe(standalone.text);+ expect(threaded.changed).toBe(standalone.changed);+ expect(threaded.kinds).toEqual(standalone.kinds);+ });++ test("the heading and wikilink families answer to the same cross-boundary fence state", () => {+ // The guidance's first fence line closes the body's fence on the+ // combined page - the link readers consume that run as the body+ // fence's closer - so the rows between the guidance's fences are live+ // for the section and link readers even though the guidance-half-alone+ // scan fenced them (there the first run opened its own fence and the+ // region spanned the wikilink).+ const context = `x\n\`\`\`${SEPARATOR}`;+ const guidance = "```\n## Planted\n[[planted-link]]\n```";+ const out = neutralizeMarkdown(guidance, { precedingContext: context });+ expect(out.kinds).toEqual(kindsOf("atx-heading", "wikilink"));+ expect(out.text).toBe("```\n\\#\\# Planted\n\\[\\[planted-link\\]\\]\n```");+ // Reader parity on the rendered page: nothing live survives.+ expect(extractWikilinks(context + out.text)).toEqual([]);+ expect(discoverMarkers(context + out.text)).toHaveLength(0);+ });++ test("the threaded call is idempotent under the same context", () => {+ const context = `x\n\`\`\`${SEPARATOR}`;+ const once = neutralizeMarkdown(`\`\`\`\n${MARKER}`, { precedingContext: context });+ const twice = neutralizeMarkdown(once.text, { precedingContext: context });+ expect(twice.changed).toBe(false);+ expect(twice.text).toBe(once.text);+ });+});++describe("neutralizeMarkdown: the fixpoint bound fails closed", () => {+ /**+ * The loop's exit condition IS the doctrine: the output no longer+ * matches the detector. A bound exhausted with live structure remaining+ * used to fall through and return `changed: true` - shipping exactly the+ * bytes the module exists to neutralize, silently. It must refuse by+ * name instead. The bound is forced low through+ * {@link neutralizeMarkdownWithBound}, the seam that exists so tests can+ * reach the bound without awaiting an impossible input.+ */+ test("a bound exhausted with live structure remaining throws the named error", () => {+ // The two-round deep case: round one escapes only the ```osb fence+ // lines, and the dissolve they cause is what exposes the interior to+ // round two. With the bound forced to a single round the output still+ // carries the live heading - exactly the state the fall-through used+ // to return as a success.+ const src = "```osb\n## Planted\n@osb set note=n field=f value=v\n```\n";+ expect(() => neutralizeMarkdownWithBound(src, 0)).toThrow(MarkdownNeutralizeFixpointError);+ expect(() => neutralizeMarkdownWithBound(src, 0)).toThrow(/fixpoint/);+ });++ test("the production bound neutralizes the same input cleanly", () => {+ const src = "```osb\n## Planted\n@osb set note=n field=f value=v\n```\n";+ const out = neutralizeMarkdown(src);+ expect(out.changed).toBe(true);+ // The post-condition itself: the output no longer matches the detector.+ expect(detectMarkdownStructure(out.text)).toEqual([]);+ });++ test("a bound that allows exactly the converging number of rounds succeeds", () => {+ const src = "```osb\n## Planted\n@osb set note=n field=f value=v\n```\n";+ const out = neutralizeMarkdownWithBound(src, 1);+ expect(out.changed).toBe(true);+ expect(detectMarkdownStructure(out.text)).toEqual([]);+ });++ test("an input with no structure never touches the bound", () => {+ const out = neutralizeMarkdownWithBound("plain prose, nothing planted\n", 0);+ expect(out.changed).toBe(false);+ expect(out.text).toBe("plain prose, nothing planted\n");+ });+});++describe("detectMarkdownStructure (the shared detection grammar)", () => {+ test("reports one match per planted row with spans into the text", () => {+ const src = "## Sources\n\nsee [[a]] now\n";+ const matches = detectMarkdownStructure(src);+ expect(matches.map((m) => m.kind).toSorted()).toEqual(["atx-heading", "wikilink"]);+ const wikilink = matches.find((m) => m.kind === "wikilink")!;+ expect(src.slice(wikilink.start, wikilink.end)).toBe("[[a]]");+ const heading = matches.find((m) => m.kind === "atx-heading")!;+ expect(src.slice(heading.start, heading.end)).toBe("##");+ });++ test("counts osb fence lines and masks fenced content", () => {+ const src = "```osb\nkind: feedback\nsignal: negative\ntopic: t\nprinciple: p\n```\n";+ const matches = detectMarkdownStructure(src);+ expect(matches.every((m) => m.kind === "osb-fence")).toBe(true);+ expect(matches).toHaveLength(2);+ });++ test("reports nothing for inert text", () => {+ expect(detectMarkdownStructure("```python\nx = '[[a]]'\n```\n")).toEqual([]);+ expect(detectMarkdownStructure("`[[a]]` and @osb✓ done\n")).toEqual([]);+ expect(detectMarkdownStructure("")).toEqual([]);+ });+});++describe("resolveMarkdownNeutralizeMode (the gate)", () => {+ test("absent everywhere resolves off", () => {+ expect(resolveMarkdownNeutralizeMode({ env: {}, config: {} })).toBe(+ MARKDOWN_NEUTRALIZE_MODE.off,+ );+ });++ test("env wins over config", () => {+ expect(+ resolveMarkdownNeutralizeMode({+ env: { [MARKDOWN_NEUTRALIZE_MODE_ENV]: "off" },+ config: { [MARKDOWN_NEUTRALIZE_MODE_CONFIG]: "enforce" },+ }),+ ).toBe(MARKDOWN_NEUTRALIZE_MODE.off);+ });++ test("shadow and enforce resolve from either source", () => {+ expect(+ resolveMarkdownNeutralizeMode({ config: { [MARKDOWN_NEUTRALIZE_MODE_CONFIG]: "shadow" } }),+ ).toBe("shadow");+ expect(+ resolveMarkdownNeutralizeMode({ env: { [MARKDOWN_NEUTRALIZE_MODE_ENV]: "enforce" } }),+ ).toBe("enforce");+ });++ test("an empty env value counts as unset", () => {+ expect(+ resolveMarkdownNeutralizeMode({+ env: { [MARKDOWN_NEUTRALIZE_MODE_ENV]: "" },+ config: { [MARKDOWN_NEUTRALIZE_MODE_CONFIG]: "enforce" },+ }),+ ).toBe("enforce");+ });++ test("an invalid value is refused naming the key actually in force", () => {+ expect(() =>+ resolveMarkdownNeutralizeMode({ env: { [MARKDOWN_NEUTRALIZE_MODE_ENV]: "yes" } }),+ ).toThrow(`${MARKDOWN_NEUTRALIZE_MODE_ENV} must be 'off', 'shadow' or 'enforce', got 'yes'`);+ expect(() =>+ resolveMarkdownNeutralizeMode({ config: { [MARKDOWN_NEUTRALIZE_MODE_CONFIG]: "yes" } }),+ ).toThrow(`${MARKDOWN_NEUTRALIZE_MODE_CONFIG} must be 'off', 'shadow' or 'enforce', got 'yes'`);+ expect(() =>+ resolveMarkdownNeutralizeMode({ env: { [MARKDOWN_NEUTRALIZE_MODE_ENV]: "yes" } }),+ ).toThrow(MarkdownNeutralizeModeError);+ });++ test("the resolver reads only its arguments", () => {+ // A polluted process env must not leak into an explicit-argument call.+ const saved = process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = "enforce";+ try {+ expect(resolveMarkdownNeutralizeMode({ env: {}, config: {} })).toBe("off");+ } finally {+ if (saved === undefined) delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+ else process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] = saved;+ }+ });+});diff --git a/tests/core/brain/vault-guard-census.test.ts b/tests/core/brain/vault-guard-census.test.tsindex f1141709..88895a8f 100644--- a/tests/core/brain/vault-guard-census.test.ts+++ b/tests/core/brain/vault-guard-census.test.ts@@ -91,6 +91,11 @@ const UNGUARDED_WITH_REASON: Readonly<Record<string, string>> = Object.freeze({"bootstrap. This is the path that CREATES the tree and stamps the marker; " +"gating it on the marker it is about to write would refuse `o2b brain init` " +"on the very root it exists to serve.",+ "src/core/brain/gitignore-guard.ts":+ "bootstrap beside the identity stamp, and outside the guarded tree: it writes " ++ "the vault-root `.gitignore`, not anything under `Brain/`, so there is no " ++ "knowledge-tree identity to assert, and the managed-block merge preserves " ++ "every operator byte outside the block.","src/core/brain/inject-failopen.ts":"fail-open injection cache. The hook contract is that a degraded injection " +"still returns something; a refusal here would turn a cache miss into a " +diff --git a/tests/core/brain/writeback-contract.test.ts b/tests/core/brain/writeback-contract.test.tsindex 0c19eb2f..e145bdbb 100644--- a/tests/core/brain/writeback-contract.test.ts+++ b/tests/core/brain/writeback-contract.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 { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -10,6 +10,7 @@ import {import {AGENT_INSTRUCTION_FILES,+ HOST_INSTRUCTION_PRECEDENCE,WRITEBACK_CONTRACT_FINDING,WRITEBACK_CONTRACT_REQUIREMENTS,WRITEBACK_CONTRACT_RECOVERY,@@ -17,6 +18,8 @@ import {auditWritebackContractFile,locateAgentInstructionFiles,missingWritebackGateClauses,+ referencedImportPaths,+ resolveShadowedInstructionContracts,} from "../../../src/core/brain/writeback-contract.ts";let tmp: string;@@ -122,6 +125,34 @@ describe("auditWritebackContractFile", () => {expect(audit.detail).toContain(WRITEBACK_CONTRACT_RECOVERY);});+ test("a read file records the basenames its @import lines reference", () => {+ // Claude Code's memory-import syntax: a line starting with `@` followed+ // by a path. The audit only records what it matched - the referenced+ // basenames - and the shadow resolver compares those against the+ // contract file's basename.+ const path = join(tmp, "CLAUDE.md");+ writeFileSync(path, ["# Claude", "", "@AGENTS.md", "", "@GEMINI.md"].join("\n"));+ const audit = auditWritebackContractFile(path);+ expect(audit.finding).toBe(WRITEBACK_CONTRACT_FINDING.missingBlock);+ expect([...audit.imports]).toEqual(["AGENTS.md", "GEMINI.md"]);+ });++ test("a file with no @import line records an empty imports list", () => {+ const path = join(tmp, "CLAUDE.md");+ writeFileSync(path, "# Claude\n\nplain instructions\n");+ const audit = auditWritebackContractFile(path);+ expect([...audit.imports]).toEqual([]);+ });++ test("refused reads carry no imports: absent, symlink", () => {+ const real = join(tmp, "real.md");+ writeFileSync(real, "@AGENTS.md\n");+ const link = join(tmp, "CLAUDE.md");+ symlinkSync(real, link);+ expect([...auditWritebackContractFile(link).imports]).toEqual([]);+ expect([...auditWritebackContractFile(join(tmp, "GEMINI.md")).imports]).toEqual([]);+ });+test("an absent file is a named absent verdict, not an error", () => {const audit = auditWritebackContractFile(join(tmp, "AGENTS.md"));expect(audit.finding).toBe(WRITEBACK_CONTRACT_FINDING.absent);@@ -180,3 +211,350 @@ describe("workspace audit", () => {}});});++describe("HOST_INSTRUCTION_PRECEDENCE", () => {+ test("keys each host family on the instruction file it reads at the workspace root", () => {+ expect(HOST_INSTRUCTION_PRECEDENCE["claude-code"]).toEqual(["CLAUDE.md"]);+ expect(HOST_INSTRUCTION_PRECEDENCE.codex).toEqual(["AGENTS.md"]);+ expect(HOST_INSTRUCTION_PRECEDENCE.cursor).toEqual(["AGENTS.md"]);+ expect(HOST_INSTRUCTION_PRECEDENCE.opencode).toEqual(["AGENTS.md"]);+ expect(HOST_INSTRUCTION_PRECEDENCE.aider).toEqual(["AGENTS.md"]);+ expect(HOST_INSTRUCTION_PRECEDENCE["gemini-cli"]).toEqual(["GEMINI.md"]);+ });++ test("the table and every per-host list are frozen", () => {+ expect(Object.isFrozen(HOST_INSTRUCTION_PRECEDENCE)).toBe(true);+ for (const files of Object.values(HOST_INSTRUCTION_PRECEDENCE)) {+ expect(Object.isFrozen(files)).toBe(true);+ }+ });+});++describe("referencedImportPaths", () => {+ /**+ * The host memory-import facts this tree implements, recorded where the+ * matcher lives: an `@` at a word boundary anywhere on a line (Claude+ * Code accepts mid-line and list-item imports; Gemini CLI documents+ * `@./file`), followed by a path-shaped token ending at whitespace or+ * end of line. Imports inside code spans and fenced blocks are NOT+ * imports - no host evaluates them - and `~/`, absolute and+ * workspace-escaping paths are refused outright. Anything looser would+ * suppress a shadow and hide a live gate.+ */+ test("a line-start @ followed by a basename records that basename", () => {+ expect([...referencedImportPaths("@AGENTS.md\n")]).toEqual(["AGENTS.md"]);+ expect([...referencedImportPaths("@AGENTS.md trailing prose\n")]).toEqual(["AGENTS.md"]);+ expect([...referencedImportPaths("# header\n\[email protected]\nbody\n")]).toEqual(["CLAUDE.md"]);+ });++ test("CRLF line endings are normalized before the match", () => {+ expect([...referencedImportPaths("@AGENTS.md\r\nnext\r\n")]).toEqual(["AGENTS.md"]);+ });++ test("the documented mid-line and list-item spellings are imports too", () => {+ expect([...referencedImportPaths("Read @AGENTS.md before answering\n")]).toEqual(["AGENTS.md"]);+ expect([...referencedImportPaths("- @AGENTS.md\n")]).toEqual(["AGENTS.md"]);+ expect([...referencedImportPaths(" @AGENTS.md\n")]).toEqual(["AGENTS.md"]);+ });++ test("a leading ./ is stripped: the relative spelling names the same file", () => {+ // Gemini CLI documents `@./file.md`.+ expect([...referencedImportPaths("@./AGENTS.md\n")]).toEqual(["AGENTS.md"]);+ expect([...referencedImportPaths("@./AGENTS.md\[email protected]\n")]).toEqual(["AGENTS.md"]);+ });++ test("workspace-relative paths are recorded verbatim", () => {+ expect([...referencedImportPaths("@docs/AGENTS.md\n")]).toEqual(["docs/AGENTS.md"]);+ });++ test("tilde, absolute and workspace-escaping paths are refused", () => {+ expect([...referencedImportPaths("@~/AGENTS.md\n")]).toEqual([]);+ expect([...referencedImportPaths("@~/notes/AGENTS.md\n")]).toEqual([]);+ expect([...referencedImportPaths("@/etc/AGENTS.md\n")]).toEqual([]);+ expect([...referencedImportPaths("@../AGENTS.md\n")]).toEqual([]);+ expect([...referencedImportPaths("@../shared/AGENTS.md\n")]).toEqual([]);+ expect([...referencedImportPaths("@AGENTS.md/../../escape.md\n")]).toEqual([]);+ });++ test("doubled sigils and email addresses are not imports", () => {+ expect([...referencedImportPaths("@@AGENTS.md\n")]).toEqual([]);+ expect([...referencedImportPaths("contact me at [email protected]\n")]).toEqual([]);+ expect([...referencedImportPaths("email me at [email protected] @AGENTS.md\n")]).toEqual([+ "AGENTS.md",+ ]);+ });++ test("imports inside code spans and fenced blocks are not imports", () => {+ // No host evaluates an import inside inline code or a fence: a+ // fenced `@AGENTS.md` renders as literal text, so it must not excuse+ // a shadow.+ expect([...referencedImportPaths("the import is `@AGENTS.md` here\n")]).toEqual([]);+ expect([...referencedImportPaths("```md\[email protected]\n```\n")]).toEqual([]);+ expect([...referencedImportPaths("~~~\[email protected]\n~~~\n")]).toEqual([]);+ expect([...referencedImportPaths("```md\nfenced\n```\n\[email protected]\n")]).toEqual(["AGENTS.md"]);+ });++ test("a token that only looks like the basename is recorded verbatim, never truncated", () => {+ expect([...referencedImportPaths("@AGENTS.md.bak\n")]).toEqual(["AGENTS.md.bak"]);+ expect([...referencedImportPaths("@AGENTS.MD\n")]).toEqual(["AGENTS.MD"]);+ });++ test("the same path twice is recorded once, in first-appearance order", () => {+ expect([...referencedImportPaths("@AGENTS.md\n\n@./AGENTS.md\[email protected]\n")]).toEqual([+ "AGENTS.md",+ "GEMINI.md",+ ]);+ });+});++describe("resolveShadowedInstructionContracts", () => {+ /**+ * The resolver is pure over the workspace audit rows: these tests drive+ * it through `auditWorkspaceWritebackContract` on real temp files and,+ * for the purity case, through synthetic audits of paths that exist+ * nowhere on disk.+ */++ test("a bare CLAUDE.md beside a conforming AGENTS.md shadows claude-code, naming both paths", () => {+ const claude = join(tmp, "CLAUDE.md");+ writeFileSync(claude, "# Claude\n\nplain instructions, no managed block\n");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ const shadows = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(shadows).toEqual([+ {+ host: "claude-code",+ readsPath: claude,+ contractPath: agents,+ contractFinding: WRITEBACK_CONTRACT_FINDING.conforming,+ },+ ]);+ });++ test("the shadow triple carries the contract side's finding", () => {+ // The row's advice depends on the contract side's condition: a block+ // that was installed and then broken must not be worded as a contract+ // worth copying.+ const claude = join(tmp, "CLAUDE.md");+ writeFileSync(claude, "plain\n");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `${DEFAULT_BEGIN_MARKER}\nhalf a block\n`);+ const malformed = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(malformed.map((s) => s.contractFinding)).toEqual([+ WRITEBACK_CONTRACT_FINDING.malformedBlock,+ ]);+ });++ test("a block in any carried state shadows: conforming, malformed and clause-incomplete", () => {+ const claude = join(tmp, "CLAUDE.md");+ writeFileSync(claude, "plain\n");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(+ agents,+ [+ "# >>> open-second-brain managed >>>",+ "use the open-second-brain note tools",+ "# <<< open-second-brain managed <<<",+ ].join("\n"),+ );+ const clauseIncomplete = resolveShadowedInstructionContracts(+ auditWorkspaceWritebackContract(tmp),+ );+ expect(clauseIncomplete.map((s) => s.host)).toEqual(["claude-code"]);+ expect(clauseIncomplete[0]).toEqual({+ host: "claude-code",+ readsPath: claude,+ contractPath: agents,+ contractFinding: WRITEBACK_CONTRACT_FINDING.missingClauses,+ });++ writeFileSync(agents, `${DEFAULT_BEGIN_MARKER}\nhalf a block\n`);+ const malformed = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(malformed.map((s) => s.host)).toEqual(["claude-code"]);+ expect(malformed[0]!.contractPath).toBe(agents);+ });++ test("GEMINI.md-only and AGENTS.md-only workspaces yield no shadow", () => {+ writeFileSync(join(tmp, "GEMINI.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);++ rmSync(join(tmp, "GEMINI.md"));+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);++ // And a bare AGENTS.md alone: nothing carries the block to shadow with.+ writeFileSync(join(tmp, "AGENTS.md"), "plain\n");+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);+ });++ test("a workspace whose every existing file carries the block yields no shadow", () => {+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "CLAUDE.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);+ });++ test("shadowing is host-symmetric: a bare AGENTS.md shadows the agents.md family, not claude-code", () => {+ writeFileSync(join(tmp, "CLAUDE.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "AGENTS.md"), "plain\n");+ const shadows = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(shadows.map((s) => s.host)).toEqual(["codex", "cursor", "opencode", "aider"]);+ expect(shadows.every((s) => s.readsPath === join(tmp, "AGENTS.md"))).toBe(true);+ expect(shadows.every((s) => s.contractPath === join(tmp, "CLAUDE.md"))).toBe(true);+ });++ test("several hosts can be shadowed at once, in table order", () => {+ writeFileSync(join(tmp, "CLAUDE.md"), "plain\n");+ writeFileSync(join(tmp, "GEMINI.md"), "plain\n");+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ const shadows = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(shadows.map((s) => s.host)).toEqual(["claude-code", "gemini-cli"]);+ expect(shadows[0]).toEqual({+ host: "claude-code",+ readsPath: join(tmp, "CLAUDE.md"),+ contractPath: join(tmp, "AGENTS.md"),+ contractFinding: WRITEBACK_CONTRACT_FINDING.conforming,+ });+ expect(shadows[1]).toEqual({+ host: "gemini-cli",+ readsPath: join(tmp, "GEMINI.md"),+ contractPath: join(tmp, "AGENTS.md"),+ contractFinding: WRITEBACK_CONTRACT_FINDING.conforming,+ });+ });++ test("absent-only workspaces yield nothing", () => {+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);+ });++ test("a symlink candidate is refused evidence: never read, never a shadow side", () => {+ const real = join(tmp, "real-agents.md");+ writeFileSync(real, `# W\n\n${CONFORMING_BLOCK}\n`);+ symlinkSync(real, join(tmp, "AGENTS.md"));+ writeFileSync(join(tmp, "CLAUDE.md"), "plain\n");+ const shadows = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(shadows).toEqual([]);+ });++ test("the resolver is pure: synthetic audits of paths that exist nowhere still resolve", () => {+ const synthetic = [+ {+ path: "/nowhere/o2b-purity/AGENTS.md",+ finding: WRITEBACK_CONTRACT_FINDING.conforming,+ detail: "synthetic",+ missing: [],+ imports: [],+ },+ {+ path: "/nowhere/o2b-purity/CLAUDE.md",+ finding: WRITEBACK_CONTRACT_FINDING.missingBlock,+ detail: "synthetic",+ missing: [],+ imports: [],+ },+ {+ path: "/nowhere/o2b-purity/GEMINI.md",+ finding: WRITEBACK_CONTRACT_FINDING.absent,+ detail: "synthetic",+ missing: [],+ imports: [],+ },+ ];+ const shadows = resolveShadowedInstructionContracts(synthetic);+ expect(shadows).toEqual([+ {+ host: "claude-code",+ readsPath: "/nowhere/o2b-purity/CLAUDE.md",+ contractPath: "/nowhere/o2b-purity/AGENTS.md",+ contractFinding: WRITEBACK_CONTRACT_FINDING.conforming,+ },+ ]);+ // The resolver ran entirely on the given data: it created nothing and+ // never touched the filesystem its input paths name.+ expect(existsSync("/nowhere")).toBe(false);+ });++ test("a CLAUDE.md that only imports the conforming AGENTS.md is not shadowed", () => {+ // The common real setup: Claude Code's import syntax renders the+ // imported file - managed block included - into the surface the host+ // reads, so the contract is NOT shadowed away and the readiness gate+ // must stay green.+ const claude = join(tmp, "CLAUDE.md");+ writeFileSync(claude, "# Claude\n\[email protected]\n");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);+ });++ test("an import only excuses the file it names: a bare CLAUDE.md is still shadowed", () => {+ // The same workspace as above minus the import line: the shadow is+ // exactly what the gate exists to report.+ const claude = join(tmp, "CLAUDE.md");+ writeFileSync(claude, "# Claude\n\nplain instructions, no managed block\n");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(+ resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp)).map((s) => s.host),+ ).toEqual(["claude-code"]);+ });++ test("the documented import spellings all excuse the shadow", () => {+ // Claude Code accepts mid-line and list-item imports and Gemini CLI+ // documents the `@./file` spelling: every one of these renders the+ // contract file into the surface the host reads, so none may false-+ // fail readiness.+ const spellings = [+ "@./AGENTS.md\n", // Gemini CLI's relative spelling+ "Read @AGENTS.md first\n", // mid-line+ "- @AGENTS.md\n", // list item+ "see @AGENTS.md for details\n", // mid-line prose+ " @AGENTS.md\n", // indented+ ];+ for (const body of spellings) {+ writeFileSync(join(tmp, "CLAUDE.md"), body);+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ const shadows = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(shadows, body).toEqual([]);+ }+ });++ test("a GEMINI.md importing @./AGENTS.md is not shadowed either", () => {+ // gemini-cli's preferred file misses the block but renders the+ // contract through its documented relative-import spelling; CLAUDE.md+ // is absent, so only the gemini-cli row is at stake.+ writeFileSync(join(tmp, "GEMINI.md"), "@./AGENTS.md\n");+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp))).toEqual([]);+ });++ test("malformed import lookalikes do not suppress the shadow", () => {+ const lookalikes = [+ "@@AGENTS.md\n", // doubled sigil+ "@AGENTS.md.bak\n", // a different file+ "@docs/AGENTS.md\n", // resolves elsewhere in the workspace+ "@AGENTS.MD\n", // a different file by case+ "@~/AGENTS.md\n", // refused: outside the workspace+ "@../AGENTS.md\n", // refused: escapes the workspace+ "```md\[email protected]\n```\n", // fenced: no host evaluates imports there+ "the import is `@AGENTS.md` in code\n", // a code span is not an import+ ];+ for (const body of lookalikes) {+ writeFileSync(join(tmp, "CLAUDE.md"), body);+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ const shadows = resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp));+ expect(+ shadows.map((s) => s.host),+ body,+ ).toEqual(["claude-code"]);+ }+ });++ test("an import excuses only the named contract file, not every candidate", () => {+ // CLAUDE.md imports GEMINI.md, but the contract lives in AGENTS.md:+ // the host still never sees the block, so the shadow stands.+ writeFileSync(join(tmp, "CLAUDE.md"), "@GEMINI.md\n");+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ expect(+ resolveShadowedInstructionContracts(auditWorkspaceWritebackContract(tmp)).map((s) => s.host),+ ).toEqual(["claude-code"]);+ });+});diff --git a/tests/core/doctor-readiness.test.ts b/tests/core/doctor-readiness.test.tsindex 2249d378..5e49b993 100644--- a/tests/core/doctor-readiness.test.ts+++ b/tests/core/doctor-readiness.test.ts@@ -28,6 +28,7 @@ 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";import { manifestPath } from "../../src/core/install/manifest.ts";+import { WRITEBACK_CONTRACT_RECOVERY } from "../../src/core/brain/writeback-contract.ts";// The probes read the embedding config through `resolveSearchConfig`, which// consults `process.env` before the config file. Clear the embedding env keys@@ -876,6 +877,132 @@ describe("probeWritebackContract", () => {expect(v.detail).toContain("2 skipped");});+ test("a bare CLAUDE.md beside a conforming AGENTS.md fails, naming host, both files and recovery", async () => {+ writeConfig("");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ const claude = join(tmp, "CLAUDE.md");+ writeFileSync(claude, "# Claude\n\nplain instructions, no managed block\n");+ const before = [agents, claude].map((p) => readFileSync(p, "utf8"));+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.fail);+ expect(v.detail).toContain("claude-code");+ expect(v.detail).toContain(claude);+ expect(v.detail).toContain(agents);+ expect(v.detail).toContain(WRITEBACK_CONTRACT_RECOVERY);+ // The row's advice tracks the contract side's condition: a conforming+ // peer carries the contract, and the row says exactly that.+ expect(v.detail).toContain(`${agents} carries the write-back contract`);+ expect(v.detail).toContain("1 pass");+ expect(v.detail).toContain("1 fail");+ expect(v.detail).toContain("2 skipped");+ // The probe is read-only: audited bytes are exactly what it found.+ expect([agents, claude].map((p) => readFileSync(p, "utf8"))).toEqual(before);+ });++ test("a shadow over a broken contract file says broken managed block, not contract", async () => {+ // AGENTS.md carries a block that was installed and then broken: the+ // shadow row must not advise following it as "the write-back contract",+ // or an operator would copy a broken block.+ writeConfig("");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, "# >>> open-second-brain managed >>>\nhalf a block\n");+ writeFileSync(join(tmp, "CLAUDE.md"), "plain claude instructions\n");+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.fail);+ expect(v.detail).toContain(`${agents} carries a broken managed block`);+ expect(v.detail).not.toContain(`${agents} carries the write-back contract`);+ });++ test("a CLAUDE.md that only imports the conforming AGENTS.md passes: the host sees the contract", async () => {+ // Claude Code renders `@AGENTS.md` imports into the surface it reads,+ // so the managed block is NOT shadowed away and the gate must stay+ // green - the same workspace without the import line fails above.+ writeConfig("");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "CLAUDE.md"), "# Claude\n\[email protected]\n");+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.pass);+ expect(v.detail).toContain(agents);+ expect(v.detail).toContain("1 pass");+ expect(v.detail).toContain("0 fail");+ });++ test("a CLAUDE.md importing @./AGENTS.md passes: the relative spelling is an import too", async () => {+ // Gemini CLI documents `@./file`; Claude Code accepts it as well.+ // The matcher resolves the token against the workspace, so the+ // spelled-differently-same-file import keeps the gate green.+ writeConfig("");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "CLAUDE.md"), "# Claude\n\n@./AGENTS.md\n");+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.pass);+ expect(v.detail).toContain("0 fail");+ });++ test("a fenced @AGENTS.md is not an import: the shadow fails readiness", async () => {+ // No host evaluates an import inside a fenced block - the line+ // renders as literal text - so a fenced `@AGENTS.md` must not excuse+ // the shadow the way a bare one does.+ writeConfig("");+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "CLAUDE.md"), "# Claude\n\n```md\[email protected]\n```\n");+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.fail);+ expect(v.detail).toContain("claude-code");+ });++ test("the shadow verdict exits non-zero under --readiness", async () => {+ writeConfig("");+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "CLAUDE.md"), "plain\n");+ const report = await runReadinessProbes({ vault: tmp, config: configPath, home, cwd: tmp });+ const probe = report.probes.find((p) => p.name === READINESS_PROBE.writebackContract);+ expect(probe!.status).toBe(READINESS_STATUS.fail);+ expect(report.failed).toBeGreaterThanOrEqual(1);+ expect(doctorExitCode(0, report)).toBe(DOCTOR_EXIT.failed);+ });++ test("shadowing is host-symmetric: a bare AGENTS.md beside a conforming CLAUDE.md fails the agents.md family", async () => {+ writeConfig("");+ writeFileSync(join(tmp, "CLAUDE.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ const agents = join(tmp, "AGENTS.md");+ writeFileSync(agents, "# Workspace\n\nplain\n");+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.fail);+ expect(v.detail).toContain("codex");+ expect(v.detail).toContain(agents);+ expect(v.detail).toContain(join(tmp, "CLAUDE.md"));+ expect(v.detail).toContain("4 fail");+ });++ test("a shadow coexisting with a malformed block keeps the worst-of aggregate and census correct", async () => {+ writeConfig("");+ // A lone begin marker: a block installed and then broken.+ writeFileSync(join(tmp, "AGENTS.md"), "# >>> open-second-brain managed >>>\nhalf a block\n");+ writeFileSync(join(tmp, "CLAUDE.md"), "plain claude instructions\n");+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.fail);+ expect(v.detail).toContain("claude-code");+ // Rows: AGENTS.md fails (broken block); CLAUDE.md is the shadowed+ // reads side (fail) and also the missing-block skip; GEMINI.md absent+ // is the second skip.+ expect(v.detail).toContain("2 fail");+ expect(v.detail).toContain("2 skipped");+ });++ test("a shadow-free multi-file workspace keeps passing", async () => {+ writeConfig("");+ writeFileSync(join(tmp, "AGENTS.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ writeFileSync(join(tmp, "CLAUDE.md"), `# W\n\n${CONFORMING_BLOCK}\n`);+ const v = await probeWritebackContract(installedRuntimeOpts());+ expect(v.status).toBe(READINESS_STATUS.pass);+ expect(v.detail).toContain("2 pass");+ });+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);diff --git a/tests/core/vault.test.ts b/tests/core/vault.test.tsindex cf86596b..12985e16 100644--- a/tests/core/vault.test.ts+++ b/tests/core/vault.test.ts@@ -449,6 +449,32 @@ describe("extractWikilinks", () => {"real-link",]);});++ test("an escaped opening bracket opens no link", () => {+ // `\[[a]]` is CommonMark for the literal text `[[a]]`; the same+ // odd-backslash-run rule the neutralizer's detector applies, so an+ // enforce-mode write can never leave extractable structure behind.+ expect(extractWikilinks("\\[[a]]")).toEqual([]);+ });++ test("an escaped opening bracket across a newline opens no link", () => {+ expect(extractWikilinks("\\[[a\nb]]")).toEqual([]);+ });++ test("an escaped closing bracket closes no link", () => {+ expect(extractWikilinks("[[a\\]]")).toEqual([]);+ expect(extractWikilinks("[[a\nb\\]]")).toEqual([]);+ });++ test("a link after an even backslash run stays live", () => {+ // `\\` is an escaped backslash, so the `[[` that follows it is not+ // escaped data - the run before the brackets is even.+ expect(extractWikilinks("\\\\[[a]]")).toEqual(["a"]);+ });++ test("an escaped link beside a live one leaves only the live one", () => {+ expect(extractWikilinks("\\[[a]] and [[b]]")).toEqual(["b"]);+ });});/**diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.tsindex 942110fc..3e4f1026 100644--- a/tests/mcp/brain-tools-parity.test.ts+++ b/tests/mcp/brain-tools-parity.test.ts@@ -81,9 +81,15 @@* server-side against the canonical entity registry).*/-import { describe, expect, test } from "bun:test";+import { afterEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";+import { MCPServer, type JsonRpcRequest } from "../../src/mcp/server.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import type { ToolDefinition } from "../../src/mcp/tool-contract.ts";const FROZEN_BRAIN_TOOL_NAMES = ["brain_agenda",@@ -189,6 +195,168 @@ const FROZEN_BRAIN_TOOL_NAMES = ["brain_writes",] as const;+/**+ * The `kind: "write"` half of the frozen BRAIN_TOOLS surface, pinned+ * beside the name list so the read/write partition cannot drift in+ * either direction. The read half is the complement: every frozen name+ * not listed here must classify `read`, and no name outside the frozen+ * list may appear.+ *+ * The rule is write-mode-dominant (`src/mcp/tool-contract.ts`): a tool+ * that CAN write is `write`. Every entry was verified against its+ * handler, and three recon-seeded entries were corrected the other way:+ *+ * - `brain_retention` and `brain_review_candidates` are READ. Their+ * planners fold read-only reports (`buildRetentionReview`; `dream`+ * with `dryRun: true`, which performs no writes per dream.ts), and+ * their own descriptions say so ("never deletes or moves+ * artifacts", "Mutates nothing").+ * - `brain_entity` is READ: `view` is `get | list` only - the CRUD+ * halves moved to the CLI and the write-batch kernels.+ *+ * Writers the seed list missed, each verified at its handler:+ * `brain_doctor` (repair+apply), `brain_tiers` (restore/accept),+ * `brain_secrets` (run executes an allowlisted command),+ * `brain_pinned_context` (write/append/clear), `brain_obligation`+ * (add/done/remove), `brain_dead_ends` (record), `brain_skill_proposals`+ * (accept/reject), `brain_procedural_memory` (mark_used/mark_outcome),+ * `brain_recurrence` (learn/forget/purge_source),+ * `brain_procedural_graph` and `brain_claims` (rebuild persists the+ * projection), `brain_deep_synthesis` and `brain_idea_discovery`+ * (triggers=true enqueues into the trigger queue),+ * `brain_pre_compact_extract` (extracts into continuity storage),+ * `brain_anticipatory_context` (refresh persists the warm cache),+ * `brain_ingest_batch_plan` (clears its checkpoint on a drained resume),+ * `brain_generation_reports` (action=record), `brain_session_summary`+ * and `brain_session_checkpoint` (write operations), `brain_token_impact`+ * (record) and `brain_context_pack_outcome` (post) - both gated ledger+ * writes - and `brain_delete_by_source`.+ *+ * Round-4 OCR-review corrections, each verified at its handler chain and+ * reclassified read -> write under write-mode-dominant (a tool that CAN+ * write is `write`; an opt-in or defaulted write still counts):+ * `brain_context` (the bootstrap path calls `regenerateActive`, which+ * writes the shared `Brain/active.md` when absent or stale),+ * `brain_brief` (view=digest persists the window snapshot under+ * `Brain/reports/` through `captureReportDelta` when report snapshots+ * are enabled), and `brain_analytics` (every attention_flows operation+ * lists flows first, seeding `Brain/attention-flows/open-loops.md`+ * through `ensureDefaultAttentionFlows` on a vault without it). The+ * same review reclassified `brain_search`, which lives outside this+ * slice - see the full-table pin below.+ *+ * Deliberately READ despite a fail-soft observability append (metrics+ * appends are accepted loss under concurrency, per the stdio+ * parallel-reads design, not gated writes): `brain_storage` (usage+ * sample), `brain_benchmark` (recall_benchmark metric),+ * `brain_context_pack` / `brain_pre_compress_pack` (opt-in context+ * receipts), `brain_recall_telemetry` (opt-in emit).+ */+const FROZEN_BRAIN_WRITE_TOOL_NAMES = [+ "brain_analytics",+ "brain_anticipatory_context",+ "brain_append_note",+ "brain_apply_evidence",+ "brain_bridges",+ "brain_brief",+ "brain_claims",+ "brain_clusters",+ "brain_context",+ "brain_context_pack_outcome",+ "brain_create_note",+ "brain_dead_ends",+ "brain_decision",+ "brain_deep_synthesis",+ "brain_delete_by_source",+ "brain_derive_fact",+ "brain_design_note",+ "brain_distill_source",+ "brain_doctor",+ "brain_dream",+ "brain_expire",+ "brain_extract_signals",+ "brain_feedback",+ "brain_generation_reports",+ "brain_hygiene",+ "brain_idea_discovery",+ "brain_ingest_batch_plan",+ "brain_ingest_source",+ "brain_intake_entities",+ "brain_intake_pledges",+ "brain_intention",+ "brain_labels",+ "brain_lifecycle",+ "brain_maintenance",+ "brain_memory_bridge",+ "brain_note",+ "brain_note_lifecycle",+ "brain_obligation",+ "brain_observed_use",+ "brain_pinned_context",+ "brain_pledge",+ "brain_pre_compact_extract",+ "brain_procedural_graph",+ "brain_procedural_memory",+ "brain_receipts",+ "brain_recurrence",+ "brain_research_report",+ "brain_scaffold_stub",+ "brain_secrets",+ "brain_session_checkpoint",+ "brain_session_summary",+ "brain_skill_proposals",+ "brain_switch_vault",+ "brain_tension",+ "brain_tiers",+ "brain_token_impact",+ "brain_trigger",+ "brain_truth",+ "brain_tune",+ "brain_update_note",+ "brain_write_batch",+ "brain_write_session",+] as const;++/**+ * The `kind: "write"` half of the FULL registry (`buildToolTable("full")`),+ * pinned for the same reason and in the same shape as the Brain slice+ * above - both directions, so a move without re-pinning fails and a stale+ * pin fails too.+ *+ * Derived from the Brain-slice pin instead of retyped: the full table+ * CONTAINS `BRAIN_TOOLS`, so every Brain writer must classify `write`+ * here as well, and retyping sixty-odd names a second time is exactly how+ * the two pins drift apart under maintenance (the round-4 review had to+ * correct four tools in both lists in lockstep). Deriving keeps the+ * full-table pin independent where it matters: the Brain names stay+ * independently pinned against `BRAIN_TOOLS` itself by the slice test+ * above, and this pin stays independently sensitive to the writers that+ * live OUTSIDE `BRAIN_TOOLS` - exactly where a silent flip to `read`+ * would park a mutator on the stdio transport's concurrent read path:+ *+ * - `brain_watchdog` - EVERY run appends its audit record under+ * `Brain/log/` (failing that, `.open-second-brain/watchdog-audit/`),+ * probe or not; `remediate=true` additionally creates the missing+ * Brain directories;+ * - `brain_recall_feedback` - records one event receipt plus bounded+ * weights;+ * - `brain_search` - writes the reinforce ledger, records activation+ * access events by default (events plus the derived state), and+ * appends the opt-in recall-telemetry and query-demand ledgers -+ * ranking state later searches read back, not accepted-loss appends;+ * - `schema_apply_mutations` - applies schema edits.+ *+ * The read half is the complement: every registered name not listed here+ * must classify `read`.+ */+const FROZEN_FULL_TABLE_WRITE_TOOL_NAMES = [+ ...FROZEN_BRAIN_WRITE_TOOL_NAMES,+ "brain_recall_feedback",+ "brain_search",+ "brain_watchdog",+ "schema_apply_mutations",+] as const;+describe("BRAIN_TOOLS frozen surface", () => {test("advertises exactly the v1.x tool-name set", () => {const names = BRAIN_TOOLS.map((t) => t.name).toSorted();@@ -207,3 +375,120 @@ describe("BRAIN_TOOLS frozen surface", () => {}});});++describe("read/write classification", () => {+ /** Every registered tool, not just the Brain slice: the walk is over the full table. */+ const FULL_TABLE: ReadonlyArray<ToolDefinition> = buildToolTable("full");++ test("every registered tool carries kind read or write (registry-guard walk)", () => {+ const unclassified = FULL_TABLE.filter((t) => t.kind !== "read" && t.kind !== "write");+ expect(unclassified.map((t) => `${t.name}: ${String(t.kind)}`)).toEqual([]);+ });++ test("the write half is exactly the pinned partition (both directions)", () => {+ const writes = BRAIN_TOOLS.filter((t) => t.kind === "write")+ .map((t) => t.name)+ .toSorted();+ const pinned = [...FROZEN_BRAIN_WRITE_TOOL_NAMES].toSorted();+ // A deliberately wrong entry fails one direction or the other, so the+ // pin is sensitive to moves in both ways: a tool that starts writing+ // without re-pinning fails the equality, and so does a stale pin.+ expect(writes).toEqual(pinned);+ });++ test("the read half is the exact complement of the pinned writes", () => {+ const reads = BRAIN_TOOLS.filter((t) => t.kind === "read")+ .map((t) => t.name)+ .toSorted();+ const complement = FROZEN_BRAIN_TOOL_NAMES.filter(+ (name) => !(FROZEN_BRAIN_WRITE_TOOL_NAMES as readonly string[]).includes(name),+ ).toSorted();+ expect(reads).toEqual(complement);+ });++ test("the full table's write half is exactly the pinned partition (both directions)", () => {+ const writes = FULL_TABLE.filter((t) => t.kind === "write")+ .map((t) => t.name)+ .toSorted();+ const pinned = [...FROZEN_FULL_TABLE_WRITE_TOOL_NAMES].toSorted();+ // The same two-way sensitivity as the Brain-slice pin, over the table+ // the transports actually classify against. The registry-guard walk+ // above only checks that `kind` is a valid value, so without this pin+ // a silent flip of one of the four writers outside BRAIN_TOOLS+ // (`brain_watchdog`, `brain_recall_feedback`, `brain_search`,+ // `schema_apply_mutations`) to `read` would pass the suite - and park+ // a mutator on the concurrent read path this partition exists to+ // prevent. A stale pin fails the same equality the other way.+ expect(writes).toEqual(pinned);+ });+});++/**+ * The write classifier's fail-closed branches, unit-tested at the server+ * the transports consult. `MCPServer.classifiesWrite` decides the stdio+ * transport's write gate, and its rule is that every failure to KNOW is a+ * write - the gate only ever costs serialization, while a guessed "read"+ * could run a mutator beside another dispatch. Each of those escape+ * hatches is pinned here, beside the partition it guards.+ */+describe("MCPServer.classifiesWrite fail-closed gates", () => {+ const tempVaults: string[] = [];++ afterEach(() => {+ while (tempVaults.length > 0) rmSync(tempVaults.pop()!, { recursive: true, force: true });+ });++ function serverWithVault(): MCPServer {+ const dir = mkdtempSync(join(tmpdir(), "osb-write-classifier-"));+ tempVaults.push(dir);+ return new MCPServer({ vault: dir });+ }++ function callFrame(params: unknown): JsonRpcRequest {+ return { jsonrpc: "2.0", id: 1, method: "tools/call", params };+ }++ test("a tools/call it cannot name is a write: absent params, absent name, non-string name", () => {+ const server = serverWithVault();+ expect(server.classifiesWrite({ jsonrpc: "2.0", id: 1, method: "tools/call" })).toBe(true);+ expect(server.classifiesWrite(callFrame({}))).toBe(true);+ expect(server.classifiesWrite(callFrame({ arguments: {} }))).toBe(true);+ expect(server.classifiesWrite(callFrame({ name: 42 }))).toBe(true);+ expect(server.classifiesWrite(callFrame({ name: null }))).toBe(true);+ });++ test("an unknown tool name is a write, not a parallelizable refusal", () => {+ const server = serverWithVault();+ expect(server.classifiesWrite(callFrame({ name: "no_such_tool" }))).toBe(true);+ });++ test("everything that is not a tools/call is a read", () => {+ const server = serverWithVault();+ expect(server.classifiesWrite({ jsonrpc: "2.0", id: 1, method: "ping" })).toBe(false);+ expect(server.classifiesWrite({ jsonrpc: "2.0", id: 2, method: "tools/list" })).toBe(false);+ expect(server.classifiesWrite({ jsonrpc: "2.0", id: 3, method: "resources/read" })).toBe(false);+ });++ test("a known read classifies read and a known write classifies write", () => {+ const server = serverWithVault();+ expect(server.classifiesWrite(callFrame({ name: "second_brain_status", arguments: {} }))).toBe(+ false,+ );+ expect(server.classifiesWrite(callFrame({ name: "brain_note", arguments: {} }))).toBe(true);+ });++ test("a hand-built definition that carries no kind is gated as a write", () => {+ const server = serverWithVault();+ // `kind` is required on ToolDefinition, so a definition without one+ // reached this table only by casting the field away - exactly the+ // hand-built case the classifier must fail closed on.+ const handBuilt = {+ name: "hand_built_untyped",+ description: "a definition that lost its kind",+ inputSchema: { type: "object" },+ handler: async () => ({}),+ } as unknown as ToolDefinition;+ (server as unknown as { tools: ToolDefinition[] }).tools = [...server.tools, handBuilt];+ expect(server.classifiesWrite(callFrame({ name: "hand_built_untyped" }))).toBe(true);+ });+});diff --git a/tests/mcp/brief-owner-scope.test.ts b/tests/mcp/brief-owner-scope.test.tsnew file mode 100644index 00000000..bffaaa2e--- /dev/null+++ b/tests/mcp/brief-owner-scope.test.ts@@ -0,0 +1,533 @@+/**+ * The `brain_brief` views that build their envelopes themselves - daily,+ * weekly, monthly and today - answer at the caller's enforced ownership+ * scope, not at the transport reach alone.+ *+ * The digest and morning views thread `agent_scope` through their+ * builders, and `monthly`/`today` reach the ownership rule through the+ * request's readable predicate. The daily and weekly envelopes had no+ * such seam at local reach: the per-request row view short-circuited at+ * `TRANSPORT_REACH.local` and returned the builder's own envelope, so+ * under `integrity.owner_scope_delivery: fail` a caller with an enforced+ * identity received another owner's preference ids, transition reasons+ * and source pointers from `retired`, `contradictions` and+ * `status_transitions` while every section beside them was already+ * narrowed.+ *+ * The report snapshot follows the same rule: a caller the enforced scope+ * narrows renders one owner's slice, so it neither takes a snapshot of+ * that slice under the shared date key nor is shown a delta whose key+ * paths were computed against another caller's render - the same+ * position a reader below local reach is already in.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendLogEvent } from "../../src/core/brain/log.ts";+import { renderDigest } from "../../src/core/brain/digest.ts";+import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import {+ BRAIN_CONFIDENCE,+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+} from "../../src/core/brain/types.ts";+import { GATE_MODE } from "../../src/core/integrity/stamp.ts";+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";+import { readResource } from "../../src/mcp/resources.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";++const OWNER_A = "agent-a";+const OWNER_B = "agent-b";+/** The private page: delivered to its owner, withheld from every other scope. */+const OWNED_BY_A = "owned-by-a";+/** The ownerless page: delivered to every scope, so a scoped answer is never empty. */+const SHARED = "shared";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-brief-owner-scope-"));+ for (const sub of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function setGate(mode: string | null): void {+ const body = mode === null ? "" : `integrity:\n owner_scope_delivery: ${mode}\n`;+ writeFileSync(brainConfigPath(vault), `schema_version: 1\n${body}`);+}++function makePref(slug: string, owner?: string): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle for ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: BRAIN_CONFIDENCE.high,+ confidence_value: 0.8,+ ...(owner !== undefined ? { owner } : {}),+ });+}++function log(+ timestamp: string,+ eventType: string,+ body: Record<string, unknown>,+ agent?: string,+): void {+ appendLogEvent(+ vault,+ { timestamp, eventType, ...(agent !== undefined ? { agent } : {}), body } as Parameters<+ typeof appendLogEvent+ >[1],+ { deviceId: "" },+ );+}++/**+ * Two preferences and the events that name them: a dream confirming both+ * and retiring the private one (a promotion and a retirement row each),+ * plus violated evidence on the private one (a contradiction row and a+ * source pointer naming its artifact).+ */+function seedTwoOwnerActivity(): string {+ const recent = new Date(Date.now() - 60 * 60 * 1000).toISOString();+ makePref(SHARED);+ // Written while no gate is set, so the owner is the one this fixture+ // states rather than one a write-time gate stamped.+ makePref(OWNED_BY_A, OWNER_A);+ log(recent, BRAIN_LOG_EVENT_KIND.dream, {+ run_id: `run-${recent}`,+ confirmed: [`[[pref-${SHARED}|rule]]`, `[[pref-${OWNED_BY_A}|rule]]`],+ retired: [`[[ret-${OWNED_BY_A}|rule]] (superseded-by-context)`],+ });+ log(recent, BRAIN_LOG_EVENT_KIND.applyEvidence, {+ path: `Brain/preferences/pref-${OWNED_BY_A}.md`,+ preference: `[[pref-${OWNED_BY_A}]]`,+ artifact: `[[Notes/${OWNED_BY_A}-violated]]`,+ result: "violated",+ });+ return recent;+}++const BRIEF = buildToolTable("full").find((t) => t.name === "brain_brief") as ToolDefinition;++function ctx(agentName?: string): ServerContext {+ return { vault, configPath: null, repoRoot: null, agentName, reach: TRANSPORT_REACH.local };+}++async function call(+ args: Record<string, unknown>,+ agentName?: string,+): Promise<Record<string, unknown>> {+ return (await BRIEF.handler(ctx(agentName), args)) as Record<string, unknown>;+}++/** `value` as JSON with the per-render stamp fields replaced. */+function stableText(value: unknown): string {+ return JSON.stringify(value)+ .replace(/"generated_at":"[^"]*"/g, '"generated_at":"<T>"')+ .replace(/"local_time":"[^"]*"/g, '"local_time":"<T>"');+}++interface TransitionRow {+ readonly kind: string;+ readonly prefId: string;+}++describe("brain_brief views honour the caller's enforced owner scope", () => {+ const weekEnd = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 10);+ const month = new Date().toISOString().slice(0, 7);+ // A pinned instant one hour ahead, so the digest's window ([until-24h,+ // until]) covers the fixtures' now-1h events and the rendered markdown+ // carries no moving timestamp between two calls.+ const digestUntil = new Date(Date.now() + 60 * 60 * 1000).toISOString();++ test("view=weekly hides another owner's rows under fail and keeps the caller's own", async () => {+ seedTwoOwnerActivity();+ setGate(GATE_MODE.fail);++ const asB = await call({ view: "weekly", week_end: weekEnd }, OWNER_B);+ expect(stableText(asB)).not.toContain(OWNED_BY_A);+ // The shared half still travels, so the absence is the ownership rule+ // and not an empty window.+ expect(stableText(asB)).toContain(`pref-${SHARED}`);+ expect(asB["retired"]).toEqual([]);+ expect(asB["contradictions"]).toEqual([]);+ expect(asB["source_pointers"]).toEqual([]);+ expect((asB["status_transitions"] as TransitionRow[]).map((t) => t.prefId)).toEqual([+ `pref-${SHARED}`,+ ]);+ // The counts are recomputed from the same selection, so the withheld+ // rows move none of them.+ expect(asB["events_by_kind"]).toEqual({ dream: 1 });+ expect(asB["vault_delta"]).toMatchObject({ newPromotions: 1, newRetired: 0 });++ // No over-filtering: its own owner still sees every row.+ const asA = await call({ view: "weekly", week_end: weekEnd }, OWNER_A);+ expect((asA["retired"] as Array<{ prefId: string }>).map((r) => r.prefId)).toEqual([+ `ret-${OWNED_BY_A}`,+ ]);+ expect(stableText(asA)).toContain(OWNED_BY_A);+ });++ test("view=daily hides another owner's rows under fail and keeps the caller's own", async () => {+ seedTwoOwnerActivity();+ setGate(GATE_MODE.fail);++ const asB = await call({ view: "daily" }, OWNER_B);+ expect(stableText(asB)).not.toContain(OWNED_BY_A);+ expect(asB["source_pointers"]).toEqual([]);+ expect((asB["status_transitions"] as TransitionRow[]).map((t) => t.prefId)).toEqual([+ `pref-${SHARED}`,+ ]);+ expect(asB["vault_delta"]).toMatchObject({ newPromotions: 1, newRetired: 0 });++ const asA = await call({ view: "daily" }, OWNER_A);+ expect(stableText(asA)).toContain(OWNED_BY_A);+ expect((asA["status_transitions"] as TransitionRow[]).map((t) => t.prefId)).toContain(+ `pref-${OWNED_BY_A}`,+ );+ });++ test("view=monthly counts only the events the caller may see under fail", async () => {+ seedTwoOwnerActivity();+ setGate(GATE_MODE.fail);++ const asB = (await call({ view: "monthly", month }, OWNER_B))["summary"] as Record<+ string,+ number+ >;+ // The dream is shared by construction, so it stays with the private+ // transitions trimmed out; the violated evidence is dropped whole.+ expect(asB).toMatchObject({ events: 1, status_transitions: 1, retired: 0, contradictions: 0 });++ const asA = (await call({ view: "monthly", month }, OWNER_A))["summary"] as Record<+ string,+ number+ >;+ expect(asA).toMatchObject({ events: 2, status_transitions: 3, retired: 1, contradictions: 1 });+ });++ test("view=today shows another owner's activity only to its owner under fail", async () => {+ seedTwoOwnerActivity();+ setGate(GATE_MODE.fail);++ const asB = await call({ view: "today" }, OWNER_B);+ expect(stableText(asB)).not.toContain(OWNED_BY_A);+ const activityB = asB["recent_activity"] as { total: number; bullets: string[] };+ expect(activityB.total).toBe(1);+ expect(activityB.bullets.join("\n")).toContain("confirmed=1");++ const asA = await call({ view: "today" }, OWNER_A);+ expect(stableText(asA)).toContain(OWNED_BY_A);+ expect((asA["recent_activity"] as { total: number }).total).toBe(2);+ });++ // The load-bearing convention of the delivery surfaces: a gate that+ // withholds nothing must change nothing, so a vault that never opted in+ // (or only set `warn`) is byte-identical whether or not an identity is+ // resolved.+ for (const mode of [null, GATE_MODE.off, GATE_MODE.warn] as const) {+ test(`a resolved identity changes no view under ${mode ?? "an absent gate"}`, async () => {+ seedTwoOwnerActivity();+ setGate(mode);++ const unscoped = {+ weekly: await call({ view: "weekly", week_end: weekEnd }),+ daily: await call({ view: "daily" }),+ monthly: await call({ view: "monthly", month }),+ today: await call({ view: "today" }),+ digest: await call({ view: "digest", until: digestUntil }),+ };+ // Not vacuous: the private rows really are on the unscoped envelopes.+ expect(stableText(unscoped.weekly)).toContain(OWNED_BY_A);+ expect(stableText(unscoped.digest)).toContain(OWNED_BY_A);++ const scoped = {+ weekly: await call({ view: "weekly", week_end: weekEnd }, OWNER_B),+ daily: await call({ view: "daily" }, OWNER_B),+ monthly: await call({ view: "monthly", month }, OWNER_B),+ today: await call({ view: "today" }, OWNER_B),+ digest: await call({ view: "digest", until: digestUntil }, OWNER_B),+ };+ expect(stableText(scoped.weekly)).toBe(stableText(unscoped.weekly));+ expect(stableText(scoped.daily)).toBe(stableText(unscoped.daily));+ expect(stableText(scoped.monthly)).toBe(stableText(unscoped.monthly));+ expect(stableText(scoped.today)).toBe(stableText(unscoped.today));+ expect(stableText(scoped.digest)).toBe(stableText(unscoped.digest));+ });+ }+});++// ----- the digest tool against the digest resource --------------------------++/**+ * One `## Heading` section of a digest markdown render, heading included:+ * the text from the heading through the line before the next one.+ */+function digestSection(digest: string, heading: string): string {+ const start = digest.indexOf(`## ${heading}`);+ if (start === -1) return "";+ const rest = digest.slice(start);+ const next = rest.indexOf("\n## ", 1);+ return next === -1 ? rest : rest.slice(0, next);+}++describe("brain_brief view=digest answers the same caller as the digest resource", () => {+ /**+ * The two-owner fixture whose rows the digest tool at local reach read+ * unfiltered: the retired record is a real file because+ * `connection_health` counts the retired directory directly, and the+ * events carry their author so `agent_summary` groups them per agent.+ */+ function seedDigestResourceFixture(): void {+ makePref(SHARED);+ makePref(OWNED_BY_A, OWNER_A);+ writeFileSync(+ join(brainDirs(vault).retired, `ret-${OWNED_BY_A}.md`),+ [+ "---",+ "kind: brain-retired",+ `id: ret-${OWNED_BY_A}`,+ `owner: ${OWNER_A}`,+ "created_at: 2026-05-01T00:00:00Z",+ "tags: []",+ `topic: ${OWNED_BY_A}`,+ "principle: retired private principle",+ "provenance: observed",+ "retired_at: 2026-05-03T00:00:00Z",+ `retired_by: "[[pref-${SHARED}]]"`,+ "retired_reason: superseded-by-context",+ "_status: retired",+ "_evidenced_by: []",+ "---",+ "",+ "retired.",+ "",+ ].join("\n"),+ );+ setGate(GATE_MODE.fail);+ const recent = new Date(Date.now() - 60 * 60 * 1000).toISOString();+ for (let i = 0; i < 3; i++) {+ log(+ recent,+ BRAIN_LOG_EVENT_KIND.applyEvidence,+ {+ path: `Brain/preferences/pref-${OWNED_BY_A}.md`,+ preference: `[[pref-${OWNED_BY_A}]]`,+ artifact: `[[Notes/${OWNED_BY_A}-applied-${i}]]`,+ result: "applied",+ },+ OWNER_A,+ );+ }+ log(+ recent,+ BRAIN_LOG_EVENT_KIND.applyEvidence,+ {+ path: `Brain/preferences/pref-${SHARED}.md`,+ preference: `[[pref-${SHARED}]]`,+ artifact: `[[Notes/${SHARED}-applied]]`,+ result: "applied",+ },+ OWNER_B,+ );+ }++ function digestResource(agentName: string): string {+ return readResource({ vault, agentName, reach: TRANSPORT_REACH.local }, "osb://digest/latest")+ .text;+ }++ test("at local reach under fail the tool's sections are the resource's", async () => {+ seedDigestResourceFixture();++ const toolMarkdown = String(+ (await call({ view: "digest", format: "markdown" }, OWNER_B))["content"],+ );+ const resourceMarkdown = digestResource(OWNER_B);++ // The sections whose rows and counts the unfiltered render filled from+ // the other owner's events and records must match, character for+ // character, what the resource hands the same caller.+ for (const heading of ["Agent summary", "Connection health", "Top referenced"]) {+ expect(digestSection(toolMarkdown, heading)).toBe(digestSection(resourceMarkdown, heading));+ }+ // Not vacuous: the caller's own activity and the shared record travel.+ expect(digestSection(toolMarkdown, "Agent summary")).toContain(OWNER_B);+ expect(digestSection(toolMarkdown, "Connection health")).toContain("Total nodes: 1");+ expect(digestSection(toolMarkdown, "Top referenced")).toContain(`pref-${SHARED}`);+ // The other owner's name and records are absent from the tool's answer.+ expect(toolMarkdown).not.toContain(OWNER_A);+ expect(toolMarkdown).not.toContain(OWNED_BY_A);+ });++ test("the scoped tool counts the caller's own events and none of the other owner's", async () => {+ seedDigestResourceFixture();++ const asB = JSON.parse(+ String((await call({ view: "digest", format: "json" }, OWNER_B))["content"]),+ );+ expect(asB["agent_summary"]).toEqual([+ {+ agent: OWNER_B,+ total_events: 1,+ feedback_count: 0,+ apply_evidence_count: 1,+ note_count: 0,+ confirmed_attributed: 0,+ retired_attributed: 0,+ },+ ]);+ // The shared preference is the only node left: the other owner's+ // retired record moves no count either.+ expect(asB["connection_health"]).toMatchObject({+ total_nodes: 1,+ linked_nodes: 1,+ orphan_nodes: 0,+ });++ // The records' own owner still counts both sides - the scope withholds,+ // it does not destroy: two preferences plus the retired record.+ const asA = JSON.parse(+ String((await call({ view: "digest", format: "json" }, OWNER_A))["content"]),+ );+ expect(asA["connection_health"]).toMatchObject({ total_nodes: 3 });+ expect((asA["agent_summary"] as ReadonlyArray<{ agent: string }>).map((r) => r.agent)).toEqual([+ OWNER_A,+ OWNER_B,+ ]);+ });++ test("an unscoped digest under fail stays byte-identical to the unfiltered render", async () => {+ seedDigestResourceFixture();+ const until = new Date(Date.now() + 60 * 60 * 1000).toISOString();++ const toolMarkdown = String((await call({ view: "digest", until }, undefined))["content"]);+ // Not vacuous: the unfiltered render really carries the other owner's rows.+ expect(toolMarkdown).toContain(OWNED_BY_A);+ // With no resolved identity nothing is narrowed, so the tool's render is+ // the renderer's own - the pre-gate output, byte for byte.+ expect(toolMarkdown).toBe(renderDigest(vault, { until: new Date(until) }).content);+ });+});++// ----- the report snapshot --------------------------------------------------++describe("the brain_brief report snapshots follow the caller's scope", () => {+ const savedSnapshots = process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"];++ beforeEach(() => {+ process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"] = "true";+ });+ afterEach(() => {+ if (savedSnapshots === undefined) delete process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"];+ else process.env["OPEN_SECOND_BRAIN_REPORT_SNAPSHOTS"] = savedSnapshots;+ });++ /** The date key the digest snapshots under for this fixture's pinned `until`. */+ function digestFile(until: string): string {+ return join(vault, "Brain", "reports", "digest", `${until.slice(0, 10)}.json`);+ }++ /**+ * A digest fixture whose rows are inside the window, so the snapshot+ * payload really carries both owners' ids.+ */+ function seedWindowDigest(): string {+ const until = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 10);+ for (const [slug, owner] of [+ [SHARED, undefined],+ [OWNED_BY_A, OWNER_A],+ ] as const) {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle for ${slug}`,+ created_at: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ unconfirmed_until: until,+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,+ evidenced_by: [`[[sig-${slug}]]`],+ ...(owner !== undefined ? { owner } : {}),+ });+ }+ return until;+ }++ function snapshotPayload(until: string): string {+ return readFileSync(digestFile(until), "utf8");+ }++ test("a scoped caller takes no digest snapshot and is shown no delta", async () => {+ const until = seedWindowDigest();++ // The first, unscoped run is the shared record: full render, first+ // snapshot, no prior.+ const first = await call({ view: "digest", until }, undefined);+ expect((first["delta"] as { prior_date: string | null }).prior_date).toBeNull();+ expect(snapshotPayload(until)).toContain(OWNED_BY_A);++ // A caller the enforced scope narrows renders one owner's slice: it+ // neither persists that slice under the shared date key nor receives+ // a delta whose key paths were diffed against the full render.+ setGate(GATE_MODE.fail);+ const asB = await call({ view: "digest", until }, OWNER_B);+ expect(asB["delta"]).toBeUndefined();+ expect(stableText(asB)).not.toContain(OWNED_BY_A);+ const asA = await call({ view: "digest", until }, OWNER_A);+ expect(asA["delta"]).toBeUndefined();+ // Both scoped runs left the shared record exactly as the unscoped+ // run wrote it, so the next full render diffs against a full render.+ expect(snapshotPayload(until)).toContain(OWNED_BY_A);+ expect(JSON.parse(snapshotPayload(until))["payload"]["new_unconfirmed"]).toHaveLength(2);+ });++ test("a scoped caller still snapshots when the gate delivers everything", async () => {+ const until = seedWindowDigest();+ setGate(GATE_MODE.off);++ const first = await call({ view: "digest", until }, undefined);+ expect((first["delta"] as { prior_date: string | null }).prior_date).toBeNull();++ const scoped = await call({ view: "digest", until }, OWNER_B);+ // Under `off` nothing is narrowed, so the scoped run is an ordinary+ // one: it takes the snapshot and reports the (empty) delta.+ expect(scoped["delta"]).toMatchObject({ prior_date: null, added: [], removed: [] });+ expect(existsSync(digestFile(until))).toBe(true);+ });++ test("a scoped caller takes no daily or weekly snapshot either", async () => {+ seedTwoOwnerActivity();+ setGate(GATE_MODE.fail);++ const until = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString().slice(0, 10);+ const dailyAsB = await call({ view: "daily" }, OWNER_B);+ expect(dailyAsB["delta"]).toBeUndefined();+ const weeklyAsB = await call({ view: "weekly", week_end: until }, OWNER_B);+ expect(weeklyAsB["delta"]).toBeUndefined();++ // A later unscoped run is still the first: no scoped slice was+ // persisted for it to diff against.+ const dailyFull = await call({ view: "daily" }, undefined);+ expect((dailyFull["delta"] as { prior_date: string | null }).prior_date).toBeNull();+ const weeklyFull = await call({ view: "weekly", week_end: until }, undefined);+ expect((weeklyFull["delta"] as { prior_date: string | null }).prior_date).toBeNull();+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 6c129e61..1a5463c8 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -784,6 +784,54 @@ describe("MCPServer serverName override", () => {});describe("serveStdioFromString respects scope+name", () => {+ test("tools/list serializes exactly the wire contract per tool", async () => {+ // Wire identity (parallel-reads classification, task D1): the+ // registry now carries a required `kind` (and already carried+ // `hidden` and `previewBudget`), and none of it may reach the+ // payload every client pays tokens for. The projection in+ // `handleToolsList` picks its fields explicitly; this pins the exact+ // serialized key set so an added advertised field fails here even+ // if the projection is later rewritten to spread.+ for (const scope of ["full", "writer", "catalog"] as const) {+ const server = new MCPServer({ vault: tmp }, { scope });+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/list",+ params: {},+ }))! as any;+ const tools = r.result.tools as Array<Record<string, unknown>>;+ expect(tools.length).toBeGreaterThan(0);+ for (const tool of tools) {+ // Exactly the wire contract: the three mandatory members, plus+ // outputSchema for the two tools that declare one - and nothing+ // else, now that the definition also carries `kind`.+ expect(Object.keys(tool).toSorted()).toEqual(+ [+ "description",+ "inputSchema",+ "name",+ ...("outputSchema" in tool ? ["outputSchema"] : []),+ ].toSorted(),+ );+ }+ // The optional outputSchema half of the same contract: the wire+ // payload mirrors the definition's declared shape exactly - a tool+ // advertises outputSchema iff its definition declares one, and no+ // registry member (kind, hidden, previewBudget) leaks instead.+ const table = new Map(buildToolTable(scope).map((t) => [t.name, t]));+ const withOutput = tools+ .filter((t) => "outputSchema" in t)+ .map((t) => t.name)+ .toSorted();+ const declared = [...table.values()]+ .filter((t) => t.outputSchema !== undefined && t.hidden !== true)+ .map((t) => t.name)+ .toSorted();+ expect(withOutput).toEqual(declared);+ }+ });+test("writer scope filters tools/list response", async () => {const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };const initReq = JSON.stringify({diff --git a/tests/mcp/preview-budget-dispatch.test.ts b/tests/mcp/preview-budget-dispatch.test.tsindex 04c8e016..fcefee98 100644--- a/tests/mcp/preview-budget-dispatch.test.ts+++ b/tests/mcp/preview-budget-dispatch.test.ts@@ -16,6 +16,7 @@ function tool(overrides: Partial<ToolDefinition>): ToolDefinition {name: "synthetic_tool",description: "test",inputSchema: { type: "object", properties: {}, additionalProperties: false },+ kind: "read",handler: () => ({}),...overrides,};diff --git a/tests/mcp/progress-token.test.ts b/tests/mcp/progress-token.test.tsindex c7b09567..2fb398fd 100644--- a/tests/mcp/progress-token.test.ts+++ b/tests/mcp/progress-token.test.ts@@ -179,6 +179,53 @@ describe("stdio carries a progress token", () => {expect(frames.every((f) => f["id"] !== undefined)).toBe(true);});+ test("two concurrent calls keep per-request adjacency on a real stream", async () => {+ // The production loop dispatches read-classified calls concurrently,+ // so two progress-carrying calls can emit between each other's+ // notifications: cross-request interleaving is legal (clients+ // correlate by token). What must hold is adjacency - ALL of a+ // request's notifications precede ITS response - and frame+ // atomicity on the shared stream.+ const stdin = new PassThrough();+ const chunks: string[] = [];+ const stdout = new PassThrough();+ stdout.on("data", (c: Buffer) => chunks.push(c.toString("utf8")));++ const briefCall = (id: number, token: string): JsonObject => ({+ jsonrpc: JSONRPC_VERSION,+ id,+ method: "tools/call",+ params: {+ name: "brain_brief",+ arguments: { view: "operator" },+ _meta: { progressToken: token },+ },+ });++ const done = serveStdio({ vault }, { stdin, stdout });+ stdin.write(JSON.stringify(INITIALIZE) + "\n");+ stdin.write(JSON.stringify(briefCall(2, "tok-a")) + "\n");+ stdin.write(JSON.stringify(briefCall(3, "tok-b")) + "\n");+ stdin.end();+ await done;++ // Frame atomicity: the shared stream still splits into clean frames.+ const frames = lines(chunks.join(""));+ const response2 = frames.findIndex((f) => f["id"] === 2);+ const response3 = frames.findIndex((f) => f["id"] === 3);+ expect(response2).toBeGreaterThan(-1);+ expect(response3).toBeGreaterThan(-1);+ const notifications = frames+ .map((f, index) => ({ f, index }))+ .filter(({ f }) => f["method"] === PROGRESS_NOTIFICATION_METHOD);+ expect(notifications.length).toBeGreaterThan(0);+ for (const { f, index } of notifications) {+ const token = (f["params"] as JsonObject)["progressToken"];+ expect(index).toBeLessThan(token === "tok-a" ? response2 : response3);+ }+ for (const chunk of chunks) expect(chunk.endsWith("\n")).toBe(true);+ });+test("a progress frame never interleaves inside a response frame on a real stream", async () => {const stdin = new PassThrough();const chunks: string[] = [];diff --git a/tests/mcp/reach-refusal.test.ts b/tests/mcp/reach-refusal.test.tsindex 206efa41..546816bb 100644--- a/tests/mcp/reach-refusal.test.ts+++ b/tests/mcp/reach-refusal.test.ts@@ -130,6 +130,7 @@ const OPEN_SCHEMA_TOOL: ToolDefinition = Object.freeze({name: "open_schema_probe",description: "probe",inputSchema: { type: "object", properties: {} },+ kind: "read",handler: () => ({}),});diff --git a/tests/mcp/resources-owner-scope.test.ts b/tests/mcp/resources-owner-scope.test.tsindex 2731a88e..bf362745 100644--- a/tests/mcp/resources-owner-scope.test.ts+++ b/tests/mcp/resources-owner-scope.test.ts@@ -30,7 +30,11 @@ import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { appendLogEvent } from "../../src/core/brain/log.ts";import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";import { writePreference } from "../../src/core/brain/preference.ts";-import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";+import {+ BRAIN_CONFIDENCE,+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+} from "../../src/core/brain/types.ts";import { GATE_MODE } from "../../src/core/integrity/stamp.ts";import { readResource, type ResourceContext } from "../../src/mcp/resources.ts";import { pinHome, tempDirs } from "../helpers/temp-dir.ts";@@ -102,6 +106,15 @@ function setGate(mode: string): void {);}+/** The `## Actions` section of a digest render: its heading through the next. */+function actionsSection(digest: string): string {+ const start = digest.indexOf("\n## Actions");+ if (start === -1) return "";+ const rest = digest.slice(start + 1);+ const next = rest.indexOf("\n## ");+ return next === -1 ? rest : rest.slice(0, next);+}+/** Read one resource AS `agentName`, folding a refusal into the answer. */function read(uri: string, agentName: string = OWNER_B): string {const ctx: ResourceContext = { vault, agentName };@@ -193,3 +206,77 @@ test("gate off leaves every resource unfiltered", () => {setGate(GATE_MODE.off);for (const { uri } of OWNER_BEARING_URIS) expect(read(uri)).toContain(MARKER);});++/**+ * The digest resource renders its maintenance actions from a vault-wide+ * scan, so an owned page past the stale-stable cap can reach this+ * surface through `actions` long after it stopped appearing in any+ * windowed section. The scope is threaded into the render itself (the+ * way `osb://preferences/active` does), so the row is judged like the+ * sections beside it.+ *+ * The fixture separates the two halves: an ownerless, in-window+ * preference keeps the windowed sections non-empty (the shared half must+ * keep travelling), while the marked page is dated far enough back to be+ * stale on any run date and confirmed. Its `## Actions` lifecycle row is+ * the row under test, so the assertions below check THAT row in THAT+ * section - a marker check over the whole render would pass on the+ * fixture's windowed sections alone and prove nothing about Actions.+ */+test("osb://digest/latest: the actions section carries the ownership rule too", () => {+ const now = new Date();+ writePreference(vault, {+ slug: "digest-window-active",+ topic: "digest-window-active",+ principle: "principle for digest-window-active",+ created_at: now.toISOString(),+ unconfirmed_until: new Date(now.getTime() + 7 * 86_400_000).toISOString(),+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,+ evidenced_by: ["[[sig-digest-window-active]]"],+ });+ writePreference(vault, {+ slug: `${MARKER}-stale`,+ topic: `${MARKER}-stale`,+ principle: `principle for ${MARKER}-stale`,+ created_at: "2024-01-01T00:00:00Z",+ unconfirmed_until: "2024-01-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2024-01-01-${MARKER}]]`],+ confirmed_at: "2024-01-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2024-01-02T00:00:00Z",+ confidence: BRAIN_CONFIDENCE.high,+ confidence_value: 0.8,+ owner: OWNER_A,+ });++ setGate(GATE_MODE.off);+ const unscoped = read("osb://digest/latest");+ expect(unscoped).toContain("digest-window-active");+ expect(unscoped).toContain(MARKER);+ // The row under test, in the section under test: a lifecycle action row+ // naming the marked page. The fixture can surface the marked page+ // elsewhere too (its applied_count feeds a windowed section), so only+ // this pins the Actions surface.+ const unscopedActions = actionsSection(unscoped);+ const row = unscopedActions.split("\n").find((line) => line.includes(`pref-${MARKER}-stale`));+ expect(row, `an Actions row must name the marked page:\n${unscopedActions}`).toBeDefined();+ expect(row).toMatch(/^- \[lifecycle\] impact \d+ — /);++ setGate(GATE_MODE.fail);+ const scoped = read("osb://digest/latest");+ // The shared half still travels, so the marker's absence is the+ // ownership rule and not an empty digest.+ expect(scoped).toContain("digest-window-active");+ expect(scoped).not.toContain(MARKER);+ // And within the section under test: it still renders, the ownerless+ // stale page's row still travels in it, and the marked page's row is+ // the one withheld.+ const scopedActions = actionsSection(scoped);+ expect(scopedActions).toContain("pref-shared");+ expect(scopedActions).not.toContain(`pref-${MARKER}-stale`);++ // Its own owner still reads the maintenance suggestion.+ expect(read("osb://digest/latest", OWNER_A)).toContain(MARKER);+});diff --git a/tests/mcp/stdio-parallel.test.ts b/tests/mcp/stdio-parallel.test.tsnew file mode 100644index 00000000..76e9c9d5--- /dev/null+++ b/tests/mcp/stdio-parallel.test.ts@@ -0,0 +1,644 @@+/**+ * Parallel reads with exclusive writes on the real stdio loop.+ *+ * The production loop used to await each request inside its `for await`+ * body, so one slow read head-of-line blocked every later request. It+ * now dispatches read-classified requests without awaiting them, up to+ * {@link STDIO_READ_CONCURRENCY} in flight, and runs every write alone:+ * a write waits for the reads already in flight to settle, and no new+ * line is read while a write is running (writes kept exclusive on the+ * stdio transport; see `src/mcp/stdio.ts`).+ *+ * The fixture is the real `serveStdio` over a real PassThrough pair+ * (the pattern from `progress-token.test.ts`), dispatching against a+ * scripted `MCPServer` subclass whose handlers the test holds and+ * releases - the controllability the HTTP drain tests get from a+ * half-sent body (`http-drain.test.ts`), which a line-delimited+ * transport cannot reproduce. The real dispatch path is covered with+ * the real table by `mcp.test.ts` and `progress-token.test.ts`; this+ * file pins the transport's concurrency invariants.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";++import { serveStdio, STDIO_READ_CONCURRENCY } from "../../src/mcp/stdio.ts";+import { RequestDrain, type DrainOutcome } from "../../src/mcp/drain.ts";+import { MCPServer, type JsonRpcRequest, type JsonRpcResponse } from "../../src/mcp/server.ts";+import { INTERNAL_ERROR, JSONRPC_VERSION, PROTOCOL_VERSION } from "../../src/mcp/protocol.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";++const temps: string[] = [];++afterEach(() => {+ while (temps.length > 0) rmSync(temps.pop()!, { recursive: true, force: true });+});++function tempVault(): string {+ const dir = mkdtempSync(join(tmpdir(), "osb-stdio-parallel-"));+ temps.push(dir);+ return dir;+}++/** Poll a condition the loop reaches on its own schedule, or say what failed. */+async function until(condition: () => boolean, what: string): Promise<void> {+ for (let attempt = 0; attempt < 400; attempt++) {+ if (condition()) return;+ await Bun.sleep(5);+ }+ throw new Error(`timed out waiting for ${what}`);+}++/**+ * When a scripted handler may finish: held until the test releases the+ * id, or immediate.+ */+const RELEASES = new Map<unknown, Array<() => void>>();++/** Release one held handler. */+function release(id: unknown): void {+ const next = RELEASES.get(id)?.shift();+ if (next === undefined) throw new Error(`no held handler for id ${String(id)}`);+ next();+}++beforeEach(() => {+ // The held-handler register is module-level and the tests reuse ids+ // (1..6): a failure that leaves resolvers queued would strand every+ // LATER test's hold() behind stale entries and turn one failure into a+ // pile of 5000 ms timeouts. Each test starts from an empty register.+ RELEASES.clear();+});++/** Hold every handler until released, one `hold()` per in-flight call. */+function hold(id: unknown): Promise<void> {+ return new Promise((resolve) => {+ const queue = RELEASES.get(id) ?? [];+ queue.push(resolve);+ RELEASES.set(id, queue);+ });+}++interface LogEntry {+ readonly id: unknown;+ readonly event: "start" | "end";+ readonly write: boolean;+}++/**+ * A dispatcher the test observes and controls: every call is logged and+ * write-classified calls can be held independently of reads.+ */+class ScriptedServer extends MCPServer {+ readonly log: LogEntry[] = [];++ override async handleRequest(request: JsonRpcRequest): Promise<JsonRpcResponse | null> {+ const write = this.classifiesWrite(request);+ this.log.push({ id: request.id, event: "start", write });+ await hold(request.id);+ this.log.push({ id: request.id, event: "end", write });+ return { jsonrpc: JSONRPC_VERSION, id: request.id, result: { echo: request.id } };+ }+}++/** One `tools/call` frame; `name` picks the read/write class. */+function call(id: number, name: string): string {+ return JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ id,+ method: "tools/call",+ params: { name, arguments: {} },+ });+}++/**+ * The read and write names this fixture classifies through the real+ * table. `brain_search` used to be the read fixture until the round-4+ * classification review found its handler writes ranking state (the+ * reinforce ledger, default-on access recording) and reclassified it+ * `write`; the fixtures moved to a tool whose every operation is a read.+ */+const READ_TOOL = "brain_recall_gate";+const WRITE_TOOL = "brain_note";++/** Start a loop over a scripted server; returns everything the test drives. */+function startScripted(opts: { drainDeadlineMs?: number } = {}): {+ loop: Promise<number>;+ server: ScriptedServer;+ stdin: PassThrough;+ frames: () => string[];+ close: (deadlineMs?: number) => Promise<DrainOutcome>;+} {+ const stdin = new PassThrough();+ const stdout = new PassThrough();+ const chunks: string[] = [];+ stdout.on("data", (c: Buffer) => chunks.push(c.toString("utf8")));+ const server = new ScriptedServer({ vault: tempVault() });+ let drain: RequestDrain | undefined;+ const loop = serveStdio(+ { vault: server.vault },+ {+ stdin,+ stdout,+ ...(opts.drainDeadlineMs !== undefined ? { drainDeadlineMs: opts.drainDeadlineMs } : {}),+ onStart: (handle) => {+ drain = handle.drain;+ },+ server,+ },+ );+ return {+ loop,+ server,+ stdin,+ frames: () => chunks.join("").split("\n").filter(Boolean),+ // A later call with a longer deadline is how a test waits out work a+ // first drain's deadline abandoned.+ close: (deadlineMs?: number) => drain!.drain(deadlineMs ?? opts.drainDeadlineMs ?? 10_000),+ };+}++describe("stdio parallel reads", () => {+ test("a second read dispatches while a first is still in flight", async () => {+ const { loop, server, stdin } = startScripted();+ stdin.write(call(1, READ_TOOL) + "\n");+ await until(+ () => server.log.some((e) => e.id === 1 && e.event === "start"),+ "the first read to dispatch",+ );+ stdin.write(call(2, READ_TOOL) + "\n");+ // The assertion the sequential loop fails: the second read reaches+ // its handler while the first is still held.+ await until(+ () => server.log.some((e) => e.id === 2 && e.event === "start"),+ "the second read to dispatch beside the held first",+ );+ release(1);+ release(2);+ stdin.end();+ expect(await loop).toBe(0);+ });++ test("responses carry their own ids whatever order the handlers settle in", async () => {+ const { loop, server, stdin, frames } = startScripted();+ stdin.write(call(1, READ_TOOL) + "\n" + call(2, READ_TOOL) + "\n");+ await until(() => server.log.filter((e) => e.event === "start").length === 2, "both reads");+ release(2);+ await until(() => frames().length >= 1, "the first response frame");+ release(1);+ stdin.end();+ await loop;+ const ids = frames().map((f) => (JSON.parse(f) as JsonRpcResponse).id);+ expect(ids).toEqual([2, 1]);+ });++ test("in-flight reads never exceed the cap, which backpressures the loop", async () => {+ const { loop, server, stdin } = startScripted();+ const ids = [1, 2, 3, 4, 5, 6];+ for (const id of ids) stdin.write(call(id, READ_TOOL) + "\n");+ await until(+ () => server.log.filter((e) => e.event === "start").length === STDIO_READ_CONCURRENCY,+ `${STDIO_READ_CONCURRENCY} reads to dispatch`,+ );+ await Bun.sleep(25);+ // The cap held: the lines beyond it were not dispatched - and were+ // not even read, which is the backpressure.+ expect(server.log.filter((e) => e.event === "start").length).toBe(STDIO_READ_CONCURRENCY);+ release(1);+ release(2);+ await until(+ () => server.log.some((e) => e.id === 5 && e.event === "start"),+ "the fifth read to dispatch as slots free",+ );+ release(3);+ release(4);+ await until(+ () => server.log.some((e) => e.id === 6 && e.event === "start"),+ "the sixth read to dispatch",+ );+ release(5);+ release(6);+ stdin.end();+ expect(await loop).toBe(0);+ });++ test("a write waits for the reads in flight and runs alone", async () => {+ const { loop, server, stdin } = startScripted();+ stdin.write(call(1, READ_TOOL) + "\n");+ await until(+ () => server.log.some((e) => e.id === 1 && e.event === "start"),+ "the held read to dispatch",+ );+ stdin.write(call(2, WRITE_TOOL) + "\n");+ await Bun.sleep(25);+ // The write gate: the write has not started while the read is held.+ expect(server.log.some((e) => e.id === 2 && e.event === "start")).toBe(false);+ release(1);+ await until(() => server.log.some((e) => e.id === 2 && e.event === "start"), "the write");+ // No new read starts beside the write either: the loop does not read+ // another line until the write has settled.+ stdin.write(call(3, READ_TOOL) + "\n");+ await Bun.sleep(25);+ expect(server.log.some((e) => e.id === 3 && e.event === "start")).toBe(false);+ release(2);+ await until(() => server.log.some((e) => e.id === 3 && e.event === "start"), "the late read");+ release(3);+ stdin.end();+ expect(await loop).toBe(0);++ // The interleaving log, as intervals: no two dispatch intervals+ // overlap when either one is a write, and a write never overlaps a+ // write.+ const intervals = new Map<unknown, { start: number; end: number; write: boolean }>();+ server.log.forEach((e, index) => {+ if (e.event === "start") intervals.set(e.id, { start: index, end: -1, write: e.write });+ else intervals.get(e.id)!.end = index;+ });+ const all = [...intervals.entries()];+ const overlapping: Array<[unknown, unknown]> = [];+ for (let i = 0; i < all.length; i++) {+ for (let j = i + 1; j < all.length; j++) {+ const [, a] = all[i]!;+ const [, b] = all[j]!;+ const disjoint = a.end < b.start || b.end < a.start;+ if (!disjoint && (a.write || b.write)) overlapping.push([all[i]![0], all[j]![0]]);+ }+ }+ expect(overlapping).toEqual([]);+ });++ test("EOF does not resolve the loop while a dispatched read is still running", async () => {+ const { loop, server, stdin } = startScripted();+ stdin.write(call(1, READ_TOOL) + "\n");+ await until(() => server.log.some((e) => e.id === 1 && e.event === "start"), "the read");+ stdin.end();+ // The loop must be pending: EOF arrived, the read is still held.+ let settled = false;+ void loop.then(() => {+ settled = true;+ });+ await Bun.sleep(25);+ expect(settled).toBe(false);+ release(1);+ expect(await loop).toBe(0);+ });++ test("EOF does not resolve the loop while a dispatched write is still running", async () => {+ const { loop, server, stdin, frames } = startScripted();+ stdin.write(call(1, WRITE_TOOL) + "\n");+ await until(() => server.log.some((e) => e.id === 1 && e.event === "start"), "the write");+ stdin.end();+ // The loop must be pending under the floating write, exactly as it is+ // under a floating read: the exit barrier covers both paths.+ let settled = false;+ void loop.then(() => {+ settled = true;+ });+ await Bun.sleep(25);+ expect(settled).toBe(false);+ // The write completes and answers before the loop resolves: its+ // response frame exists while the exit barrier is still holding.+ release(1);+ await until(() => frames().length === 1, "the write's answer");+ expect(await loop).toBe(0);+ expect(frames().length).toBe(1);+ });+});++/**+ * The frame-integrity invariants, on a real stream against the real+ * dispatch table (no scripted server): whatever the concurrency does to+ * ORDER, it must never touch FRAMES.+ */+describe("stdio frame integrity under concurrency", () => {+ function realLoop(vault: string): {+ loop: Promise<number>;+ stdin: PassThrough;+ chunks: () => string;+ rawChunks: () => string[];+ } {+ const stdin = new PassThrough();+ const stdout = new PassThrough();+ const collected: string[] = [];+ stdout.on("data", (c: Buffer) => collected.push(c.toString("utf8")));+ const loop = serveStdio({ vault }, { stdin, stdout });+ return {+ loop,+ stdin,+ chunks: () => collected.join(""),+ rawChunks: () => collected,+ };+ }++ test("every chunk ends on a frame boundary and every frame parses under N concurrent calls", async () => {+ const vault = tempVault();+ bootstrapBrain(vault);+ const { loop, stdin, chunks, rawChunks } = realLoop(vault);+ stdin.write(+ JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ id: 0,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION },+ }) + "\n",+ );+ const N = 8;+ for (let id = 1; id <= N; id++) {+ stdin.write(+ JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ id,+ method: "tools/call",+ params: { name: "second_brain_status", arguments: {} },+ }) + "\n",+ );+ }+ stdin.end();+ expect(await loop).toBe(0);++ // Chunk integrity, asserted per chunk the transport actually emitted:+ // every write is exactly one newline-terminated frame, so no chunk+ // ever stops mid-frame - each one ends on a frame boundary.+ for (const chunk of rawChunks()) {+ expect(chunk.endsWith("\n")).toBe(true);+ }+ // Frame atomicity on the joined stream: it splits into clean JSON+ // lines, so no frame was ever spliced inside another frame's bytes.+ const raw = chunks();+ for (const chunk of raw.split("\n").slice(0, -1)) {+ expect(() => JSON.parse(chunk)).not.toThrow();+ }+ const frames = raw+ .split("\n")+ .filter((l) => l.trim() !== "")+ .map((l) => JSON.parse(l) as JsonRpcResponse);+ const ids = frames.map((f) => f.id).toSorted();+ expect(ids).toEqual([0, ...Array.from({ length: N }, (_, i) => i + 1)].toSorted());+ // N+1 distinct answers for N+1 requests: an id was neither lost nor+ // answered twice.+ expect(new Set(ids).size).toBe(N + 1);+ });+});++describe("the stdio drain under parallel dispatch", () => {+ test("the drain deadline names the reads it abandoned", async () => {+ const { loop, server, stdin, close } = startScripted({ drainDeadlineMs: 60 });+ stdin.write(call(1, READ_TOOL) + "\n" + call(2, READ_TOOL) + "\n");+ await until(() => server.log.filter((e) => e.event === "start").length === 2, "both reads");+ const outcome = await close();+ expect(outcome.state).toBe("deadline_expired");+ expect(outcome.abandoned.map((r) => r.label).toSorted()).toEqual([+ "tools/call (id 1)",+ "tools/call (id 2)",+ ]);+ // The abandoned reads still settle and still answer: abandoning the+ // WAIT is not dropping the work.+ release(1);+ release(2);+ stdin.end();+ expect(await loop).toBe(0);+ expect(server.log.filter((e) => e.event === "end").length).toBe(2);+ });++ test("close() resolves drained once the held reads settle, however many", async () => {+ const { loop, server, stdin, close } = startScripted({ drainDeadlineMs: 5_000 });+ stdin.write([1, 2, 3].map((id) => call(id, READ_TOOL)).join("\n") + "\n");+ await until(() => server.log.filter((e) => e.event === "start").length === 3, "all three");+ const closing = close();+ release(1);+ release(2);+ release(3);+ const outcome = await closing;+ expect(outcome.state).toBe("drained");+ expect(outcome.abandoned).toEqual([]);+ stdin.end();+ expect(await loop).toBe(0);+ });++ test("a line parked behind the read cap is left unread once a drain has started", async () => {+ const { loop, server, stdin, frames, close } = startScripted({ drainDeadlineMs: 5_000 });+ // Fill the cap and park one more line behind it: the fifth line is+ // READ by the loop, then held at the backpressure gate.+ stdin.write([1, 2, 3, 4, 5].map((id) => call(id, READ_TOOL)).join("\n") + "\n");+ await until(+ () => server.log.filter((e) => e.event === "start").length === STDIO_READ_CONCURRENCY,+ "the cap to fill",+ );+ await Bun.sleep(25);+ expect(server.log.some((e) => e.id === 5)).toBe(false);+ // Drain while the fifth line is parked. Every dispatched read is+ // released together, so the drain's register empties before the+ // parked line's wake-up runs again.+ const closing = close();+ release(1);+ release(2);+ release(3);+ release(4);+ const outcome = await closing;+ expect(outcome.state).toBe("drained");+ // Let any post-drain dispatch surface before judging.+ await Bun.sleep(25);+ // The parked line was left unread, not served outside the drain's+ // wait: no dispatch, no answer.+ expect(server.log.some((e) => e.id === 5)).toBe(false);+ expect(frames().length).toBe(STDIO_READ_CONCURRENCY);+ stdin.end();+ expect(await loop).toBe(0);+ });++ test("the drain deadline names the write it abandoned, and the write still settles", async () => {+ const { loop, server, stdin, frames, close } = startScripted({ drainDeadlineMs: 60 });+ stdin.write(call(1, WRITE_TOOL) + "\n");+ await until(() => server.log.some((e) => e.id === 1 && e.event === "start"), "the held write");+ const outcome = await close();+ // The deadline names the write it abandoned: the label is the+ // write's, so an operator reading the report knows the exclusive+ // path is what was still open.+ expect(outcome.state).toBe("deadline_expired");+ expect(outcome.abandoned.map((r) => r.label)).toEqual(["tools/call (id 1)"]);+ // Abandoning the wait is not dropping the work: released, the write+ // settles and answers, and a second drain resolves drained.+ release(1);+ await until(() => frames().length === 1, "the write's answer");+ const settled = await close(5_000);+ expect(settled.state).toBe("drained");+ expect(settled.abandoned).toEqual([]);+ stdin.end();+ expect(await loop).toBe(0);+ });++ test("the drain deadline names a write still parked behind in-flight reads", async () => {+ const { loop, server, stdin, frames, close } = startScripted({ drainDeadlineMs: 60 });+ stdin.write(call(1, READ_TOOL) + "\n" + call(2, READ_TOOL) + "\n");+ await until(() => server.log.filter((e) => e.event === "start").length === 2, "both reads");+ // The write arrives while both reads are held: the gate parks it, and+ // it has not dispatched - a drain starting NOW must still see it.+ stdin.write(call(3, WRITE_TOOL) + "\n");+ await Bun.sleep(25);+ expect(server.log.some((e) => e.id === 3)).toBe(false);+ const outcome = await close();+ // Not a drained-success over a queued write: the deadline expires,+ // and the report names the WRITE beside the reads it was parked+ // behind - it is the write an operator least expects a shutdown to+ // drop, so it is the one the report must carry.+ expect(outcome.state).toBe("deadline_expired");+ expect(outcome.abandoned.map((r) => r.label).toSorted()).toEqual([+ "tools/call (id 1)",+ "tools/call (id 2)",+ "tools/call (id 3)",+ ]);+ // Abandoning the wait is not dropping the work: the reads settle, the+ // gate dispatches the parked write, and it answers.+ release(1);+ release(2);+ await until(+ () => server.log.some((e) => e.id === 3 && e.event === "start"),+ "the parked write to dispatch",+ );+ release(3);+ await until(+ () => frames().some((f) => (JSON.parse(f) as JsonRpcResponse).id === 3),+ "the parked write's answer",+ );+ const settled = await close(5_000);+ expect(settled.state).toBe("drained");+ expect(settled.abandoned).toEqual([]);+ stdin.end();+ expect(await loop).toBe(0);+ expect(server.log.filter((e) => e.event === "end").length).toBe(3);+ });++ test("a drain started while a write is parked behind reads holds for the write", async () => {+ const { loop, server, stdin, frames, close } = startScripted({ drainDeadlineMs: 5_000 });+ stdin.write(call(1, READ_TOOL) + "\n" + call(2, READ_TOOL) + "\n");+ await until(() => server.log.filter((e) => e.event === "start").length === 2, "both reads");+ stdin.write(call(3, WRITE_TOOL) + "\n");+ await Bun.sleep(25);+ expect(server.log.some((e) => e.id === 3)).toBe(false);+ const closing = close();+ release(1);+ release(2);+ // The reads settle and the gate dispatches the queued write, which+ // the fixture then holds: the drain must still be waiting on it, not+ // have resolved the moment the reads emptied the register.+ await until(+ () => server.log.some((e) => e.id === 3 && e.event === "start"),+ "the parked write to dispatch",+ );+ let settled = false;+ void closing.then(() => {+ settled = true;+ });+ await Bun.sleep(25);+ expect(settled).toBe(false);+ release(3);+ const outcome = await closing;+ expect(outcome.state).toBe("drained");+ expect(outcome.abandoned).toEqual([]);+ // The write's answer left inside the window: the frame exists by the+ // time the drain resolved, so the client that sent it gets its+ // correlation instead of a closed pipe.+ await until(+ () => frames().some((f) => (JSON.parse(f) as JsonRpcResponse).id === 3),+ "the write's answer",+ );+ stdin.end();+ expect(await loop).toBe(0);+ });++ test("EOF with a write parked behind held reads still waits for the write to answer", async () => {+ const { loop, server, stdin, frames } = startScripted();+ stdin.write(call(1, READ_TOOL) + "\n" + call(2, READ_TOOL) + "\n");+ await until(() => server.log.filter((e) => e.event === "start").length === 2, "both reads");+ stdin.write(call(3, WRITE_TOOL) + "\n");+ await Bun.sleep(25);+ stdin.end();+ // EOF arrived with both reads held and the write parked behind them.+ let settled = false;+ void loop.then(() => {+ settled = true;+ });+ await Bun.sleep(25);+ expect(settled).toBe(false);+ release(1);+ release(2);+ // The reads settle, the gate dispatches the parked write, and the+ // loop is STILL pending under the held write: the exit barrier covers+ // the parked shape, not just the already-dispatched one.+ await until(+ () => server.log.some((e) => e.id === 3 && e.event === "start"),+ "the parked write to dispatch",+ );+ await Bun.sleep(25);+ expect(settled).toBe(false);+ release(3);+ await until(() => frames().length === 3, "all three answers");+ expect(await loop).toBe(0);+ });+});++/**+ * A dispatcher whose every request fails: the transport, not the server,+ * owns what the caller sees when dispatch itself throws.+ */+class ExplodingServer extends MCPServer {+ override async handleRequest(): Promise<JsonRpcResponse | null> {+ throw new Error("handler exploded");+ }+}++describe("dispatch failures answer their id", () => {+ test("a rejecting handler yields a JSON-RPC error frame and the loop survives", async () => {+ const stdin = new PassThrough();+ const stdout = new PassThrough();+ const chunks: string[] = [];+ stdout.on("data", (c: Buffer) => chunks.push(c.toString("utf8")));+ const server = new ExplodingServer({ vault: tempVault() });+ const loop = serveStdio({ vault: server.vault }, { stdin, stdout, server });+ stdin.write(call(7, READ_TOOL) + "\n" + call(8, READ_TOOL) + "\n");+ stdin.end();+ // The loop resolves cleanly instead of dying on the rejection.+ expect(await loop).toBe(0);+ const frames = chunks+ .join("")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as JsonRpcResponse);+ // Both requests were answered, by their own ids, with error frames.+ expect(frames.map((f) => f.id).toSorted((a, b) => Number(a) - Number(b))).toEqual([7, 8]);+ for (const frame of frames) {+ expect(frame.error?.code).toBe(INTERNAL_ERROR);+ expect(frame.error?.message).toContain("handler exploded");+ }+ });++ test("a failing notification is never answered - it has no id to answer", async () => {+ const stdin = new PassThrough();+ const stdout = new PassThrough();+ const chunks: string[] = [];+ stdout.on("data", (c: Buffer) => chunks.push(c.toString("utf8")));+ const server = new ExplodingServer({ vault: tempVault() });+ const loop = serveStdio({ vault: server.vault }, { stdin, stdout, server });+ const notification = JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ method: "tools/call",+ params: { name: READ_TOOL, arguments: {} },+ });+ stdin.write(call(9, READ_TOOL) + "\n" + notification + "\n");+ stdin.end();+ expect(await loop).toBe(0);+ const frames = chunks+ .join("")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l) as JsonRpcResponse);+ // The request gets its error frame by its own id; the notification -+ // no `id` member - gets NO frame at all, not an `id: null` error+ // nobody can correlate: the dispatcher itself returns null for a+ // failed notification, and the transport catch-all mirrors that.+ expect(frames.map((f) => f.id)).toEqual([9]);+ });+});diff --git a/tests/mcp/surface-error-codes.test.ts b/tests/mcp/surface-error-codes.test.tsindex 6fa69b39..f6e76b6e 100644--- a/tests/mcp/surface-error-codes.test.ts+++ b/tests/mcp/surface-error-codes.test.ts@@ -286,6 +286,7 @@ describe("refusal codes", () => {properties: { query: { type: "string", description: "The search text." } },additionalProperties: false,},+ kind: "read",handler: () => ({}),};diff --git a/tests/setup.ts b/tests/setup.tsindex abde6821..7ac27845 100644--- a/tests/setup.ts+++ b/tests/setup.ts@@ -22,6 +22,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { clearOriginChannel } from "../src/core/origin-channel.ts";+import { MARKDOWN_NEUTRALIZE_MODE_ENV } from "../src/core/brain/text/neutralize-markdown.ts";// The origin channel (`src/core/origin-channel.ts`) is process-scoped by// design: an entry point claims it once and every record written under@@ -140,6 +141,20 @@ if (process.env["O2B_TEST_KEEP_EMBEDDING_ENV"] !== "1") {}}+// The markdown neutralization gate resolves from an env twin of its+// config key (`neutralize-markdown.ts`), and the default posture of a+// dozen seam and doctor tests depends on it staying `off`. A developer+// who exports it for daily use would flip what those tests mean, so the+// suite starts without it - the same sweep the embedding twins get. A+// run that wants it kept sets `O2B_TEST_KEEP_NEUTRALIZE_MODE_ENV=1`; a+// test that needs a mode sets it itself.+if (+ process.env["O2B_TEST_KEEP_NEUTRALIZE_MODE_ENV"] !== "1" &&+ process.env[MARKDOWN_NEUTRALIZE_MODE_ENV] !== undefined+) {+ delete process.env[MARKDOWN_NEUTRALIZE_MODE_ENV];+}+// Every temp entry a test mints lands under ONE per-run root, and the run// fails if any of them is still there after the last file (issue #194).//diff --git a/uv.lock b/uv.lockindex 61e85bad..837a5e23 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.95.0"+version = "1.96.0"source = { editable = "." }