Skip to content

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: exactly-one binding for mentions and imports, once-only write receipts, selectable search breadth and per-device ledgers (v1.63.0) (#222)

Serg Eroshea0b3c2e00cad
diff --git a/.apb/playbooks/osb-release/1.0.0/scripts/stage.sh b/.apb/playbooks/osb-release/1.0.0/scripts/stage.sh
index ccd76a59..ac275664 100755
--- a/.apb/playbooks/osb-release/1.0.0/scripts/stage.sh
+++ b/.apb/playbooks/osb-release/1.0.0/scripts/stage.sh
@@ -41,7 +41,7 @@ IFS=$'\t' read -r is_draft name target url names <<<"$info"
[ "$is_draft" = true ] || die "the staged release is not a draft"
[ "$name" = "$title" ] || die "the draft title is '$name', expected '$title'"
[ "$target" = "$OSB_TARGET_SHA" ] || die "the draft targets '$target', expected $OSB_TARGET_SHA"
-expected=$(printf '%s\n' "${assets[@]##*/}" | sort | paste -sd, -)
+expected=$(printf '%s\n' "${assets[@]##*/}" | LC_ALL=C sort | paste -sd, -)
[ "$names" = "$expected" ] || die "the draft assets are '$names', expected '$expected'"
if git ls-remote --exit-code --tags origin "refs/tags/$OSB_TAG" >/dev/null 2>&1; then
die "tag $OSB_TAG appeared on origin while staging; stop and inspect"
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index d1be9021..2b8588bf 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.62.0",
+ "version": "1.63.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.json
index 94008309..f2b2884e 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.62.0",
+ "version": "1.63.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.md
index 43ce846a..ec4ae390 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,33 @@ 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.63.0] - 2026-09-30
+
+Integrity and control on the agent-facing memory surface: a prose mention binds to a page only when exactly one page carries the term, relative imports and JSX component usage become code-structure edges, a `brain_write_batch` call can carry a request ID that makes a retry apply once, keyword search gets a selectable match breadth, and every append-only Brain ledger that several synced machines write now keeps one file per device.
+
+### Added
+
+- **The repair lane binds alias mentions, and only to a single page.** `o2b brain repair-lane` pools each corpus page's title with every frontmatter alias that page claims. A note that mentions a term (title or alias, at least four characters, at a word boundary) carried by exactly one page gets the explicit-reference candidate a title mention always had, with the same 0.9 confidence, and the reason names the term that matched. Threshold, ordering, write cap, dry-run default and idempotent reruns are unchanged.
+- **Relative imports bind to the ingested file they name.** With `pre_extract` on `brain_ingest_source`, an `imports` seed whose specifier is relative (`./` or `../` in TypeScript and JavaScript, a leading-dot `from .x import` in Python) gains `resolved_to` (`resolvedTo` on the core result), the vault-relative path of the one ingested file it names, checked against the ingest content manifest. TypeScript and JavaScript probe the path as written, then each TypeScript/JavaScript extension and `/index` plus each; Python probes `<name>.py` and `<name>/__init__.py` (a dots-only specifier only the package `__init__.py`). No match, several matches or a specifier that climbs above the vault root leave the seed exactly as before, `to` always keeps the raw specifier, and a Python import never binds to a TypeScript file or the reverse. `o2b brain pre-extract` reads no manifest and never binds.
+- **JSX component usage edges.** In `.tsx` and `.jsx` sources the pre-extract pass emits a `uses` edge from the file to each component an opening tag names. The rule is structural, with no tag vocabulary: only names starting with an uppercase letter, `_` or `$` count, so DOM tags (`<div>`), member-expression tags (`<Nav.Item>`), type-argument lists (`Array<Foo>`), type-parameter lists (`<T,>`, `<K extends string>`) and generic call signatures (`<T>(value: T) => T`) produce nothing. As a line grammar it misses a generic component (`<Foo<T> />`) and an element whose text opens with `(` on the same line, and closing tags never match. The `pre_extract` description on `brain_ingest_source` now names `uses` edges and `resolved_to`.
+- **`brain_write_batch` request receipts.** An optional `request_id` (`requestId` on `applyWriteBatch`) makes a retried batch apply once. The result then carries `request_id` and `receipt`: `applied` when this call committed; `duplicate` when the same ID with the same operations was already recorded (the retained original result comes back, nothing is written, re-validated or linted); `concurrent_duplicate` when this call committed but a concurrent call recorded the same ID and payload in between (both writes landed; the fields are this call's own); and `payload_conflict` when this call committed but a concurrent call recorded the same ID for a different payload in between (the writes landed, this call's receipt is not recorded, and a `receipt_note` says not to resend the batch under a new `request_id`). The same ID with different operations found before the commit is refused as `INVALID_PARAMS` with the idempotency ledger's mismatch message, a blank ID or one over 256 characters after trimming is refused as `INVALID_PARAMS` before any write, and an ID already recorded without a readable batch receipt is refused by name rather than answered with an empty result. The receipt is recorded in the idempotency ledger after the commit under its own `write_batch` namespace, so a request ID never collides with a `brain_feedback` or apply-evidence `idempotency_key` of the same text; records without a namespace read exactly as before. The stored receipt keeps log paths vault-relative, and a duplicate rebuilds them under the vault serving the retry. While a synced peer still runs 1.62.0, which ignores the key space, that peer refuses a feedback key equal to a synced batch request ID with the named idempotency mismatch error rather than deduplicating it. Without `request_id` the call and its payload are unchanged.
+- **Keyword match breadth.** `brain_search` accepts `match_mode` (`all`, the default, or `any`), the search API `matchMode`, and `o2b search` `--match-mode all|any`. `any` joins the cleaned query tokens with `OR`, so a document carrying any one term is a keyword candidate; caller-typed `AND`, `OR`, `NOT` and `NEAR` tokens are dropped in both modes, and query expansion composes with either. Any other value is refused with the accepted list (a CLI error, `INVALID_PARAMS` on MCP, `INVALID_INPUT` from the API). The query cache keys an `any` search apart from the default, so neither mode is served the other's rows. Absent, the query and its cache key are byte-identical to before; the semantic lane is unaffected.
+
+### Changed
+
+- **The `brain_search` description tells the agent when to widen.** It now ends with one sentence: when a query misses, consult `brain_recall_gate` before widening recall, since it classifies whether widening is warranted.
+- **`o2b brain doctor` sweeps the newly sharded directories for Syncthing conflict copies.** The `sync-conflict-log` check now also lists `Brain/log/session-lifecycle/`, `hygiene/`, `secret-custody/`, `watchdog/` and `schema-mutations/`, `.open-second-brain/hook-audit/` and `.open-second-brain/watchdog-audit/`, `Brain/skill-proposals/`, `Brain/preferences/` and each repository directory under `Brain/projects/git/`, with the same union-and-dedup instruction. In the directories that also hold whole files (`Brain/skill-proposals/`, `Brain/preferences/` and the git repository directories), a conflict copy that is not a `.jsonl` shard, such as a proposal file, a preference note or a repository `state.json`, is reported under the same `sync-conflict-log` code with its own remedy: compare it with the original, keep the right version by hand, then delete the copy. A parent it cannot list is reported under `uncertain` by name, never read as clean.
+- **`o2b state status` sees sharded ledgers.** The query-demand, recurrence-support, capture-decision and maintenance-journal surfaces, and the session lineage ledger, report present when the legacy file or any device shard exists, so a device with an id that never writes the legacy name no longer reads as absent. Conflict copies never count.
+- **A source-layout test keeps append-only writers on the shard grammar.** A file that appends with `appendFileSync` or `openSync(..., "a")` fails the suite unless it uses the shard helpers or sits on a named allow-list with a reason (such as the per-run dream workrun files and the doctor repair that appends to them).
+- **`--disclosure` and `disclosure` refusals list the accepted modes** from one shared vocabulary, the same way `match_mode` does.
+- **Docs:** `docs/mcp.md` documents `request_id` and the receipt, `match_mode`, the search cue and the widened doctor sweep; `docs/cli-reference.md` lists `o2b search --match-mode`, the `uses` edge and the repair lane's `skip-ambiguous` decision; `docs/observability.md` and `docs/how-it-works.md` describe the per-device audit weeks and fixed-name ledgers; the README names this release.
+
+### Fixed
+
+- **A mention of a term several pages carry no longer links all of them.** The repair lane used to propose an edge from a note to every page whose title it mentioned, so a title two pages share produced two edges. Such a term, title or an alias two pages claim, now binds to none: every (mentioning page, carrying page) pair comes back as a named `skip-ambiguous` decision in the dry-run and apply reports (and under `--json`), which is never written, never counted against the write cap and never sent to the apply holdout gate. A note that already links one of the carriers has resolved the mention itself and is not refused, and a page naming its own shared title is a self-reference that gets no refusal.
+- **Two synced machines no longer split an audit week or a fixed-name ledger into conflict copies.** Every writer of an ISO-week audit file (session lifecycle, hygiene and targeted recompiles, schema mutations, secret custody, the watchdog and its fallback directory, and the hook audit) now appends to `<ISO-week>[.<device-id>].jsonl`, and the fixed-name ledgers follow the same grammar: `Brain/log/query-demand`, `recurrence-support` and `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 empty device id keeps every legacy name, so existing vaults need no migration. Readers merge every shard and never parse a `*.sync-conflict-*` copy: the maintenance journal, the git store and the recurrence-support ledger interleave shards by row time without reordering any one shard (so a purge on one device is never replayed before another device's earlier event), the git store keeps one copy of each commit and tag two devices both ingested, the query-demand read keeps its timestamp order, and the schema-pack digest reads every week shard. Query-demand compaction and the maintenance-journal cap rewrite only the shard this device writes, so the journal cap now applies per device.
+- **The release stage script compares asset names in byte order.** The expected asset list now sorts under `LC_ALL=C`, the order `jq` uses, so names such as `-source.svg` and `[email protected]` no longer fail the draft check.
+
## [1.62.0] - 2026-09-29
Wider egress redaction, honest write receipts, an ingest plan that accounts for what it sets aside, a search store that keeps its journal mode honest on remote filesystems, and two more brain-doctor checks with a confirm-gated repair verb.
@@ -7835,6 +7862,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.63.0]: https://github.com/itechmeat/open-second-brain/compare/v1.62.0...v1.63.0
[1.62.0]: https://github.com/itechmeat/open-second-brain/compare/v1.61.0...v1.62.0
[1.61.0]: https://github.com/itechmeat/open-second-brain/compare/v1.60.0...v1.61.0
[1.60.0]: https://github.com/itechmeat/open-second-brain/compare/v1.59.0...v1.60.0
diff --git a/README.md b/README.md
index 6cdaa0ee..2e3ea20e 100644
--- a/README.md
+++ b/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-1.61.0 moves MCP server start-up off the Brain upgrade path, makes ingest locks fair, puts the Claude Code MCP manifest inside `plugin.json`, and adds an inbox archive. Every release is described in the [CHANGELOG](CHANGELOG.md).
+1.63.0 binds a prose mention to a page only when exactly one page carries the term, turns relative imports and JSX component usage into code-structure edges, lets a `brain_write_batch` retry apply once through a request ID, adds a keyword match breadth to search, and gives every append-only Brain ledger one file per synced device. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/brainstorm/integrity-control-agent-memory-surface/cli-output/claude.md b/docs/brainstorm/integrity-control-agent-memory-surface/cli-output/claude.md
new file mode 100644
index 00000000..a5d06b81
--- /dev/null
+++ b/docs/brainstorm/integrity-control-agent-memory-surface/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Narrowest seams, per-card local logic
+- **Approach**: Each card lands as an isolated edit at its existing call site with no shared abstraction. Card 1 adds a title-plus-alias term pool and an inline "exactly one page carries this term" filter inside `collectRepairCandidates`; Card 2 adds a post-pass in `runPreExtract` that probes relative specifiers against the manifest path set and fills an optional `resolvedTo` on the seed; Card 3 adds one JSX opening-tag regex and a `uses` kind; Card 4 calls `rememberKey` from `applyWriteBatch` with a `write_batch` record whose `ref` carries the receipt; Card 5 is one sentence; Card 6 threads a `matchMode` boolean-ish flag through `SearchOptions` to `buildFtsMatch`.
+- **Trade-offs**:
+ - Pro: smallest diff, every default byte-identical, each card reviewable on its own.
+ - Pro: no new modules, no new public types beyond the widened union and optional fields.
+ - Con: the unique-match discipline is written twice (pages in Card 1, files in Card 2) with two chances to diverge.
+ - Con: ambiguous terms and unbound specifiers tend to vanish silently unless each site remembers to count and report them, which strains the "nothing degrades silently" convention.
+ - Con: Card 4 records the ledger entry after the commit, leaving a crash window between apply and remember that a retry can double-apply through.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 2: Shared unique-resolution primitive with named refusals
+- **Approach**: Introduce one small pure module (a term index plus a resolver that returns `unique | ambiguous | none` with the candidate list) and consume it from both the repair-lane term resolver (Card 1, terms pooled from titles and `buildAliasIndex`) and the pre-extract specifier binder (Card 2, terms are extension-probed paths over the ingested-file set passed in as an explicit input). Both surfaces carry the refusal counts outward: the repair report gains an ambiguous-terms section and the pre-extract result gains an `unbound` list with reasons. Card 4 reuses `rememberKey` unchanged with the batch receipt in `ref`, consulted before any commit and recorded inside the batch's atomic unit so the receipt and the writes land together; Card 6 defines one `FtsMatchMode` type shared by `buildFtsMatch` and `buildExpandedFtsMatch`; Cards 3 and 5 stay local.
+- **Trade-offs**:
+ - Pro: one tested discipline for "bind only when exactly one target matches", so Cards 1 and 2 cannot drift.
+ - Pro: honesty by construction, since the resolver returns a typed status and callers must map every status to something visible.
+ - Pro: no new dependencies, no new machinery beyond a pure function module, determinism is trivial to prove because the resolver takes the index as an argument.
+ - Con: a new cross-cutting module means a broader test surface and one more thing for the link-graph and ingest owners to agree on.
+ - Con: putting the ledger record inside the batch commit touches the write-batch kernel's atomic path, which is the most sensitive code in the wave.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Index-first candidate tables and a separate receipt store
+- **Approach**: Build explicit reusable indexes as first-class inputs: `loadPages` returns a corpus term index that the repair lane, `findUnlinkedMentions` and future consumers share, and `ingestSource` builds an ingested-file index from the manifest and hands it to pre-extract. Cards 1 and 2 produce a full candidate table (every term with all matching targets and a resolution status) as an intermediate artifact surfaced in dry-run reports, and binding becomes a filter over that table. Card 4 gets a dedicated receipt store keyed by request ID rather than a ledger record, and Card 6 replaces the boolean with a parsed query object carrying tokens and mode.
+- **Trade-offs**:
+ - Pro: richest operator visibility, and the shared indexes would let the target-centric mention scanner converge with the corpus-wide path later.
+ - Pro: the candidate table makes ambiguity a reported fact instead of a dropped edge.
+ - Con: changes the shape of `loadPages` output and the pre-extract input contract, the widest blast radius in the wave.
+ - Con: a separate receipt store duplicates what the idempotency ledger already does and drifts from the card's stated scope of extending `rememberKey` semantics; it also edges toward the struck durable-queue territory.
+ - Con: the parsed query object for Card 6 is more than the card asks for and risks touching the two derived-term callers.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 2
+**Rationale**: Variant 2 keeps every default byte-identical and adds no machinery, yet it gives the two resolution cards one shared, typed unique-match discipline so ambiguity is always named rather than silently dropped, which is the project's core honesty rule. It reuses the existing idempotency ledger exactly as the validator scoped Card 4, while closing the apply-then-remember crash window that Variant 1 leaves open. Variant 3 buys visibility the cards did not ask for at the cost of public-shape changes and a parallel receipt store the constraints explicitly steer away from.
diff --git a/docs/brainstorm/integrity-control-agent-memory-surface/cli-output/prompt.md b/docs/brainstorm/integrity-control-agent-memory-surface/cli-output/prompt.md
new file mode 100644
index 00000000..f423e434
--- /dev/null
+++ b/docs/brainstorm/integrity-control-agent-memory-surface/cli-output/prompt.md
@@ -0,0 +1,102 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+One release wave for Open Second Brain combining six cards under the spine "Integrity and control of the agent-facing memory surface of Open Second Brain". All premises below were verified against the live source.
+
+## Card 1 - t_ec6b155d: corpus-wide unique-match mention-to-wikilink edge resolution in link-graph through the apply-gated repair lane
+
+Turn a prose mention of a known corpus page (its title or a declared frontmatter alias) into a link-graph edge, without the author writing a wikilink, under a unique-match-only discipline: a term binds to a target only when exactly one corpus page matches it; ambiguous terms link to nothing. Verified state: the apply-gated repair lane already ships (`src/core/brain/link-graph/repair-lane.ts` - `runRepairLane` writes proposed edges as wikilinks only after an exact confirmation phrase, dry-run default, confidence threshold, write cap, never creates dangling edges). Its `collectRepairCandidates` already collects an `explicit_reference` tier that matches a note's bare TITLE in another note's prose (wikilink and code spans masked, word-boundary, minimum title length 4). Verified gaps: (a) `buildAliasIndex` (`src/core/brain/link-graph/alias-index.ts`) is never consulted by the candidate collector, so alias spellings produce no candidates; (b) there is no unique-match rule - when two corpus pages share a title, a mention produces one candidate edge to EACH, so both false edges reach the operator's apply report; (c) the separate target-centric scanner `findUnlinkedMentions` (`src/core/brain/link-graph/unlinked-mentions.ts`) scans only `Brain/preferences/` + `Brain/retired/` and produces mention reports, not edges - it is not the corpus-wide path. The corpus walk in `loadPages` covers the whole vault with a readable status-scope filter. The increment: pool title + alias terms per corpus page, resolve each mention term to a target only when exactly one corpus page carries that term, feed the existing apply-gated lane.
+
+## Card 2 - t_2356dace: bind relative import specifiers in pre-extract to ingested files, unambiguous resolution only, no Elixir/Rust/Ruby
+
+The deterministic pre-extractor (`src/core/brain/ingest/pre-extract.ts`) emits `imports` edge seeds whose `to` is a raw module specifier (`./foo`, `../bar`, `from .mod import`); nothing binds them to the vault file that satisfies the specifier. Verified: `CodeEdgeSeed.kind` is `"imports" | "inherits"`; `LANGUAGE_BY_EXTENSION` (pre-extract.ts:61) covers .ts/.tsx/.mts/.cts/.js/.jsx/.mjs/.cjs/.py/.pyi only; the P4 pass runs off by default in `ingestSource` (`src/core/brain/ingest/ingest.ts`, `opts.preExtract`), and seeds travel on the result only, never into the summary page. The ingest content manifest (`src/core/brain/ingest/content-manifest.ts`, `readManifest`) records canonical vault-relative paths of ingested sources. Scope: bind RELATIVE specifiers only (TS/JS `./`- and `../`-prefixed, Python leading-dot `from .x import`), resolved against the ingested-file set, binding only when exactly one ingested file satisfies the specifier (extension probing over the supported extensions, candidate set ambiguity refuses); otherwise the seed stays raw. No new languages.
+
+## Card 3 - t_998aa4e6: JSX component-usage edge kind in pre-extract, conservative DOM/member-tag skipping
+
+Widen `CodeEdgeSeed.kind` with a new usage kind. When pre-extracting a .tsx/.jsx source, a JSX element opening tag (`<MyButton/>`, `<_Row>`) becomes an edge seed from the using file to the used component name, while conservatively skipping lowercase DOM tags (`<div>`) and member-expression tags (`<Nav.Item>`). Verified: the line grammar regexes (pre-extract.ts:74-99) cover class/function/extends/implements/import/require only - no JSX-element regex; the edge-push sites in `parseTsJs` (pre-extract.ts:144-164) have no usage site; `edgeKey` (pre-extract.ts:240-242) is already kind-aware, so dedupe/sort keys survive the widened union; .tsx/.jsx are already supported extensions.
+
+## Card 4 - t_b34439d9: write-batch accepts a client request ID and returns a durable receipt, extending idempotency-ledger rememberKey semantics
+
+`applyWriteBatch` (`src/core/brain/write-batch.ts`, MCP surface `brain_write_batch` in `src/mcp/brain/write-batch-tools.ts`) has no client request ID and no durable receipt: a lost MCP response forces a blind retry that can double-apply. Verified prior art in the same codebase: the idempotency ledger (`src/core/brain/idempotency-ledger.ts`) gives signal/preference/apply-evidence writes `rememberKey` semantics - `inserted` / `duplicate_match` / `payload_mismatch`, the stored record's `ref` carries the original write's coordinates, and the signal writer consults the ledger BEFORE writing, returns the original coordinates with `deduped: true` on a same-key-same-hash retry, and throws `IdempotencyPayloadMismatchError` on same-key-different-hash. MCP tools already accept an optional `idempotency_key` string param for those writers. Scope: the same semantics for the write batch - a client-supplied request ID, a payload hash over the batch's semantic operations, consult before commit, the retained original batch receipt returned on a same-key retry, an explicit named refusal on same-key-different-hash. NO durable-queue half (no expiry/queue machinery) and NO worktree-pause half - both explicitly struck by the validator.
+
+## Card 5 - t_cb1e9d3d: one when-to-search cue in the brain_search description pointing at brain_recall_gate as the bound
+
+The `brain_search` tool description (`src/mcp/search-tools.ts:1872`) is purely mechanical: "Full-text search across the vault. Optional semantic layer when configured. Read-only." - the agent gets no when-to-search calibration. Verified: `brain_recall_gate` (search-tools.ts:1863) exists and classifies recall attempts (sufficient/proceed, weak/re_recall, insufficient/abstain) - the validator ruled the cue must point AT brain_recall_gate as the bound rather than inventing a fan-out number. Scope: exactly one when-to-search cue sentence added to the brain_search description naming brain_recall_gate; the recall-inject header (recall-inject.ts:575, "Recalled vault context (relevance-matched to this prompt):") is already neutral and stays untouched; no fan-out counts, no parallel-search language.
+
+## Card 6 - t_c5326ece: explicit caller-selectable AND/OR match mode in FTS via buildFtsMatch, operator tokens still dropped
+
+`buildFtsMatch` (`src/core/search/fts.ts:31`) joins quoted tokens with an implicit AND; uppercase FTS5 operator tokens (AND/OR/NOT/NEAR) typed by the caller are dropped when other tokens remain; OR exists only as automatic synonym expansion in `buildExpandedFtsMatch`. Verified: no `matchMode`/`match_mode` exists anywhere in src/tests/docs. Threading path verified: `SearchOptions` (types.ts:810) -> `resolveSearchRequest` (pipeline/request.ts) -> `runKeywordLane` (search.ts:125, pipeline/keyword-lane.ts) -> `runFtsQueryDetailed` -> `buildFtsMatch`. Two other direct `runFtsQueryDetailed` callers (pipeline/second-pass.ts, evidence-verification.ts) use derived terms, not caller queries. Exposed surfaces: MCP `brain_search` input schema (search-tools.ts:106) and the CLI `o2b search` verb flags (src/cli/search/verbs/query.ts). Scope: an explicit caller-selectable ALL (default, unchanged) vs ANY (OR-joined) match mode through buildFtsMatch and the surfaces above; operator-typed operator tokens stay dropped in both modes; synonym expansion composes unchanged.
+
+# Project context
+
+Open Second Brain - a memory layer for AI agents living in an Obsidian vault. TypeScript on Bun 1.1+, no LLM in the deterministic kernel paths, MCP servers + lifecycle hooks + `o2b` CLI surfaces over one core.
+
+Recent commits:
+f4f9e3e6 feat: silent failures surface by name in redaction, receipts, ingest, search store, doctor (v1.62.0) (#220)
+eb3c4c85 docs: concise README, ZCode client page, CLI reference and safety notes moved to child pages (#219)
+f22df2c5 chore(apb): zg search, code-ranker and OpenCodeReview before push, scope-scan hardening (#218)
+83979b9d fix: MCP startup off the upgrade path, fair ingest locks, inline plugin MCP manifest, inbox archive (v1.61.0) (#217)
+3e59f319 feat: decision-model uses, adapters and setup skill (v1.60.0) (#215)
+eacad953 feat: optional decision-model core and decision-model rerank kind (v1.59.0) (#214)
+0afa0c5a chore(deps): bump the bun-minor-and-patch group with 5 updates (#201)
+f6212cd2 fix: quiet one-line Stop reminder via Claude Code feedback channel (v1.58.2) (#202)
+534befdb chore(deps): bump the github-actions group with 3 updates (#200)
+5c550263 fix: session capture off the hook path, registry scanner hygiene (v1.58.1) (#199)
+6f33c424 feat: payload registry and knowledge packs, boundary hardening, CJK chunking (v1.58.0) (#197)
+d7e6094a feat: a second platform (v1.57.0) (#191)
+54bb28d9 feat: what this install knows (v1.56.0) (#185)
+5f415267 feat: who wrote what, and how to take it back (v1.55.0) (#184)
+dc552590 feat: private is not a suggestion (v1.54.0) (#183)
+23e6b81e fix(brain): merged pages leave the dedup pool, and the write seam refuses cycles (v1.53.1) (#182)
+323e2f09 feat: nothing writes silently, nothing degrades silently (v1.52.0) (#178)
+
+Related files:
+- src/core/brain/link-graph/repair-lane.ts (apply-gated repair lane, collectRepairCandidates)
+- src/core/brain/link-graph/alias-index.ts (buildAliasIndex)
+- src/core/brain/link-graph/unlinked-mentions.ts (findUnlinkedMentions, target-centric)
+- src/core/brain/ingest/pre-extract.ts (deterministic pre-extractor)
+- src/core/brain/ingest/ingest.ts (P4 pass wiring, runPreExtract)
+- src/core/brain/ingest/content-manifest.ts (ingested-file manifest)
+- src/core/brain/write-batch.ts (atomic write-batch kernel)
+- src/core/brain/idempotency-ledger.ts (rememberKey ledger)
+- src/core/brain/signal.ts (established consult-before-write idempotency pattern)
+- src/mcp/brain/write-batch-tools.ts (brain_write_batch MCP surface)
+- src/mcp/search-tools.ts (brain_search, brain_recall_gate)
+- src/core/search/fts.ts (buildFtsMatch, buildExpandedFtsMatch, runFtsQueryDetailed)
+- src/core/search/pipeline/keyword-lane.ts, src/core/search/pipeline/request.ts, src/core/search/search.ts, src/core/search/types.ts (match-mode threading path)
+- src/cli/search/verbs/query.ts (o2b search flags)
+- tests/core/brain/, tests/core/search/, tests/mcp/ (colocated test suites)
+
+Conventions:
+- Deterministic kernel: no LLM, no wall-clock beyond caller-supplied time, output depends only on explicit inputs; no natural-language word lists anywhere (programming keywords count as grammar).
+- Honesty: no fake empty success; unsupported/unresolvable states are named (typed errors, `extracted: false` with reason, machine-readable codes); "nothing writes silently, nothing degrades silently".
+- Writes go through the vault-identity guard (`assertVaultIdentityForWrite`) and atomic writes (temp file + rename); byte-identical rewrites skip and say so.
+- Client-facing idempotency: optional `idempotency_key` MCP param; ledger statuses inserted/duplicate_match/payload_mismatch; same-key-different-hash is a named error, never a silent overwrite.
+- Parameter style: camelCase in core APIs, snake_case on MCP/CLI surfaces; optional knobs default to byte-identical behavior.
+- Docs live beside the code as module doc comments; user-facing docs in docs/ (mcp.md, cli-reference.md, how-it-works.md). Tests are bun tests under tests/ mirroring src/ layout.
+
+Constraints:
+- No new external dependencies (runtime deps today: proper-lockfile only).
+- Do not change existing public API shapes incompatibly: new parameters are optional and default to today's byte-identical behavior.
+- No durable-queue or worktree-pause machinery (explicitly struck).
+- No hardcoded natural-language phrases in any language beyond the established grammar-level tokens; the search description cue is the one sanctioned English prompt-layer string.
+- All-or-nothing batch semantics must be preserved; the request-ID consult must run before any commit.
+- Determinism in pre-extract: binding may depend only on explicit inputs (path, content, ingested-file set), never on ambient state.
+
+# 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/integrity-control-agent-memory-surface/design.md b/docs/brainstorm/integrity-control-agent-memory-surface/design.md
new file mode 100644
index 00000000..7f9b546c
--- /dev/null
+++ b/docs/brainstorm/integrity-control-agent-memory-surface/design.md
@@ -0,0 +1,117 @@
+# Integrity and control of the agent-facing memory surface - seven-card release wave (mention-to-wikilink unique-match resolution, import binding, JSX usage edges, write-batch request receipts, when-to-search cue, FTS match mode, per-device audit sharding)
+
+**Status:** draft
+**Author:** orchestrator (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain's agent-facing memory surface leaves integrity and control gaps on seven fronts, each verified against the live source. Prose mentions of known pages bind to nothing (and ambiguous titles bind to several things at once); pre-extract import seeds stay dangling specifiers; JSX render relationships are invisible; a retried `brain_write_batch` call can double-apply because no client request ID and no durable receipt exist; the `brain_search` description gives the agent no when-to-search calibration; FTS matching is hardcoded to implicit-AND with no caller-selectable breadth; and every append-only ledger that never adopted the per-device shard grammar shares one file per week across all synced machines, so Syncthing splits their history into `*.sync-conflict-*` copies no reader merges. The wave closes all seven under one spine without changing any default behavior for callers who do not opt in.
+
+## Scope
+
+- t_ec6b155d: corpus-wide unique-match mention-to-wikilink edge resolution through the apply-gated repair lane - title and alias terms pooled per corpus page, a mention term binds only when exactly one corpus page carries it, ambiguous terms are refused by name in the lane's decision list.
+- t_2356dace: bind relative import specifiers (TS/JS `./`- and `../`-prefixed, Python leading-dot `from .x import`) to ingested files via an optional `resolvedTo` field on the `imports` edge seed, resolved against the ingest content manifest, exactly-one-candidate only, never clobbering a raw seed. No new languages.
+- t_998aa4e6: a `uses` edge kind in the pre-extract line grammar for JSX element tags in .tsx/.jsx sources, skipping lowercase-initial DOM/intrinsic tags and member-expression tags.
+- t_b34439d9: `applyWriteBatch` accepts an optional client request ID; on a repeated ID with the same semantic payload the retained original batch receipt is returned without re-applying; on a repeated ID with a different payload a named error refuses. The idempotency ledger's `rememberKey` semantics are extended; no durable-queue and no worktree-pause machinery.
+- t_cb1e9d3d: exactly one when-to-search cue sentence added to the `brain_search` tool description, naming `brain_recall_gate` as the bound for widening recall.
+- t_c5326ece: a caller-selectable FTS match mode (`all` default, `any` OR-joined) on `buildFtsMatch`, threaded through the keyword lane, the search API options, the MCP `brain_search` schema and the `o2b search` CLI flags; caller-typed FTS5 operator tokens stay dropped in both modes.
+- t_774dea61 (owner-mandated addition, mid-wave): per-device file names for the Brain logs written from multiple synced machines. `appendAuditRecord` writes `<ISO-week>[.<deviceId>].jsonl` through the `ledger-shards.ts` grammar, so every audit-week writer (session-lifecycle, hygiene, schema-mutations, secret-custody, watchdog and the hook audit) gets its own file per device with the empty device id keeping the legacy name; the one content reader an audit directory has (`readRecordedSchemaPackDigest`) lists shards through the grammar and skips `*.sync-conflict-*`; the fixed-name ledgers (query-demand, recurrence-support, capture-decisions, verifier-rejections, preference edit history, git commits, maintenance runs) write per-device shards with merged readers and own-shard-only rewrites; the doctor's sync-conflict sweep covers the audit subdirectories; a source-layout guard keeps new appends on the grammar.
+
+## Out of scope
+
+- No durable-queue, expiry or worktree-pause machinery (validator-struck halves of t_b34439d9).
+- No Elixir/Rust/Ruby support in pre-extract.
+- No change to `findUnlinkedMentions` (it stays the target-centric report scanner for `Brain/preferences/` + `Brain/retired/`).
+- No change to the recall-inject header or `deriveRecallHint` wording (already neutral).
+- No fan-out counts, parallel-search language, or invented recall bounds in the search description.
+- No new external dependencies; no version bump in this node (the bump rides with the release phases per CLAUDE.md).
+- No change to the two internal derived-term `runFtsQueryDetailed` callers (`pipeline/second-pass.ts`, `evidence-verification.ts`) - they keep the default `all` mode.
+- No automated merge verb for `*.sync-conflict-*` copies (the card's fix step 4 "one-shot, opt-in merge"). The established convention - the `ledger-shards.ts` contract and the existing `sync-conflict-log` doctor message - is report plus manual union+dedup; the doctor extension names the copies and carries the same instruction. An opt-in automatic merge is operator-facing recovery machinery this wave does not build; deferred with that reason.
+- No CHANGELOG entry in this node; the card's documentation criterion is satisfied by the osb-pr-prepare docs phase inside the PR, per the run boundaries.
+- No change to the low-risk writers the card lists as already unique per run (dream-run workrun files and the doctor repair appending to them) - they stay on the guard test's allow-list.
+
+## Chosen approach
+
+Variant 2 from the brainstorm (shared unique-resolution discipline with named refusals, existing ledger reuse, local edits for the two lexical cards), with two orchestrator refinements recorded under Design decisions.
+
+One small pure module, `src/core/graph/unique-match.ts` (placement mirrors the existing `src/core/graph/` shared helpers; final home confirmed during implementation against the import-direction rules), exposes the shared discipline:
+
+```ts
+type UniqueMatch<T> = { readonly status: "unique"; readonly target: T }
+ | { readonly status: "ambiguous"; readonly matches: ReadonlyArray<T> }
+ | { readonly status: "none" };
+function resolveUniqueMatch<T>(candidates: ReadonlyArray<T>): UniqueMatch<T>;
+```
+
+- The repair lane's explicit-reference collector (t_ec6b155d) builds a term index over `loadPages` output: NFC + lowercase term keys from each page's title plus the aliases `buildAliasIndex` resolves to that page's key. A masked, word-boundary mention scan per source page (the existing `mentionsTerm` mechanics) looks each matched term up in the index; `resolveUniqueMatch` decides. `unique` proposes a candidate (existing `explicit_reference` strength and confidence); `ambiguous` emits one `skip-ambiguous` decision per matching pair into the existing `RepairReport.decisions` list; `none` contributes nothing. Alias terms are exactly as strong as title terms; the reason string names the term it matched.
+- The pre-extract specifier binder (t_2356dace) takes an optional third options argument `{ ingestedFiles?: ReadonlySet<string> }` on `preExtractCodeStructure`. `ingest.runPreExtract` passes the manifest's canonical path set (`readManifest(vault).entries` keys). For a relative specifier the binder probes the candidate path set (specifier joined to the source dir; each supported extension; `/index` + each supported extension); `resolveUniqueMatch` over the candidates that are members of `ingestedFiles` decides: exactly one ingested file fills the seed's new optional `resolvedTo` field (canonical vault-relative path); `ambiguous` or `none` leaves the seed raw.
+- The JSX usage kind (t_998aa4e6) widens `CodeEdgeSeed.kind` with `"uses"`. One line-grammar regex matches JSX opening tags whose name is immediately after `<`, the preceding character is not an identifier character or `.`, and the name itself is `[A-Z_$][A-Za-z0-9_$]*` - which skips lowercase-initial DOM/intrinsic tags and every member-expression tag containing a dot, without a DOM vocabulary list. `edgeKey` is already kind-aware; the dedupe/sort order survives the widened union unchanged.
+- The write-batch receipt (t_b34439d9) follows the established `signal.ts` consult-before-write pattern: after the existing vault-identity assert and before validation/commit, a supplied request ID is hashed (`computePayloadHash` over the semantic operations array) and consulted with `lookupKey`; `duplicate_match` returns the retained original `WriteBatchResult` (stored in the ledger record's `ref`) with a receipt status, committing nothing; `payload_mismatch` throws the ledger's own `IdempotencyPayloadMismatchError`; an unseen key proceeds. After a successful commit, `rememberKey` records the key with the receipt in `ref`. Absent request ID: byte-identical behavior. The MCP surface `brain_write_batch` accepts `request_id` (string) and returns `request_id` plus the receipt status on every result.
+- The search cue (t_cb1e9d3d) appends one sentence to the `brain_search` description naming `brain_recall_gate` as the tool that classifies whether widening recall is warranted. No fan-out numbers.
+- The FTS match mode (t_c5326ece) adds a `FtsMatchMode` type (`"all" | "any"`) and an options argument on `buildFtsMatch`; `"any"` joins the quoted, operator-dropped tokens with ` OR `. The mode threads `SearchOptions.matchMode` -> `ResolvedSearchRequest.matchMode` -> `KeywordLaneInput.matchMode` -> `RunFtsOptions.matchMode`. `buildExpandedFtsMatch` composes unchanged (an OR-joined base group OR'd with expansion terms is semantically the flat ANY superset). MCP: `match_mode` enum on `brain_search`. CLI: `--match-mode all|any` on `o2b search`.
+- The per-device audit sharding (t_774dea61) reuses `ledger-shards.ts` unchanged - it is the same answer the daily log, metrics, preference audit, lineage, truth claims, decision receipts, idempotency ledger and continuity store already ship. `appendAuditRecord` names its file with `shardedFileName(isoWeekLabel(timestamp), resolveAppendShardId(), "jsonl")`, so all of its callers (session-lifecycle, hygiene, schema-mutations, secret-custody, watchdog with its derived-store fallback, and the seven hook audit sites) inherit per-device files from one function; the empty device id yields the legacy `<week>.jsonl`, which is what the test preload's `O2B_DEVICE_ID=""` pins and what existing vaults keep reading. The fixed-name ledgers swap their fixed path helpers for grammar-shaped ones: the writer appends to `<base>[.<deviceId>].jsonl`, a reader merges all shards through `listShardedFiles` + `mergeShardedRows` (which preserves single-shard file order), and every rewrite path (query-demand compaction, the maintenance-journal cap sweep) operates on the one shard the caller just wrote. The state inventory's reachability probe for a sharded fixed-name ledger reports present when the legacy name or any shard exists. The doctor's `syncConflictLogCheck` gains the audit subdirectories, the hook-audit and watchdog-audit roots, the skill-proposal ledger dir, the per-repo git store dirs and the preferences dir. A source-layout guard test scans the sources for bare `appendFileSync`/`openSync(..., "a")` writers and requires each file to use the shard helpers or appear on a named allow-list (run-id-unique dream-run files and their doctor repair).
+
+## Design decisions
+
+- **Shared resolver is generic and tiny; domain index-building stays local.** The link-graph term map and the pre-extract path probing are different domains; only the exactly-one decision is shared. A generic three-status resolver keeps the discipline from drifting without forcing a common input shape. (Variant 2's core, trimmed of its broader index-first suggestions.)
+- **Ambiguity is named where the report already lives.** Card 1's refusals ride the existing `RepairReport.decisions` via a new `skip-ambiguous` action - no report-shape change, no silent drop. Card 2's refused bindings are NOT surfaced as a separate `unbound` list (refinement over Variant 2): the seed staying raw is itself the visible conservative outcome, and an aggregate list would duplicate the seeds it describes.
+- **The receipt ledger write is not inside the batch's atomic unit.** Refinement over Variant 2's wording: the ledger is a separate JSONL store and no cross-file atomic unit exists. The sequencing is the one `signal.ts` already ships and the ledger's own documentation accepts - consult before any commit, `rememberKey` re-checks under its shard lock on record, and the primary target (a sequential retry after a lost response) is fully deduped because the record is durable before the retry runs.
+- **Core option named `requestId`, MCP param named `request_id`.** The card's vocabulary is request ID + receipt; the mapping stays in the tools layer (no MCP shapes in the core). Validation is delegated to the ledger's `normaliseKey` (non-empty, max 256) so an invalid ID raises the ledger's own named error rather than a duplicate validator.
+- **`resolvedTo` is additive; `to` keeps its raw-specifier semantics.** Existing consumers of pre-extract seeds see unchanged required fields; the bound file path is explicit and optional, matching the convention that new parameters default to byte-identical behavior.
+- **JSX skipping is structural, not lexical.** Lowercase-initial and dotted tag names are skipped by character class, not by a DOM tag list - the project has no per-language word lists, and the conservative rule cannot fall out of date.
+- **ANY mode keeps operator-token dropping and composes with expansion.** `dropStandaloneOperators` runs before the join in both modes; `buildExpandedFtsMatch` reuses `buildFtsMatch`, so expansion in ANY mode yields `(a OR b) OR "exp1"` - semantically the flat ANY superset, byte-stable code path.
+- **Alias terms carry the same `explicit_reference` confidence as titles.** The load-bearing discipline is the unique-match rule, not the term's spelling; downstream thresholds are unchanged.
+- **The audit sharding is a one-function writer fix plus per-ledger reader work, not a new abstraction.** `appendAuditRecord` is the single write chokepoint for items 1-6 of the card's inventory, so sharding there converts eight writer sites at once; the card's "make every reader merge" premise was checked against the live source and found mostly vacuous (see the premise corrections), leaving exactly one content reader to convert (`readRecordedSchemaPackDigest`) plus the state inventory's reachability probes.
+- **Fixed-name ledgers shard by file name, not by directory.** A `query-demand[.<device>].jsonl` family inside `Brain/log/` keeps every path-constant, state-surface descriptor and snapshot-diff listing valid; a per-device subdirectory would rename the surface and move the legacy file. The grammar base stays the old file stem, so `literalBase` semantics and the conflict-copy rule carry over unchanged.
+- **Prune and rewrite stay per shard.** Query-demand compaction caps the shard it just appended to; the maintenance-journal cap sweep rewrites only the local device's shard. Across N devices the combined ledger can hold N caps - the honest reading of "only rewrite this device's shard" the card's fix step 3 states - and a per-shard cap keeps a runaway device bounded.
+- **The guard test names files, not call sites.** Mirroring the hook-audit root guard, it scans the sources for `appendFileSync`/`openSync` append-mode writers and requires each file to reference the shard helpers or sit on an explicit allow-list whose entries carry reasons (dream-run files are per-run unique by construction). A new append site then fails the suite until it adopts the grammar or is allowed by name - a review gate, not a heuristic.
+- **Doctor reports conflicts; the merge stays manual.** The existing `sync-conflict-log` issue text already instructs the union+dedup merge; extending `LEDGER_DIRS` covers the newly sharded directories with the same one-exit-one-meaning code. Building the card's one-shot opt-in merge verb would duplicate the established recovery path for no row the manual merge cannot recover.
+
+## File changes
+
+New files:
+- `src/core/graph/unique-match.ts` (shared `resolveUniqueMatch`)
+- `tests/core/graph/unique-match.test.ts`
+
+Modified files:
+- `src/core/brain/link-graph/repair-lane.ts` (term index, unique-match resolution, `skip-ambiguous` action)
+- `src/core/brain/link-graph/alias-index.ts` (read as-is; the collector inverts the frozen alias-to-id map in memory to group alias terms per page key, so no modification is expected)
+- `src/core/brain/ingest/pre-extract.ts` (`uses` kind, JSX regex, relative-specifier binding, optional `ingestedFiles` argument, optional `resolvedTo` on seeds)
+- `src/core/brain/ingest/ingest.ts` (`runPreExtract` passes the manifest path set)
+- `src/core/brain/write-batch.ts` (request ID option, consult-before-commit, receipt in result)
+- `src/mcp/brain/write-batch-tools.ts` (`request_id` param and result fields)
+- `src/mcp/search-tools.ts` (`brain_search` description cue, `match_mode` schema param)
+- `src/core/search/fts.ts` (`FtsMatchMode`, `buildFtsMatch` options, `RunFtsOptions.matchMode`)
+- `src/core/search/pipeline/keyword-lane.ts`, `src/core/search/pipeline/request.ts`, `src/core/search/search.ts`, `src/core/search/types.ts` (threading)
+- `src/cli/search/verbs/query.ts` (`--match-mode` flag)
+- `src/core/reliability/audit.ts` (per-device week file name via `shardedFileName` + `resolveAppendShardId`)
+- Tests: `tests/core/brain/link-graph/repair-collect.test.ts`, `tests/core/brain/link-graph/repair-lane.test.ts`, `tests/core/brain/ingest/pre-extract.test.ts`, `tests/core/brain/ingest/ingest.test.ts`, `tests/core/brain/write-batch.test.ts`, `tests/mcp/brain-write-batch.test.ts`, `tests/core/search/fts.test.ts`, `tests/core/search/search.test.ts`, `tests/mcp/search-global.test.ts`, plus CLI test coverage for the flag
+- `src/core/brain/schema-integrity.ts` (digest reader lists shards through the grammar, skips conflict copies)
+- `src/core/brain/query-demand.ts`, `src/core/brain/recurrence.ts`, `src/core/brain/capture/telegram-capture.ts`, `src/core/brain/skill-proposals.ts` (per-device shard file names; merged read for query-demand)
+- `src/core/brain/paths.ts` (shard-aware path helpers for the fixed-name ledgers)
+- `src/core/brain/health/edit-history.ts`, `src/core/brain/git/store.ts`, `src/core/brain/maintenance/journal.ts` (per-device shards, merged reads, own-shard rewrites)
+- `src/core/state/surfaces.ts` (shard-aware reachability probe for sharded fixed-name ledgers)
+- `src/core/brain/doctor/store-integrity.ts` (`LEDGER_DIRS` gains the audit subdirectories and the remaining fixed-ledger roots)
+- Tests: `tests/core/reliability.test.ts`, `tests/core/brain/schema-integrity*.test.ts`, `tests/core/brain/query-demand*.test.ts`, `tests/core/brain/recurrence*.test.ts`, capture/skill-proposal/edit-history/git-store/maintenance-journal suites, `tests/core/brain/doctor/store-integrity*.test.ts`, plus the new source-layout guard suite
+- Docs touched by the release phase (not this node's commit): `docs/mcp.md`, `docs/cli-reference.md`
+
+## Risks and open questions
+
+- The mention scan is O(pages x terms) in the explicit-reference collector (already true today for the title-only loop); alias terms grow the term set. The existing vault-size bounds apply; if the collector's cost regresses on large vaults, the term scan can reuse the masked-body lowercasing it already computes once per source page.
+- `skip-ambiguous` decisions can list many pairs for a generic term shared by many pages; the existing `MIN_EXPLICIT_REFERENCE_TITLE_LENGTH` guard keeps the common noise out, and dry-run default means the operator sees the list before any apply.
+- JSX tag detection in a line grammar misclassifies contrived lines (a capitalized comparison operand, a multi-line JSX open); the module comment documents the heuristic limits, and the conservative skip rules keep false edges out at the cost of missing some usages.
+- The ledger scan on `lookupKey` is linear over shards; a batch retry on a vault with heavy idempotency traffic pays the same scan the signal writers already pay.
+- The audit week scan is unchanged for readers that merge (one directory listing per read); `readRecordedSchemaPackDigest` already read every `.jsonl` in the directory, so the shard grammar only tightens what it accepts.
+- The maintenance-journal cap becomes per shard: N devices can hold up to N caps of rows in total. This is the stated per-device-shard semantics, not a regression; a single-device vault keeps exactly today's cap.
+- The guard test's allow-list is a reviewed set: a new bare append site fails the suite by design until it adopts the grammar or is allowed by name with a reason.
+- Open question resolved during implementation: the exact export home for `resolveUniqueMatch` (module placement must respect the codebase's import-direction conventions between `src/core/graph/` and `src/core/brain/`).
+
+## Premise verification for t_774dea61 (owner-mandated addition)
+
+The card was verified against the live source the same way the six picked cards were. Verified as written: the `appendAuditRecord` anchor (`src/core/reliability/audit.ts:15-34`, the week name built at line 21); the `ledger-shards.ts` grammar (`<base>[.<shardId>].<ext>`, `shardedFileName`, `resolveAppendShardId`, conflict-copy rejection, merged reads); `O2B_DEVICE_ID` exists (`src/core/config.ts:466`, read by `resolveDeviceId`, which `resolveAppendShardId` delegates to; `tests/setup.ts:55-57` already pins it to the empty string as the test preload default); every writer-inventory line anchor (items 1-13 plus the two low-risk sites and all seven hook audit sites); and the already-sharded list (daily log, metrics `metrics.ts:94-96`, preference audit via `listShardedFiles`/`mergeShardedRows`, lineage ledger, truth claims and decision receipts with their own conflict-skipping shard parsers, idempotency ledger and continuity store via `ledger-shards.ts` imports). Corrections recorded against the card:
+
+- **"Every reader of these audit directories" (fix step 2) overstates the live reader set.** The audit week directories have almost no content readers: `Brain/log/session-lifecycle/`, `hygiene/`, `secret-custody/` and `watchdog/` have none in `src/` (the doctor's orphan-session check reads the already-sharded daily Brain log, not the audit copy; the hook-audit reader is an existence probe only). The one content reader is `readRecordedSchemaPackDigest` (`schema-integrity.ts`), which already scans every `.jsonl` in the directory and picks the newest record by timestamp - it needs the grammar's conflict-copy exclusion, not a merge rewrite. The reader-merge work is therefore one reader plus the state inventory's reachability probes, not a sweep of eight consumers.
+- **The doctor conflict sweep already exists** (`syncConflictLogCheck` in `src/core/brain/doctor/store-integrity.ts` over `LEDGER_DIRS`) and its issue text already carries the manual merge instruction; the card's step 4 reduces to extending the swept directory list, and its "one-shot, opt-in merge" is deferred (see Out of scope) rather than built.
+- **The card's items 9 and 10 (capture-decisions, verifier-rejections) have no reader in `src/`**, so their conversion is writer-side only plus the state inventory's probe for capture-decisions.
+- The `.stignore-shared` claim about which `.open-second-brain/` entries sync is operator infrastructure outside the repository and is taken as given; it changes no code path (the grammar's conflict-copy rule holds regardless).
diff --git a/docs/brainstorm/integrity-control-agent-memory-surface/plan.md b/docs/brainstorm/integrity-control-agent-memory-surface/plan.md
new file mode 100644
index 00000000..2b821b74
--- /dev/null
+++ b/docs/brainstorm/integrity-control-agent-memory-surface/plan.md
@@ -0,0 +1,68 @@
+# Integrity and control of the agent-facing memory surface - implementation plan
+
+## Tasks
+
+### Task 1: Shared unique-match resolver
+- **Files**: `src/core/graph/unique-match.ts` (new), `tests/core/graph/unique-match.test.ts` (new)
+- **Acceptance**: `resolveUniqueMatch` returns the typed three-status outcome (`unique` with the single target, `ambiguous` with every candidate in a deterministic order, `none` for an empty candidate list); a repeated identical candidate is deduped before the decision so one page naming a term twice never reads as ambiguity.
+- **Depends on**: none
+
+### Task 2: Repair-lane unique-match mention-to-wikilink resolution (t_ec6b155d)
+- **Files**: `src/core/brain/link-graph/repair-lane.ts`, `tests/core/brain/link-graph/repair-collect.test.ts`, `tests/core/brain/link-graph/repair-lane.test.ts`
+- **Acceptance**: the explicit-reference collector pools title and `buildAliasIndex` alias terms per corpus page; a mention term proposes a candidate only when exactly one corpus page key carries it; a term carried by two pages produces `skip-ambiguous` decisions (new `RepairAction` member) in the lane's decision list and no candidates; dry-run and apply behavior, ordering, confidence (`explicit_reference`), threshold, write cap and idempotent rerun are unchanged; an alias mention proposes the same 0.9-confidence candidate a title mention would.
+- **Depends on**: Task 1
+
+### Task 3: Pre-extract relative-import binding (t_2356dace)
+- **Files**: `src/core/brain/ingest/pre-extract.ts`, `src/core/brain/ingest/ingest.ts`, `tests/core/brain/ingest/pre-extract.test.ts`, `tests/core/brain/ingest/ingest.test.ts`
+- **Acceptance**: `preExtractCodeStructure` takes optional `{ ingestedFiles }`; a TS/JS `./`- or `../`-specifier and a Python leading-dot `from .x import` whose probed candidates (joined path, each supported extension, `/index` + each supported extension) contain exactly one ingested file carry `resolvedTo` with that canonical vault-relative path; zero or multiple ingested candidates, a bare package specifier, and a call without `ingestedFiles` all leave seeds byte-identical to today; `ingest.runPreExtract` passes the manifest's canonical path set.
+- **Depends on**: Task 1
+
+### Task 4: JSX component-usage edge kind (t_998aa4e6)
+- **Files**: `src/core/brain/ingest/pre-extract.ts`, `tests/core/brain/ingest/pre-extract.test.ts`
+- **Acceptance**: a .tsx/.jsx line whose opening tag matches the structural rule (name immediately after `<`, preceding character not an identifier or `.`, name in `[A-Z_$][A-Za-z0-9_$]*`) yields a `uses` edge from the source path to the component name; `<div>`, `<nav>`, `<Nav.Item>` and generic type arguments (`Array<Foo>`) produce nothing; the widened kind union dedupes and sorts deterministically through the existing kind-aware `edgeKey`.
+- **Depends on**: Task 3 (same file, `pre-extract.ts`; the `uses` kind and the relative-import binding land on one coherent grammar)
+
+### Task 5: Write-batch client request ID and durable receipt (t_b34439d9)
+- **Files**: `src/core/brain/write-batch.ts`, `src/mcp/brain/write-batch-tools.ts`, `tests/core/brain/write-batch.test.ts`, `tests/mcp/brain-write-batch.test.ts`
+- **Acceptance**: `applyWriteBatch` accepts optional `requestId`; with no request ID behavior is byte-identical; a repeated ID with the same semantic payload returns the retained original result (ledger `ref`) marked as a duplicate receipt and writes nothing; a repeated ID with a different payload throws `IdempotencyPayloadMismatchError`; a fresh ID records the key with the receipt in `ref` after commit; the MCP `brain_write_batch` accepts `request_id` and returns `request_id` plus the receipt status; invalid IDs (empty, over 256 chars) surface the ledger's own named error before any write.
+- **Depends on**: none
+
+### Task 6: brain_search when-to-search cue (t_cb1e9d3d)
+- **Files**: `src/mcp/search-tools.ts`, MCP search test coverage for the description
+- **Acceptance**: the `brain_search` description carries exactly one added sentence that names `brain_recall_gate` as the classifier to consult before widening recall; no fan-out counts, no parallel-search language, and the recall-inject header text is untouched.
+- **Depends on**: none
+
+### Task 7: Caller-selectable FTS match mode (t_c5326ece)
+- **Files**: `src/core/search/fts.ts`, `src/core/search/types.ts`, `src/core/search/pipeline/request.ts`, `src/core/search/pipeline/keyword-lane.ts`, `src/core/search/search.ts`, `src/mcp/search-tools.ts`, `src/cli/search/verbs/query.ts`, `tests/core/search/fts.test.ts`, `tests/core/search/search.test.ts`, `tests/mcp/search-global.test.ts`, CLI flag test coverage
+- **Acceptance**: `buildFtsMatch` with `any` OR-joins the quoted tokens and still drops caller-typed `AND`/`OR`/`NOT`/`NEAR` tokens; default `all` output is byte-identical to today, including empty-input and single-token cases; the mode threads from `SearchOptions` through the request resolution and keyword lane; MCP `match_mode` validates the enum and rejects anything else; the CLI `--match-mode` flag mirrors it; expansion composition and the derived-term callers (`second-pass.ts`, `evidence-verification.ts`) are unchanged.
+- **Depends on**: none
+
+### Task 8: Per-device audit week files (t_774dea61, writer half)
+- **Files**: `src/core/reliability/audit.ts`, `tests/core/reliability.test.ts`
+- **Acceptance**: `appendAuditRecord` names its file `shardedFileName(isoWeekLabel(timestamp), resolveAppendShardId(), "jsonl")`; two writes with `O2B_DEVICE_ID=a` and `=b` in one week produce `<week>.a.jsonl` and `<week>.b.jsonl` and no process writes the other device's file; `O2B_DEVICE_ID=""` (the test preload default) keeps the legacy `<week>.jsonl` name and byte-identical behavior; the returned path is the file actually written; redaction, timestamp validation and the fsync discipline are unchanged.
+- **Depends on**: none
+
+### Task 9: Audit-reader and probe conversion (t_774dea61, reader half)
+- **Files**: `src/core/brain/schema-integrity.ts`, `src/core/state/surfaces.ts`, plus their test suites
+- **Acceptance**: `readRecordedSchemaPackDigest` lists the schema-mutation directory through `listShardedFiles` with the week grammar, so device shards merge (newest record still wins by its own timestamp) and `*.sync-conflict-*` copies are never parsed; the state inventory's reachability probe for a sharded fixed-name ledger reports the surface present when the legacy name or any shard of its grammar exists, and absent only when neither does; single-file vaults read exactly as before.
+- **Depends on**: Task 8 (same grammar), Task 10-11 for the probe's ledger set (landed together with them)
+
+### Task 10: Fixed-name ledgers in `Brain/log/` (t_774dea61, items 7-10)
+- **Files**: `src/core/brain/paths.ts`, `src/core/brain/query-demand.ts`, `src/core/brain/recurrence.ts`, `src/core/brain/capture/telegram-capture.ts`, `src/core/brain/skill-proposals.ts`, plus their test suites
+- **Acceptance**: query-demand, recurrence-support, capture-decisions and verifier-rejections write `<base>[.<deviceId>].jsonl` through the shard grammar; `readQueryDemand` returns the union of all shards (and the legacy file) in its existing ts-sorted order; query-demand compaction caps only the shard just appended; two devices produce two files and a merged read sees both; `O2B_DEVICE_ID=""` keeps every name and byte identical.
+- **Depends on**: Task 8
+
+### Task 11: Remaining fixed-name ledgers (t_774dea61, items 11-13)
+- **Files**: `src/core/brain/health/edit-history.ts`, `src/core/brain/git/store.ts`, `src/core/brain/maintenance/journal.ts`, plus their test suites
+- **Acceptance**: `pref-<slug>.history`, per-repo `commits` and `maintenance-runs` write per-device shards; `readEditHistory`, the git record read (and its dedup-before-append) and `listJournal`/`consecutiveTaskFailures` merge all shards deterministically with single-shard file order preserved; `sweepJournal` rewrites only the local device's shard to the cap; the git append lock moves to the device's own shard path; two-device tests cover each.
+- **Depends on**: Task 8
+
+### Task 12: Doctor conflict sweep extension and append guard (t_774dea61)
+- **Files**: `src/core/brain/doctor/store-integrity.ts`, plus the doctor test suite and a new source-layout guard suite
+- **Acceptance**: `LEDGER_DIRS` also sweeps `Brain/log/{session-lifecycle,hygiene,schema-mutations,secret-custody,watchdog}`, the hook-audit and watchdog-audit roots, the skill-proposal ledger directory, the per-repo git store directories and `Brain/preferences/`, reporting every `*.sync-conflict-*` copy with the existing merge instruction; a guard test fails when a source file appends via `appendFileSync`/`openSync(..., "a")` without using the shard helpers, with a named allow-list (per-run-unique dream-run files and the doctor repair appending to them).
+- **Depends on**: Tasks 8-11
+
+### Task 13: Wave integration check
+- **Files**: none (verification only)
+- **Acceptance**: `bun run typecheck`, `bun run lint`, and the touched test files all pass; the seven cards' behaviors coexist (a pre-extract result can carry `uses` edges with `resolvedTo` bindings; a repair-lane dry run with alias terms; a batch retry returning a duplicate receipt; a two-device audit week read back merged) without interfering defaults.
+- **Depends on**: Tasks 1-7, 8-12
diff --git a/docs/brainstorm/integrity-control-agent-memory-surface/variants.md b/docs/brainstorm/integrity-control-agent-memory-surface/variants.md
new file mode 100644
index 00000000..7108e734
--- /dev/null
+++ b/docs/brainstorm/integrity-control-agent-memory-surface/variants.md
@@ -0,0 +1,64 @@
+# Variants - integrity-control-agent-memory-surface
+
+Consultant: Claude Code (primary; exit 0, three parseable variants plus a recommendation). The fallback consultant did not run. Prompt and raw output: `cli-output/prompt.md`, `cli-output/claude.md`. Premise verification ran before the consultant; the verified premises embedded in the prompt are recorded in `design.md`.
+
+## Variants (verbatim consultant output)
+
+### Variant 1: Narrowest seams, per-card local logic
+- **Approach**: Each card lands as an isolated edit at its existing call site with no shared abstraction. Card 1 adds a title-plus-alias term pool and an inline "exactly one page carries this term" filter inside `collectRepairCandidates`; Card 2 adds a post-pass in `runPreExtract` that probes relative specifiers against the manifest path set and fills an optional `resolvedTo` on the seed; Card 3 adds one JSX opening-tag regex and a `uses` kind; Card 4 calls `rememberKey` from `applyWriteBatch` with a `write_batch` record whose `ref` carries the receipt; Card 5 is one sentence; Card 6 threads a `matchMode` boolean-ish flag through `SearchOptions` to `buildFtsMatch`.
+- **Trade-offs**:
+ - Pro: smallest diff, every default byte-identical, each card reviewable on its own.
+ - Pro: no new modules, no new public types beyond the widened union and optional fields.
+ - Con: the unique-match discipline is written twice (pages in Card 1, files in Card 2) with two chances to diverge.
+ - Con: ambiguous terms and unbound specifiers tend to vanish silently unless each site remembers to count and report them, which strains the "nothing degrades silently" convention.
+ - Con: Card 4 records the ledger entry after the commit, leaving a crash window between apply and remember that a retry can double-apply through.
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 2: Shared unique-resolution primitive with named refusals
+- **Approach**: Introduce one small pure module (a term index plus a resolver that returns `unique | ambiguous | none` with the candidate list) and consume it from both the repair-lane term resolver (Card 1, terms pooled from titles and `buildAliasIndex`) and the pre-extract specifier binder (Card 2, terms are extension-probed paths over the ingested-file set passed in as an explicit input). Both surfaces carry the refusal counts outward: the repair report gains an ambiguous-terms section and the pre-extract result gains an `unbound` list with reasons. Card 4 reuses `rememberKey` unchanged with the batch receipt in `ref`, consulted before any commit and recorded inside the batch's atomic unit so the receipt and the writes land together; Card 6 defines one `FtsMatchMode` type shared by `buildFtsMatch` and `buildExpandedFtsMatch`; Cards 3 and 5 stay local.
+- **Trade-offs**:
+ - Pro: one tested discipline for "bind only when exactly one target matches", so Cards 1 and 2 cannot drift.
+ - Pro: honesty by construction, since the resolver returns a typed status and callers must map every status to something visible.
+ - Pro: no new dependencies, no new machinery beyond a pure function module, determinism is trivial to prove because the resolver takes the index as an argument.
+ - Con: a new cross-cutting module means a broader test surface and one more thing for the link-graph and ingest owners to agree on.
+ - Con: putting the ledger record inside the batch commit touches the write-batch kernel's atomic path, which is the most sensitive code in the wave.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Index-first candidate tables and a separate receipt store
+- **Approach**: Build explicit reusable indexes as first-class inputs: `loadPages` returns a corpus term index that the repair lane, `findUnlinkedMentions` and future consumers share, and `ingestSource` builds an ingested-file index from the manifest and hands it to pre-extract. Cards 1 and 2 produce a full candidate table (every term with all matching targets and a resolution status) as an intermediate artifact surfaced in dry-run reports, and binding becomes a filter over that table. Card 4 gets a dedicated receipt store keyed by request ID rather than a ledger record, and Card 6 replaces the boolean with a parsed query object carrying tokens and mode.
+- **Trade-offs**:
+ - Pro: richest operator visibility, and the shared indexes would let the target-centric mention scanner converge with the corpus-wide path later.
+ - Pro: the candidate table makes ambiguity a reported fact instead of a dropped edge.
+ - Con: changes the shape of `loadPages` output and the pre-extract input contract, the widest blast radius in the wave.
+ - Con: a separate receipt store duplicates what the idempotency ledger already does and drifts from the card's stated scope of extending `rememberKey` semantics; it also edges toward the struck durable-queue territory.
+ - Con: the parsed query object for Card 6 is more than the card asks for and risks touching the two derived-term callers.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 2
+**Rationale**: Variant 2 keeps every default byte-identical and adds no machinery, yet it gives the two resolution cards one shared, typed unique-match discipline so ambiguity is always named rather than silently dropped, which is the project's core honesty rule. It reuses the existing idempotency ledger exactly as the validator scoped Card 4, while closing the apply-then-remember crash window that Variant 1 leaves open. Variant 3 buys visibility the cards did not ask for at the cost of public-shape changes and a parallel receipt store the constraints explicitly steer away from.
+
+## Orchestrator decision
+
+Variant 2 is adopted, with two documented refinements:
+
+1. **Card 4 sequencing** - the consultant placed the ledger record "inside the batch's atomic unit". No cross-file atomic unit exists: the ledger is a JSONL store separate from the note files the batch writes. The implementation follows the pattern `src/core/brain/signal.ts` already ships and the ledger's own documentation accepts - `lookupKey` consult before any commit, `rememberKey` after a successful commit with its re-check under the shard lock. The residual crash window between commit and record is the one the ledger already documents; the card's target, a sequential retry after a lost response, stays fully deduped because the record is durable before the retry runs.
+2. **Card 2 refusal visibility** - the consultant's separate `unbound` list with reasons on the pre-extract result is trimmed. A seed whose binding is refused keeps its raw specifier, which is itself the visible conservative outcome; an aggregate list would restate the seeds. Card 1 keeps named refusals because there the refusal genuinely erases output: the new `skip-ambiguous` action in the existing decision list is what tells the operator why no edge was proposed.
+
+Variant 3 was rejected for the reasons the consultant gives: it changes public shapes (`loadPages` output, pre-extract input contract) and duplicates the ledger with a parallel receipt store, against the card's explicit "extend rememberKey semantics" scope. Variant 1 was rejected because the unique-match discipline in two places is exactly the drift the shared resolver prevents, and its silent-ambiguity tendency conflicts with the project's nothing-degrades-silently rule.
+
+## Appendix: owner-mandated addition t_774dea61 (mid-wave)
+
+The owner added triage card t_774dea61 (priority 4, "Per-device file names for Brain logs written from multiple synced machines") to the picked scope after the design node ran; this wave ships it in the same PR as the seventh feature. No second consultant run was made: the card arrives with a proposed fix of its own, and the live-source premise check below found the proposal sound with three corrections, so the adopted approach is the card's own fix, trimmed to the established conventions of `src/core/brain/ledger-shards.ts`.
+
+**Premise verification result.** Every anchor held: `appendAuditRecord` (`src/core/reliability/audit.ts:15-34`, name built at line 21); the `ledger-shards.ts` grammar and helpers; `O2B_DEVICE_ID` (exists at `src/core/config.ts:466`, read by `resolveDeviceId`, delegated to by `resolveAppendShardId`; `tests/setup.ts` already pins it to `""` as the test preload default, exactly as the card's criterion 6 assumes); all thirteen writer-inventory line anchors plus the two low-risk sites and seven hook audit sites; and the already-sharded list. No inventory item turned out to be already sharded, and no named env var needed correction.
+
+**Corrections applied to the card's fix.**
+
+1. Fix step 2's premise - "make every reader of these audit directories merge" - overstates the reader set: the audit week directories have almost no content readers (session-lifecycle, hygiene, secret-custody, watchdog have none; the doctor's orphan-session check reads the already-sharded daily Brain log; the hook-audit reader probes existence only). The real reader work is one function (`readRecordedSchemaPackDigest`, which already scans every `.jsonl` and needs the conflict-copy exclusion) and the state inventory's reachability probes for the sharded fixed-name ledgers.
+2. The doctor conflict sweep already exists (`syncConflictLogCheck` over `LEDGER_DIRS`, message carrying the manual union+dedup instruction); the card's step 4 reduces to extending the swept directory list. The "one-shot, opt-in merge" verb is deferred: the ledger-shards contract and the existing doctor message define merge-by-hand as the established recovery path, and an automatic merge is operator-facing machinery the wave does not build. Recorded in design.md's Out of scope.
+3. Items 9 and 10 (capture-decisions, verifier-rejections) have no reader in `src/`, so their conversion is writer-side plus the capture-decisions state probe.
+
+The card's criterion 8 (CHANGELOG entry and docs) is satisfied by the osb-pr-prepare docs phase inside the PR, per this run's boundaries, and is noted as deferred there.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index ecd0f2bb..d2d80af5 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -631,7 +631,7 @@ Supersession is now consumer-aware: context packs inject only the tip of a super
```text
o2b brain batch-plan gains --src-subpath <rel> (scope a monorepo ingest to one subtree; escaping the source root is a typed error, and one crossing a submodule or nested checkout is refused outright; a subpath below a directory the repository itself ignores plans nothing and says so as an ignore warning), --exclude <pattern> (gitignore-style patterns through the shared ignore engine), and --reconcile (diff the plan's dispatched set against checkpoint completions and name every silently-lost source; a complete plan reports an explicit empty gap)
-o2b brain pre-extract <file> [--json] - deterministic no-LLM code-structure extraction (classes, functions, imports, inheritance edges as JSON entity/edge seeds) for TypeScript, JavaScript, and Python; unknown extensions report extracted:false with a reason, never an empty success
+o2b brain pre-extract <file> [--json] - deterministic no-LLM code-structure extraction (classes, functions, imports, inheritance edges, and in .tsx/.jsx files uses edges to the components opening tags name, as JSON entity/edge seeds) for TypeScript, JavaScript, and Python; relative imports are bound to files (resolved_to) only on the ingest path, which has the content manifest; unknown extensions report extracted:false with a reason, never an empty success
o2b brain scan-citations [--strict] - promote structural [Source: <name>, YYYY-MM-DD] markers in note prose into dated source-citation events on the temporal timeline; dedup on normalized name + date, malformed markers are reported and skipped (--strict exits nonzero on them)
o2b brain doctor gains --repair (preview targeted fixes for doctor-detected classes: dangling workrun checkpoints, dead evidence links; dry-run default) and --repair --apply (perform the fixes idempotently, one typed doctor-repair event each); unfixable classes are reported needs-review; plain doctor and --strict stay read-only
o2b brain status one consolidated operator snapshot: doctor, semantic health, hygiene, stale scan, review queue depth, active profile, and state-file health; every problem line carries the exact next command from the shared diagnostics-signal registry; healthy vaults print a compact all-clear
@@ -716,7 +716,7 @@ byte-identical when unset.
o2b brain telegram-capture run | catchup - explicit inbound capture runner (fetch-based long-poll getUpdates); gated by telegram_bot_token (env TELEGRAM_BOT_TOKEN) and the telegram_chat_allowlist chat-id allowlist (env TELEGRAM_CHAT_ALLOWLIST, empty accepts nothing); each accepted message becomes one staged capture note under Brain/captures/ with provenance; rejected updates log one decision each; catchup replays captures since the last acknowledged one; a missing token is a typed startup error
o2b brain inbox-drain [--apply] - walk staged captures, classify each structurally (URL-shaped body -> source reference, explicit obligation marker -> task, otherwise atomic idea), route on apply (source ingest, note in captured/, obligation open), archive processed captures, and report every item with action and reason; dry-run default writes nothing; rerun after apply is a no-op
o2b brain diarize <entity> [--json] - entity profile skeleton plus one needs-llm-step envelope; the stated-vs-evidenced section is computed deterministically (stated claims versus evidence frequency and recency), every line carrying an evidence identity; unknown entity is a typed error
-o2b brain repair-lane [--apply --confirm "apply repair"] - propose link-graph edges ordered by identity strength (explicit references, session continuity, same-topic evidence; inferred opt-in) under a confidence threshold and a hard per-run write cap; dry-run default; reruns after apply converge to zero writes. --apply plans first and then runs the paired graph-efficacy holdout harness over every edge that plan proposes, taking anchor and target from the edge itself: it reports graph lift (targets reachable only through the graph) apart from direct recall (targets already a 1-hop neighbour) and refuses the apply, writing nothing, when any target resolves to no durable-memory note or hydrates into no evidence. The refusal names the failing edges with their verdict and resolves its exit through the registered repair-holdout-unresolved diagnostic; --json carries the counts in an additive holdout object beside next_command. Dry-run does not evaluate the gate and its bytes are unchanged - it already names each unresolvable endpoint as a skip-missing-target decision
+o2b brain repair-lane [--apply --confirm "apply repair"] - propose link-graph edges ordered by identity strength (explicit references, session continuity, same-topic evidence; inferred opt-in) under a confidence threshold and a hard per-run write cap; dry-run default; reruns after apply converge to zero writes. --apply plans first and then runs the paired graph-efficacy holdout harness over every edge that plan proposes, taking anchor and target from the edge itself: it reports graph lift (targets reachable only through the graph) apart from direct recall (targets already a 1-hop neighbour) and refuses the apply, writing nothing, when any target resolves to no durable-memory note or hydrates into no evidence. The refusal names the failing edges with their verdict and resolves its exit through the registered repair-holdout-unresolved diagnostic; --json carries the counts in an additive holdout object beside next_command. Dry-run does not evaluate the gate and its bytes are unchanged - it already names each unresolvable endpoint as a skip-missing-target decision. Explicit references pool page titles and frontmatter aliases; a mentioned term that exactly one page carries proposes an edge, and a term several pages carry proposes none - each (mentioning page, carrying page) pair is reported as a skip-ambiguous decision, never written, never counted against the write cap and never sent to the holdout gate
o2b brain orphan-repair [--apply --confirm "apply orphan repair"] - detach dangling session references from observation signals (the findings `o2b brain doctor` reports as `orphan-session-ref`, each naming this verb on its `fix` field); --apply removes ONLY the `session_ref` key from each signal's frontmatter, keeping the observation body, topic and every other field, and quotes the detached value in the report; dry-run default writes nothing, the exact confirmation phrase is required for apply, a hard per-run write cap bounds the run, and a rerun after apply converges to zero writes; the doctor pass never repairs
o2b brain design-note <topic> [--payload <json> | --payload-file <path>] [--agent <name>] [--json] - the one-shot sibling of `o2b brain panel`. Without a payload it is read-only: it grounds the topic in the vault's tension records, decision records and truth projections and prints the single needs-llm-step envelope the calling agent answers, naming any store the vault holds nothing in (which is not the same as a store that matched nothing). With a payload it validates the written note and commits it as Brain/decisions/design-<date>-<topic>.md. The note must weigh named alternatives and mark EXACTLY ONE recommended: zero and two-plus are both refused, and the refusal states the count. A second note for the same topic on the same day is refused, never overwritten
o2b brain skill-proposals page-candidates [--json] - read-only: gate the vault's user pages on the page-meta trio (core tier, non-stale lifecycle, high confidence) and an observed-reuse floor, skip any page an installed skill already covers, and return one needs-llm-step envelope per admitted page plus every skip with its reason
@@ -1326,8 +1326,8 @@ reported per row and counted in the summary line - 17 of the 45 can.
Only two overrides move anything: `OPEN_SECOND_BRAIN_SEARCH_DB` /
`search_db_path` relocate the search store and everything that follows it,
-and `O2B_DEVICE_ID` / `device_id` select which shard of the log and the
-truth ledger this machine writes. The second is reported as provenance and
+and `O2B_DEVICE_ID` / `device_id` select which shard of the log, the
+truth ledger and every other per-device ledger this machine writes. The second is reported as provenance and
not substituted into the path, because it names a file inside a directory
the inventory reports at directory granularity. Every other row prints `at
its only location - nothing can move it`.
@@ -1508,6 +1508,8 @@ o2b search "<query>" Hybrid full-text + semantic search across the vaul
CJK text is expanded for FTS recall without polluting returned content
--profile fast|balanced|thorough picks a recall preset; no profile leaves ranking unchanged
--disclosure cards returns compact cards (path, title, score, snippet, line range) instead of full content; default full
+ --match-mode all|any picks the keyword match breadth: all (default) requires every
+ term, any matches a note carrying any one term; typed AND/OR/NOT/NEAR stay dropped
o2b search expand Drill one card: --chunk <id> (printed on the card) returns the fuller note and the raw chunk transcript, paged by --cursor; read-only
o2b search feedback Record explicit recall feedback for one result
(--query Q --result <path> --verdict up|down; one JSON event file
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 78c5824f..e854998a 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -828,9 +828,24 @@ place. The differ used to carry a pattern of its own, which is how it
came to predate sharding and classify both the per-device markdown and
the machine-primary JSONL as `other`, mislabelling the surface a
`rollback --dry-run` is most likely to be showing. Ledgers and
-subdirectories under `log/` (`capture-decisions.jsonl`, `dream-runs/`,
+subdirectories under `log/` (`capture-decisions[.<deviceId>].jsonl`, `dream-runs/`,
`pref-audit/`) are not days of the log and stay in the catch-all class.
+Every append-only ledger that several synced machines write keeps one
+file per device, named `<stem>[.<deviceId>].jsonl`: the fixed-name
+`Brain/log/` ledgers (`query-demand`, `recurrence-support`,
+`capture-decisions`), the verifier-rejection ledger under
+`Brain/skill-proposals/`, each preference's `pref-<slug>.history`, each
+repository's git `commits` and the maintenance journal
+`.open-second-brain/maintenance-runs` (merged by row time on read). The
+ISO-week audit directories (`session-lifecycle/`, `hygiene/`,
+`secret-custody/`, `schema-mutations/`, `watchdog/` and the hook and
+watchdog audit roots under `.open-second-brain/`) write
+`<YYYY-Www>[.<deviceId>].jsonl`. `O2B_DEVICE_ID` / `device_id` select the
+shard; the empty device id writes the legacy un-suffixed name, and a
+legacy file stays readable without any migration. The full contract is in
+[`observability.md`](observability.md#the-per-device-shard-rule).
+
## Primary agent declaration
`Brain/_brain.yaml` carries an optional `primary_agent: <name> | null`
@@ -1242,7 +1257,9 @@ present. `o2b brain git ingest <repo-path>` walks a worktree with a
sanitized read-only reader (fixed argv, full-40-hex sha validation on
everything a caller could supply) and lands commits, tags, and
release ranges as structured records in
-`Brain/projects/git/<repo-key>/commits.jsonl`. Typed edges are record
+`Brain/projects/git/<repo-key>/commits[.<deviceId>].jsonl` (one shard per
+device, merged by record time on read, one copy of each commit and of
+each tag even when two devices ingested the same history). Typed edges are record
fields - touched files, author, the carrying release attributed by
chronological tag ranges - and a watermark bounds every later run to
`<last>..HEAD`, so incremental ingest is duplicate-free by
diff --git a/docs/mcp.md b/docs/mcp.md
index d7efa5d8..61db7f01 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -211,7 +211,7 @@ flags for a narrower per-process full server.
| `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`. | `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, and a selectable recall `profile` (`fast \| balanced \| thorough`). | `query` |
+| `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`), and an FTS `match_mode` (`all` \| `any`). | `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`. | `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. | `max_tokens` |
@@ -1576,3 +1576,57 @@ log line is machine-composed rather than authored.
(`embeddings-backlog`, `embeddings-census-unrecorded`,
`embeddings-health-unmeasured`) that is fail-soft: an unrecorded census
lands in `uncertain`, never in healthy.
+- Since v1.63.0 `brain_write_batch` accepts an optional string `request_id`
+ (at most 256 characters after trimming) that makes a retried batch apply
+ once. With it, the result gains `request_id` and `receipt`:
+ - `applied`: this call committed the batch and recorded the ID.
+ - `duplicate`: the same ID with the same operations was already recorded.
+ Every other field is the retained result of the call that committed;
+ nothing is written, re-validated or linted.
+ - `concurrent_duplicate`: this call committed, but a concurrent call
+ recorded the same ID and payload in between. Both writes landed and the
+ fields are this call's own.
+ - `payload_conflict`: this call committed, but a concurrent call recorded
+ the same ID for a different payload in between. The writes landed and
+ this call's receipt is not recorded; a `receipt_note` says so and that
+ the batch must never be resent under a new `request_id`.
+
+ The same ID with different operations, found before any write, is refused
+ with `INVALID_PARAMS` and the idempotency ledger's mismatch message; a
+ blank ID, one over the cap or a non-string value is refused with
+ `INVALID_PARAMS` before any write. The receipt is recorded in the
+ idempotency ledger after the commit, with its log paths vault-relative
+ (a duplicate rebuilds them under the vault serving the retry), under its
+ own `write_batch` key space, so a request ID never collides with a
+ `brain_feedback` or `brain_apply_evidence` `idempotency_key` of the same
+ text. The one exception is a peer still running v1.62.0, which ignores the
+ key space: there a feedback key equal to a synced batch request ID is
+ refused with the named idempotency mismatch error, never silently
+ deduplicated, until that peer is upgraded. Without `request_id` none of
+ these keys appears and the payload is unchanged.
+- Since v1.63.0 `brain_search` accepts `match_mode`: `all` (the default)
+ requires every term, `any` matches a document carrying any one term.
+ Caller-typed `AND` / `OR` / `NOT` / `NEAR` tokens are dropped in both
+ modes, and an `any` search is cached apart from an `all` one. `match_mode`
+ (`all` | `any`) and `disclosure` (`full` | `cards`) are literal enums; any
+ other value is refused with `INVALID_PARAMS` naming the accepted values.
+ The `brain_search` description now ends with a when-to-search cue: when a
+ query misses, consult `brain_recall_gate` before widening recall.
+- Since v1.63.0 `brain_ingest_source` with `pre_extract` adds `uses` edges
+ from `.tsx` / `.jsx` sources to the components their opening tags name,
+ and an `imports` seed whose relative specifier (`./` or `../` in
+ TypeScript and JavaScript, leading-dot in Python) names exactly one
+ ingested file carries `resolved_to`, that file's vault-relative path. A
+ specifier that climbs above the vault root, or matches no file or several,
+ binds nothing; `to` always keeps the raw specifier.
+- Since v1.63.0 the `brain_doctor` `sync-conflict-log` finding also sweeps
+ the audit week directories (`Brain/log/session-lifecycle/`, `hygiene/`,
+ `secret-custody/`, `watchdog/`, `schema-mutations/`), the hook-audit and
+ watchdog-audit directories under `.open-second-brain/`,
+ `Brain/skill-proposals/`, `Brain/preferences/` and each repository
+ directory under `Brain/projects/git/`; a directory it cannot list lands in
+ `uncertain`. In the directories that also hold whole files, a conflict copy
+ that is not a `.jsonl` shard (a proposal file, a preference note, a git
+ `state.json`) keeps the same code with the whole-file remedy: compare it
+ with the original, keep the right version by hand, then delete the copy.
+ The maintenance journal's `.open-second-brain/` root is not swept.
diff --git a/docs/observability.md b/docs/observability.md
index faaa1804..1290fb2a 100644
--- a/docs/observability.md
+++ b/docs/observability.md
@@ -11,7 +11,9 @@ Open Second Brain records what it did - learning events, recall decisions, serve
| Idempotency ledger | `Brain/logs/idempotency/<month>[.<device-id>].jsonl` | `rememberKey()` in `src/core/brain/idempotency-ledger.ts` | one `key -> content hash` record per line |
| Preference mutation audit | `Brain/log/pref-audit/<pref-id>/device[.<device-id>].jsonl` (legacy flat `Brain/log/pref-audit/<pref-id>[.<device-id>].jsonl` still read) | `appendPrefAudit()` in `src/core/brain/pref-audit.ts` | one JSON record per line |
| Session lineage ledger | `Brain/.state/session-lineage[.<device-id>].jsonl` (+ `session-lineage-gaps[.<device-id>].jsonl`) | `recordLineageObservation()` in `src/core/brain/lineage/ledger.ts` | one JSON record per line, sequence-numbered and hash-chained per file |
-| Session lifecycle audit | `Brain/log/session-lifecycle/` | `captureSessionLifecycleEvent()` in `src/core/brain/session-lifecycle.ts` | JSONL audit rows |
+| 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` |
| 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`) |
@@ -28,6 +30,8 @@ Every reader merges every shard it finds, in the one order all devices agree on:
Two names are never shards. A `*.sync-conflict-*` copy is excluded from every listing even when its middle segment fits the shard-id shape (the `sync-conflict` prefix is reserved in the device-id validator for the same reason), and `o2b brain doctor` reports any leftover copy under any ledger directory as `sync-conflict-log`, naming the directory so the union+dedup merge has an address. A name whose base does not match the ledger's own layout is not that ledger's file at all — bases go into the grammar as patterns, or as escaped literals where the base is a value (a preference id may legitimately contain a dot).
+The audit weeks and the fixed-name ledgers adopted the grammar in 1.63.0. Their readers merge every shard: the maintenance journal, the git commit store and the recurrence-support ledger interleave shards by each row's own time without ever reordering the rows of one shard (so a single-shard vault reads exactly as before, and the order-sensitive recurrence fold never replays one device's purge before another device's earlier event), the git store keeps one copy of each commit and tag, the query-demand read keeps its timestamp order, the preference edit history reads shards in shard-id order, and the schema-pack digest picks the newest record across every week shard. The capture-decision and verifier-rejection ledgers have no reader; only their writers changed. A rewrite touches only the shard this device writes: query-demand compaction caps that shard, and the maintenance-journal cap sweep rewrites only the local shard, so the journal cap applies per device. `o2b state status` reports a sharded fixed-name ledger present when its legacy file or any shard exists, and the doctor's `sync-conflict-log` sweep covers the directories of these two rows except the maintenance journal's `.open-second-brain/` root. Where a swept directory also holds whole files (`Brain/skill-proposals/`, `Brain/preferences/`, a git repository's `state.json`), a conflict copy without the `.jsonl` extension is not a split shard: it keeps the `sync-conflict-log` code with a hand-resolve remedy instead of the merge instruction. A source-layout test fails when a new append-mode writer uses neither the shard helpers nor a named allow-list entry.
+
The session lineage ledger is the one with an extra invariant: its sequence numbers and hash chain are per FILE, so a per-device shard is a per-device chain, compaction is per shard, and `verifyLineageLedger` verifies each shard separately and reports each finding under that shard's own path. A break in one machine's ledger says nothing about another's.
The `prompt_prefix` metric surface measures STRUCTURAL prompt-prefix stability (whether the kernel handed the agent a byte-stable, cache-eligible preamble across a generation pass), never a provider's cache-hit rate the kernel cannot observe. It stores only the SHA-256 hash and length of the prefix, never the raw prompt - the same payload-safety rule as `generation_report`. See `docs/metrics.md`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 415f6336..208322c5 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.62.0",
+ "version": "1.63.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 59ba534c..5b758fbb 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.62.0",
+ "version": "1.63.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.yaml
index c0d7f985..be07fb2f 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.62.0"
+version: "1.63.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index d6c97195..b97ee58f 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.62.0",
+ "version": "1.63.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/codex/README.md b/plugins/codex/README.md
index 3e6ed8d3..9023e5c4 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-1.61.0 moves MCP server start-up off the Brain upgrade path, makes ingest locks fair, puts the Claude Code MCP manifest inside `plugin.json`, and adds an inbox archive. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+1.63.0 binds a prose mention to a page only when exactly one page carries the term, turns relative imports and JSX component usage into code-structure edges, lets a `brain_write_batch` retry apply once through a request ID, adds a keyword match breadth to search, and gives every append-only Brain ledger one file per synced device. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/hermes/_schemas.py b/plugins/hermes/_schemas.py
index f399159a..0f8132f7 100644
--- a/plugins/hermes/_schemas.py
+++ b/plugins/hermes/_schemas.py
@@ -237,7 +237,8 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'additionalProperties': False}},
{'name': 'brain_search',
'description': 'Full-text search across the vault. Optional semantic layer when configured. '
- 'Read-only.',
+ 'Read-only. 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,
@@ -263,7 +264,10 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'focus_path_prefix': {'type': 'string',
'minLength': 1,
'maxLength': 256,
- 'description': 'Steer this one call towards a vault subtree, paired with focus_query as a transient focus.'},
+ 'description': 'Steer this one call '
+ 'towards a vault subtree, '
+ 'paired with focus_query '
+ 'as a transient focus.'},
'focus_session': {'type': 'string',
'minLength': 1,
'maxLength': 128,
@@ -277,7 +281,13 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'and the false-absence guard. '
'Default false.'},
'include_superseded': {'type': 'boolean',
- 'description': 'History mode for relation polarity: keep matched superseded predecessors undemoted and skip successor pull-in. Default false.'},
+ 'description': 'History mode for '
+ 'relation polarity: keep '
+ 'matched superseded '
+ 'predecessors undemoted '
+ 'and skip successor '
+ 'pull-in. Default '
+ 'false.'},
'since': {'type': 'string',
'maxLength': 64,
'description': 'Hard filter on event time (validity, '
@@ -303,6 +313,13 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'description': 'Skip the semantic lane '
'entirely, so no embedding is '
'needed. Default false.'},
+ 'match_mode': {'type': 'string',
+ 'enum': ['all', 'any'],
+ 'description': "FTS match breadth: 'all' "
+ '(default) requires every term; '
+ "'any' matches a document "
+ 'carrying any one term. Absent '
+ 'leaves the implicit AND.'},
'disclosure': {'type': 'string',
'enum': ['full', 'cards'],
'description': "Result depth: 'full' (default) "
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index c0d7f985..be07fb2f 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.62.0"
+version: "1.63.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 073a0618..b74133b1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.62.0"
+version = "1.63.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/scripts/hermes-plugin-scan.ts b/scripts/hermes-plugin-scan.ts
index cf73544f..e9ec542e 100644
--- a/scripts/hermes-plugin-scan.ts
+++ b/scripts/hermes-plugin-scan.ts
@@ -15,7 +15,9 @@
* commit and checked against pinned SHA-256 digests before it runs. It is
* three stdlib-only Python modules; nothing else from Hermes is needed. To
* move the pin: change HERMES_COMMIT, run with `--print-digests`, paste the
- * new digests, and re-check the verdict.
+ * new digests, and re-check the verdict. A rate-limited (HTTP 429) or server-error
+ * response is retried a bounded number of times with backoff; the last status
+ * is reported by name once the attempts run out.
*
* Scanned trees (the tracked files only, exported to a temp dir, as a clone
* would have them):
@@ -70,7 +72,41 @@ function sha256(data: Uint8Array): string {
return createHash("sha256").update(data).digest("hex");
}
-async function fetchGuardFile(path: string): Promise<Uint8Array> {
+/** Attempts per scanner file before a rate limit or server error is final. */
+export const GUARD_FETCH_ATTEMPTS = 5;
+/** Wait before the first retry; each later retry doubles it. */
+export const GUARD_FETCH_BASE_DELAY_MS = 2000;
+const HTTP_TOO_MANY_REQUESTS = 429;
+const HTTP_SERVER_ERROR_MIN = 500;
+const MS_PER_SECOND = 1000;
+
+/** The network and clock a fetch uses; tests pass stubs. */
+export interface GuardFetchDeps {
+ fetch: (url: string, init: RequestInit) => Promise<Response>;
+ sleep: (ms: number) => Promise<void>;
+}
+
+const defaultDeps: GuardFetchDeps = {
+ fetch: (url, init) => fetch(url, init),
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
+};
+
+/** A shared runner can hit the API rate limit or a transient server error. */
+function isRetryable(status: number): boolean {
+ return status === HTTP_TOO_MANY_REQUESTS || status >= HTTP_SERVER_ERROR_MIN;
+}
+
+/** The wait the server asked for (`Retry-After` in seconds), else exponential backoff. */
+function retryDelayMs(res: Response, retry: number): number {
+ const seconds = Number(res.headers.get("Retry-After"));
+ if (Number.isFinite(seconds) && seconds > 0) return seconds * MS_PER_SECOND;
+ return GUARD_FETCH_BASE_DELAY_MS * 2 ** retry;
+}
+
+export async function fetchGuardFile(
+ path: string,
+ deps: GuardFetchDeps = defaultDeps,
+): Promise<Uint8Array> {
const url = `https://api.github.com/repos/${HERMES_REPO}/contents/${path}?ref=${HERMES_COMMIT}`;
const token = process.env["GITHUB_TOKEN"] ?? process.env["GH_TOKEN"];
const headers: Record<string, string> = {
@@ -78,9 +114,19 @@ async function fetchGuardFile(path: string): Promise<Uint8Array> {
"User-Agent": "open-second-brain-hermes-plugin-scan",
};
if (token) headers["Authorization"] = `Bearer ${token}`;
- const res = await fetch(url, { headers });
- if (!res.ok) throw new Error(`fetch ${path}@${HERMES_COMMIT}: HTTP ${res.status}`);
- return new Uint8Array(await res.arrayBuffer());
+ // Retries are sequential by design: each waits on the previous response.
+ for (let attempt = 1; ; attempt++) {
+ // oxlint-disable-next-line no-await-in-loop
+ const res = await deps.fetch(url, { headers });
+ // oxlint-disable-next-line no-await-in-loop
+ if (res.ok) return new Uint8Array(await res.arrayBuffer());
+ if (!isRetryable(res.status) || attempt === GUARD_FETCH_ATTEMPTS) {
+ const tries = `${attempt} attempt${attempt === 1 ? "" : "s"}`;
+ throw new Error(`fetch ${path}@${HERMES_COMMIT}: HTTP ${res.status} after ${tries}`);
+ }
+ // oxlint-disable-next-line no-await-in-loop
+ await deps.sleep(retryDelayMs(res, attempt - 1));
+ }
}
/** Write the scanner modules at the pinned commit, digest-checked, under `dir`. */
@@ -109,7 +155,10 @@ async function writeGuard(dir: string): Promise<void> {
/** Copy the tracked files (working-tree content) under `out`: what a clone holds. */
function exportTrackedTree(out: string): string {
- const ls = spawnSync("git", ["ls-files", "-z", "--cached"], { cwd: ROOT, encoding: "utf8" });
+ const ls = spawnSync("git", ["ls-files", "-z", "--cached"], {
+ cwd: ROOT,
+ encoding: "utf8",
+ });
if (ls.status !== 0) throw new Error(`git ls-files failed: ${ls.stderr}`);
const tree = join(out, "open-second-brain");
for (const rel of ls.stdout.split("\0")) {
@@ -209,4 +258,6 @@ async function main(): Promise<number> {
}
}
-process.exit(await main());
+if (import.meta.main) {
+ process.exit(await main());
+}
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 39252ad3..db4713ca 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -931,7 +931,7 @@ export const VERB_HELP: Record<string, string> = {
"Read opt-in recall telemetry continuity records and aggregate coverage gaps. cost folds write volume (feedback/apply-evidence/note/host writes) against reads into a write-vs-read ratio, a write-heavy flag, and a rough weighted cost signal per period.\n",
"knowledge-gaps":
"usage: o2b brain knowledge-gaps [--min-occurrences <n>] [--max-satisfaction <0..1>] [--since <iso>] [--until <iso>] [--limit <n>] [--vault <path>] [--json]\n" +
- "Aggregate the persisted cross-query demand log (Brain/log/query-demand.jsonl) into recurring queries the vault answers poorly. Buckets by normalized query terms and ranks by frequency x (1 - satisfaction), where satisfaction is the reused IDF-weighted coverage (or the non-empty-result fraction when coverage was not recorded). Turns repeated recall failures into a prioritized backlog of what to write next. Read-only; the log is written only by opt-in recall telemetry.\n",
+ "Aggregate the persisted cross-query demand log (Brain/log/query-demand[.<deviceId>].jsonl, every device's shard merged) into recurring queries the vault answers poorly. Buckets by normalized query terms and ranks by frequency x (1 - satisfaction), where satisfaction is the reused IDF-weighted coverage (or the non-empty-result fraction when coverage was not recorded). Turns repeated recall failures into a prioritized backlog of what to write next. Read-only; the log is written only by opt-in recall telemetry.\n",
"generation-reports":
"usage: o2b brain generation-reports record <write_session|context_pack|dream_stage> --ref <id> --agent <name> --prompt <text> [--enable] [--provider <p>] [--model <m>] [--finish-reason <r>] [--latency-ms <n>] [--input-tokens <n>] [--output-tokens <n>] [--cached-tokens <n>] [--total-tokens <n>] [--scope <s>] [--source <id[=path]>...] [--created-at <iso>] [--vault <path>] [--json]\n" +
" o2b brain generation-reports list [--handoff <kind>] [--agent <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--vault <path>] [--json]\n" +
@@ -1075,6 +1075,9 @@ export const VERB_HELP: Record<string, string> = {
"phrase via --confirm. A confidence threshold and a hard per-run write cap\n" +
"bound the writes; existing edges are skipped, so a rerun converges to zero\n" +
"writes. Inferred candidates are opt-in behind --include-inferred.\n" +
+ "An explicit reference is a mention of a page title or alias that exactly\n" +
+ "one page carries; a term several pages carry binds to none of them and is\n" +
+ "reported as a skip-ambiguous decision naming each carrier.\n" +
"--apply is gated by the paired graph-efficacy holdout harness: every\n" +
"proposed edge is checked as an (anchor, target) holdout, graph lift is\n" +
"counted apart from direct recall, and the apply is refused without writing\n" +
diff --git a/src/cli/brain/verbs/pre-extract.ts b/src/cli/brain/verbs/pre-extract.ts
index 2b929e47..cbc8ac3f 100644
--- a/src/cli/brain/verbs/pre-extract.ts
+++ b/src/cli/brain/verbs/pre-extract.ts
@@ -5,8 +5,8 @@
*
* This is the agent-facing form of the pre-ingest pass: an agent runs it before
* extracting from a code source so the structural seeds (classes, functions,
- * imports, inheritance) are available as pre-extracted facts. Read-only and
- * deterministic - the kernel runs no model. An unsupported extension is
+ * imports, inheritance, JSX component usages) are available as pre-extracted
+ * facts. Read-only and deterministic - the kernel runs no model. An unsupported extension is
* reported as unextracted with a reason, never a fake empty success.
*/
diff --git a/src/cli/brain/verbs/repair-lane.ts b/src/cli/brain/verbs/repair-lane.ts
index f904e2de..94d46d9c 100644
--- a/src/cli/brain/verbs/repair-lane.ts
+++ b/src/cli/brain/verbs/repair-lane.ts
@@ -36,7 +36,7 @@
import {
REPAIR_CONFIRM_PHRASE,
RepairConfirmationError,
- collectRepairCandidates,
+ collectRepairCandidatesWithRefusals,
runRepairLane,
type RepairDecision,
type RepairReport,
@@ -78,9 +78,13 @@ function decisionJson(decision: RepairDecision): Record<string, unknown> {
};
}
-/** Every edge the lane proposes, as an (anchor, target) holdout pair. */
+/** Every edge the lane proposes, as an (anchor, target) holdout pair.
+ * A `skip-ambiguous` refusal proposes no edge - it records why nothing was
+ * proposed - so it is not a holdout. */
function holdoutsFor(decisions: readonly RepairDecision[]): GraphHoldout[] {
- return decisions.map((decision) => ({ anchor: decision.source, target: decision.target }));
+ return decisions
+ .filter((decision) => decision.action !== "skip-ambiguous")
+ .map((decision) => ({ anchor: decision.source, target: decision.target }));
}
function holdoutJson(gate: HoldoutGateResult): Record<string, unknown> {
@@ -189,11 +193,15 @@ export async function cmdBrainRepairLane(argv: string[]): Promise<number> {
return refuse(message);
}
- const candidates = collectRepairCandidates(vault);
+ const collected = collectRepairCandidatesWithRefusals(vault);
// Plan first, always as a dry run: the gate must see the proposed edges
// before any of them reaches disk.
- const plan = runRepairLane(vault, candidates, { apply: false, ...laneOptions });
+ const plan = runRepairLane(vault, collected.candidates, {
+ apply: false,
+ collectedRefusals: collected.refusals,
+ ...laneOptions,
+ });
if (!apply) {
if (asJson) okJson(reportJson(plan, null));
else renderReport(plan, null, false);
@@ -208,9 +216,10 @@ export async function cmdBrainRepairLane(argv: string[]): Promise<number> {
});
}
- const report = runRepairLane(vault, candidates, {
+ const report = runRepairLane(vault, collected.candidates, {
apply: true,
confirm: REPAIR_CONFIRM_PHRASE,
+ collectedRefusals: collected.refusals,
...laneOptions,
});
if (asJson) okJson(reportJson(report, gate));
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index d73a244c..5fb3403c 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -728,6 +728,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
flag("limit", "string"),
flag("semantic", "boolean"),
flag("keyword-only", "boolean"),
+ flag("match-mode", "string"),
flag("path", "string"),
flag("keyword-weight", "string"),
flag("semantic-weight", "string"),
diff --git a/src/cli/search/verbs/query.ts b/src/cli/search/verbs/query.ts
index 337995b1..68121510 100644
--- a/src/cli/search/verbs/query.ts
+++ b/src/cli/search/verbs/query.ts
@@ -29,6 +29,12 @@ import {
VAULT_FLAGS,
} from "../helpers.ts";
import { CLI_TRANSPORT_REACH } from "../../transport-reach.ts";
+import { FTS_MATCH_MODES, isFtsMatchMode } from "../../../core/search/fts-match-mode.ts";
+import {
+ DISCLOSURE_MODE,
+ DISCLOSURE_MODES,
+ isDisclosureMode,
+} from "../../../core/search/disclosure-mode.ts";
/** Both malformed `--property` shapes report the same way. */
function propertyFormatError(entry: string): CliError {
@@ -41,6 +47,7 @@ export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<numbe
limit: { type: "string", default: "10" },
semantic: { type: "boolean" },
"keyword-only": { type: "boolean" },
+ "match-mode": { type: "string" },
path: { type: "string" },
"keyword-weight": { type: "string" },
"semantic-weight": { type: "string" },
@@ -86,9 +93,14 @@ export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<numbe
throw new CliError(`--limit must be an integer in ${SEARCH_LIMIT_MIN}..${SEARCH_LIMIT_MAX}`);
}
const disclosureRaw = flagString(flags, "disclosure");
- if (disclosureRaw !== undefined && disclosureRaw !== "full" && disclosureRaw !== "cards") {
- throw new CliError("--disclosure must be 'full' or 'cards'");
+ if (disclosureRaw !== undefined && !isDisclosureMode(disclosureRaw)) {
+ throw new CliError(`--disclosure must be one of ${DISCLOSURE_MODES.join(", ")}`);
+ }
+ const matchModeRaw = flagString(flags, "match-mode");
+ if (matchModeRaw !== undefined && !isFtsMatchMode(matchModeRaw)) {
+ throw new CliError(`--match-mode must be one of ${FTS_MATCH_MODES.join(", ")}`);
}
+ const matchMode = matchModeRaw;
const cfg = resolveConfig(flags);
@@ -125,6 +137,7 @@ export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<numbe
semantic: semanticOverride,
keywordOnly: flagBoolean(flags, "keyword-only"),
pathPrefix: flagString(flags, "path"),
+ ...(matchMode !== undefined ? { matchMode } : {}),
...(properties !== undefined ? { properties } : {}),
...(degreeFilters !== undefined ? { degreeFilters } : {}),
...(visibility !== undefined && visibility.length > 0 ? { visibility } : {}),
@@ -138,7 +151,7 @@ export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<numbe
...(agentScope !== undefined ? { agentScope } : {}),
...(structuredQuery !== undefined ? { structuredQuery } : {}),
...(flagBoolean(flags, "expand") ? { expand: true } : {}),
- ...(disclosureRaw === "cards" ? { disclosure: "cards" as const } : {}),
+ ...(disclosureRaw === DISCLOSURE_MODE.cards ? { disclosure: disclosureRaw } : {}),
...(profile !== undefined ? { profile } : {}),
...(flagBoolean(flags, "evidence-pack") ? { evidencePack: true } : {}),
...(flagBoolean(flags, "include-superseded") ? { includeSuperseded: true } : {}),
diff --git a/src/core/brain/audit-dirs.ts b/src/core/brain/audit-dirs.ts
new file mode 100644
index 00000000..4ea8dbab
--- /dev/null
+++ b/src/core/brain/audit-dirs.ts
@@ -0,0 +1,39 @@
+/**
+ * One spelling of every audit subdirectory a writer appends week shards
+ * to (t_774dea61).
+ *
+ * Each name used to be a bare literal at its write site, and the doctor's
+ * sync-conflict sweep needs the same directories: a rename performed at
+ * the writer alone would leave the sweep looking at a directory nobody
+ * writes, and report it clean. Writers and the sweep both read the names
+ * from here. The schema-mutation audit keeps its own constant beside its
+ * reader (`schema-integrity.ts`), the hook-audit root lives in
+ * `path-constants.ts`, and the watchdog fallback's absolute path is built
+ * in `watchdog.ts`, the module the state inventory attributes it to.
+ */
+
+/** `Brain/log/session-lifecycle/`: runtime session-lifecycle captures. */
+export const SESSION_LIFECYCLE_AUDIT_DIR = "session-lifecycle";
+
+/** `Brain/log/hygiene/`: hygiene applies and targeted recompiles. */
+export const HYGIENE_AUDIT_DIR = "hygiene";
+
+/** `Brain/log/secret-custody/`: secret reads, writes and exec decisions. */
+export const SECRET_CUSTODY_AUDIT_DIR = "secret-custody";
+
+/** `Brain/log/watchdog/`: watchdog probe records. */
+export const WATCHDOG_AUDIT_DIR = "watchdog";
+
+/**
+ * `.open-second-brain/watchdog-audit/`: where a watchdog record lands
+ * when its `Brain/log/` directory refuses the write.
+ */
+export const WATCHDOG_FALLBACK_AUDIT_DIR = "watchdog-audit";
+
+/** Every audit subdirectory of `Brain/log/` named in this module. */
+export const BRAIN_LOG_AUDIT_DIRS: ReadonlyArray<string> = Object.freeze([
+ SESSION_LIFECYCLE_AUDIT_DIR,
+ HYGIENE_AUDIT_DIR,
+ SECRET_CUSTODY_AUDIT_DIR,
+ WATCHDOG_AUDIT_DIR,
+]);
diff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.ts
index bf77de6f..0f66bd4a 100644
--- a/src/core/brain/decisions/receipts.ts
+++ b/src/core/brain/decisions/receipts.ts
@@ -28,6 +28,12 @@ import { createHash } from "node:crypto";
import { join } from "node:path";
import { resolveDeviceId } from "../../config.ts";
+import {
+ JSONL_LEDGER_EXT,
+ jsonlLedgerGrammar,
+ parseShardedName,
+ shardedFileName,
+} from "../ledger-shards.ts";
import { appendLogEvent } from "../log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
@@ -57,8 +63,9 @@ export const DECISION_CHANGE_REASON = Object.freeze({
/** Same canonical UTC shape the truth ledger and log writer emit. */
const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
-/** `decision-change.jsonl` or `decision-change.<deviceId>.jsonl`. */
-const RECEIPT_SHARD_RE = /^decision-change(?:\.([a-z0-9-]{1,32}))?\.jsonl$/;
+/** `decision-change.jsonl` or `decision-change.<deviceId>.jsonl`, via the shared ledger-shard grammar. */
+const RECEIPT_STEM = "decision-change";
+const RECEIPT_GRAMMAR = jsonlLedgerGrammar(RECEIPT_STEM);
/** Cap on the length of any single string field (mirrors note-text caps). */
const FIELD_MAX_LEN = 2000;
@@ -169,7 +176,7 @@ export function receiptsDir(vault: string): string {
*/
export function receiptShardPath(vault: string, configPath?: string): string {
const deviceId = resolveDeviceId(configPath);
- const name = deviceId === "" ? "decision-change.jsonl" : `decision-change.${deviceId}.jsonl`;
+ const name = shardedFileName(RECEIPT_STEM, deviceId, JSONL_LEDGER_EXT);
return join(receiptsDir(vault), name);
}
@@ -390,10 +397,9 @@ export function readDecisionChangeReceipts(vault: string): ReadReceiptsResult {
const warnings: ReceiptParseWarning[] = [];
for (const name of names) {
- const m = RECEIPT_SHARD_RE.exec(name);
- if (!m) continue;
- const shardId = m[1] ?? "";
- if (shardId.startsWith("sync-conflict")) continue;
+ const shard = parseShardedName(name, RECEIPT_GRAMMAR);
+ if (shard === null) continue;
+ const shardId = shard.shardId;
const path = join(dir, name);
let text: string;
try {
diff --git a/src/core/brain/doctor/store-integrity.ts b/src/core/brain/doctor/store-integrity.ts
index eca04cf3..7ba2002d 100644
--- a/src/core/brain/doctor/store-integrity.ts
+++ b/src/core/brain/doctor/store-integrity.ts
@@ -10,15 +10,20 @@
import { join } from "node:path";
-import { realpathInsideVault, vaultRelative } from "../../path-safety.ts";
+import { ensureInsideVault, realpathInsideVault, vaultRelative } from "../../path-safety.ts";
+import { BRAIN_LOG_AUDIT_DIRS } from "../audit-dirs.ts";
import { continuityLogDir } from "../continuity/store.ts";
import { scanDanglingWorkruns } from "../dream-workrun.ts";
import { readTierDriftCount } from "../frontmatter-tiers.ts";
+import { gitStoreRootDir } from "../git/store.ts";
import { idempotencyLogDir } from "../idempotency-ledger.ts";
-import { listSyncConflictFiles } from "../ledger-shards.ts";
+import { JSONL_LEDGER_EXT, listSyncConflictFiles } from "../ledger-shards.ts";
import { brainStateDirPath } from "../lineage/ledger.ts";
import { metricsDir } from "../metrics.ts";
-import { brainDirs, prefAuditDir } from "../paths.ts";
+import { BRAIN_SKILL_PROPOSALS_REL } from "../path-constants.ts";
+import { brainDirs, hookAuditDir, prefAuditDir } from "../paths.ts";
+import { schemaMutationAuditDir } from "../schema-integrity.ts";
+import { watchdogFallbackAuditDir } from "../watchdog.ts";
import type { DoctorCheck } from "./check.ts";
import type { DoctorUncertainEntry } from "./report.ts";
import {
@@ -80,47 +85,105 @@ export const danglingWorkrunCheck: DoctorCheck = {
* Every append-only ledger directory in the vault, each named by the
* module that owns it rather than by a path spelled a second time here.
*
- * All six shard per device (who-wrote-what, Task B), which is what makes
- * one finding cover all of them: the shard layout prevents NEW conflicts
- * everywhere, so a `*.sync-conflict-*` copy under any of these means the
- * same thing - a file that exists and that no reader merges.
+ * All of them shard per device (who-wrote-what, Task B; t_774dea61),
+ * which is what makes one finding cover all of them: the shard layout
+ * prevents NEW conflicts everywhere, so a `*.sync-conflict-*` copy under
+ * any of these means the same thing - a file that exists and that no
+ * reader merges.
*/
-const LEDGER_DIRS: ReadonlyArray<(vault: string, uncertain: DoctorUncertainEntry[]) => string[]> =
- Object.freeze([
- (vault: string) => [brainDirs(vault).log],
- (vault: string) => [continuityLogDir(vault)],
- (vault: string) => [idempotencyLogDir(vault)],
- prefAuditSweepDirs,
- (vault: string) => [metricsDir(vault)],
- (vault: string) => [brainStateDirPath(vault)],
- ]);
+interface LedgerSweep {
+ readonly resolve: (vault: string, uncertain: DoctorUncertainEntry[]) => string[];
+ /**
+ * The directory also holds files that are not ledger shards (notes,
+ * atomically replaced JSON state). There only a copy carrying the JSON
+ * Lines ledger extension is a split-off shard; any other copy is a
+ * conflict of a whole file and is reported with its own remedy.
+ */
+ readonly mixed: boolean;
+}
+
+const LEDGER_DIRS: ReadonlyArray<LedgerSweep> = Object.freeze([
+ { resolve: (vault: string) => [brainDirs(vault).log], mixed: false },
+ {
+ resolve: (vault: string) =>
+ BRAIN_LOG_AUDIT_DIRS.map((name) => join(brainDirs(vault).log, name)),
+ mixed: false,
+ },
+ { resolve: (vault: string) => [schemaMutationAuditDir(vault)], mixed: false },
+ { resolve: (vault: string) => [watchdogFallbackAuditDir(vault)], mixed: false },
+ { resolve: (vault: string) => [hookAuditDir(vault)], mixed: false },
+ { resolve: (vault: string) => [continuityLogDir(vault)], mixed: false },
+ { resolve: (vault: string) => [idempotencyLogDir(vault)], mixed: false },
+ { resolve: prefAuditSweepDirs, mixed: false },
+ { resolve: (vault: string) => [metricsDir(vault)], mixed: false },
+ { resolve: (vault: string) => [brainStateDirPath(vault)], mixed: false },
+ // The verifier-rejection ledger sits at the proposals root, next to the
+ // proposal files. Named through the path constant rather than
+ // `verifierRejectionLedgerPath`: `skill-proposals.ts` reaches the doctor,
+ // so importing it here closes an import cycle.
+ {
+ resolve: (vault: string) => [ensureInsideVault(join(vault, BRAIN_SKILL_PROPOSALS_REL), vault)],
+ mixed: true,
+ },
+ // Preference edit-history shards sit next to the preference notes.
+ { resolve: (vault: string) => [brainDirs(vault).preferences], mixed: true },
+ // Each repository's commits shards sit next to its state.json.
+ { resolve: gitStoreSweepDirs, mixed: true },
+]);
+
+/** What to do with a conflict copy of a ledger shard. */
+const LEDGER_COPY_REMEDY =
+ "Merge its rows into the shard it was split from (union + dedup by timestamp and " +
+ "content), then delete it.";
+
+/** What to do with a conflict copy of a whole file that is not a ledger shard. */
+const FILE_COPY_REMEDY =
+ "It is not a ledger shard: compare it with the file it was copied from, keep the right " +
+ "version by hand, then delete the copy.";
/**
* The preference audit keeps one DIRECTORY per preference
* (`pref-audit/<pref-id>/`), so its shards - and therefore any conflict
* copy of one - live a level below the others. Sweeping only the parent
* would report a clean ledger while a copy nobody merges sat inside it.
- *
- * A parent that cannot be listed is reported by name through the shared
- * swept-path reporter rather than read as "no preferences": the whole
- * point of this check is to keep "nothing found" and "nothing looked at"
- * apart.
*/
function prefAuditSweepDirs(vault: string, uncertain: DoctorUncertainEntry[]): string[] {
const parent = prefAuditDir(vault);
+ return [parent, ...subdirectories(parent, uncertain, "per-preference")];
+}
+
+/**
+ * The git store keeps one directory per repository
+ * (`Brain/projects/git/<repo>/`), each holding its own `commits` shards,
+ * so the repositories are discovered from the tree on every pass. The
+ * root itself holds no ledger. Its path comes from the store's own
+ * root builder rather than being spelled a second time here.
+ */
+function gitStoreSweepDirs(vault: string, uncertain: DoctorUncertainEntry[]): string[] {
+ return subdirectories(gitStoreRootDir(vault), uncertain, "per-repository");
+}
+
+/**
+ * The immediate subdirectories of `parent`. A parent that cannot be
+ * listed is reported by name through the shared swept-path reporter
+ * rather than read as "no subdirectories": the whole point of this check
+ * is to keep "nothing found" and "nothing looked at" apart. An absent
+ * parent is simply empty.
+ */
+function subdirectories(parent: string, uncertain: DoctorUncertainEntry[], kind: string): string[] {
const entries = readSweptDir(
parent,
{
site: SYNC_CONFLICT_SITE,
consequence:
- "its per-preference subdirectories were not listed for Syncthing conflict copies, so a " +
+ `its ${kind} subdirectories were not listed for Syncthing conflict copies, so a ` +
"leftover copy waiting to be merged is missing from this report",
uncertain,
},
SWEEP_ORIGIN.root,
);
- if (entries === null) return [parent];
- return [parent, ...entries.filter((e) => e.isDirectory()).map((e) => join(parent, e.name))];
+ if (entries === null) return [];
+ return entries.filter((e) => e.isDirectory()).map((e) => join(parent, e.name));
}
/**
@@ -136,10 +199,10 @@ function prefAuditSweepDirs(vault: string, uncertain: DoctorUncertainEntry[]): s
export const syncConflictLogCheck: DoctorCheck = {
failSoft: true,
run({ vault }, { issues, uncertain }) {
- for (const resolve of LEDGER_DIRS) {
+ for (const sweep of LEDGER_DIRS) {
let ledgerDirs: string[];
try {
- ledgerDirs = resolve(vault, uncertain);
+ ledgerDirs = sweep.resolve(vault, uncertain);
} catch {
// A directory whose own resolver refuses (a vault path that
// escapes its root) is not a directory this sweep can visit;
@@ -148,14 +211,14 @@ export const syncConflictLogCheck: DoctorCheck = {
}
for (const ledgerDir of ledgerDirs) {
for (const path of listSyncConflicts(ledgerDir, uncertain)) {
+ const ledgerCopy = !sweep.mixed || path.endsWith(`.${JSONL_LEDGER_EXT}`);
issues.push({
severity: "warning",
code: "sync-conflict-log",
path,
message:
`Syncthing sync-conflict copy under ${vaultRelative(ledgerDir, vault)}/: ${path}. ` +
- "Merge its rows into the shard it was split from (union + dedup by timestamp and " +
- "content), then delete it.",
+ (ledgerCopy ? LEDGER_COPY_REMEDY : FILE_COPY_REMEDY),
});
}
}
@@ -174,7 +237,7 @@ const SYNC_CONFLICT_SITE = "brain.doctor.syncConflictLog";
* a throw. Swallowed by the pass's fail-soft arm it produced no finding
* at all, which reads as "no conflict copies" - the answer this check
* exists to distinguish from "the directory was not read". Reported per
- * directory, so one unreadable ledger does not silence the other five.
+ * directory, so one unreadable ledger does not silence the others.
*/
function listSyncConflicts(dir: string, uncertain: DoctorUncertainEntry[]): string[] {
try {
diff --git a/src/core/brain/git/store.ts b/src/core/brain/git/store.ts
index 7e48813f..14dcd649 100644
--- a/src/core/brain/git/store.ts
+++ b/src/core/brain/git/store.ts
@@ -2,11 +2,13 @@
* Per-repo git record store (Project History Suite, t_c812752c).
*
* Canonical source of truth for ingested history. Each linked repo owns
- * `Brain/projects/git/<repo-key>/` with two files:
+ * `Brain/projects/git/<repo-key>/` with two kinds of file:
*
- * - `commits.jsonl` - append-only mixed-kind records (`commit` | `tag`),
+ * - `commits[.<deviceId>].jsonl` - one append-only shard per device of
+ * mixed-kind records (`commit` | `tag`), merged on read by record time,
* snake_case on disk like the continuity shards, deduplicated by
- * commit sha / tag name on append. Typed edges (touched files,
+ * commit sha / tag (name, target) on append and again on the merged
+ * read. Typed edges (touched files,
* author, carrying release) are STRUCTURED FIELDS here; wikilinks in
* rendered notes are always derived from these records, never
* hand-maintained (design decision: contain dual-representation drift).
@@ -22,6 +24,14 @@
*/
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
+import {
+ interleaveShardRows,
+ JSONL_LEDGER_EXT,
+ jsonlLedgerGrammar,
+ readShardLinesByShard,
+ resolveAppendShardId,
+ shardedFileName,
+} from "../ledger-shards.ts";
import { appendFileSync } from "node:fs";
import { join } from "node:path";
@@ -84,13 +94,29 @@ export interface AppendGitRecordsResult {
readonly skipped: number;
}
+/** The commits ledger's shard stem: `commits[.<deviceId>].jsonl`. */
+const COMMITS_STEM = "commits";
+
+/** The commits ledger's file-name layout, handed to the shared shard grammar. */
+const COMMITS_GRAMMAR = jsonlLedgerGrammar(COMMITS_STEM);
+
+/** `Brain/projects/git/`: the root that holds one store directory per repository. */
+export function gitStoreRootDir(vault: string): string {
+ return join(vault, "Brain", "projects", "git");
+}
+
/** Per-repo store directory inside the vault. */
export function gitStoreDir(vault: string, repoKey: string): string {
- return join(vault, "Brain", "projects", "git", repoKey);
+ return join(gitStoreRootDir(vault), repoKey);
}
function commitsPath(vault: string, repoKey: string): string {
- return join(gitStoreDir(vault, repoKey), "commits.jsonl");
+ // Per-device shard (t_774dea61): each machine appends to - and locks -
+ // its own file; the empty device id keeps the legacy un-sharded name.
+ return join(
+ gitStoreDir(vault, repoKey),
+ shardedFileName(COMMITS_STEM, resolveAppendShardId(), JSONL_LEDGER_EXT),
+ );
}
function statePath(vault: string, repoKey: string): string {
@@ -159,16 +185,57 @@ function parseRecord(line: string): GitRecord | null {
return null;
}
+/**
+ * When a record happened, as the cross-device merge orders it. A record
+ * without a readable time (a tag with no `createdAt`) sorts as early as
+ * possible, which in the merge means straight after the record its own
+ * shard holds before it.
+ */
+function recordTime(record: GitRecord): number {
+ const time = Date.parse(record.kind === "commit" ? record.committedAt : (record.createdAt ?? ""));
+ return Number.isFinite(time) ? time : Number.NEGATIVE_INFINITY;
+}
+
+/**
+ * Every record across every device's shard (t_774dea61), oldest first:
+ * shards are interleaved by record time, each shard keeping its own file
+ * order, so a single-shard store reads exactly as before and `limit` and
+ * the latest-tag view see one timeline whatever the shard names are. The
+ * dedup on append reads the same merge, so it also sees commits a synced
+ * peer ingested.
+ *
+ * The merge also keeps only the first occurrence of each record identity
+ * (see {@link recordIdentity}). The append dedup cannot see a shard that
+ * has not synced yet, so two devices ingesting the same history before
+ * Syncthing delivers both write it; without this, every commit they share
+ * would list twice and a `limit` would count the copies.
+ */
function readRecords(vault: string, repoKey: string): ReadonlyArray<GitRecord> {
- const path = commitsPath(vault, repoKey);
- if (!existsSync(path)) return [];
- const records: GitRecord[] = [];
- for (const line of readFileSync(path, "utf8").split("\n")) {
- if (line.trim() === "") continue;
- const record = parseRecord(line);
- if (record !== null) records.push(record);
- }
- return records;
+ const shards = readShardLinesByShard(gitStoreDir(vault, repoKey), COMMITS_GRAMMAR).map(
+ (shard) => ({
+ shardId: shard.shardId,
+ rows: shard.rows.map(parseRecord).filter((record) => record !== null),
+ }),
+ );
+ const seen = new Set<string>();
+ return interleaveShardRows(shards, recordTime).filter((record) => {
+ const identity = recordIdentity(record);
+ if (seen.has(identity)) return false;
+ seen.add(identity);
+ return true;
+ });
+}
+
+/**
+ * What makes two records the same record: a commit's sha, a tag's
+ * (name, target). A retargeted tag (same name, new target) is a new
+ * record; listGitTags surfaces the latest per name. The kind prefix keeps
+ * the two key spaces apart.
+ */
+function recordIdentity(record: GitRecord): string {
+ return record.kind === "commit"
+ ? `commit\x00${record.sha}`
+ : `tag\x00${record.name}\x00${record.targetSha}`;
}
/**
@@ -205,23 +272,16 @@ function appendGitRecordsLocked(
repoKey: string,
records: ReadonlyArray<GitRecord>,
): AppendGitRecordsResult {
- const existing = readRecords(vault, repoKey);
- const seenShas = new Set<string>();
// Tag identity is (name, target): a RETARGETED tag (same name, new
// commit after a force-move) appends a fresh record instead of being
// silently dropped; listGitTags surfaces the latest record per name.
- const seenTags = new Set<string>();
- for (const record of existing) {
- if (record.kind === "commit") seenShas.add(record.sha);
- else seenTags.add(`${record.name}\x00${record.targetSha}`);
- }
+ const seen = new Set(readRecords(vault, repoKey).map(recordIdentity));
const lines: string[] = [];
let skipped = 0;
let appendedCommits = 0;
let appendedTags = 0;
for (const record of records) {
- const key = record.kind === "commit" ? record.sha : `${record.name}\x00${record.targetSha}`;
- const seen = record.kind === "commit" ? seenShas : seenTags;
+ const key = recordIdentity(record);
if (seen.has(key)) {
skipped += 1;
continue;
@@ -238,7 +298,7 @@ function appendGitRecordsLocked(
return { appended: lines.length, appendedCommits, appendedTags, skipped };
}
-/** Commits oldest-first (file order), optionally filtered. */
+/** Commits oldest-first (file order, devices merged by commit time), optionally filtered. */
export function listGitCommits(
vault: string,
repoKey: string,
@@ -357,17 +417,33 @@ export interface GitRepoEntry {
readonly stateError: string | null;
}
-/** Every per-repo store under Brain/projects/git/, sorted by key. */
+/**
+ * Stat errors that mean the entry is simply not there any more (removed
+ * between the listing and the stat, or a dangling link), so skipping it
+ * is the honest answer. Any other code is a store that could not be read.
+ */
+const VANISHED_ENTRY_CODES: ReadonlySet<string> = new Set(["ENOENT", "ENOTDIR"]);
+
+/**
+ * Every per-repo store under Brain/projects/git/, sorted by key. An entry
+ * that vanished is skipped; one that exists but cannot be stat'ed throws
+ * an error naming the path and its code instead of disappearing from the
+ * list.
+ */
export function listGitRepos(vault: string): ReadonlyArray<GitRepoEntry> {
- const root = join(vault, "Brain", "projects", "git");
+ const root = gitStoreRootDir(vault);
if (!existsSync(root)) return [];
const entries: GitRepoEntry[] = [];
for (const name of readdirSync(root).toSorted()) {
const dir = join(root, name);
try {
if (!statSync(dir).isDirectory()) continue;
- } catch {
- continue;
+ } catch (exc) {
+ const code = (exc as NodeJS.ErrnoException).code;
+ if (code !== undefined && VANISHED_ENTRY_CODES.has(code)) continue;
+ throw new Error(`git store entry ${dir} could not be read: ${code ?? String(exc)}`, {
+ cause: exc,
+ });
}
const probe = readGitState(vault, name);
entries.push(Object.freeze({ key: name, state: probe.state, stateError: probe.error }));
diff --git a/src/core/brain/health/edit-history.ts b/src/core/brain/health/edit-history.ts
index 7b4c03b5..9777a3f3 100644
--- a/src/core/brain/health/edit-history.ts
+++ b/src/core/brain/health/edit-history.ts
@@ -11,10 +11,11 @@
* files.
*/
-import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { appendFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
-import { preferenceHistoryPath } from "../paths.ts";
+import { jsonlLedgerGrammar, readShardedLines } from "../ledger-shards.ts";
+import { preferenceHistoryPath, preferenceHistoryStem } from "../paths.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export interface EditHistoryEntry {
@@ -49,16 +50,22 @@ function isEntry(value: unknown): value is EditHistoryEntry {
);
}
-/** Read the sidecar, skipping malformed lines. Missing file -> `[]`. */
+/**
+ * The sidecar shard family's layout for one slug. The base is the slug's
+ * own `pref-<slug>.history` stem, escaped, so a slug containing a dot can
+ * never be read as a device shard of a shorter slug.
+ */
+function historyGrammar(slug: string) {
+ return jsonlLedgerGrammar(preferenceHistoryStem(slug));
+}
+
+/** Read every device's shard, skipping malformed lines. No shards -> `[]`. */
export function readEditHistory(vault: string, slug: string): EditHistoryEntry[] {
- const path = preferenceHistoryPath(vault, slug);
- if (!existsSync(path)) return [];
+ const dir = dirname(preferenceHistoryPath(vault, slug));
const out: EditHistoryEntry[] = [];
- for (const line of readFileSync(path, "utf8").split("\n")) {
- const trimmed = line.trim();
- if (trimmed.length === 0) continue;
+ for (const line of readShardedLines(dir, historyGrammar(slug))) {
try {
- const parsed: unknown = JSON.parse(trimmed);
+ const parsed: unknown = JSON.parse(line);
if (isEntry(parsed)) out.push(parsed);
} catch {
// malformed line - skip, do not throw
diff --git a/src/core/brain/hygiene/apply.ts b/src/core/brain/hygiene/apply.ts
index a069b70e..837886e6 100644
--- a/src/core/brain/hygiene/apply.ts
+++ b/src/core/brain/hygiene/apply.ts
@@ -20,6 +20,7 @@
import { join } from "node:path";
import { appendAuditRecord } from "../../reliability/audit.ts";
+import { HYGIENE_AUDIT_DIR } from "../audit-dirs.ts";
import { mergePreferences } from "../merge.ts";
import { brainDirsForWrite } from "../paths.ts";
import { archivePage, executeRecompile, planRecompile } from "../recompile.ts";
@@ -172,7 +173,7 @@ export async function applyHygienePlan(
}
if (applied.length > 0 || errors.length > 0) {
- appendAuditRecord(join(brainDirsForWrite(vault).log, "hygiene"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR), {
timestamp: opts.now.toISOString(),
actor: opts.agent,
action: "hygiene_apply",
diff --git a/src/core/brain/idempotency-ledger.ts b/src/core/brain/idempotency-ledger.ts
index 99e2c431..3699dd7d 100644
--- a/src/core/brain/idempotency-ledger.ts
+++ b/src/core/brain/idempotency-ledger.ts
@@ -41,6 +41,7 @@ import { join } from "node:path";
import { canonicalJson, sha256Hex } from "../integrity/digest.ts";
import {
+ JSONL_LEDGER_EXT,
listShardedFiles,
resolveAppendShardId,
shardedFileName,
@@ -55,13 +56,13 @@ import { assertVaultIdentityForWrite } from "./vault-identity.ts";
const IDEMPOTENCY_REL = `${BRAIN_ROOT_REL}/logs/idempotency`;
/** Shard base: one file per UTC month, per device. */
-const MONTH_RE = /^\d{4}-\d{2}$/;
-const IDEMPOTENCY_EXT = "jsonl";
+const MONTH_BASE = "\\d{4}-\\d{2}";
+const MONTH_RE = new RegExp(`^${MONTH_BASE}$`);
/** The ledger's file-name layout, handed to the shared shard grammar. */
const IDEMPOTENCY_GRAMMAR: LedgerShardGrammar = Object.freeze({
- base: "\\d{4}-\\d{2}",
- extensions: Object.freeze([IDEMPOTENCY_EXT]),
+ base: MONTH_BASE,
+ extensions: Object.freeze([JSONL_LEDGER_EXT]),
});
/** Hard cap on a client key. Long enough for `<session-id>:<slug>` joins. */
@@ -80,6 +81,14 @@ export type RememberKeyStatus = (typeof REMEMBER_KEY_STATUS)[keyof typeof REMEMB
* original write's identity (e.g. `{ id, path }`). */
export interface IdempotencyRecord {
readonly key: string;
+ /**
+ * The key space the record belongs to. Absent is the shared key space of
+ * the historical writers (signal, apply-evidence, preference, session
+ * checkpoint), whose records never carry the field. A writer whose keys
+ * come from a different client vocabulary names its own namespace, so a
+ * string reused across tools never collides.
+ */
+ readonly namespace?: string;
readonly contentHash: string;
readonly createdAt: string;
readonly ref?: Readonly<Record<string, unknown>>;
@@ -87,6 +96,8 @@ export interface IdempotencyRecord {
export interface RememberKeyInput {
readonly key: string;
+ /** See {@link IdempotencyRecord.namespace}. Absent keeps the shared key space. */
+ readonly namespace?: string;
readonly contentHash: string;
/** Canonical UTC ISO-8601; defaults to `isoSecond(new Date())`. Drives the
* month shard, so a backfilled write lands in its real month. */
@@ -104,6 +115,19 @@ export interface RememberKeyResult {
readonly record: IdempotencyRecord;
}
+/**
+ * Thrown for a client key the ledger cannot store: not a string, blank
+ * after trimming, or longer than the cap. A caller-side mistake, so a
+ * transport maps it to its invalid-parameters error rather than to a
+ * server fault.
+ */
+export class IdempotencyKeyError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "IdempotencyKeyError";
+ }
+}
+
/**
* Thrown by the writers ({@link import('./signal.ts').writeSignal} et al.)
* when a supplied idempotency key was already used with a DIFFERENT
@@ -164,7 +188,7 @@ export function idempotencyLogPath(
): string {
if (!MONTH_RE.test(month)) throw new Error(`invalid idempotency month: ${month}`);
return ensureInsideVault(
- join(vault, IDEMPOTENCY_REL, shardedFileName(month, shardId, IDEMPOTENCY_EXT)),
+ join(vault, IDEMPOTENCY_REL, shardedFileName(month, shardId, JSONL_LEDGER_EXT)),
vault,
);
}
@@ -173,16 +197,22 @@ export function idempotencyLogPath(
* Look up the stored record for a client key across EVERY shard of every
* month. Returns the first-written record for the key (shards read in
* ascending file-name order, lines in append order) or `null` when the
- * key is unseen.
+ * key is unseen. `namespace` selects the key space (see
+ * {@link IdempotencyRecord.namespace}); absent matches only records of the
+ * shared key space, so the historical callers read exactly what they wrote.
*
* The scan spans devices on purpose: a key remembered on one machine has
* to be honoured on another once Syncthing has delivered its shard, or
* the retry this ledger exists to dedupe would go through twice.
*/
-export function lookupKey(vault: string, key: string): IdempotencyRecord | null {
+export function lookupKey(
+ vault: string,
+ key: string,
+ namespace?: string,
+): IdempotencyRecord | null {
const normalised = normaliseKey(key);
for (const record of readAllRecords(vault)) {
- if (record.key === normalised) return record;
+ if (record.key === normalised && record.namespace === namespace) return record;
}
return null;
}
@@ -208,7 +238,7 @@ export function rememberKey(vault: string, input: RememberKeyInput): RememberKey
// The lock is on THIS device's shard - the only file this call can
// append to - while the scan still spans every shard, so a key a
// synced peer already remembered is honoured here too.
- const existing = lookupKey(vault, key);
+ const existing = lookupKey(vault, key, input.namespace);
if (existing) {
return {
status:
@@ -220,6 +250,7 @@ export function rememberKey(vault: string, input: RememberKeyInput): RememberKey
}
const record: IdempotencyRecord = Object.freeze({
key,
+ ...(input.namespace !== undefined ? { namespace: input.namespace } : {}),
contentHash,
createdAt,
...(input.ref !== undefined ? { ref: input.ref } : {}),
@@ -235,11 +266,11 @@ export function rememberKey(vault: string, input: RememberKeyInput): RememberKey
function normaliseKey(key: unknown): string {
if (typeof key !== "string" || key.trim() === "") {
- throw new Error("idempotency key must be a non-empty string");
+ throw new IdempotencyKeyError("idempotency key must be a non-empty string");
}
const trimmed = key.trim();
if (trimmed.length > KEY_MAX_LEN) {
- throw new Error(`idempotency key too long (max ${KEY_MAX_LEN} chars)`);
+ throw new IdempotencyKeyError(`idempotency key too long (max ${KEY_MAX_LEN} chars)`);
}
return trimmed;
}
@@ -253,7 +284,7 @@ function requireHash(hash: unknown): string {
function monthOf(createdAt: string): string {
const month = createdAt.slice(0, 7);
- if (!/^\d{4}-\d{2}$/.test(month)) {
+ if (!MONTH_RE.test(month)) {
throw new Error(
`idempotency createdAt must start with YYYY-MM; got ${JSON.stringify(createdAt)}`,
);
diff --git a/src/core/brain/ingest/ingest.ts b/src/core/brain/ingest/ingest.ts
index 79fde53f..079cba4b 100644
--- a/src/core/brain/ingest/ingest.ts
+++ b/src/core/brain/ingest/ingest.ts
@@ -43,8 +43,12 @@ import {
type Provenance,
} from "../provenance/provenance.ts";
import { PLAN_ID_LABEL, recordCompleted } from "./checkpoint.ts";
-import { updateManifest } from "./content-manifest.ts";
-import { preExtractCodeStructure, type PreExtractResult } from "./pre-extract.ts";
+import { readManifest, updateManifest } from "./content-manifest.ts";
+import {
+ isCodeStructureSource,
+ preExtractCodeStructure,
+ type PreExtractResult,
+} from "./pre-extract.ts";
/** Frontmatter `kind:` marker of an ingested source summary page. */
export const BRAIN_SOURCE_KIND = "brain-source";
@@ -254,9 +258,14 @@ function runPreExtract(vault: string, canonicalSource: string): PreExtractResult
reason: `source does not resolve inside this vault; code-structure pre-extraction skipped: ${canonicalSource}`,
};
}
- const abs = join(vault, canonicalSource);
+ // A source the pass cannot parse needs neither its bytes nor the manifest:
+ // the pass itself reports the unsupported extension, by name.
+ if (!isCodeStructureSource(canonicalSource)) {
+ return preExtractCodeStructure(canonicalSource, "");
+ }
+ let content: string;
try {
- return preExtractCodeStructure(canonicalSource, readFileSync(abs, "utf8"));
+ content = readFileSync(join(vault, canonicalSource), "utf8");
} catch {
// A source with no readable file bytes - a URL/identity-only source, a
// directory, a permission failure, or a deletion race - cannot be parsed,
@@ -266,6 +275,16 @@ function runPreExtract(vault: string, canonicalSource: string): PreExtractResult
reason: `source has no readable file bytes for code-structure pre-extraction: ${canonicalSource}`,
};
}
+ // The manifest's canonical path set is what a relative import specifier
+ // may bind to: a specifier probes it and fills the seed's `resolvedTo`
+ // only on an exactly-one match. The source's OWN entry is not in the set
+ // yet - the manifest is updated after this pass - which is the correct
+ // incremental reality: a module cannot have been ingested before it was.
+ // Read once, outside the source-read guard: a corrupted or unsupported
+ // manifest is its own named error, never "no readable file bytes".
+ return preExtractCodeStructure(canonicalSource, content, {
+ ingestedFiles: new Set(Object.keys(readManifest(vault).entries)),
+ });
}
/**
diff --git a/src/core/brain/ingest/pre-extract.ts b/src/core/brain/ingest/pre-extract.ts
index f935fb92..652143c2 100644
--- a/src/core/brain/ingest/pre-extract.ts
+++ b/src/core/brain/ingest/pre-extract.ts
@@ -18,6 +18,8 @@
* has no declarations returns an empty-but-`extracted: true` result.
*/
+import { resolveUniqueMatch } from "../../graph/unique-match.ts";
+
/** A class/function declaration surfaced as an entity seed. */
export interface CodeEntitySeed {
readonly kind: "class" | "function";
@@ -27,12 +29,30 @@ export interface CodeEntitySeed {
/**
* A structural relationship surfaced as an edge seed. `imports` runs from the
* source path to a module specifier; `inherits` runs from a subclass to a base
- * class (TS `extends`/`implements`, Python base classes).
+ * class (TS `extends`/`implements`, Python base classes); `uses` runs from a
+ * `.tsx`/`.jsx` source path to a JSX component it renders.
+ *
+ * `resolvedTo` is present only when the caller supplied the ingested-file set
+ * and a relative import specifier probed to exactly one ingested file; it
+ * carries that file's canonical vault-relative path. An ambiguous or unmet
+ * probe leaves the seed with its raw specifier and no field.
*/
export interface CodeEdgeSeed {
- readonly kind: "imports" | "inherits";
+ readonly kind: "imports" | "inherits" | "uses";
readonly from: string;
readonly to: string;
+ readonly resolvedTo?: string;
+}
+
+/** Options for the pre-extract pass. Absent, every default is byte-identical. */
+export interface PreExtractOptions {
+ /**
+ * Canonical vault-relative paths of the files already ingested - the
+ * content manifest's key set. Supplied, a relative import specifier
+ * (`./`/`../` for TS/JS, leading-dot for Python) that probes to exactly
+ * one member fills the seed's `resolvedTo`.
+ */
+ readonly ingestedFiles?: ReadonlySet<string>;
}
/** A source whose language family was recognized and parsed. */
@@ -42,7 +62,7 @@ export interface PreExtractSuccess {
readonly language: string;
/** Class/function seeds, deduped and sorted by (kind, name). */
readonly entities: readonly CodeEntitySeed[];
- /** Import/inheritance seeds, deduped and sorted by (kind, from, to). */
+ /** Import/inheritance/uses seeds, deduped and sorted by (kind, from, to). */
readonly edges: readonly CodeEdgeSeed[];
}
@@ -71,6 +91,23 @@ const LANGUAGE_BY_EXTENSION: ReadonlyMap<string, Language> = new Map([
[".pyi", "python"],
]);
+/**
+ * The TS/JS-family extensions in declaration order: what a `./`/`../`
+ * specifier may resolve to. A Python file is never a TS/JS module target.
+ */
+const JS_FAMILY_EXTENSIONS: ReadonlyArray<string> = [...LANGUAGE_BY_EXTENSION]
+ .filter(([, language]) => language !== "python")
+ .map(([ext]) => ext);
+
+/** Directory entry file a TS/JS specifier naming a directory resolves to, minus extension. */
+const JS_INDEX_BASENAME = "index";
+/** Extension a Python relative module specifier resolves to. */
+const PY_MODULE_EXTENSION = ".py";
+/** File a Python relative specifier naming a package resolves to. */
+const PY_PACKAGE_INIT = "__init__.py";
+/** A Python specifier of dots only (`.`, `..`): it names a package, never a module file. */
+const PY_PACKAGE_ONLY_SPECIFIER = /^\.+$/;
+
/** TS/JS class declaration head, capturing the class name. */
const TS_CLASS = /^(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/;
/** TS/JS function declaration head, capturing the function name. */
@@ -98,12 +135,107 @@ const PY_FROM = /^from\s+(\.*[\w.]*)\s+import\b/;
/** A bare Python identifier or dotted name (used to filter base-class args). */
const PY_DOTTED_NAME = /^[A-Za-z_][\w.]*$/;
+/**
+ * How one language family binds a relative import specifier: which
+ * specifiers are relative, how one becomes a `/`-relative path, and the
+ * candidate files it may name, in probe tiers. The first tier holding any
+ * ingested file decides; a later tier is consulted only when every earlier
+ * one is empty.
+ */
+interface RelativeImportRule {
+ readonly relative: RegExp;
+ readonly toRelative: (specifier: string) => string;
+ readonly probeTiers: (joined: string, specifier: string) => ReadonlyArray<ReadonlyArray<string>>;
+}
+
+/**
+ * TS/JS: a `./`/`../` specifier. The joined path is probed alone first, as a
+ * module resolver does for a specifier that already names its file
+ * (`./widget.css`, `./view.js`); then every TS/JS-family extension and the
+ * `/index` form of each.
+ */
+const TS_RELATIVE_IMPORT: RelativeImportRule = {
+ relative: /^\.{1,2}\//,
+ toRelative: (specifier) => specifier,
+ probeTiers: (joined) => [
+ [joined],
+ [
+ ...JS_FAMILY_EXTENSIONS.map((ext) => `${joined}${ext}`),
+ ...JS_FAMILY_EXTENSIONS.map((ext) => childPath(joined, `${JS_INDEX_BASENAME}${ext}`)),
+ ],
+ ],
+};
+
+/**
+ * Python: a leading-dot `from .x import` specifier names the module file
+ * `x.py` or the package `x/__init__.py`. A bare-dot specifier (`from .
+ * import y`) names the enclosing package, so only its `__init__.py`.
+ */
+const PY_RELATIVE_IMPORT: RelativeImportRule = {
+ relative: /^\./,
+ toRelative: pythonSpecifierToRelative,
+ probeTiers: (joined, specifier) => [
+ PY_PACKAGE_ONLY_SPECIFIER.test(specifier)
+ ? [childPath(joined, PY_PACKAGE_INIT)]
+ : [`${joined}${PY_MODULE_EXTENSION}`, childPath(joined, PY_PACKAGE_INIT)],
+ ],
+};
+
+/**
+ * A JSX opening tag whose name is a component, decided by structure alone:
+ *
+ * - the name sits immediately after `<`, and it starts uppercase (or
+ * `_`/`$`): a lowercase-initial name is a DOM/intrinsic tag;
+ * - the character before `<` is not an identifier character, a `.`, or a
+ * `)`: those make the `<` a type-argument list (`Array<Foo>`,
+ * `make()<Foo>`) or a comparison, not an element;
+ * - the name is followed by what only an opening tag allows: the end of the
+ * line (attributes continue below), `>`, `/>`, or whitespace and then an
+ * attribute start (a name or a `{...spread}`). That refuses a dotted
+ * member-expression tag (`<Nav.Item>`) and a type-parameter list, whose
+ * name is followed by `,` (`<T,>`) or by `extends` (`<K extends string>`);
+ * - a bare `>` is not followed by `(`: that is a generic call signature
+ * (`type Fn = <T>(value: T) => T`, `const id: <U>(x: U) => U`), not an
+ * element.
+ *
+ * No per-language tag vocabulary that could fall out of date. Known limits of
+ * a line grammar, accepted on purpose: a capitalized comparison operand
+ * written without a space (`a <Foo b`) can misfire, a generic component
+ * (`<Foo<T> />`) is missed, an element whose text child opens with `(`
+ * (`<Foo>(note)</Foo>`) is missed, and a closing tag never matches. False edges are
+ * bounded by the uppercase-initial rule; missed usages only thin the `uses`
+ * tier.
+ */
+const JSX_COMPONENT_TAG =
+ /(^|[^A-Za-z0-9_$.)])<([A-Z_$][A-Za-z0-9_$]*)(?=$|\s*(?:\/>|>(?!\s*\())|\s+(?!extends\b)[A-Za-z_${])/g;
+
+/** Extensions whose line grammar carries JSX (the `uses` tier). */
+const JSX_EXTENSIONS: ReadonlySet<string> = new Set([".tsx", ".jsx"]);
+
+/**
+ * Whether `path` carries an extension the pass parses. A caller that must
+ * gather inputs before parsing (file bytes, the ingested-file set) asks this
+ * first, so an unsupported source costs no read.
+ */
+export function isCodeStructureSource(path: string): boolean {
+ return LANGUAGE_BY_EXTENSION.has(extensionOf(path));
+}
+
/**
* Extract code structure from `content` addressed by `path`. Returns
* `extracted: false` with a reason when the extension is unsupported, otherwise
* the deduped, sorted entity/edge seeds for the recognized language.
+ *
+ * With `opts.ingestedFiles`, every relative import specifier is probed
+ * against that set in its own language's forms - TS/JS: the joined path, then
+ * each TS/JS-family extension and `/index` + each; Python: `<name>.py` and
+ * `<name>/__init__.py` - and exactly one member fills the seed's `resolvedTo`.
*/
-export function preExtractCodeStructure(path: string, content: string): PreExtractResult {
+export function preExtractCodeStructure(
+ path: string,
+ content: string,
+ opts: PreExtractOptions = {},
+): PreExtractResult {
const ext = extensionOf(path);
const language = ext ? LANGUAGE_BY_EXTENSION.get(ext) : undefined;
if (language === undefined) {
@@ -117,9 +249,9 @@ export function preExtractCodeStructure(path: string, content: string): PreExtra
const entities: CodeEntitySeed[] = [];
const edges: CodeEdgeSeed[] = [];
if (language === "python") {
- parsePython(path, content, entities, edges);
+ parsePython(path, content, entities, edges, opts.ingestedFiles);
} else {
- parseTsJs(path, content, entities, edges);
+ parseTsJs(path, content, entities, edges, opts.ingestedFiles);
}
return {
@@ -136,6 +268,7 @@ function parseTsJs(
content: string,
entities: CodeEntitySeed[],
edges: CodeEdgeSeed[],
+ ingestedFiles?: ReadonlySet<string>,
): void {
for (const raw of content.split("\n")) {
const line = raw.trim();
@@ -159,9 +292,15 @@ function parseTsJs(
if (fnMatch) entities.push({ kind: "function", name: fnMatch[1]! });
const from = TS_FROM.exec(line) ?? TS_BARE_IMPORT.exec(line);
- if (from) edges.push({ kind: "imports", from: path, to: from[1]! });
+ if (from) edges.push(importSeed(path, from[1]!, ingestedFiles, TS_RELATIVE_IMPORT));
const req = TS_REQUIRE.exec(line);
- if (req) edges.push({ kind: "imports", from: path, to: req[1]! });
+ if (req) edges.push(importSeed(path, req[1]!, ingestedFiles, TS_RELATIVE_IMPORT));
+
+ if (JSX_EXTENSIONS.has(extensionOf(path))) {
+ for (const match of line.matchAll(JSX_COMPONENT_TAG)) {
+ edges.push({ kind: "uses", from: path, to: match[2]! });
+ }
+ }
}
}
@@ -171,6 +310,7 @@ function parsePython(
content: string,
entities: CodeEntitySeed[],
edges: CodeEdgeSeed[],
+ ingestedFiles?: ReadonlySet<string>,
): void {
for (const raw of content.split("\n")) {
const line = raw.trim();
@@ -200,7 +340,7 @@ function parsePython(
const fromMatch = PY_FROM.exec(line);
if (fromMatch) {
const mod = fromMatch[1]!;
- if (mod.length > 0) edges.push({ kind: "imports", from: path, to: mod });
+ if (mod.length > 0) edges.push(importSeed(path, mod, ingestedFiles, PY_RELATIVE_IMPORT));
continue;
}
const importMatch = PY_IMPORT.exec(line);
@@ -213,6 +353,72 @@ function parsePython(
}
}
+/** Build an `imports` seed, binding a relative specifier to its ingested file. */
+function importSeed(
+ path: string,
+ to: string,
+ ingestedFiles: ReadonlySet<string> | undefined,
+ rule: RelativeImportRule,
+): CodeEdgeSeed {
+ if (ingestedFiles === undefined || !rule.relative.test(to)) {
+ return { kind: "imports", from: path, to };
+ }
+ const resolvedTo = resolveRelativeImport(path, to, ingestedFiles, rule);
+ return resolvedTo === undefined
+ ? { kind: "imports", from: path, to }
+ : { kind: "imports", from: path, to, resolvedTo };
+}
+
+/**
+ * Probe one relative specifier against the ingested-file set: the specifier
+ * joined to the source's directory (a Python leading-dot specifier first
+ * becomes `./`/`../` form, one `..` per extra dot, module dots as slashes),
+ * then the language's probe tiers in order. The first tier with any ingested
+ * member decides: exactly one names the bound file; several bind nothing.
+ */
+function resolveRelativeImport(
+ path: string,
+ to: string,
+ ingestedFiles: ReadonlySet<string>,
+ rule: RelativeImportRule,
+): string | undefined {
+ const joined = posixJoin(path, rule.toRelative(to));
+ // A specifier climbing above the vault root names nothing the vault holds.
+ if (joined === undefined) return undefined;
+ for (const tier of rule.probeTiers(joined, to)) {
+ const verdict = resolveUniqueMatch(tier.filter((candidate) => ingestedFiles.has(candidate)));
+ if (verdict.status === "unique") return verdict.target;
+ if (verdict.status === "ambiguous") return undefined;
+ }
+ return undefined;
+}
+
+/** `name` inside directory `dir`, where an empty `dir` is the vault root. */
+function childPath(dir: string, name: string): string {
+ return dir.length === 0 ? name : `${dir}/${name}`;
+}
+
+/**
+ * `/`-joined normalization of `specifier` relative to the directory of
+ * `path`, or `undefined` when a `..` would climb above the vault root.
+ */
+function posixJoin(path: string, specifier: string): string | undefined {
+ const segments = path.replaceAll("\\", "/").split("/").slice(0, -1);
+ for (const segment of specifier.replaceAll("\\", "/").split("/")) {
+ if (segment === "" || segment === ".") continue;
+ if (segment !== "..") segments.push(segment);
+ else if (segments.pop() === undefined) return undefined;
+ }
+ return segments.join("/");
+}
+
+/** A Python leading-dot specifier (`..util`) as a `./`-form relative path. */
+function pythonSpecifierToRelative(specifier: string): string {
+ const dots = /^\.+/.exec(specifier)?.[0].length ?? 0;
+ const rest = specifier.slice(dots).replace(/\./g, "/");
+ return "../".repeat(Math.max(0, dots - 1)) + rest;
+}
+
/** Whether a TS/JS line is a comment (line, block-open, or JSDoc continuation). */
function isTsComment(line: string): boolean {
return line.startsWith("//") || line.startsWith("/*") || line.startsWith("*");
diff --git a/src/core/brain/ledger-shards.ts b/src/core/brain/ledger-shards.ts
index 6cd10aa1..425ea15e 100644
--- a/src/core/brain/ledger-shards.ts
+++ b/src/core/brain/ledger-shards.ts
@@ -32,7 +32,7 @@
* Syncthing delivered the files in.
*/
-import { existsSync, readdirSync } from "node:fs";
+import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { resolveDeviceId } from "../config.ts";
@@ -79,6 +79,22 @@ export interface LedgerShardGrammar {
readonly extensions: ReadonlyArray<string>;
}
+/** The extension every JSON Lines ledger writes, without the leading dot. */
+export const JSONL_LEDGER_EXT = "jsonl";
+
+/**
+ * The grammar of a JSON Lines ledger whose base is one fixed file stem
+ * (`<stem>[.<shardId>].jsonl`). The stem is escaped through
+ * {@link literalBase}, so the writer can hand the same stem to
+ * {@link shardedFileName} and the two can never disagree on the name.
+ */
+export function jsonlLedgerGrammar(stem: string): LedgerShardGrammar {
+ return Object.freeze({
+ base: literalBase(stem),
+ extensions: Object.freeze([JSONL_LEDGER_EXT]),
+ });
+}
+
/** The shape of one recognised ledger file name. */
export interface ParsedShardedName {
readonly base: string;
@@ -201,6 +217,95 @@ export function listSyncConflictFiles(dir: string): string[] {
.toSorted();
}
+/** One shard's rows, in the order the shard itself holds them. */
+export interface ShardRows<T> {
+ /** Empty string for the legacy un-sharded file. */
+ readonly shardId: string;
+ readonly rows: ReadonlyArray<T>;
+}
+
+/**
+ * Every non-blank line of every shard of one ledger, grouped by shard:
+ * shards in ascending name order, lines in append order.
+ *
+ * A shard listed but vanished before the read is skipped (a concurrent
+ * compactor won); any other read failure propagates - "could not tell"
+ * must never resolve to "no rows". Conflict copies are never listed.
+ */
+export function readShardLinesByShard(
+ dir: string,
+ grammar: LedgerShardGrammar,
+): Array<ShardRows<string>> {
+ const out: Array<ShardRows<string>> = [];
+ for (const shard of listShardedFiles(dir, grammar)) {
+ let text: string;
+ try {
+ text = readFileSync(shard.path, "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
+ throw err;
+ }
+ out.push({
+ shardId: shard.shardId,
+ rows: text.split("\n").filter((line) => line.trim() !== ""),
+ });
+ }
+ return out;
+}
+
+/**
+ * Every non-blank line of every shard of one ledger, shards in ascending
+ * name order (the legacy name sorts among the device shards by the shared
+ * stem) and lines in append order.
+ *
+ * This is the merged read for ledgers whose rows carry no sort key of their
+ * own: a single-shard vault reads back in exactly the order it always did,
+ * and a multi-device one gets the deterministic shard-id order instead of
+ * Syncthing's arrival order. Failure handling is
+ * {@link readShardLinesByShard}'s.
+ */
+export function readShardedLines(dir: string, grammar: LedgerShardGrammar): string[] {
+ return readShardLinesByShard(dir, grammar).flatMap((shard) => shard.rows);
+}
+
+/**
+ * Interleave shards into one ascending sequence by each row's time `at`,
+ * WITHOUT ever reordering the rows of one shard.
+ *
+ * This is the merge for a ledger whose own file order is authoritative -
+ * an append-only journal read newest-first, where a clock stepped back on
+ * one device must not reshuffle that device's history. Each step takes the
+ * earliest head among the shards; equal heads go to the lower shard id, so
+ * every device sees the same sequence. A single shard reads back in
+ * exactly its file order. `at` must return a comparable number for every
+ * row (map an unreadable time to a fixed sentinel, not NaN).
+ */
+export function interleaveShardRows<T>(
+ shards: ReadonlyArray<ShardRows<T>>,
+ at: (value: T) => number,
+): T[] {
+ const cursors = shards.map(() => 0);
+ const out: T[] = [];
+ for (;;) {
+ let pick = -1;
+ let pickAt = 0;
+ for (const [index, shard] of shards.entries()) {
+ const head = shard.rows[cursors[index]!];
+ if (head === undefined) continue;
+ const time = at(head);
+ const earlier =
+ pick === -1 || time < pickAt || (time === pickAt && shard.shardId < shards[pick]!.shardId);
+ if (earlier) {
+ pick = index;
+ pickAt = time;
+ }
+ }
+ if (pick === -1) return out;
+ out.push(shards[pick]!.rows[cursors[pick]!]!);
+ cursors[pick] = cursors[pick]! + 1;
+ }
+}
+
/** One row read out of one shard, tagged with where it came from. */
export interface ShardedRow<T> {
readonly value: T;
diff --git a/src/core/brain/link-graph/alias-index.ts b/src/core/brain/link-graph/alias-index.ts
index 04ed83a9..194a01d9 100644
--- a/src/core/brain/link-graph/alias-index.ts
+++ b/src/core/brain/link-graph/alias-index.ts
@@ -15,7 +15,9 @@
*
* Collisions (two artifacts claim the same alias) resolve
* first-wins by sorted canonical id - deterministic without an
- * extra timestamp lookup. A follow-up `brain_doctor` lint can
+ * extra timestamp lookup. A caller that must refuse a colliding
+ * alias instead of guessing reads `listAliasClaims`, which keeps
+ * every claimant. A follow-up `brain_doctor` lint can
* later surface colliding aliases for operator attention; this
* helper is intentionally tolerant so the index keeps building.
*
@@ -45,8 +47,39 @@ export type AliasIndex = ReadonlyMap<string, string>;
* incremental update path on purpose.
*/
export function buildAliasIndex(vault: string): AliasIndex {
- const dirs = brainDirs(vault);
const map = new Map<string, string>();
+ // First-wins: only set when the key isn't taken yet.
+ forEachAliasClaim(vault, (key, canonicalId) => {
+ if (!map.has(key)) map.set(key, canonicalId);
+ });
+ return Object.freeze(map) as AliasIndex;
+}
+
+/**
+ * Frozen `aliasLowerNFC → canonicalIds` multimap: every artifact that
+ * claims each alias, in the same sorted order whose first entry
+ * `buildAliasIndex` keeps. An artifact listing one alias twice is one
+ * claimant.
+ */
+export type AliasClaims = ReadonlyMap<string, ReadonlyArray<string>>;
+
+/**
+ * Every claimant of every alias, under the same normalisation and
+ * shadowing rules as `buildAliasIndex`, without resolving collisions.
+ */
+export function listAliasClaims(vault: string): AliasClaims {
+ const map = new Map<string, string[]>();
+ forEachAliasClaim(vault, (key, canonicalId) => {
+ const claimants = map.get(key);
+ if (claimants === undefined) map.set(key, [canonicalId]);
+ else if (!claimants.includes(canonicalId)) claimants.push(canonicalId);
+ });
+ return Object.freeze(map) as AliasClaims;
+}
+
+/** Visit every (alias key, canonical id) claim in deterministic order. */
+function forEachAliasClaim(vault: string, visit: (key: string, canonicalId: string) => void): void {
+ const dirs = brainDirs(vault);
// Collect every on-disk canonical id (lower-cased + NFC) in one
// pass so the alias-collection phase can skip any alias that
@@ -56,14 +89,11 @@ export function buildAliasIndex(vault: string): AliasIndex {
collectCanonicalNames(dirs.preferences, reservedCanonical);
collectCanonicalNames(dirs.retired, reservedCanonical);
- // Single sorted pass yields deterministic first-wins resolution
- // when two artifacts claim the same alias. Sorting by `(kind,
- // basename)` puts `pref-*` before `ret-*`; within each kind,
- // alphabetical basename order wins.
- collect(dirs.preferences, reservedCanonical, map);
- collect(dirs.retired, reservedCanonical, map);
-
- return Object.freeze(map) as AliasIndex;
+ // A single sorted pass yields a deterministic claim order. Sorting
+ // by `(kind, basename)` puts `pref-*` before `ret-*`; within each
+ // kind, alphabetical basename order comes first.
+ collect(dirs.preferences, reservedCanonical, visit);
+ collect(dirs.retired, reservedCanonical, visit);
}
function collectCanonicalNames(dir: string, into: Set<string>): void {
@@ -78,12 +108,11 @@ function collectCanonicalNames(dir: string, into: Set<string>): void {
function collect(
dir: string,
reservedCanonical: ReadonlySet<string>,
- into: Map<string, string>,
+ visit: (key: string, canonicalId: string) => void,
): void {
if (!existsSync(dir)) return;
- // Sort the directory listing so the first-wins rule is
- // deterministic across filesystems that don't enumerate in
- // stable order.
+ // Sort the directory listing so the claim order is deterministic
+ // across filesystems that don't enumerate in stable order.
const entries = readdirSync(dir).toSorted();
for (const name of entries) {
if (!name.endsWith(".md")) continue;
@@ -107,8 +136,7 @@ function collect(
// to avoid hijacking its backlinks. A follow-up brain_doctor
// lint surfaces these collisions for operator attention.
if (reservedCanonical.has(key)) continue;
- // First-wins: only set when the key isn't taken yet.
- if (!into.has(key)) into.set(key, canonicalId);
+ visit(key, canonicalId);
}
}
}
diff --git a/src/core/brain/link-graph/repair-lane.ts b/src/core/brain/link-graph/repair-lane.ts
index cafeca9e..fe6c3b44 100644
--- a/src/core/brain/link-graph/repair-lane.ts
+++ b/src/core/brain/link-graph/repair-lane.ts
@@ -36,6 +36,8 @@ import {
import { listContinuityRecords } from "../continuity/store.ts";
import { ENTITY_STATUS_SCOPE, vaultPageInStatusScope } from "../entities/page-scope.ts";
import { canonicalCoOccurrenceKey, computeCoOccurrenceSuggestions } from "./co-occurrence.ts";
+import { listAliasClaims } from "./alias-index.ts";
+import { resolveUniqueMatch } from "../../graph/unique-match.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { scaffoldStub } from "../notes/scaffold-stub.ts";
import { MAINTENANCE_LANE_REACH } from "../../graph/transport-reach.ts";
@@ -91,7 +93,8 @@ export type RepairAction =
| "skip-missing-source"
| "skip-missing-target"
| "skip-unsafe-path"
- | "skip-null-endpoint-key";
+ | "skip-null-endpoint-key"
+ | "skip-ambiguous";
export interface RepairDecision extends RepairCandidate {
readonly action: RepairAction;
@@ -134,6 +137,16 @@ export interface RepairLaneOptions {
* repair pass.
*/
readonly scaffoldMissingTargets?: boolean;
+ /**
+ * Named refusals collected upstream - today, the explicit-reference
+ * collector's `skip-ambiguous` decisions for a mention term carried by
+ * more than one corpus page. They are reported verbatim in `decisions`
+ * (ordered by the candidate order) and nothing else: never re-decided
+ * by the loop below, never counted in `written`, never capped. A
+ * refusal proposes no edge, so it is the caller's job to keep it out
+ * of any downstream population that reasoning over proposed edges.
+ */
+ readonly collectedRefusals?: ReadonlyArray<RepairDecision>;
}
/** Raised when an apply is requested without the exact confirmation phrase. */
@@ -146,7 +159,7 @@ export class RepairConfirmationError extends Error {
}
}
-function orderCandidates(candidates: readonly RepairCandidate[]): RepairCandidate[] {
+function orderCandidates<T extends RepairCandidate>(candidates: readonly T[]): T[] {
return [...candidates].toSorted((a, b) => {
const rank = STRENGTH_RANK[a.strength] - STRENGTH_RANK[b.strength];
if (rank !== 0) return rank;
@@ -302,7 +315,7 @@ export function runRepairLane(
return {
mode: apply ? "apply" : "dry-run",
written,
- decisions: Object.freeze(decisions),
+ decisions: Object.freeze([...orderCandidates(opts.collectedRefusals ?? []), ...decisions]),
scaffolded: Object.freeze(scaffolded.toSorted()),
};
}
@@ -375,11 +388,10 @@ function isWordEdge(ch: string | undefined): boolean {
return ch === undefined || !WORD_CHAR_RE.test(ch);
}
-/** True when `term` occurs in `masked` at a word boundary (case-insensitive). */
-function mentionsTerm(masked: string, term: string): boolean {
- if (term.length < MIN_EXPLICIT_REFERENCE_TITLE_LENGTH) return false;
- const lower = masked.toLowerCase();
- const needle = term.toLowerCase();
+/** True when `needle` occurs in `masked` at a word boundary (case-insensitive).
+ * `lower` is `masked` pre-lowercased, hoisted out of the per-term loop. */
+function mentionsTerm(lower: string, masked: string, needle: string): boolean {
+ if (needle.length < MIN_EXPLICIT_REFERENCE_TITLE_LENGTH) return false;
let from = 0;
for (;;) {
const idx = lower.indexOf(needle, from);
@@ -438,14 +450,109 @@ export interface CollectRepairCandidatesOptions {
readonly minCoDocuments?: number;
}
+/** One mention term in the corpus pool: its scanned form, its display spelling, and every page carrying it. */
+interface MentionTerm {
+ /** NFC + lowercase form the word-boundary scan matches. */
+ readonly needle: string;
+ /** Spelling the reason strings name (the title, or the alias as indexed). */
+ readonly display: string;
+ /** The corpus pages carrying the term, one per path, ordered by path. */
+ readonly carriers: ReadonlyArray<CollectedPage>;
+}
+
+/** Code-point order of two strings, for deterministic sorts. */
+function compareStrings(a: string, b: string): number {
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
+/** Normalized lookup form of a term, exactly as the alias index keys its side. */
+function termNeedle(value: string): string {
+ return value.normalize("NFC").toLowerCase();
+}
+
/**
- * Collect deterministic repair candidates from vault structure. Never emits an
- * edge that already exists, and never emits inferred candidates.
+ * Pool the mention terms every corpus page carries: each page's title, plus
+ * every page claiming each alias (`listAliasClaims`, never the first-wins
+ * index, so a colliding alias reaches the exactly-one rule with all its
+ * carriers). Titles register first, so a term spelled as a title keeps the
+ * title as its display form; a claimant matching no corpus page contributes
+ * nothing.
*/
-export function collectRepairCandidates(
+function collectMentionTerms(pages: ReadonlyArray<CollectedPage>, vault: string): MentionTerm[] {
+ // Carriers pool by path while terms register, so a page reached through
+ // both its title and an alias carries a term once.
+ const terms = new Map<
+ string,
+ {
+ readonly needle: string;
+ readonly display: string;
+ readonly carriers: Map<string, CollectedPage>;
+ }
+ >();
+ for (const page of pages) {
+ const needle = termNeedle(page.title);
+ if (needle.length === 0) continue;
+ const existing = terms.get(needle);
+ if (existing === undefined) {
+ terms.set(needle, { needle, display: page.title, carriers: new Map([[page.rel, page]]) });
+ } else {
+ existing.carriers.set(page.rel, page);
+ }
+ }
+ const byKey = new Map<string, CollectedPage[]>();
+ for (const page of pages) {
+ const bucket = byKey.get(page.key);
+ if (bucket === undefined) byKey.set(page.key, [page]);
+ else bucket.push(page);
+ }
+ for (const [aliasKey, canonicalIds] of listAliasClaims(vault)) {
+ for (const canonicalId of canonicalIds) {
+ const bucket = byKey.get(canonicalId.normalize("NFC").toLowerCase().trim());
+ if (bucket === undefined) continue;
+ const existing = terms.get(aliasKey);
+ if (existing === undefined) {
+ terms.set(aliasKey, {
+ needle: aliasKey,
+ display: aliasKey,
+ carriers: new Map(bucket.map((page) => [page.rel, page])),
+ });
+ } else {
+ for (const page of bucket) existing.carriers.set(page.rel, page);
+ }
+ }
+ }
+ return [...terms.values()]
+ .map((term) => ({
+ needle: term.needle,
+ display: term.display,
+ carriers: [...term.carriers.values()].toSorted((a, b) => compareStrings(a.rel, b.rel)),
+ }))
+ .toSorted((a, b) => compareStrings(a.needle, b.needle));
+}
+
+/** Refusal reason for a term the corpus cannot bind to one page. */
+function ambiguousTermReason(display: string, carrierCount: number): string {
+ return (
+ `explicit textual reference to ${JSON.stringify(display)} is ambiguous: ` +
+ `${carrierCount} pages carry it`
+ );
+}
+
+/**
+ * Collect deterministic repair candidates from vault structure, together
+ * with the mention terms the corpus refuses to bind. Never emits an edge that
+ * already exists, and never emits inferred candidates.
+ *
+ * A term (title or alias) that exactly one corpus page carries proposes the
+ * same explicit-reference candidate a title match always has. A term carried
+ * by several pages binds to none of them: every (mentioning page, carrying
+ * page) pair comes back as a `skip-ambiguous` refusal, so the operator sees
+ * why no edge was proposed instead of finding one arbitrary target linked.
+ */
+export function collectRepairCandidatesWithRefusals(
vault: string,
opts: CollectRepairCandidatesOptions = {},
-): RepairCandidate[] {
+): RepairCandidateCollection {
const pages = loadPages(vault);
const byKey = new Map<string, CollectedPage>();
for (const page of pages) byKey.set(page.key, page);
@@ -463,20 +570,46 @@ export function collectRepairCandidates(
}
};
- // Explicit references: a note names another note's title but does not link it.
+ // Explicit references: a note names a corpus term but does not link its
+ // page. Terms pool titles and aliases; only an exactly-one carrier binds.
+ const refusals: RepairDecision[] = [];
+ const terms = collectMentionTerms(pages, vault);
for (const page of pages) {
const masked = maskSpans(page.body);
- for (const other of pages) {
- if (other.key === page.key) continue;
- if (page.linkedKeys.has(other.key)) continue;
- if (!mentionsTerm(masked, other.title)) continue;
- consider({
- source: page.rel,
- target: other.rel,
- strength: IDENTITY_STRENGTH.explicitReference,
- confidence: EXPLICIT_REFERENCE_CONFIDENCE,
- reason: `explicit textual reference to ${JSON.stringify(other.title)}`,
- });
+ const lower = masked.toLowerCase();
+ for (const term of terms) {
+ if (!mentionsTerm(lower, masked, term.needle)) continue;
+ const verdict = resolveUniqueMatch(term.carriers);
+ if (verdict.status === "unique") {
+ const target = verdict.target;
+ if (target.key === page.key) continue;
+ if (page.linkedKeys.has(target.key)) continue;
+ consider({
+ source: page.rel,
+ target: target.rel,
+ strength: IDENTITY_STRENGTH.explicitReference,
+ confidence: EXPLICIT_REFERENCE_CONFIDENCE,
+ reason: `explicit textual reference to ${JSON.stringify(term.display)}`,
+ });
+ } else if (verdict.status === "ambiguous") {
+ // A page that already links one carrier has resolved the mention
+ // itself, exactly as the unique path skips an existing edge: there
+ // is nothing left to refuse.
+ if (verdict.matches.some((carrier) => page.linkedKeys.has(carrier.key))) continue;
+ // A carrier naming the term names itself, the same self-reference
+ // the unique path skips: refusing it would point at the others.
+ if (verdict.matches.includes(page)) continue;
+ for (const target of verdict.matches) {
+ refusals.push({
+ source: page.rel,
+ target: target.rel,
+ strength: IDENTITY_STRENGTH.explicitReference,
+ confidence: EXPLICIT_REFERENCE_CONFIDENCE,
+ action: "skip-ambiguous",
+ reason: ambiguousTermReason(term.display, verdict.matches.length),
+ });
+ }
+ }
}
}
@@ -531,5 +664,15 @@ export function collectRepairCandidates(
});
}
- return orderCandidates([...best.values()]);
+ return {
+ candidates: orderCandidates([...best.values()]),
+ refusals: orderCandidates(refusals),
+ };
+}
+
+/** Candidates plus the named refusals the corpus recorded while collecting. */
+export interface RepairCandidateCollection {
+ readonly candidates: RepairCandidate[];
+ /** `skip-ambiguous` decisions, ordered by the candidate order. */
+ readonly refusals: ReadonlyArray<RepairDecision>;
}
diff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.ts
index a8f4fc59..521d29d3 100644
--- a/src/core/brain/maintenance/journal.ts
+++ b/src/core/brain/maintenance/journal.ts
@@ -10,6 +10,15 @@
import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
+import {
+ interleaveShardRows,
+ JSONL_LEDGER_EXT,
+ jsonlLedgerGrammar,
+ readShardLinesByShard,
+ resolveAppendShardId,
+ shardedFileName,
+} from "../ledger-shards.ts";
+import { DERIVED_STORE_DIR } from "../path-constants.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import type { HostPressureUnmeasurableReason } from "./host-pressure.ts";
import { renameWithRetry } from "../../fs-atomic.ts";
@@ -20,7 +29,7 @@ export const MAINTENANCE_JOURNAL_CAP = 500;
* What one journal row records.
*
* A closed vocabulary rather than a bare union because these values are
- * persisted to `.open-second-brain/maintenance-runs.jsonl` and read back
+ * persisted to `.open-second-brain/maintenance-runs[.<deviceId>].jsonl` and read back
* by whichever build runs next - across an upgrade, that is not the build
* that wrote them. The guard is the boundary for a row this build does
* not understand.
@@ -72,8 +81,23 @@ export interface MaintenanceJournalEntry {
readonly streak?: number;
}
+/** The journal's shard stem: `maintenance-runs[.<deviceId>].jsonl`. */
+export const MAINTENANCE_JOURNAL_STEM = "maintenance-runs";
+
+/** The journal's file-name layout, handed to the shared shard grammar. */
+const JOURNAL_GRAMMAR = jsonlLedgerGrammar(MAINTENANCE_JOURNAL_STEM);
+
+/**
+ * The journal file THIS device appends to, and the only shard the cap
+ * sweep rewrites: `maintenance-runs[.<deviceId>].jsonl` (t_774dea61). The
+ * empty device id yields the legacy un-sharded name.
+ */
function journalPath(vault: string): string {
- return join(vault, ".open-second-brain", "maintenance-runs.jsonl");
+ return join(
+ vault,
+ DERIVED_STORE_DIR,
+ shardedFileName(MAINTENANCE_JOURNAL_STEM, resolveAppendShardId(), JSONL_LEDGER_EXT),
+ );
}
export function appendJournal(vault: string, entry: MaintenanceJournalEntry): void {
@@ -102,21 +126,47 @@ export function sweepJournal(vault: string, cap: number = MAINTENANCE_JOURNAL_CA
renameWithRetry(tmp, path);
}
-/** Journal entries, newest first. Unparseable lines are skipped. */
-export function listJournal(vault: string, limit?: number): MaintenanceJournalEntry[] {
- const lines = readLines(journalPath(vault));
- const out: MaintenanceJournalEntry[] = [];
- for (const line of lines) {
- try {
- const parsed: unknown = JSON.parse(line);
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
- out.push(parsed as MaintenanceJournalEntry);
- }
- } catch {
- // Fail-soft: a torn line never breaks the journal read.
- }
+/**
+ * When a row was written, as the merge orders it. A row whose stamp does
+ * not parse sorts as the oldest, so it can never displace a readable row
+ * from the head of the newest-first list.
+ */
+function entryTime(entry: MaintenanceJournalEntry): number {
+ const time = Date.parse(entry.ts);
+ return Number.isFinite(time) ? time : Number.NEGATIVE_INFINITY;
+}
+
+/** One journal line as an entry, or `null` for a torn or non-object line. */
+function parseEntry(line: string): MaintenanceJournalEntry | null {
+ try {
+ const parsed: unknown = JSON.parse(line);
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as MaintenanceJournalEntry)
+ : null;
+ } catch {
+ // Fail-soft: a torn line never breaks the journal read.
+ return null;
}
- out.reverse();
+}
+
+/**
+ * Journal entries, newest first - the one order both this list and
+ * {@link consecutiveTaskFailures} walk.
+ *
+ * Every device's shard (t_774dea61) is interleaved by row timestamp, so a
+ * failure on one device that is newer than a success on another reads as
+ * newer whatever the shard names are; each shard's own append order is
+ * never changed, so a single-shard vault reads exactly as before.
+ * Unparseable lines are skipped.
+ */
+export function listJournal(vault: string, limit?: number): MaintenanceJournalEntry[] {
+ const shards = readShardLinesByShard(dirname(journalPath(vault)), JOURNAL_GRAMMAR).map(
+ (shard) => ({
+ shardId: shard.shardId,
+ rows: shard.rows.map(parseEntry).filter((entry) => entry !== null),
+ }),
+ );
+ const out = interleaveShardRows(shards, entryTime).toReversed();
return limit !== undefined ? out.slice(0, Math.max(0, limit)) : out;
}
diff --git a/src/core/brain/maintenance/lease.ts b/src/core/brain/maintenance/lease.ts
index 9f00c849..18112d14 100644
--- a/src/core/brain/maintenance/lease.ts
+++ b/src/core/brain/maintenance/lease.ts
@@ -12,6 +12,7 @@ import { Database } from "bun:sqlite";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { closeDatabase } from "../../sqlite-close.ts";
+import { DERIVED_STORE_DIR } from "../path-constants.ts";
export const MAINTENANCE_LEASE_NAME = "maintenance";
@@ -34,7 +35,7 @@ export interface LeaseState {
}
function leaseDbPath(vault: string): string {
- return join(vault, ".open-second-brain", "maintenance.sqlite");
+ return join(vault, DERIVED_STORE_DIR, "maintenance.sqlite");
}
function openLeaseDb(vault: string): Database {
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 3c8021a3..c1fbd491 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -30,7 +30,7 @@ import { join } from "node:path";
import { isFileAlreadyExists } from "../fs-atomic.ts";
import { ensureInsideVault, vaultRelative } from "../path-safety.ts";
import type { DegradationNotice } from "../integrity/degradation.ts";
-import { resolveAppendShardId, shardedFileName } from "./ledger-shards.ts";
+import { JSONL_LEDGER_EXT, resolveAppendShardId, shardedFileName } from "./ledger-shards.ts";
import {
BRAIN_ARTIFACTS_REL,
BRAIN_ACTIVE_FILE,
@@ -395,8 +395,23 @@ export function reportPagePath(vault: string, date: string, slug: string): strin
* because the walker only yields `.md` files.
*/
export function preferenceHistoryPath(vault: string, slug: string): string {
- const s = validateSlug(slug);
- return ensureInsideVault(join(brainDirs(vault).preferences, `pref-${s}.history.jsonl`), vault);
+ // Per-device shard (t_774dea61): each machine appends to its own
+ // history file; the empty device id keeps the legacy un-sharded name.
+ return ensureInsideVault(
+ join(
+ brainDirs(vault).preferences,
+ shardedFileName(preferenceHistoryStem(slug), resolveAppendShardId(), JSONL_LEDGER_EXT),
+ ),
+ vault,
+ );
+}
+
+/**
+ * The shard stem of one preference's edit history, `pref-<slug>.history`:
+ * the writer names its shard from it and the reader's grammar escapes it.
+ */
+export function preferenceHistoryStem(slug: string): string {
+ return `pref-${validateSlug(slug)}.history`;
}
/** Retired-preference path: `Brain/retired/ret-<slug>.md`. */
@@ -516,19 +531,45 @@ export function proposalWatermarkPath(vault: string): string {
);
}
-/** Recurrence support ledger path: `Brain/log/recurrence-support.jsonl`. */
+/** Shard stem of the recurrence support ledger under `Brain/log/`. */
+export const RECURRENCE_LEDGER_STEM = "recurrence-support";
+
+/** Shard stem of the cross-query demand ledger under `Brain/log/`. */
+export const QUERY_DEMAND_LEDGER_STEM = "query-demand";
+
+/** Shard stem of the capture-decision ledger under `Brain/log/`. */
+export const CAPTURE_DECISION_LEDGER_STEM = "capture-decisions";
+
+/**
+ * The `Brain/log/` ledger file THIS device appends to for `stem`:
+ * `<stem>[.<deviceId>].jsonl` (t_774dea61). The empty device id yields the
+ * legacy un-sharded name, so a vault without a device id writes the same
+ * file it always did.
+ */
+function brainLogLedgerPath(vault: string, stem: string): string {
+ return ensureInsideVault(
+ join(vault, BRAIN_LOG_REL, shardedFileName(stem, resolveAppendShardId(), JSONL_LEDGER_EXT)),
+ vault,
+ );
+}
+
+/**
+ * Recurrence support ledger, this device's shard:
+ * `Brain/log/recurrence-support[.<deviceId>].jsonl`.
+ */
export function proceduralRecurrencePath(vault: string): string {
- return ensureInsideVault(join(vault, BRAIN_LOG_REL, "recurrence-support.jsonl"), vault);
+ return brainLogLedgerPath(vault, RECURRENCE_LEDGER_STEM);
}
/**
- * Cross-query demand ledger path: `Brain/log/query-demand.jsonl`. A
- * rolling, byte-budget-capped append-only log of normalized recall
- * queries with their result count and IDF-weighted coverage, aggregated
- * to surface recurring queries the vault answers poorly (unmet demand).
+ * Cross-query demand ledger, this device's shard:
+ * `Brain/log/query-demand[.<deviceId>].jsonl`. A rolling,
+ * byte-budget-capped append-only log of normalized recall queries with
+ * their result count and IDF-weighted coverage, aggregated to surface
+ * recurring queries the vault answers poorly (unmet demand).
*/
export function queryDemandLogPath(vault: string): string {
- return ensureInsideVault(join(vault, BRAIN_LOG_REL, "query-demand.jsonl"), vault);
+ return brainLogLedgerPath(vault, QUERY_DEMAND_LEDGER_STEM);
}
/** Inbound-capture staging dir: `Brain/captures/` (seam 1, t_f8f5ef6a). */
@@ -561,12 +602,15 @@ export function captureWatermarkPath(vault: string): string {
}
/**
- * Capture-decision ledger: `Brain/log/capture-decisions.jsonl` (seam 1).
+ * Capture-decision ledger, this device's shard:
+ * `Brain/log/capture-decisions[.<deviceId>].jsonl` (seam 1).
* One JSON line per inbound update the bot handled - accepted, rejected, or
* malformed - so no update is ever silently dropped.
*/
export function captureDecisionLogPath(vault: string): string {
- return ensureInsideVault(join(vault, BRAIN_LOG_REL, "capture-decisions.jsonl"), vault);
+ // Per-device shard (t_774dea61): the capture host on each machine appends
+ // to its own file; the empty device id keeps the legacy name.
+ return brainLogLedgerPath(vault, CAPTURE_DECISION_LEDGER_STEM);
}
/** Log file for the given UTC date: `Brain/log/<YYYY-MM-DD>.md`. */
diff --git a/src/core/brain/query-demand.ts b/src/core/brain/query-demand.ts
index 16f24546..c37310a3 100644
--- a/src/core/brain/query-demand.ts
+++ b/src/core/brain/query-demand.ts
@@ -22,18 +22,22 @@
* (never the raw query), each run through the secret redactor, so a
* query carrying a token or path cannot leak into the log.
*
- * Storage: `Brain/log/query-demand.jsonl`, one JSON record per line,
- * rolling and byte-budget-capped (see {@link DEMAND_LOG_MAX_BYTES}).
+ * Storage: one shard per device, `Brain/log/query-demand[.<deviceId>].jsonl`
+ * (the empty device id keeps the legacy un-sharded name), one JSON record
+ * per line. Each device appends to and compacts only its own shard, within
+ * the byte budget (see {@link DEMAND_LOG_MAX_BYTES}); reads merge every
+ * shard.
*/
-import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
-import { dirname } from "node:path";
+import { appendFileSync, mkdirSync, readFileSync, statSync } from "node:fs";
+import { dirname, join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { clamp01 } from "../math.ts";
-import { ensureInsideVault } from "../path-safety.ts";
import { redactRawOutput } from "../redactor.ts";
-import { queryDemandLogPath } from "./paths.ts";
+import { BRAIN_LOG_REL } from "./path-constants.ts";
+import { jsonlLedgerGrammar, readShardedLines } from "./ledger-shards.ts";
+import { QUERY_DEMAND_LEDGER_STEM, queryDemandLogPath } from "./paths.ts";
import { acquireLockSync } from "./sync-lockfile.ts";
import {
COMPLETENESS_COMPLETE_THRESHOLD,
@@ -222,6 +226,9 @@ function isSecretShapedTerm(term: string): boolean {
return /[a-z]/.test(term) && /[0-9]/.test(term);
}
+/** The demand ledger's file-name layout, handed to the shared shard grammar. */
+const DEMAND_LEDGER_GRAMMAR = jsonlLedgerGrammar(QUERY_DEMAND_LEDGER_STEM);
+
/**
* Append one recall observation to the demand log. Terms are derived
* from `terms` (redacted) or `query` (normalized+redacted); a query with
@@ -247,8 +254,11 @@ export function recordQueryDemand(
};
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
+ // Per-device shard (t_774dea61): this device appends to a file no other
+ // device writes, and the per-file lock plus the in-place compaction are
+ // scoped to that one shard.
const path = queryDemandLogPath(vault);
- mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
+ mkdirSync(dirname(path), { recursive: true });
const handle = acquireLockSync(path);
try {
appendFileSync(path, `${JSON.stringify(record)}\n`, { encoding: "utf8" });
@@ -327,8 +337,9 @@ export function readQueryDemand(
vault: string,
filter: QueryDemandFilter = {},
): ReadonlyArray<QueryDemandRecord> {
- const path = queryDemandLogPath(vault);
- if (!existsSync(path)) return Object.freeze([]);
+ // Merged read over every device's shard (t_774dea61); the absent
+ // directory lists nothing, which is the same empty result as before.
+ const lines = readShardedLines(join(vault, BRAIN_LOG_REL), DEMAND_LEDGER_GRAMMAR);
// Normalize the filter bounds to the same millisecond-precision form the
// stored `ts` already uses (records are normalized at write time). The
// comparison below is lexical, so a second-precision `--since
@@ -338,8 +349,7 @@ export function readQueryDemand(
const since = filter.since !== undefined ? normalizeDemandTimestamp(filter.since) : undefined;
const until = filter.until !== undefined ? normalizeDemandTimestamp(filter.until) : undefined;
const out: QueryDemandRecord[] = [];
- for (const line of readFileSync(path, "utf8").split("\n")) {
- if (!line.trim()) continue;
+ for (const line of lines) {
const record = coerceRecord(line);
if (record === null) continue;
if (since !== undefined && record.ts < since) continue;
@@ -522,13 +532,10 @@ function coerceRecord(line: string): QueryDemandRecord | null {
* O(1) until the rare compaction.
*/
function compactIfNeeded(path: string): void {
- let size: number;
- try {
- size = statSync(path).size;
- } catch {
- return;
- }
- if (size <= DEMAND_LOG_MAX_BYTES) return;
+ // Only a vanished shard is "nothing to compact"; any other stat failure
+ // (EACCES, EIO) propagates by its code instead of leaving the cap unchecked.
+ const size = statSync(path, { throwIfNoEntry: false })?.size;
+ if (size === undefined || size <= DEMAND_LOG_MAX_BYTES) return;
const lines = readFileSync(path, "utf8")
.split("\n")
.filter((line) => line.trim().length > 0);
diff --git a/src/core/brain/recompile.ts b/src/core/brain/recompile.ts
index 2c166384..a831d507 100644
--- a/src/core/brain/recompile.ts
+++ b/src/core/brain/recompile.ts
@@ -16,6 +16,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { basename, isAbsolute, join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
+import { HYGIENE_AUDIT_DIR } from "./audit-dirs.ts";
import { scanFreshness } from "./freshness.ts";
import { writeHandoffNote } from "./handoff.ts";
import { brainDirsForWrite, BRAIN_SNAPSHOTS_REL } from "./paths.ts";
@@ -206,7 +207,7 @@ export async function executeRecompile(
!dryRun &&
(rederived.length > 0 || archived.length > 0 || manual.length > 0 || errors.length > 0)
) {
- appendAuditRecord(join(brainDirsForWrite(vault).log, "hygiene"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, HYGIENE_AUDIT_DIR), {
timestamp: opts.now.toISOString(),
actor: opts.agent,
action: "targeted_recompile",
diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.ts
index b4e02613..2fdf34d7 100644
--- a/src/core/brain/recurrence.ts
+++ b/src/core/brain/recurrence.ts
@@ -1,10 +1,14 @@
-import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
-import { dirname } from "node:path";
+import { appendFileSync, mkdirSync } from "node:fs";
+import { dirname, join } from "node:path";
-import { ensureInsideVault } from "../path-safety.ts";
-import { proceduralRecurrencePath } from "./paths.ts";
+import { interleaveShardRows, jsonlLedgerGrammar, readShardLinesByShard } from "./ledger-shards.ts";
+import { BRAIN_LOG_REL } from "./path-constants.ts";
+import { proceduralRecurrencePath, RECURRENCE_LEDGER_STEM } from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+/** The recurrence ledger's file-name layout, handed to the shared shard grammar. */
+const RECURRENCE_LEDGER_GRAMMAR = jsonlLedgerGrammar(RECURRENCE_LEDGER_STEM);
+
export type RecurrenceCommitment = "exploring" | "leaning" | "decided" | "locked";
export type RecurrenceAction = "learn" | "forget";
@@ -234,22 +238,43 @@ function commitmentForSupport(
function appendEvent(vault: string, event: RecurrenceEvent): void {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
+ // This device's shard (t_774dea61); the path helper confines it to the vault.
const path = proceduralRecurrencePath(vault);
- mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
+ mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, `${JSON.stringify(event)}\n`, { encoding: "utf8" });
}
-function readEvents(vault: string): RecurrenceEvent[] {
- const path = proceduralRecurrencePath(vault);
- if (!existsSync(path)) return [];
- const out: RecurrenceEvent[] = [];
- for (const line of readFileSync(path, "utf8").split("\n")) {
- if (!line.trim()) continue;
- try {
- out.push(JSON.parse(line) as RecurrenceEvent);
- } catch {
- continue;
- }
+/**
+ * When an event happened, as the cross-device merge orders it. An event
+ * whose stamp does not parse sorts as early as possible, which in the
+ * merge means straight after the event its own shard holds before it.
+ */
+function eventTime(event: RecurrenceEvent): number {
+ const time = Date.parse(event.at);
+ return Number.isFinite(time) ? time : Number.NEGATIVE_INFINITY;
+}
+
+/** One ledger line as an event, or `null` for a torn line. */
+function parseEvent(line: string): RecurrenceEvent | null {
+ try {
+ return JSON.parse(line) as RecurrenceEvent;
+ } catch {
+ return null;
}
- return out;
+}
+
+function readEvents(vault: string): RecurrenceEvent[] {
+ // Merged read over every device's shard (t_774dea61), interleaved by
+ // event time with each shard keeping its own file order. The fold is
+ // order-sensitive (`purge-source` deletes, `forget` decrements), so a
+ // shard-name order would replay one device's purge before another
+ // device's earlier learn and bring the purged source back. The absent
+ // directory lists nothing, which is the same empty result as before.
+ const shards = readShardLinesByShard(join(vault, BRAIN_LOG_REL), RECURRENCE_LEDGER_GRAMMAR).map(
+ (shard) => ({
+ shardId: shard.shardId,
+ rows: shard.rows.map(parseEvent).filter((event) => event !== null),
+ }),
+ );
+ return interleaveShardRows(shards, eventTime);
}
diff --git a/src/core/brain/schema-integrity.ts b/src/core/brain/schema-integrity.ts
index c07ef385..4a090446 100644
--- a/src/core/brain/schema-integrity.ts
+++ b/src/core/brain/schema-integrity.ts
@@ -50,11 +50,13 @@
* `formatStampMismatch` every other integrity surface uses.
*/
-import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { sha256Hex } from "../integrity/digest.ts";
import { compareStamps, type StampMismatch } from "../integrity/stamp.ts";
+import { AUDIT_WEEK_SHARD_GRAMMAR } from "../reliability/audit.ts";
+import { listShardedFiles } from "./ledger-shards.ts";
import { brainDirs } from "./paths.ts";
import { readSchemaPackSource, renderSchemaBlock, type SchemaPack } from "./schema-pack.ts";
@@ -144,9 +146,6 @@ export const SCHEMA_MUTATION_AUDIT_ACTION = "schema_apply_mutations";
/** Key under an audit record's `details` holding the resulting pack digest. */
export const SCHEMA_PACK_DIGEST_FIELD = "pack_digest";
-/** Audit shards are JSON Lines, one record per line. */
-const AUDIT_SHARD_EXTENSION = ".jsonl";
-
/**
* The shape of a digest this project writes: lowercase hex, nothing else.
* The length is deliberately not asserted - the algorithm belongs to
@@ -233,16 +232,15 @@ export function readRecordedSchemaPackDigest(vault: string): RecordedSchemaPackD
let shards: ReadonlyArray<string>;
try {
- shards = readdirSync(dir)
- .filter((entry) => entry.endsWith(AUDIT_SHARD_EXTENSION))
- .toSorted();
+ // Grammar-parsed, name-sorted: device shards and the legacy week file
+ // in one deterministic order; `*.sync-conflict-*` copies excluded.
+ shards = listShardedFiles(dir, AUDIT_WEEK_SHARD_GRAMMAR).map((shard) => shard.path);
} catch {
return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);
}
let newest: { record: Record<string, unknown>; at: number; path: string } | null = null;
- for (const shard of shards) {
- const path = join(dir, shard);
+ for (const path of shards) {
let text: string;
try {
text = readFileSync(path, "utf8");
diff --git a/src/core/brain/secrets/exec.ts b/src/core/brain/secrets/exec.ts
index 43f55be3..cbc9ecb7 100644
--- a/src/core/brain/secrets/exec.ts
+++ b/src/core/brain/secrets/exec.ts
@@ -12,6 +12,7 @@
import { redactRawOutput } from "../../redactor.ts";
import { appendAuditRecord } from "../../reliability/audit.ts";
import { escapeRegex } from "../../strings.ts";
+import { SECRET_CUSTODY_AUDIT_DIR } from "../audit-dirs.ts";
import { brainDirsForWrite } from "../paths.ts";
import { join } from "node:path";
import { resolveSecretForExec, type SecretAuditContext } from "./store.ts";
@@ -134,7 +135,7 @@ export async function runWithSecret(
});
const resolved = resolveSecretForExec(vault, name, ctx);
if (!matchesAllowlist(resolved.allow, argv)) {
- appendAuditRecord(join(brainDirsForWrite(vault).log, "secret-custody"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {
timestamp: ctx.now.toISOString(),
actor: ctx.agent,
action: "secret_exec_denied",
@@ -145,7 +146,7 @@ export async function runWithSecret(
throw new SecretExecDeniedError(resolved.name, command, resolved.allow);
}
- appendAuditRecord(join(brainDirsForWrite(vault).log, "secret-custody"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {
timestamp: ctx.now.toISOString(),
actor: ctx.agent,
action: "secret_exec_started",
diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.ts
index 4886ec1c..1b6ce46d 100644
--- a/src/core/brain/secrets/store.ts
+++ b/src/core/brain/secrets/store.ts
@@ -19,6 +19,7 @@ import lockfile from "proper-lockfile";
import { renameWithRetry } from "../../fs-atomic.ts";
import { appendAuditRecord } from "../../reliability/audit.ts";
+import { SECRET_CUSTODY_AUDIT_DIR } from "../audit-dirs.ts";
import { brainDirsForWrite } from "../paths.ts";
import { isoSecond } from "../time.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
@@ -356,7 +357,7 @@ function audit(
name: string,
details: Record<string, unknown>,
): void {
- appendAuditRecord(join(brainDirsForWrite(vault).log, "secret-custody"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, SECRET_CUSTODY_AUDIT_DIR), {
timestamp: ctx.now.toISOString(),
actor: ctx.agent,
action,
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index 74acc328..d090cf53 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -4,6 +4,7 @@ import { basename, join } from "node:path";
import { delegatedAgentName } from "../agent-identity.ts";
import { appendAuditRecord } from "../reliability/audit.ts";
import { appendLogEvent } from "./log.ts";
+import { SESSION_LIFECYCLE_AUDIT_DIR } from "./audit-dirs.ts";
import { brainDirsForWrite } from "./paths.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";
import { extractFacts, routeExtractedFacts } from "./fact-extract.ts";
@@ -499,44 +500,47 @@ export async function captureSessionLifecycleEvent(
});
}
- const auditPath = appendAuditRecord(join(brainDirsForWrite(vault).log, "session-lifecycle"), {
- timestamp: now.toISOString(),
- actor: capturingAgent,
- action: "session_lifecycle_capture",
- target: "Brain/session-lifecycle",
- ok: true,
- details: {
- event: normalized.event,
- ...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),
- ...(normalized.agentId ? { agent_id: normalized.agentId } : {}),
- ...(toolCallsFailed > 0 ? { tool_calls_failed: toolCallsFailed } : {}),
- dry_run: opts.dryRun === true,
- boundary_decision: decision,
- ...(normalized.interrupted === true ? { interrupted: true } : {}),
- ...(transcriptConsumed !== undefined ? { transcript_consumed: transcriptConsumed } : {}),
- ...(chainLineage !== undefined
- ? {
- lineage_root: chainLineage.rootId,
- ...(chainLineage.parentId !== null ? { lineage_parent: chainLineage.parentId } : {}),
- lineage_depth: chainLineage.depth,
- lineage_source: chainLineage.source,
- }
- : {}),
- // Unit C: a continuation that was AVAILABLE and refused. Absent
- // on the ordinary flat path, so a session with nothing to link to
- // keeps its previous audit shape exactly.
- ...(lineageNotices.length > 0
- ? { lineage_abstained: lineageNotices.map(formatDegradationNotice) }
- : {}),
- // Block C: the observation this event tried to record and could
- // not. Absent on every successful append, so the ordinary audit
- // shape is unchanged.
- ...(lineageDrops.length > 0
- ? { lineage_dropped: lineageDrops.map(formatDegradationNotice) }
- : {}),
- ...counters,
+ const auditPath = appendAuditRecord(
+ join(brainDirsForWrite(vault).log, SESSION_LIFECYCLE_AUDIT_DIR),
+ {
+ timestamp: now.toISOString(),
+ actor: capturingAgent,
+ action: "session_lifecycle_capture",
+ target: "Brain/session-lifecycle",
+ ok: true,
+ details: {
+ event: normalized.event,
+ ...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),
+ ...(normalized.agentId ? { agent_id: normalized.agentId } : {}),
+ ...(toolCallsFailed > 0 ? { tool_calls_failed: toolCallsFailed } : {}),
+ dry_run: opts.dryRun === true,
+ boundary_decision: decision,
+ ...(normalized.interrupted === true ? { interrupted: true } : {}),
+ ...(transcriptConsumed !== undefined ? { transcript_consumed: transcriptConsumed } : {}),
+ ...(chainLineage !== undefined
+ ? {
+ lineage_root: chainLineage.rootId,
+ ...(chainLineage.parentId !== null ? { lineage_parent: chainLineage.parentId } : {}),
+ lineage_depth: chainLineage.depth,
+ lineage_source: chainLineage.source,
+ }
+ : {}),
+ // Unit C: a continuation that was AVAILABLE and refused. Absent
+ // on the ordinary flat path, so a session with nothing to link to
+ // keeps its previous audit shape exactly.
+ ...(lineageNotices.length > 0
+ ? { lineage_abstained: lineageNotices.map(formatDegradationNotice) }
+ : {}),
+ // Block C: the observation this event tried to record and could
+ // not. Absent on every successful append, so the ordinary audit
+ // shape is unchanged.
+ ...(lineageDrops.length > 0
+ ? { lineage_dropped: lineageDrops.map(formatDegradationNotice) }
+ : {}),
+ ...counters,
+ },
},
- });
+ );
return {
event: normalized.event,
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index a1fbe172..9b74e634 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -44,6 +44,7 @@ import {
skillProposalPendingPath,
skillProposalRejectedPath,
} from "./paths.ts";
+import { JSONL_LEDGER_EXT, resolveAppendShardId, shardedFileName } from "./ledger-shards.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { listContinuityRecords, type ContinuityRecord } from "./continuity/store.ts";
@@ -244,8 +245,8 @@ const SUGGESTED_BODY_HEADING = "## Suggested skill body";
/** Lock basename guarding the accept sequence, inside the proposals root. */
const ACCEPT_LOCK_NAME = "accept";
-/** JSONL ledger of verifier rejections, relative to the vault. */
-const VERIFIER_REJECTION_LEDGER_REL = join(BRAIN_SKILL_PROPOSALS_REL, "verifier-rejections.jsonl");
+/** Shard stem of the verifier-rejection JSONL ledger inside the proposals root. */
+const VERIFIER_REJECTION_LEDGER_STEM = "verifier-rejections";
export function learnSkillProposals(
vault: string,
@@ -1430,12 +1431,28 @@ function evolveAcceptedProposal(
}
}
+/**
+ * The verifier-rejection ledger file THIS device appends to:
+ * `verifier-rejections[.<deviceId>].jsonl` (t_774dea61). The empty device
+ * id yields the legacy un-sharded name.
+ */
+export function verifierRejectionLedgerPath(vault: string): string {
+ return ensureInsideVault(
+ join(
+ vault,
+ BRAIN_SKILL_PROPOSALS_REL,
+ shardedFileName(VERIFIER_REJECTION_LEDGER_STEM, resolveAppendShardId(), JSONL_LEDGER_EXT),
+ ),
+ vault,
+ );
+}
+
/** Append one verifier-rejection record to the JSONL ledger. */
function appendVerifierRejection(
vault: string,
entry: { id: string; name_key: string; reason: string; at: string },
): void {
- const path = ensureInsideVault(join(vault, VERIFIER_REJECTION_LEDGER_REL), vault);
+ const path = verifierRejectionLedgerPath(vault);
mkdirSync(dirname(path), { recursive: true });
appendFileSync(path, `${JSON.stringify(entry)}\n`, { encoding: "utf8" });
}
diff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.ts
index cd6e3ff1..93713a2f 100644
--- a/src/core/brain/truth/store.ts
+++ b/src/core/brain/truth/store.ts
@@ -25,6 +25,12 @@ import {
import { join } from "node:path";
import { resolveDeviceId } from "../../config.ts";
+import {
+ JSONL_LEDGER_EXT,
+ jsonlLedgerGrammar,
+ parseShardedName,
+ shardedFileName,
+} from "../ledger-shards.ts";
import { normalizeEntityName } from "../entities/canonical.ts";
import { computeTruthState } from "./fold.ts";
import type {
@@ -49,8 +55,10 @@ export const CLAIM_EVENT_MAX_COUNT = 10000;
const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
// `claims.jsonl` or `claims.<deviceId>.jsonl`; device ids are lowercase
-// slugs, and Syncthing conflict copies are never shards.
-const CLAIM_SHARD_RE = /^claims(?:\.([a-z0-9-]{1,32}))?\.jsonl$/;
+// slugs, and Syncthing conflict copies are never shards (the shared
+// ledger-shard grammar rejects them).
+const CLAIMS_STEM = "claims";
+const CLAIMS_GRAMMAR = jsonlLedgerGrammar(CLAIMS_STEM);
export function truthDir(vault: string): string {
return join(vault, "Brain", "truth");
@@ -74,7 +82,7 @@ export function truthStatePath(vault: string): string {
*/
export function claimShardPath(vault: string, configPath?: string): string {
const deviceId = resolveDeviceId(configPath);
- const name = deviceId === "" ? "claims.jsonl" : `claims.${deviceId}.jsonl`;
+ const name = shardedFileName(CLAIMS_STEM, deviceId, JSONL_LEDGER_EXT);
return join(truthDir(vault), name);
}
@@ -158,10 +166,9 @@ export function readClaimEvents(vault: string): ReadClaimEventsResult {
const warnings: ClaimParseWarning[] = [];
for (const name of names) {
- const m = CLAIM_SHARD_RE.exec(name);
- if (!m) continue;
- const shardId = m[1] ?? "";
- if (shardId.startsWith("sync-conflict")) continue;
+ const shard = parseShardedName(name, CLAIMS_GRAMMAR);
+ if (shard === null) continue;
+ const shardId = shard.shardId;
const path = join(dir, name);
let text: string;
try {
@@ -392,9 +399,7 @@ export function sweepClaimEvents(vault: string, opts: ClaimSweepOptions): ClaimS
const shards = new Map<string, string[]>();
const valid: ShardLine[] = [];
for (const name of names) {
- const m = CLAIM_SHARD_RE.exec(name);
- if (!m) continue;
- if ((m[1] ?? "").startsWith("sync-conflict")) continue;
+ if (parseShardedName(name, CLAIMS_GRAMMAR) === null) continue;
let text: string;
try {
text = readFileSync(join(dir, name), "utf8");
diff --git a/src/core/brain/watchdog.ts b/src/core/brain/watchdog.ts
index 440ccc25..091b39c2 100644
--- a/src/core/brain/watchdog.ts
+++ b/src/core/brain/watchdog.ts
@@ -3,6 +3,8 @@ import { join } from "node:path";
import { appendAuditRecord, type AuditRecord } from "../reliability/audit.ts";
import { buildProbeReport, type ProbeCheck, type ProbeReport } from "../reliability/probe.ts";
+import { WATCHDOG_AUDIT_DIR, WATCHDOG_FALLBACK_AUDIT_DIR } from "./audit-dirs.ts";
+import { DERIVED_STORE_DIR } from "./path-constants.ts";
import { resolveIndexPath } from "../search/paths.ts";
import {
BRAIN_CONFIG_FILE,
@@ -247,11 +249,20 @@ function pathKind(path: string): "file" | "directory" | "other" | "missing" {
}
}
+/**
+ * Where a watchdog record lands when its `Brain/log/` directory refuses
+ * the write: `.open-second-brain/watchdog-audit/`. Exported so the
+ * doctor's sync-conflict sweep visits the directory this module writes.
+ */
+export function watchdogFallbackAuditDir(vault: string): string {
+ return join(vault, DERIVED_STORE_DIR, WATCHDOG_FALLBACK_AUDIT_DIR);
+}
+
function appendWatchdogAudit(vault: string, logDir: string, record: AuditRecord): string {
try {
- return appendAuditRecord(join(logDir, "watchdog"), record);
+ return appendAuditRecord(join(logDir, WATCHDOG_AUDIT_DIR), record);
} catch (error) {
- return appendAuditRecord(join(vault, ".open-second-brain", "watchdog-audit"), {
+ return appendAuditRecord(watchdogFallbackAuditDir(vault), {
...record,
ok: false,
details: {
diff --git a/src/core/brain/write-batch.ts b/src/core/brain/write-batch.ts
index e70c62b8..a9c37c41 100644
--- a/src/core/brain/write-batch.ts
+++ b/src/core/brain/write-batch.ts
@@ -27,7 +27,7 @@
*/
import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
-import { dirname } from "node:path";
+import { dirname, join, relative } from "node:path";
import type { FrontmatterMap } from "../types.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
@@ -52,6 +52,14 @@ import { ORIGIN_CHANNEL_FIELD } from "../origin-channel.ts";
import { preferencePath, validateSlug } from "./paths.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { BRAIN_APPLY_RESULT } from "./types.ts";
+import {
+ computePayloadHash,
+ IdempotencyPayloadMismatchError,
+ lookupKey,
+ REMEMBER_KEY_STATUS,
+ rememberKey,
+ type RememberKeyStatus,
+} from "./idempotency-ledger.ts";
/** Separator inserted between the existing body and appended text. */
const APPEND_SEPARATOR = "\n\n";
@@ -65,6 +73,42 @@ const APPEND_SEPARATOR = "\n\n";
*/
export const MAX_BATCH_OPERATIONS = 100;
+/**
+ * The idempotency-ledger key space of write-batch request IDs. Request IDs
+ * come from a different client vocabulary than the `idempotency_key` of
+ * brain_feedback and apply-evidence, so they live in their own namespace:
+ * the same string supplied to both tools never collides.
+ */
+const WRITE_BATCH_KEY_NAMESPACE = "write_batch";
+
+/**
+ * What a request receipt says about the call that returned it:
+ * - `applied`: this call committed the batch and recorded the ID.
+ * - `duplicate`: the ID was already recorded with the same payload; this
+ * call wrote nothing and every other result field is the retained
+ * receipt of the call that committed.
+ * - `concurrent_duplicate`: this call committed the batch, but a concurrent
+ * call recorded the same ID with the same payload between this call's
+ * consult and its record. Both calls' writes landed; the result fields
+ * are this call's own.
+ * - `payload_conflict`: this call committed the batch - its writes landed
+ * and the result fields are this call's own - but a concurrent call
+ * recorded the same ID with a DIFFERENT payload between this call's
+ * consult and its record. The ID stays bound to that other payload, so
+ * this call's receipt was not recorded and a retry under the same ID is
+ * refused as a mismatch. Never retry this batch under a new ID: it is
+ * already applied.
+ */
+export const WRITE_BATCH_RECEIPT_STATUS = Object.freeze({
+ applied: "applied",
+ duplicate: "duplicate",
+ concurrent_duplicate: "concurrent_duplicate",
+ payload_conflict: "payload_conflict",
+} as const);
+
+export type WriteBatchReceiptStatus =
+ (typeof WRITE_BATCH_RECEIPT_STATUS)[keyof typeof WRITE_BATCH_RECEIPT_STATUS];
+
/**
* Create a new vault note. Refuses to clobber an existing file. Maps to
* the {@link createNote} core writer.
@@ -301,8 +345,23 @@ export interface WriteBatchResult {
readonly results: ReadonlyArray<WriteBatchOpResult>;
/** Terminal success marker: the batch committed, do not re-call. */
readonly done: true;
+ /**
+ * Present exactly when the caller supplied a request ID (see
+ * {@link ReceiptedWriteBatchResult}); {@link WRITE_BATCH_RECEIPT_STATUS}
+ * names what each status means.
+ */
+ readonly receipt?: WriteBatchReceipt;
+}
+
+/** The request-receipt block a caller-supplied request ID adds to a result. */
+export interface WriteBatchReceipt {
+ readonly requestId: string;
+ readonly status: WriteBatchReceiptStatus;
}
+/** A batch result for a call that supplied a request ID: the receipt is always there. */
+export type ReceiptedWriteBatchResult = WriteBatchResult & { readonly receipt: WriteBatchReceipt };
+
/** A validated operation paired with the closure that commits it. */
interface PlannedOperation {
readonly commit: () => WriteBatchOpResult;
@@ -317,6 +376,22 @@ export interface ApplyWriteBatchOptions {
* record names the agent the caller is.
*/
readonly configPath?: string;
+ /**
+ * Client-supplied request ID (t_b34439d9). Supplied, the batch consults
+ * the idempotency ledger BEFORE any validation or write: the same ID with
+ * the same semantic payload returns the retained original receipt marked
+ * `duplicate`; the same ID with a different payload throws the ledger's
+ * own {@link IdempotencyPayloadMismatchError}; an unseen ID proceeds and
+ * records the receipt after the commit - the sequencing
+ * {@link import('./signal.ts').writeSignal} already ships. A concurrent
+ * record of the same ID found only after the commit becomes a receipt
+ * status on the committed result (see {@link WRITE_BATCH_RECEIPT_STATUS}).
+ * Absent, behavior is byte-identical. Validation of the ID itself is the
+ * ledger's (non-empty, bounded length), so an invalid ID surfaces the
+ * ledger's named {@link import('./idempotency-ledger.ts').IdempotencyKeyError}
+ * before any write.
+ */
+ readonly requestId?: string;
}
/**
@@ -325,6 +400,16 @@ export interface ApplyWriteBatchOptions {
* commit them in order. The first invalid operation throws
* {@link WriteBatchError} naming its index, before any disk write.
*/
+export function applyWriteBatch(
+ vault: string,
+ operations: ReadonlyArray<WriteOperation>,
+ opts: ApplyWriteBatchOptions & { readonly requestId: string },
+): ReceiptedWriteBatchResult;
+export function applyWriteBatch(
+ vault: string,
+ operations: ReadonlyArray<WriteOperation>,
+ opts?: ApplyWriteBatchOptions,
+): WriteBatchResult;
export function applyWriteBatch(
vault: string,
operations: ReadonlyArray<WriteOperation>,
@@ -332,6 +417,9 @@ export function applyWriteBatch(
): WriteBatchResult {
// Vault-identity write guard (context-integrity-gates, Unit J).
assertVaultIdentityForWrite(vault);
+ // The batch's shape is checked first: the request-ID consult hashes the
+ // operations, and a non-array must surface as the named batch error, not
+ // as whatever the hashing throws.
if (!Array.isArray(operations) || operations.length === 0) {
throw new WriteBatchError("invalid_operation", -1, "operations must be a non-empty array");
}
@@ -343,6 +431,13 @@ export function applyWriteBatch(
{ max: MAX_BATCH_OPERATIONS, count: operations.length },
);
}
+ // The request-ID consult sits before any per-operation validation: a
+ // duplicate must never re-validate (the original already passed) and an
+ // invalid ID must surface before anything is written.
+ const requestId = opts.requestId;
+ const idempotency =
+ requestId === undefined ? undefined : consultBatchKey(vault, requestId, operations);
+ if (idempotency?.retained !== undefined) return idempotency.retained;
// A note target may appear at most once per batch: projecting each note
// op against the pre-batch disk state means a second op on the same file
@@ -353,7 +448,102 @@ export function applyWriteBatch(
);
const results = planned.map((p) => p.commit());
- return { applied: operations.length, results, done: true };
+ const result: WriteBatchResult = { applied: operations.length, results, done: true };
+ if (idempotency !== undefined && requestId !== undefined) {
+ // Record AFTER the commit so a sequential retry dedupes against a
+ // durable receipt. `rememberKey` re-checks under its shard lock; the
+ // residual crash window between commit and record is the one the
+ // ledger documents for every writer that follows this pattern.
+ const stored: Readonly<Record<string, unknown>> = {
+ applied: result.applied,
+ results: result.results.map((opResult) => storedOpResult(vault, opResult)),
+ done: result.done,
+ };
+ const remembered = rememberKey(vault, {
+ key: requestId,
+ namespace: WRITE_BATCH_KEY_NAMESPACE,
+ contentHash: idempotency.contentHash,
+ ref: stored,
+ });
+ // The unlocked consult above can miss a concurrent call's record; the
+ // locked re-check's verdict is acted on, never dropped. Either way this
+ // call's writes have landed, so the verdict is a receipt status on the
+ // committed result, never an error that would read as "nothing
+ // written" and invite a second application under a fresh ID.
+ return { ...result, receipt: { requestId, status: RECEIPT_STATUS_FOR[remembered.status] } };
+ }
+ return result;
+}
+
+/** The receipt status of a committed batch, by the locked re-check's verdict. */
+const RECEIPT_STATUS_FOR: Readonly<Record<RememberKeyStatus, WriteBatchReceiptStatus>> =
+ Object.freeze({
+ [REMEMBER_KEY_STATUS.inserted]: WRITE_BATCH_RECEIPT_STATUS.applied,
+ [REMEMBER_KEY_STATUS.duplicate_match]: WRITE_BATCH_RECEIPT_STATUS.concurrent_duplicate,
+ [REMEMBER_KEY_STATUS.payload_mismatch]: WRITE_BATCH_RECEIPT_STATUS.payload_conflict,
+ });
+
+/**
+ * One op result as the durable receipt stores it. The ledger is vault
+ * content that syncs to every device, so a log path is stored
+ * vault-relative - the form apply-evidence keeps for its own receipt -
+ * and never as this machine's absolute path. Note results already name
+ * vault-relative paths.
+ */
+function storedOpResult(vault: string, opResult: WriteBatchOpResult): WriteBatchOpResult {
+ if (opResult.kind !== "apply_evidence") return opResult;
+ return { ...opResult, log_path: relative(vault, opResult.log_path) };
+}
+
+/** Inverse of {@link storedOpResult}: the log path rebuilt under the vault serving the retry. */
+function retainedOpResult(vault: string, opResult: WriteBatchOpResult): WriteBatchOpResult {
+ if (opResult.kind !== "apply_evidence") return opResult;
+ return { ...opResult, log_path: join(vault, opResult.log_path) };
+}
+
+/**
+ * The pre-write consult for a caller-supplied request ID. Returns the hash
+ * the batch must record after a successful commit; when the ID is already
+ * in the ledger, `retained` carries the outcome instead - the stored
+ * receipt marked `duplicate` for a matching payload, or nothing after the
+ * mismatch error propagates.
+ */
+function consultBatchKey(
+ vault: string,
+ requestId: string,
+ operations: ReadonlyArray<WriteOperation>,
+): { readonly contentHash: string; readonly retained?: ReceiptedWriteBatchResult } {
+ const contentHash = computePayloadHash({ operations: [...operations] });
+ const existing = lookupKey(vault, requestId, WRITE_BATCH_KEY_NAMESPACE);
+ if (existing === null) return { contentHash };
+ if (existing.contentHash !== contentHash) {
+ throw new IdempotencyPayloadMismatchError(requestId, existing.contentHash, contentHash);
+ }
+ const ref = existing.ref as WriteBatchResult | undefined;
+ if (
+ ref === undefined ||
+ typeof ref !== "object" ||
+ ref.applied === undefined ||
+ !Array.isArray(ref.results) ||
+ ref.done !== true
+ ) {
+ // The ledger cannot answer for a key whose stored receipt is not a
+ // batch receipt. Refusing by name beats inventing an empty result that
+ // would tell the caller the batch applied when nothing did.
+ throw new WriteBatchError(
+ "invalid_operation",
+ -1,
+ `request id '${requestId}' is already recorded without a readable write-batch receipt`,
+ );
+ }
+ return {
+ contentHash,
+ retained: {
+ ...ref,
+ results: ref.results.map((opResult) => retainedOpResult(vault, opResult)),
+ receipt: { requestId, status: WRITE_BATCH_RECEIPT_STATUS.duplicate },
+ },
+ };
}
function projectOperation(
diff --git a/src/core/graph/unique-match.ts b/src/core/graph/unique-match.ts
new file mode 100644
index 00000000..9440f049
--- /dev/null
+++ b/src/core/graph/unique-match.ts
@@ -0,0 +1,43 @@
+/**
+ * The shared exactly-one decision.
+ *
+ * Two features bind a candidate to a target only when exactly one
+ * candidate carries it - the repair lane binding a mention term to a
+ * corpus page, pre-extract binding a relative import specifier to an
+ * ingested file. Both must answer "zero" and "more than one" the same
+ * conservative way, so the decision lives here instead of in two call
+ * sites that can drift. The domains stay local to their callers: this
+ * module decides, it does not know what a candidate is.
+ *
+ * Every status a caller can receive is part of the type, so a caller
+ * cannot forget the ambiguous case: dropping it is a compile error, not
+ * a silent loss.
+ */
+
+/**
+ * The outcome of an exactly-one decision: the single target, every
+ * distinct candidate in first-occurrence order, or nothing.
+ */
+export type UniqueMatch<T> =
+ | { readonly status: "none" }
+ | { readonly status: "unique"; readonly target: T }
+ | { readonly status: "ambiguous"; readonly matches: ReadonlyArray<T> };
+
+/**
+ * Decide `candidates` under the exactly-one rule. A candidate repeated in
+ * the input is one candidate: one page naming a term twice must never
+ * read as two pages naming it. The ambiguous list keeps first-occurrence
+ * order, so the same input always reports the same list.
+ */
+export function resolveUniqueMatch<T>(candidates: ReadonlyArray<T>): UniqueMatch<T> {
+ const distinct: T[] = [];
+ const seen = new Set<T>();
+ for (const candidate of candidates) {
+ if (seen.has(candidate)) continue;
+ seen.add(candidate);
+ distinct.push(candidate);
+ }
+ if (distinct.length === 0) return { status: "none" };
+ if (distinct.length === 1) return { status: "unique", target: distinct[0]! };
+ return { status: "ambiguous", matches: distinct };
+}
diff --git a/src/core/reliability/audit.ts b/src/core/reliability/audit.ts
index bc235c62..0be1edbd 100644
--- a/src/core/reliability/audit.ts
+++ b/src/core/reliability/audit.ts
@@ -2,6 +2,24 @@ import { closeSync, fsyncSync, mkdirSync, openSync, writeFileSync } from "node:f
import { join } from "node:path";
import { redactRawOutput } from "../redactor.ts";
+import {
+ JSONL_LEDGER_EXT,
+ resolveAppendShardId,
+ shardedFileName,
+ type LedgerShardGrammar,
+} from "../brain/ledger-shards.ts";
+
+/**
+ * The file-name layout of every per-device ISO-week audit directory:
+ * `<YYYY-Www>[.<deviceId>].jsonl`, the base being what {@link isoWeekLabel}
+ * produces. The writer below and every reader that lists the week files
+ * share this one grammar, so the two cannot disagree on what a week shard
+ * is, and a `*.sync-conflict-*` copy is never one.
+ */
+export const AUDIT_WEEK_SHARD_GRAMMAR: LedgerShardGrammar = Object.freeze({
+ base: "\\d{4}-W\\d{2}",
+ extensions: Object.freeze([JSONL_LEDGER_EXT]),
+});
export interface AuditRecord {
readonly timestamp: string;
@@ -18,7 +36,15 @@ export function appendAuditRecord(auditRoot: string, record: AuditRecord): strin
throw new Error(`invalid audit timestamp: ${record.timestamp}`);
}
mkdirSync(auditRoot, { recursive: true });
- const path = join(auditRoot, `${isoWeekLabel(timestamp)}.jsonl`);
+ // Per-device week shard (t_774dea61): two synced machines appending to
+ // one `<week>.jsonl` produce `*.sync-conflict-*` copies no reader
+ // merges. Each device now appends to its own `<week>[.<deviceId>].jsonl`
+ // through the shared ledger-shard grammar; the empty device id keeps the
+ // legacy un-sharded name, so existing vaults need no migration.
+ const path = join(
+ auditRoot,
+ shardedFileName(isoWeekLabel(timestamp), resolveAppendShardId(), JSONL_LEDGER_EXT),
+ );
const line = redactRawOutput(JSON.stringify(record), {
maxInput: Number.POSITIVE_INFINITY,
});
diff --git a/src/core/search/disclosure-mode.ts b/src/core/search/disclosure-mode.ts
new file mode 100644
index 00000000..f77651b6
--- /dev/null
+++ b/src/core/search/disclosure-mode.ts
@@ -0,0 +1,30 @@
+/**
+ * Result-depth disclosure vocabulary (progressive 3-layer recall), kept in
+ * a leaf module with no imports so the search types, the CLI flag and the
+ * MCP tool read one list.
+ *
+ * `full` (default) is the historical flat search: every hit carries its
+ * full chunk content. `cards` returns compact layer-1 cards instead -
+ * path/title/score/reasons/snippet/pointer, no full content - so recall
+ * stays token-cheap and the agent pays for depth only by calling
+ * `expandHit` (layer 2 fuller note, layer 3 raw transcript).
+ */
+export const DISCLOSURE_MODE = Object.freeze({ full: "full", cards: "cards" } as const);
+export type DisclosureMode = (typeof DISCLOSURE_MODE)[keyof typeof DISCLOSURE_MODE];
+
+/** Every accepted mode, in declaration order: the MCP enum and every refusal message. */
+export const DISCLOSURE_MODES: ReadonlyArray<DisclosureMode> = Object.freeze(
+ Object.values(DISCLOSURE_MODE),
+);
+
+/** The mode an absent `disclosure` resolves to: full content. */
+export const DEFAULT_DISCLOSURE_MODE: DisclosureMode = DISCLOSURE_MODE.full;
+
+/**
+ * The one enum check the CLI flag and the MCP argument apply; each layer
+ * raises its own error type naming {@link DISCLOSURE_MODES} when it
+ * answers false.
+ */
+export function isDisclosureMode(value: unknown): value is DisclosureMode {
+ return typeof value === "string" && (DISCLOSURE_MODES as ReadonlyArray<string>).includes(value);
+}
diff --git a/src/core/search/fts-match-mode.ts b/src/core/search/fts-match-mode.ts
new file mode 100644
index 00000000..e37cfaaf
--- /dev/null
+++ b/src/core/search/fts-match-mode.ts
@@ -0,0 +1,31 @@
+/**
+ * The FTS match-mode vocabulary (t_c5326ece), kept in a leaf module with no
+ * imports so the search request types, the CLI and the MCP tool can name
+ * the modes without importing the FTS query builder and its store graph.
+ */
+
+/**
+ * The caller-selectable match breadth (t_c5326ece). `all` (default) keeps
+ * the implicit AND the bag-of-tokens query always had; `any` OR-joins the
+ * same cleaned tokens so a document matching any one term is a hit. Both
+ * modes drop caller-typed FTS5 operator tokens first.
+ */
+export const FTS_MATCH_MODE = Object.freeze({ all: "all", any: "any" } as const);
+export type FtsMatchMode = (typeof FTS_MATCH_MODE)[keyof typeof FTS_MATCH_MODE];
+
+/** Every accepted mode, in declaration order: the MCP enum and every refusal message. */
+export const FTS_MATCH_MODES: ReadonlyArray<FtsMatchMode> = Object.freeze(
+ Object.values(FTS_MATCH_MODE),
+);
+
+/** The mode an absent `matchMode` resolves to: today's implicit AND. */
+export const DEFAULT_FTS_MATCH_MODE: FtsMatchMode = FTS_MATCH_MODE.all;
+
+/**
+ * The one enum check every entry point (CLI flag, MCP argument, request
+ * resolution) applies; each layer raises its own error type naming
+ * {@link FTS_MATCH_MODES} when it answers false.
+ */
+export function isFtsMatchMode(value: unknown): value is FtsMatchMode {
+ return typeof value === "string" && (FTS_MATCH_MODES as ReadonlyArray<string>).includes(value);
+}
diff --git a/src/core/search/fts.ts b/src/core/search/fts.ts
index 87f95e5c..9c044893 100644
--- a/src/core/search/fts.ts
+++ b/src/core/search/fts.ts
@@ -16,9 +16,14 @@ import { containsCjk, tokenizeCjkSearchText } from "./cjk-tokenizer.ts";
import { keywordTopKWithFtsSafety, type SafeKeywordOutcome } from "./fts-safety.ts";
import { RETRIEVAL_DEGRADATION, noteDegradation } from "./retrieval-trail.ts";
import type { RetrievalDegradationSink } from "./retrieval-trail.ts";
+import { FTS_MATCH_MODE, type FtsMatchMode } from "./fts-match-mode.ts";
const FTS5_OPERATOR_TOKENS = new Set(["AND", "OR", "NOT", "NEAR"]);
+export interface FtsMatchOptions {
+ readonly matchMode?: FtsMatchMode;
+}
+
function quoteToken(t: string): string {
return `"${t.replace(/"/g, '""')}"`;
}
@@ -28,11 +33,12 @@ function dropStandaloneOperators(tokens: ReadonlyArray<string>): ReadonlyArray<s
return withoutOperators.length > 0 ? withoutOperators : tokens;
}
-export function buildFtsMatch(rawQuery: string): string {
+export function buildFtsMatch(rawQuery: string, opts: FtsMatchOptions = {}): string {
const tokens = containsCjk(rawQuery) ? tokenizeCjkSearchText(rawQuery) : rawQuery.split(/\s+/);
const cleaned = tokens.map((t) => t.trim()).filter((t) => t.length > 0);
if (cleaned.length === 0) return "";
- return dropStandaloneOperators(cleaned).map(quoteToken).join(" ");
+ const kept = dropStandaloneOperators(cleaned).map(quoteToken);
+ return opts.matchMode === FTS_MATCH_MODE.any ? kept.join(" OR ") : kept.join(" ");
}
/**
@@ -44,13 +50,16 @@ export function buildFtsMatch(rawQuery: string): string {
* ("orig1" "orig2") OR "exp1" OR "exp2"
*
* With no expansion terms this is byte-identical to {@link buildFtsMatch},
- * so expansion is a true no-op when disabled or empty.
+ * so expansion is a true no-op when disabled or empty. In `any` mode the
+ * base group is itself OR-joined - `("orig1" OR "orig2") OR "exp1"` - which
+ * is semantically the flat ANY superset through the same composition.
*/
export function buildExpandedFtsMatch(
rawQuery: string,
expandedTerms: ReadonlyArray<string>,
+ opts: FtsMatchOptions = {},
): string {
- const base = buildFtsMatch(rawQuery);
+ const base = buildFtsMatch(rawQuery, opts);
if (base === "" || expandedTerms.length === 0) return base;
const ors = expandedTerms.map(quoteToken).join(" OR ");
return `(${base}) OR ${ors}`;
@@ -65,6 +74,12 @@ export interface RunFtsOptions {
* recall; absent/empty leaves the query byte-identical.
*/
readonly expandedTerms?: ReadonlyArray<string>;
+ /**
+ * Caller-selectable match breadth (t_c5326ece). Default `all` keeps the
+ * implicit AND; `any` OR-joins the cleaned tokens. The derived-term and
+ * second-pass internal callers leave it unset.
+ */
+ readonly matchMode?: FtsMatchMode;
/**
* Optional typed degradation sink (evidence-at-the-boundary, C2), the
* counterpart of the warnings the outcome already returns. An empty
@@ -84,8 +99,8 @@ export function runFtsQueryDetailed(
): SafeKeywordOutcome {
const match =
opts.expandedTerms && opts.expandedTerms.length > 0
- ? buildExpandedFtsMatch(rawQuery, opts.expandedTerms)
- : buildFtsMatch(rawQuery);
+ ? buildExpandedFtsMatch(rawQuery, opts.expandedTerms, { matchMode: opts.matchMode })
+ : buildFtsMatch(rawQuery, { matchMode: opts.matchMode });
if (match === "") {
// The purest silent empty in the pipeline: every token was dropped,
// so no lookup ran at all and the caller was handed the same empty
diff --git a/src/core/search/pipeline/keyword-lane.ts b/src/core/search/pipeline/keyword-lane.ts
index a21f0c03..085a8aab 100644
--- a/src/core/search/pipeline/keyword-lane.ts
+++ b/src/core/search/pipeline/keyword-lane.ts
@@ -6,6 +6,7 @@
*/
import { runFtsQueryDetailed } from "../fts.ts";
+import type { FtsMatchMode } from "../fts-match-mode.ts";
import { buildQueryPlan } from "../query-plan.ts";
import type { RetrievalDegradationSink } from "../retrieval-trail.ts";
import { DEFAULT_EXPANSION, deriveExpansionTerms, tokenizeForExpansion } from "../synonyms.ts";
@@ -38,6 +39,8 @@ export interface KeywordLaneInput {
readonly basePlan: QueryPlan;
readonly limit: number;
readonly pathPrefix: string | undefined;
+ /** The caller's FTS match breadth (`all` default, `any` OR-joins). */
+ readonly matchMode?: FtsMatchMode;
}
export interface KeywordLaneOutcome {
@@ -61,6 +64,7 @@ export function runKeywordLane(input: KeywordLaneInput): KeywordLaneOutcome {
const kwOutcome = runFtsQueryDetailed(store, keywordQuery, {
limit: limit * recall.poolMultiplier,
pathPrefix,
+ matchMode: input.matchMode,
degraded,
});
let hits = kwOutcome.hits;
@@ -123,6 +127,7 @@ function expandWithSynonyms(
limit: limit * recall.poolMultiplier,
pathPrefix,
expandedTerms,
+ matchMode: input.matchMode,
});
return { plan, hits: kwOutcome.hits, warnings: kwOutcome.warnings };
}
diff --git a/src/core/search/pipeline/outcome.ts b/src/core/search/pipeline/outcome.ts
index 60126e24..c7c82eff 100644
--- a/src/core/search/pipeline/outcome.ts
+++ b/src/core/search/pipeline/outcome.ts
@@ -11,6 +11,7 @@
import { ACCESS_EVENT_PATHS_CAP, recordAccessEvent } from "../activation/store.ts";
import { toSearchCard } from "../cards.ts";
+import { DEFAULT_DISCLOSURE_MODE, DISCLOSURE_MODE } from "../disclosure-mode.ts";
import { classifyNegativeRecall } from "../../brain/negative-recall.ts";
import { buildEvidencePack, downrankTerminalEvidenceResults } from "../evidence-pack.ts";
import { buildRetrievalTrail, corpusStatementFor } from "../retrieval-trail.ts";
@@ -223,7 +224,7 @@ export function buildSearchOutcome(input: OutcomeInput): SearchOutcome {
// filtering, and evidence pack are computed identically to full mode -
// only the surfaced depth differs - so the contract stays
// deterministic and the default `full` path is byte-identical.
- if ((opts.disclosure ?? "full") === "cards") {
+ if ((opts.disclosure ?? DEFAULT_DISCLOSURE_MODE) === DISCLOSURE_MODE.cards) {
// The residual query text anchors each card's snippet window on the
// match instead of the head of the chunk (task E).
const cards = resultsOut.map((result) => toSearchCard(result, query));
diff --git a/src/core/search/pipeline/request.ts b/src/core/search/pipeline/request.ts
index 1ed47214..7d4d31b5 100644
--- a/src/core/search/pipeline/request.ts
+++ b/src/core/search/pipeline/request.ts
@@ -8,6 +8,12 @@
*/
import { resolveRecallProfile } from "../profiles.ts";
+import {
+ DEFAULT_FTS_MATCH_MODE,
+ FTS_MATCH_MODES,
+ isFtsMatchMode,
+ type FtsMatchMode,
+} from "../fts-match-mode.ts";
import { resolveSemanticPolicy, type SemanticPolicy } from "../semantic-phase.ts";
import { readActiveSessionFocus } from "../session-focus.ts";
import {
@@ -51,6 +57,8 @@ export interface ResolvedSearchRequest {
readonly temporalIntent: TemporalIntent | null;
/** Whether local query expansion runs for this call. */
readonly expandActive: boolean;
+ /** The resolved FTS match breadth: the caller's choice, else `all`. */
+ readonly matchMode: FtsMatchMode;
/** The applied knob tuple, or null when neither profile nor tuning fired. */
readonly tuned: TunedParameters | null;
}
@@ -133,6 +141,13 @@ export function resolveSearchRequest(
);
}
+ const matchMode = opts.matchMode ?? DEFAULT_FTS_MATCH_MODE;
+ if (!isFtsMatchMode(matchMode)) {
+ throw new SearchError(
+ "INVALID_INPUT",
+ `match_mode must be one of ${FTS_MATCH_MODES.join(", ")}`,
+ );
+ }
return {
config: resolvedConfig,
query,
@@ -144,6 +159,7 @@ export function resolveSearchRequest(
timeRange,
temporalIntent,
expandActive,
+ matchMode,
tuned,
};
}
diff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.ts
index 882926f4..99b19ea2 100644
--- a/src/core/search/query-cache.ts
+++ b/src/core/search/query-cache.ts
@@ -17,6 +17,8 @@
import { normalizeScopeFilter } from "../scope-key.ts";
import { resolvedTransportReach } from "../graph/transport-reach.ts";
+import { DISCLOSURE_MODE } from "./disclosure-mode.ts";
+import { FTS_MATCH_MODE } from "./fts-match-mode.ts";
import type { Store } from "./store.ts";
import type { SearchOptions, SearchOutcome } from "./types.ts";
@@ -119,7 +121,12 @@ export function buildCacheKey(
// Disclosure depth (D3) partitions the cache: a `cards` outcome and a
// `full` outcome must not collide. Folded in only for `cards`, so the
// default `full` key (and every pre-D3 cached row) stays byte-identical.
- disclosure: opts.disclosure === "cards" ? "cards" : undefined,
+ disclosure: opts.disclosure === DISCLOSURE_MODE.cards ? DISCLOSURE_MODE.cards : undefined,
+ // Match mode partitions the cache: an `any` (OR) outcome holds rows
+ // the strict `all` default drops. Folded in only for `any`, so the
+ // default key (and every row cached before the mode existed) stays
+ // byte-identical.
+ matchMode: opts.matchMode === FTS_MATCH_MODE.any ? FTS_MATCH_MODE.any : undefined,
structuredQuery: canonicalStructuredQuery(opts),
sessionFocus: canonicalSessionFocus(opts),
plan: planHash,
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index 6a552cbe..16722d16 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -134,6 +134,7 @@ export async function search(
basePlan: shape.basePlan,
limit,
pathPrefix,
+ matchMode: request.matchMode,
});
let keywordHits = keywordLane.hits;
for (const w of keywordLane.warnings) warnings.push(w);
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index a2da3a9f..07c99114 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -22,6 +22,8 @@ import type { ReconciliationOutcome, ReconciliationReport } from "../reconciliat
import type { VaultPathRule, VaultScopeRules } from "../vault-scope/defaults.ts";
import type { DegreePredicate } from "./property-filter.ts";
import type { TemporalIntent } from "./temporal-intent.ts";
+import type { FtsMatchMode } from "./fts-match-mode.ts";
+import type { DisclosureMode } from "./disclosure-mode.ts";
import type { BrainSearchResult, ScoreBreakdown, TrustMetadata } from "./search-result.ts";
import type {
MemoryTrustAssessment,
@@ -586,18 +588,12 @@ export interface IndexCheckReport {
}
/**
- * Result-depth disclosure mode (progressive 3-layer recall). `full`
- * (default) is the historical flat search: every hit carries its full
- * chunk content. `cards` returns compact layer-1 {@link SearchCard}s
- * instead — path/title/score/reasons/snippet/pointer, no full content —
- * so recall stays token-cheap and the agent pays for depth only by
- * calling `expandHit` (layer 2 fuller note, layer 3 raw transcript).
- *
- * This is NOT the query-lane `expand` flag on {@link SearchOptions}:
- * that broadens the candidate query, this shapes how much of each
- * surfaced result is disclosed.
+ * Result-depth disclosure mode; the vocabulary lives in
+ * `disclosure-mode.ts`. This is NOT the query-lane `expand` flag on
+ * {@link SearchOptions}: that broadens the candidate query, this shapes how
+ * much of each surfaced result is disclosed.
*/
-export type DisclosureMode = "full" | "cards";
+export type { DisclosureMode };
/**
* Layer-1 compact card (progressive disclosure). The token-cheap
@@ -815,6 +811,13 @@ export interface SearchOptions {
readonly pathPrefix?: string;
readonly keywordWeight?: number;
readonly semanticWeight?: number;
+ /**
+ * Caller-selectable FTS match breadth (t_c5326ece). `all` (default)
+ * keeps the implicit AND the keyword lane always ran; `any` OR-joins the
+ * cleaned query tokens, so a document matching any one term is a keyword
+ * candidate. Absent = `all`, byte-identical to prior behaviour.
+ */
+ readonly matchMode?: FtsMatchMode;
/**
* Property filter map (v0.10.17). Each key maps to one or more
* accepted scalar values. Within one key the match is OR; across
diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.ts
index 330be935..29973ae2 100644
--- a/src/core/state/surfaces.ts
+++ b/src/core/state/surfaces.ts
@@ -68,8 +68,8 @@
* already does.
*/
-import { lstatSync, statSync } from "node:fs";
-import { dirname, join } from "node:path";
+import { lstatSync, readdirSync, statSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
import {
BRAIN_ARTIFACTS_REL,
@@ -86,6 +86,14 @@ import {
DERIVED_STORE_FILE,
HOOK_AUDIT_DIR,
} from "../brain/path-constants.ts";
+import { WATCHDOG_FALLBACK_AUDIT_DIR } from "../brain/audit-dirs.ts";
+import { JSONL_LEDGER_EXT, jsonlLedgerGrammar, parseShardedName } from "../brain/ledger-shards.ts";
+import { MAINTENANCE_JOURNAL_STEM } from "../brain/maintenance/journal.ts";
+import {
+ CAPTURE_DECISION_LEDGER_STEM,
+ QUERY_DEMAND_LEDGER_STEM,
+ RECURRENCE_LEDGER_STEM,
+} from "../brain/paths.ts";
import { CONFIG_ORIGIN, resolveWithOrigin, type ConfigOrigin } from "../validate.ts";
// ----- Vocabularies ---------------------------------------------------------
@@ -250,6 +258,13 @@ export interface StateSurface {
* a test rather than silently orphaning a location.
*/
readonly sources: ReadonlyArray<string>;
+ /**
+ * True for a fixed-name ledger that writes per-device shards beside its
+ * legacy name (t_774dea61): `derive` names the legacy, empty-shard
+ * `<base>.jsonl`, and a device with an id writes `<base>.<deviceId>.jsonl`
+ * instead. The probe reports such a surface present when either exists.
+ */
+ readonly sharded_ledger?: true;
}
// Names the resolvers spell privately. Declared here so the derivations
@@ -266,18 +281,17 @@ const SESSION_LEDGER_FILE = "session-import-ledger.json";
const INSTALL_MANIFEST_FILE = "install.lock.json";
const PROTECT_MANIFEST_FILE = "protect.lock.json";
const MAINTENANCE_LEASE_FILE = "maintenance.sqlite";
-const MAINTENANCE_JOURNAL_FILE = "maintenance-runs.jsonl";
+const MAINTENANCE_JOURNAL_FILE = `${MAINTENANCE_JOURNAL_STEM}.${JSONL_LEDGER_EXT}`;
const HOOK_STATE_DIR = "hook-state";
const SELF_HEAL_UPGRADE_MARKER_FILE = "self-heal-upgrade.json";
-const WATCHDOG_AUDIT_DIR = "watchdog-audit";
const INJECT_CACHE_DIR = "inject-cache";
const AIDER_CONTEXT_FILE = "aider-context.md";
const DREAM_RUNS_DIR = "dream-runs";
const PREF_AUDIT_DIR = "pref-audit";
const CONTINUITY_DIR = "continuity";
-const RECURRENCE_FILE = "recurrence-support.jsonl";
-const QUERY_DEMAND_FILE = "query-demand.jsonl";
-const CAPTURE_DECISIONS_FILE = "capture-decisions.jsonl";
+const RECURRENCE_FILE = `${RECURRENCE_LEDGER_STEM}.${JSONL_LEDGER_EXT}`;
+const QUERY_DEMAND_FILE = `${QUERY_DEMAND_LEDGER_STEM}.${JSONL_LEDGER_EXT}`;
+const CAPTURE_DECISIONS_FILE = `${CAPTURE_DECISION_LEDGER_STEM}.${JSONL_LEDGER_EXT}`;
const CAPTURE_WATERMARK_FILE = ".catchup-watermark.json";
const PROPOSAL_WATERMARK_FILE = "proposal-watermark.json";
const TRUTH_DIR = "truth";
@@ -524,6 +538,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "maintenance journal",
tier: STATE_TIER.derived,
derive: derivedStore(MAINTENANCE_JOURNAL_FILE),
+ sharded_ledger: true,
override_env: null,
override_config_key: null,
carries_memory: false,
@@ -578,7 +593,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
id: STATE_SURFACE_ID.watchdogAudit,
label: "watchdog audit fallback",
tier: STATE_TIER.derived,
- derive: derivedStore(WATCHDOG_AUDIT_DIR),
+ derive: derivedStore(WATCHDOG_FALLBACK_AUDIT_DIR),
override_env: null,
override_config_key: null,
carries_memory: false,
@@ -677,6 +692,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "procedural recurrence ledger",
tier: STATE_TIER.vaultContent,
derive: brainLog(RECURRENCE_FILE),
+ sharded_ledger: true,
override_env: null,
override_config_key: null,
carries_memory: false,
@@ -691,6 +707,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "query demand ledger",
tier: STATE_TIER.vaultContent,
derive: brainLog(QUERY_DEMAND_FILE),
+ sharded_ledger: true,
override_env: null,
override_config_key: null,
carries_memory: true,
@@ -705,6 +722,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "inbound capture decision log",
tier: STATE_TIER.vaultContent,
derive: brainLog(CAPTURE_DECISIONS_FILE),
+ sharded_ledger: true,
override_env: null,
override_config_key: null,
carries_memory: true,
@@ -733,6 +751,7 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze([
label: "session lineage ledger",
tier: STATE_TIER.vaultContent,
derive: brainTree(BRAIN_INTERNAL_STATE_DIR, LINEAGE_LEDGER_FILE),
+ sharded_ledger: true,
override_env: DEVICE_ID_ENV,
override_config_key: DEVICE_ID_CONFIG_KEY,
carries_memory: false,
@@ -1113,16 +1132,53 @@ function statOrAbsent(path: string): StatLike | undefined {
/** What an absent surface says. Absent is a state, not a failure. */
const ABSENT_REASON = "nothing has created it in this vault yet";
+/**
+ * The first shard of the sharded ledger whose legacy (empty-shard) file is
+ * `legacyPath`, or `undefined` when its directory holds none.
+ *
+ * The grammar is the one every writer names its files through, so the probe
+ * and the writers cannot disagree on what a shard is, and a
+ * `*.sync-conflict-*` copy is never counted. A missing directory is the same
+ * `absent` a missing file is; any other listing failure throws, and the
+ * probe reports it as `unchecked` by its code.
+ */
+function firstLedgerShard(legacyPath: string): string | undefined {
+ const name = basename(legacyPath);
+ const suffix = `.${JSONL_LEDGER_EXT}`;
+ if (!name.endsWith(suffix)) {
+ throw new Error(
+ `sharded ledger surface ${JSON.stringify(legacyPath)} does not end in ${suffix}`,
+ );
+ }
+ const grammar = jsonlLedgerGrammar(name.slice(0, -suffix.length));
+ const dir = dirname(legacyPath);
+ let names: string[];
+ try {
+ names = readdirSync(dir).toSorted();
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
+ throw error;
+ }
+ const shard = names.find((entry) => parseShardedName(entry, grammar) !== null);
+ return shard === undefined ? undefined : join(dir, shard);
+}
+
function probe(
path: string,
statAt: (path: string) => StatLike | undefined,
+ sharded: boolean,
): StateReachabilityVerdict {
try {
- const stat = statAt(path);
- if (stat === undefined) {
- return { state: STATE_REACHABILITY.absent, path, reason: ABSENT_REASON };
+ if (statAt(path) !== undefined) {
+ return { state: STATE_REACHABILITY.present, path, reason: null };
+ }
+ // A sharded ledger on a device with an id never writes the legacy
+ // name at all; one of its shards is the surface just as well.
+ const shard = sharded ? firstLedgerShard(path) : undefined;
+ if (shard !== undefined) {
+ return { state: STATE_REACHABILITY.present, path: shard, reason: null };
}
- return { state: STATE_REACHABILITY.present, path, reason: null };
+ return { state: STATE_REACHABILITY.absent, path, reason: ABSENT_REASON };
} catch (error) {
// The one branch the tri-state exists for. An EACCES on the parent
// directory, an ELOOP, an EIO from a dying disk: none of them is
@@ -1168,7 +1224,7 @@ export function inventoryStateSurfaces(input: StateInventoryInput): StateInvento
override_config_key: surface.override_config_key,
carries_memory: surface.carries_memory,
reason: surface.reason,
- reachability: probe(path, statAt),
+ reachability: probe(path, statAt, surface.sharded_ledger === true),
origin: resolved.origin,
};
});
diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.ts
index 6589f484..420743bb 100644
--- a/src/mcp/brain/ingest-tools.ts
+++ b/src/mcp/brain/ingest-tools.ts
@@ -14,6 +14,7 @@ import { planBatches, type BatchPlan } from "../../core/brain/ingest/batch-plan.
import { clearCheckpoint, PLAN_ID_LABEL } from "../../core/brain/ingest/checkpoint.ts";
import { assertCheckpointId } from "../../core/brain/checkpoint-store.ts";
import { ingestSource } from "../../core/brain/ingest/ingest.ts";
+import type { CodeEdgeSeed, PreExtractResult } from "../../core/brain/ingest/pre-extract.ts";
import { reconcilePlan } from "../../core/brain/ingest/reconcile.ts";
import { IntakeValidationError } from "../../core/brain/intake/extract-intake.ts";
import {
@@ -97,11 +98,26 @@ async function toolBrainIngestSource(
connections: [...res.connections],
// Only emitted when the pre-extract pass ran, so a call without it is
// byte-identical to before (P4).
- ...(res.preExtract !== undefined ? { pre_extract: res.preExtract } : {}),
+ ...(res.preExtract !== undefined ? { pre_extract: serializePreExtract(res.preExtract) } : {}),
};
});
}
+/** The pre-extract result with its edge keys in the payload's snake_case. */
+function serializePreExtract(result: PreExtractResult): Record<string, unknown> {
+ if (!result.extracted) return { ...result };
+ return { ...result, edges: result.edges.map(serializeEdgeSeed) };
+}
+
+function serializeEdgeSeed(edge: CodeEdgeSeed): Record<string, unknown> {
+ return {
+ kind: edge.kind,
+ from: edge.from,
+ to: edge.to,
+ ...(edge.resolvedTo !== undefined ? { resolved_to: edge.resolvedTo } : {}),
+ };
+}
+
function serializeEntry(entry: SourceCleanupEntry): Record<string, unknown> {
return {
path: entry.path,
@@ -400,7 +416,7 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
pre_extract: {
type: "boolean",
description:
- "Run the deterministic no-LLM code-structure pass over the source file; returns class/function/import/inheritance seeds under `pre_extract`. Off by default.",
+ "No-LLM code-structure pass: class/function seeds and import/inheritance/uses edges under `pre_extract`, a bound import with `resolved_to`. Off by default.",
},
},
required: ["source_path", "summary", "entities"],
diff --git a/src/mcp/brain/write-batch-tools.ts b/src/mcp/brain/write-batch-tools.ts
index edab9e57..6e68afd0 100644
--- a/src/mcp/brain/write-batch-tools.ts
+++ b/src/mcp/brain/write-batch-tools.ts
@@ -22,9 +22,15 @@ import type { BrainApplyOutcome, BrainApplyResult } from "../../core/brain/types
import {
applyWriteBatch,
MAX_BATCH_OPERATIONS,
+ WRITE_BATCH_RECEIPT_STATUS,
+ type WriteBatchReceipt,
type WriteBatchResult,
type WriteOperation,
} from "../../core/brain/write-batch.ts";
+import {
+ IdempotencyKeyError,
+ IdempotencyPayloadMismatchError,
+} from "../../core/brain/idempotency-ledger.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { noteWriteResult, parseFrontmatterArg, writeBatchErrorToMcp } from "./notes-tools.ts";
@@ -182,6 +188,26 @@ function committedNotePage(
);
}
+/**
+ * The receipt half of the response. A `payload_conflict` also says in
+ * words what the status means for the caller: the writes landed, so the
+ * batch must not be sent again under a new ID.
+ */
+function receiptFields(receipt: WriteBatchReceipt): Record<string, unknown> {
+ return {
+ request_id: receipt.requestId,
+ receipt: receipt.status,
+ ...(receipt.status === WRITE_BATCH_RECEIPT_STATUS.payload_conflict
+ ? {
+ receipt_note:
+ `The writes of this call landed (see results). request_id '${receipt.requestId}' ` +
+ "was recorded concurrently for a different payload, so this call's receipt was not " +
+ "recorded; do not resend this batch under a new request_id.",
+ }
+ : {}),
+ };
+}
+
async function toolBrainWriteBatch(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -193,15 +219,29 @@ async function toolBrainWriteBatch(
const resolveAgent = (override?: string): string =>
normalizeAgentArgument(override ?? null) ?? resolveAgentName(ctx.configPath ?? undefined);
const operations = rawOps.map((raw, index) => mapOperation(raw, index, resolveAgent));
+ const requestId = optionalStr(args, "request_id");
+ const baseOpts = ctx.configPath !== null ? { configPath: ctx.configPath } : {};
let batch: WriteBatchResult;
+ // Set exactly when a request ID was supplied: the core's receipted
+ // overload always carries the status, so nothing here invents one.
+ let receipt: WriteBatchReceipt | undefined;
try {
- batch = applyWriteBatch(
- ctx.vault,
- operations,
- ctx.configPath !== null ? { configPath: ctx.configPath } : {},
- );
+ if (requestId === undefined) {
+ batch = applyWriteBatch(ctx.vault, operations, baseOpts);
+ } else {
+ const receipted = applyWriteBatch(ctx.vault, operations, { ...baseOpts, requestId });
+ batch = receipted;
+ receipt = receipted.receipt;
+ }
} catch (err) {
+ // A reused request ID with a different payload, or an ID the ledger
+ // cannot store (blank, over-long), is the caller's mistake, not the
+ // server's: INVALID_PARAMS with the ledger's own explanation, the same
+ // mapping the checkpoint tools use. Both are raised before any write.
+ if (err instanceof IdempotencyPayloadMismatchError || err instanceof IdempotencyKeyError) {
+ throw new MCPError(INVALID_PARAMS, `brain_write_batch: request_id: ${err.message}`);
+ }
throw writeBatchErrorToMcp(err, "brain_write_batch");
}
// The pages this batch committed, in commit order. Log-writing ops name
@@ -210,11 +250,18 @@ async function toolBrainWriteBatch(
// skipped wrote nothing either, so it names no page - the same rule the
// single-write receipts follow. One report covers the whole batch, with
// the basename index and schema pack built ONCE.
- const writtenPages = batch.results.filter(committedNotePage).map((r) => r.path);
+ // A duplicate wrote nothing: its results are the retained receipt of the
+ // call that committed, read back from the synced ledger, so it names no
+ // page as one this call wrote and nothing is linted.
+ const writtenPages =
+ receipt?.status === WRITE_BATCH_RECEIPT_STATUS.duplicate
+ ? []
+ : batch.results.filter(committedNotePage).map((r) => r.path);
return noteWriteResult(ctx, writtenPages, {
applied: batch.applied,
results: batch.results.map((r) => serializeResult(ctx, r)),
done: true,
+ ...(receipt !== undefined ? receiptFields(receipt) : {}),
});
}
@@ -282,6 +329,10 @@ export const WRITE_BATCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
additionalProperties: false,
},
},
+ request_id: {
+ type: "string",
+ description: `Optional request ID for exactly-once writes: a repeat with the same operations returns receipt "${WRITE_BATCH_RECEIPT_STATUS.duplicate}" and writes nothing; other operations are refused.`,
+ },
},
required: ["operations"],
additionalProperties: false,
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index 68b278fa..8e8a345d 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -73,6 +73,12 @@ import { decisionModelSearchEnvelope } from "../core/decision-model/answerable.t
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { explainEnvelope } from "../core/search/explain-envelope.ts";
import { deriveRecallHint } from "../core/search/recall-hint.ts";
+import { FTS_MATCH_MODES, isFtsMatchMode } from "../core/search/fts-match-mode.ts";
+import {
+ DISCLOSURE_MODE,
+ DISCLOSURE_MODES,
+ isDisclosureMode,
+} from "../core/search/disclosure-mode.ts";
import {
ELLIPSIS,
HEAD_WINDOW_START,
@@ -177,9 +183,15 @@ const SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
type: "boolean",
description: "Skip the semantic lane entirely, so no embedding is needed. Default false.",
},
+ match_mode: {
+ type: "string",
+ enum: [...FTS_MATCH_MODES],
+ description:
+ "FTS match breadth: 'all' (default) requires every term; 'any' matches a document carrying any one term. Absent leaves the implicit AND.",
+ },
disclosure: {
type: "string",
- enum: ["full", "cards"],
+ enum: [...DISCLOSURE_MODES],
description:
"Result depth: 'full' (default) returns full chunk content; 'cards' returns token-cheap layer-1 cards — drill a hit with brain_search_expand.",
},
@@ -900,10 +912,24 @@ async function toolBrainSearch(
const semantic = coerceBoolOptional(args, "semantic");
const keywordOnly = coerceBoolOptional(args, "keyword_only") ?? false;
- const disclosure = coerceStringOptional(args, "disclosure", 16);
- if (disclosure !== undefined && disclosure !== "full" && disclosure !== "cards") {
- throw new MCPError(INVALID_PARAMS, "argument 'disclosure' must be 'full' or 'cards'");
+ // The enum checks alone bound these values, so no separate length cap:
+ // any present value outside the modes, whatever its type or length, is
+ // refused with the accepted list.
+ const disclosure = args["disclosure"] ?? undefined;
+ if (disclosure !== undefined && !isDisclosureMode(disclosure)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'disclosure' must be one of ${DISCLOSURE_MODES.join(", ")}`,
+ );
+ }
+ const matchModeRaw = args["match_mode"] ?? undefined;
+ if (matchModeRaw !== undefined && !isFtsMatchMode(matchModeRaw)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `argument 'match_mode' must be one of ${FTS_MATCH_MODES.join(", ")}`,
+ );
}
+ const matchMode = matchModeRaw;
const explain = coerceBoolOptional(args, "explain") ?? false;
const trust = coerceBoolOptional(args, "trust") ?? false;
const rerank = coerceBoolOptional(args, "rerank") ?? false;
@@ -991,8 +1017,9 @@ async function toolBrainSearch(
semantic: semantic ?? null,
keywordOnly,
pathPrefix,
+ ...(matchMode !== undefined ? { matchMode } : {}),
...(profile !== undefined ? { profile } : {}),
- ...(disclosure === "cards" ? { disclosure: "cards" as const } : {}),
+ ...(disclosure === DISCLOSURE_MODE.cards ? { disclosure } : {}),
...(properties !== undefined ? { properties } : {}),
...(degreeFilters !== undefined ? { degreeFilters } : {}),
...(visibility !== undefined ? { visibility } : {}),
@@ -1870,7 +1897,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_search",
description:
- "Full-text search across the vault. Optional semantic layer when configured. Read-only.",
+ "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.",
inputSchema: SEARCH_INPUT_SCHEMA,
outputSchema: SEARCH_OUTPUT_SCHEMA,
previewBudget: MCP_PREVIEW_BUDGET,
diff --git a/tests/cli/brain-dream-progress.test.ts b/tests/cli/brain-dream-progress.test.ts
index 7a167826..2cc0cfdd 100644
--- a/tests/cli/brain-dream-progress.test.ts
+++ b/tests/cli/brain-dream-progress.test.ts
@@ -60,6 +60,16 @@ afterEach(() => {
const env = (): Record<string, string> => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+const RUN_ID_MASK = "<run-id>";
+
+/** The `--json` stdout with every occurrence of its own run id masked. */
+function withoutRunId(stdout: string): string {
+ const runId = (JSON.parse(stdout) as Record<string, unknown>)["run_id"];
+ if (typeof runId !== "string" || runId === "")
+ throw new Error("dream --json stdout has no run_id");
+ return stdout.replaceAll(runId, RUN_ID_MASK);
+}
+
describe("o2b brain dream --progress", () => {
test("writes records to stderr and leaves stdout untouched", async () => {
const plain = await runCli(["brain", "dream", "--dry-run", "--json"], { env: env() });
@@ -71,8 +81,10 @@ describe("o2b brain dream --progress", () => {
expect(watched.returncode).toBe(0);
// The payload a caller parses is byte-identical with and without the
// observer. Progress that changed stdout would be a regression, not a
- // feature.
- expect(watched.stdout).toBe(plain.stdout);
+ // feature. The run id is minted per second, so two runs that straddle
+ // a second boundary differ there and nowhere else: it is masked
+ // wherever it appears (target paths embed it too) before the compare.
+ expect(withoutRunId(watched.stdout)).toBe(withoutRunId(plain.stdout));
const records = progressRecords(watched.stderr);
expect(records.length).toBeGreaterThan(0);
diff --git a/tests/cli/search-match-mode.test.ts b/tests/cli/search-match-mode.test.ts
new file mode 100644
index 00000000..8ac1af44
--- /dev/null
+++ b/tests/cli/search-match-mode.test.ts
@@ -0,0 +1,72 @@
+/**
+ * CLI `--match-mode` on `o2b search query` (t_c5326ece): the flag mirrors
+ * the MCP `match_mode` argument - `any` genuinely widens the query, and a
+ * value outside the pair is refused by name rather than read as the default.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+import { FTS_MATCH_MODES } from "../../src/core/search/fts-match-mode.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+beforeEach(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-match-mode-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\n`);
+ writeFileSync(
+ join(vault, "notes", "both.md"),
+ "# Both\n\nchimera basilisk together in one lair.\n",
+ "utf8",
+ );
+ writeFileSync(join(vault, "notes", "one.md"), "# One\n\nA lone chimera wanders here.\n", "utf8");
+ const indexed = await runCli(["search", "index"], { env: env() });
+ if (indexed.returncode !== 0) throw new Error(`search index failed: ${indexed.stderr}`);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+interface QueryJson {
+ readonly returncode: number;
+ readonly stdout: string;
+ readonly stderr: string;
+}
+
+async function runQuery(extra: ReadonlyArray<string>): Promise<QueryJson> {
+ const r = await runCli(
+ ["search", "query", "chimera basilisk", "--json", "--limit", "20", ...extra],
+ {
+ env: env(),
+ },
+ );
+ return { returncode: r.returncode, stdout: r.stdout, stderr: r.stderr };
+}
+
+const pathsIn = (stdout: string): string[] =>
+ JSON.parse(stdout).results.map((h: { path: string }) => h.path);
+
+describe("o2b search query --match-mode", () => {
+ test("--match-mode any reaches the search and keeps the single-term document", async () => {
+ const r = await runQuery(["--match-mode", "any"]);
+ expect(r.returncode).toBe(0);
+ expect(pathsIn(r.stdout).some((p) => p.includes("one.md"))).toBe(true);
+ });
+
+ test("a value outside all|any is refused", async () => {
+ const r = await runQuery(["--match-mode", "sometimes"]);
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toContain(`--match-mode must be one of ${FTS_MATCH_MODES.join(", ")}`);
+ });
+});
diff --git a/tests/core/architecture/append-shard-census.test.ts b/tests/core/architecture/append-shard-census.test.ts
new file mode 100644
index 00000000..742ea9c9
--- /dev/null
+++ b/tests/core/architecture/append-shard-census.test.ts
@@ -0,0 +1,436 @@
+/**
+ * Every append-mode writer in `src/` names its file through the per-device
+ * shard grammar, or is allowed by name with a reason (t_774dea61).
+ *
+ * Syncthing merges nothing: two devices appending to one file produce a
+ * `*.sync-conflict-*` copy that no reader merges, and the rows in it are
+ * lost to every reader until someone merges them by hand. The ledgers
+ * stopped doing that by writing one file per device; this census keeps a
+ * NEW append site from quietly reintroducing the shared file.
+ *
+ * ## The rule names files, not call sites
+ *
+ * Mirroring the hook-audit root guard (`tests/hooks/audit-root.test.ts`),
+ * a module with an append-mode write passes when it calls a shard-naming
+ * function anywhere in its code. It does not prove the append at line N
+ * uses the name built at line M; it makes a new append site in a module
+ * that never thought about devices fail until it adopts the grammar or is
+ * allowed by name - a review gate, not a proof.
+ *
+ * A shard-naming function is one of {@link SHARD_NAMING_PRIMITIVES}, or an
+ * exported function anywhere in `src/` whose body calls one (to a fixed
+ * point). That is what lets `capture/telegram-capture.ts` pass through
+ * `captureDecisionLogPath`, and the decision-receipt and truth stores pass
+ * through their own device-id shard-path builders, without an allow-list
+ * entry each.
+ *
+ * ## The append-mode forms
+ *
+ * `appendFileSync(` / `appendFile(`; `openSync(` / `open(` whose second
+ * argument is an `"a"` or `"a+"` literal; and any `flag:` / `flags:`
+ * property set to one (the `writeFileSync(..., { flag: "a" })` and
+ * `createWriteStream` spellings). Read off the shared source lexer, so a
+ * mention in a comment or a string is not a call. A mode passed through
+ * a variable is not seen; that would be a new shape in this tree, and
+ * {@link APPEND_SHAPES} below is where it gets added the day it appears.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import { lexSource } from "../../helpers/source-lexer.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+
+/** The one root the census walks. */
+const SWEPT_ROOT = "src";
+
+/**
+ * Functions whose result is a per-device shard name or the shard id
+ * itself: the shared grammar's builders, and the device-id resolver the
+ * older hand-rolled shard paths call directly.
+ */
+const SHARD_NAMING_PRIMITIVES: ReadonlyArray<string> = Object.freeze([
+ "shardedFileName",
+ "resolveAppendShardId",
+ "resolveDeviceId",
+]);
+
+/** An allow-list reason has to be an argument, not a label. */
+const MIN_REASON_LENGTH = 80;
+
+/**
+ * Append-mode writers that are not device-sharded, each with the reason a
+ * single shared file is still correct.
+ */
+const APPEND_ALLOW_LIST: Readonly<Record<string, string>> = Object.freeze({
+ "src/core/brain/dream-workrun.ts":
+ "each dream run appends to its own dream-runs/<run-id>.jsonl, a name unique to one run on one " +
+ "device, so no second device ever appends to the same file",
+ "src/core/brain/diagnostics.ts":
+ "the doctor repair appends the terminal interrupted marker to a dangling per-run dream workrun " +
+ "file, under a lock, and that file is unique to the run that created it",
+ "src/core/doctor.ts":
+ "the config-writeable probe opens the machine config file in append mode and writes zero bytes; " +
+ "it lives outside the vault, is not a ledger, and removes the file it created",
+});
+
+interface SourceFile {
+ readonly path: string;
+ readonly text: string;
+}
+
+interface AppendSite {
+ readonly path: string;
+ readonly line: number;
+ readonly form: string;
+}
+
+/** A regex over the code view plus a predicate on the call's arguments. */
+interface AppendShape {
+ readonly form: string;
+ readonly pattern: RegExp;
+ /** Receives the comment-stripped arguments; true when this is an append. */
+ readonly isAppend: (args: ReadonlyArray<string>) => boolean;
+}
+
+const APPEND_MODE_LITERAL = /^(["'`])a\+?\1$/;
+
+const APPEND_SHAPES: ReadonlyArray<AppendShape> = Object.freeze<AppendShape[]>([
+ { form: "appendFile", pattern: /\bappendFile(?:Sync)?\s*\(/g, isAppend: () => true },
+ {
+ form: 'open(..., "a")',
+ pattern: /\bopen(?:Sync)?\s*\(/g,
+ isAppend: (args) => APPEND_MODE_LITERAL.test((args[1] ?? "").trim()),
+ },
+]);
+
+/** A `flag:` / `flags:` property whose value is an append-mode literal. */
+const FLAG_PROPERTY = /\bflags?\s*:\s*/g;
+
+function readSourceTree(): ReadonlyArray<SourceFile> {
+ const files: SourceFile[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else if (entry.name.endsWith(".ts")) {
+ files.push({
+ path: relative(REPO_ROOT, abs).split("\\").join("/"),
+ text: readFileSync(abs, "utf8"),
+ });
+ }
+ }
+ };
+ walk(join(REPO_ROOT, SWEPT_ROOT));
+ return files.toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+}
+
+/**
+ * The top-level arguments of the call whose `(` is at `open`, read off
+ * `withoutComments` but split on the `code` view, where a comma or a
+ * bracket inside a literal is blanked and cannot mis-split.
+ */
+function callArguments(code: string, withoutComments: string, open: number): string[] {
+ const args: string[] = [];
+ let depth = 0;
+ let start = open + 1;
+ for (let i = open; i < code.length; i++) {
+ const ch = code[i];
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
+ else if (ch === ")" || ch === "]" || ch === "}") {
+ depth--;
+ if (depth === 0) {
+ args.push(withoutComments.slice(start, i));
+ return args;
+ }
+ } else if (ch === "," && depth === 1) {
+ args.push(withoutComments.slice(start, i));
+ start = i + 1;
+ }
+ }
+ return args;
+}
+
+function lineAt(text: string, offset: number): number {
+ return text.slice(0, offset).split("\n").length;
+}
+
+/** Every append-mode write in one module. */
+function appendSites(file: SourceFile): AppendSite[] {
+ const { code, withoutComments } = lexSource(file.text);
+ const sites: AppendSite[] = [];
+ for (const shape of APPEND_SHAPES) {
+ for (const match of code.matchAll(shape.pattern)) {
+ const open = match.index + match[0].length - 1;
+ if (shape.isAppend(callArguments(code, withoutComments, open))) {
+ sites.push({ path: file.path, line: lineAt(file.text, match.index), form: shape.form });
+ }
+ }
+ }
+ for (const match of code.matchAll(FLAG_PROPERTY)) {
+ const valueAt = match.index + match[0].length;
+ const value = /^(["'`])a\+?\1/.exec(withoutComments.slice(valueAt));
+ if (value !== null && code[valueAt] === value[1]) {
+ sites.push({ path: file.path, line: lineAt(file.text, match.index), form: 'flag: "a"' });
+ }
+ }
+ return sites.toSorted((a, b) => a.line - b.line);
+}
+
+function callsAny(code: string, names: ReadonlySet<string>): boolean {
+ for (const match of code.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)) {
+ if (names.has(match[1]!)) return true;
+ }
+ return false;
+}
+
+/**
+ * The primitives plus every exported PATH BUILDER - an exported function
+ * declared to return `string` - whose body calls a known shard-naming
+ * function, iterated to a fixed point so a builder that wraps a builder
+ * counts too. A module-private builder in the same file counts as a step
+ * on that path (`paths.ts` routes every `Brain/log/` ledger through one),
+ * but only within its own module: a private name is not a name another
+ * module can call, and two modules may each have a private `ledgerPath`.
+ * A body runs from its declaration to the next column-0 `}`, the shape
+ * the formatter gives every top-level function in this tree.
+ *
+ * Two restrictions keep a writer from passing as a name: the return
+ * type (a function that APPENDS through a sharded ledger, like
+ * `appendLogEvent`, calls a primitive too, and calling it says nothing
+ * about the file the caller then appends to itself), and a body with no
+ * append site of its own (`appendAuditRecord` returns the path it wrote).
+ */
+function shardNamingFunctions(files: ReadonlyArray<SourceFile>): ReadonlySet<string> {
+ const exported = new Set(SHARD_NAMING_PRIMITIVES);
+ const privateByFile = new Map<string, Set<string>>();
+ const builders: Array<{ file: string; name: string; isExported: boolean; body: string }> = [];
+ for (const file of files) {
+ const { code } = lexSource(file.text);
+ privateByFile.set(file.path, new Set());
+ for (const match of code.matchAll(PATH_BUILDER_DECLARATION)) {
+ const start = match.index + match[0].length;
+ const found = code.indexOf("\n}", match.index);
+ const end = found === -1 ? code.length : found;
+ // A builder that appends itself (`appendAuditRecord` returns the
+ // path it wrote) is a writer, not a name a caller appends to.
+ if (appendSites({ path: file.path, text: file.text.slice(start, end) }).length > 0) continue;
+ builders.push({
+ file: file.path,
+ name: match[2]!,
+ isExported: match[1] !== undefined,
+ body: code.slice(start, end),
+ });
+ }
+ }
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const builder of builders) {
+ const own = privateByFile.get(builder.file)!;
+ const known = builder.isExported ? exported : own;
+ if (known.has(builder.name)) continue;
+ if (callsAny(builder.body, exported) || callsAny(builder.body, own)) {
+ known.add(builder.name);
+ grew = true;
+ }
+ }
+ }
+ return exported;
+}
+
+/**
+ * `[export ]function name(<params>): string {` at column 0 - one nesting
+ * level of parens in the params. Group 1 is the `export` keyword.
+ */
+const PATH_BUILDER_DECLARATION =
+ /^(export\s+)?function\s+([\w$]+)\s*\((?:[^()]|\([^()]*\))*\)\s*:\s*string\s*\{/gm;
+
+interface CensusResult {
+ /** Append sites in modules that neither shard nor sit on the allow-list. */
+ readonly offenders: ReadonlyArray<string>;
+ /** Every module with at least one append site. */
+ readonly appendingFiles: ReadonlyArray<string>;
+ /** Appending modules recognised as sharded. */
+ readonly shardedFiles: ReadonlyArray<string>;
+}
+
+function appendCensus(
+ files: ReadonlyArray<SourceFile>,
+ allow: Readonly<Record<string, string>>,
+): CensusResult {
+ const naming = shardNamingFunctions(files);
+ const offenders: string[] = [];
+ const appendingFiles: string[] = [];
+ const shardedFiles: string[] = [];
+ for (const file of files) {
+ const sites = appendSites(file);
+ if (sites.length === 0) continue;
+ appendingFiles.push(file.path);
+ if (callsAny(lexSource(file.text).code, naming)) {
+ shardedFiles.push(file.path);
+ continue;
+ }
+ if (Object.hasOwn(allow, file.path)) continue;
+ for (const site of sites) offenders.push(`${site.path}:${site.line} ${site.form}`);
+ }
+ return { offenders, appendingFiles, shardedFiles };
+}
+
+describe("every append-mode writer is device-sharded or allowed by name", () => {
+ const files = readSourceTree();
+ const census = appendCensus(files, APPEND_ALLOW_LIST);
+
+ test("the census actually found the append sites", () => {
+ // A census over an empty set passes for the wrong reason.
+ expect(census.appendingFiles.length).toBeGreaterThan(15);
+ expect(census.shardedFiles.length).toBeGreaterThan(10);
+ });
+
+ test("no append site writes a shared file outside the allow-list", () => {
+ expect(census.offenders).toEqual([]);
+ });
+
+ test("every allow-list entry still appends and is not already sharded", () => {
+ const stale = Object.keys(APPEND_ALLOW_LIST).filter(
+ (path) => !census.appendingFiles.includes(path) || census.shardedFiles.includes(path),
+ );
+ expect(stale).toEqual([]);
+ });
+
+ test("every allow-list reason is an argument", () => {
+ const thin = Object.entries(APPEND_ALLOW_LIST)
+ .filter(([, reason]) => reason.length < MIN_REASON_LENGTH)
+ .map(([path]) => path);
+ expect(thin).toEqual([]);
+ });
+});
+
+/** A synthetic module under the swept root, for the census's own fixtures. */
+function src(path: string, text: string): SourceFile {
+ return { path: `src/${path}`, text };
+}
+
+describe("the append census can fail", () => {
+ test.each([
+ ["appendFileSync", `appendFileSync(path, "x\\n", "utf8");`],
+ ["fs namespace", `fs.appendFileSync(path, line);`],
+ ["promises appendFile", `await appendFile(path, line);`],
+ ["openSync append", `const fd = openSync(path, "a", 0o600);`],
+ ["openSync append-read", `const fd = openSync(path, 'a+');`],
+ ["writeFileSync flag", `writeFileSync(path, line, { encoding: "utf8", flag: "a" });`],
+ ["createWriteStream flags", `createWriteStream(path, { flags: "a" });`],
+ ])("a bare %s site is an offender", (_label, line) => {
+ const result = appendCensus([src("new-ledger.ts", `${line}\n`)], {});
+ expect(result.offenders).toEqual([expect.stringMatching(/^src\/new-ledger\.ts:1 /)]);
+ });
+
+ test.each([
+ ["a read-mode open", `const fd = openSync(path, "r");`],
+ ["a write-mode flag", `writeFileSync(path, line, { flag: "w" });`],
+ ["a mention in a comment", `// appendFileSync(path, line) is forbidden here`],
+ ["a mention in a string", `const hint = "appendFileSync(path, line)";`],
+ ])("%s is not an append site", (_label, line) => {
+ const result = appendCensus([src("reader.ts", `${line}\n`)], {});
+ expect(result.appendingFiles).toEqual([]);
+ });
+
+ test("calling a shard primitive clears the module", () => {
+ const text = `const path = join(dir, shardedFileName("x", resolveAppendShardId(), "jsonl"));
+appendFileSync(path, line);
+`;
+ expect(appendCensus([src("ledger.ts", text)], {}).offenders).toEqual([]);
+ });
+
+ test("calling an exported shard-path builder from another module clears the module", () => {
+ const builder = src(
+ "paths.ts",
+ `export function outerPath(vault: string): string {
+ return innerPath(vault);
+}
+
+export function innerPath(vault: string): string {
+ return join(vault, shardedFileName("x", resolveAppendShardId(), "jsonl"));
+}
+`,
+ );
+ const writer = src("writer.ts", `appendFileSync(outerPath(vault), line);\n`);
+ expect(appendCensus([builder, writer], {}).offenders).toEqual([]);
+ });
+
+ test("calling an exported function that only appends through a sharded ledger does not clear the module", () => {
+ const ledger = src(
+ "log.ts",
+ `export function appendEvent(vault: string, line: string): void {
+ appendFileSync(join(vault, shardedFileName("log", resolveAppendShardId(), "jsonl")), line);
+}
+`,
+ );
+ const writer = src("writer.ts", `appendEvent(vault, line);\nappendFileSync(path, line);\n`);
+ expect(appendCensus([ledger, writer], {}).offenders).toEqual(["src/writer.ts:2 appendFile"]);
+ });
+
+ test("calling an exported writer that returns the path it appended to does not clear the module", () => {
+ const ledger = src(
+ "audit.ts",
+ `export function appendRecord(dir: string, line: string): string {
+ const path = join(dir, shardedFileName("week", resolveAppendShardId(), "jsonl"));
+ appendFileSync(path, line);
+ return path;
+}
+`,
+ );
+ const writer = src("writer.ts", `appendRecord(dir, line);\nappendFileSync(other, line);\n`);
+ expect(appendCensus([ledger, writer], {}).offenders).toEqual(["src/writer.ts:2 appendFile"]);
+ });
+
+ test("an exported builder that reaches the grammar through a private builder clears the module", () => {
+ const builder = src(
+ "paths.ts",
+ `function ledgerPath(vault: string, stem: string): string {
+ return join(vault, shardedFileName(stem, resolveAppendShardId(), "jsonl"));
+}
+
+export function demandPath(vault: string): string {
+ return ledgerPath(vault, "demand");
+}
+`,
+ );
+ const writer = src("writer.ts", `appendFileSync(demandPath(vault), line);\n`);
+ expect(appendCensus([builder, writer], {}).offenders).toEqual([]);
+ });
+
+ test("a private builder in one module does not clear a same-named call in another", () => {
+ const builder = src(
+ "paths.ts",
+ `function ledgerPath(vault: string): string {
+ return join(vault, shardedFileName("x", resolveAppendShardId(), "jsonl"));
+}
+`,
+ );
+ const writer = src("writer.ts", `appendFileSync(ledgerPath(vault), line);\n`);
+ expect(appendCensus([builder, writer], {}).offenders).toEqual(["src/writer.ts:1 appendFile"]);
+ });
+
+ test("an unrelated exported function does not clear the module", () => {
+ const helper = src(
+ "helper.ts",
+ `export function plainPath(vault: string): string {
+ return join(vault, "ledger.jsonl");
+}
+`,
+ );
+ const writer = src("writer.ts", `appendFileSync(plainPath(vault), line);\n`);
+ expect(appendCensus([helper, writer], {}).offenders).toEqual(["src/writer.ts:1 appendFile"]);
+ });
+
+ test("an allow-list entry clears only the module it names", () => {
+ const files = [
+ src("allowed.ts", `appendFileSync(path, line);\n`),
+ src("other.ts", `appendFileSync(path, line);\n`),
+ ];
+ const result = appendCensus(files, { "src/allowed.ts": "reason" });
+ expect(result.offenders).toEqual(["src/other.ts:1 appendFile"]);
+ });
+});
diff --git a/tests/core/architecture/chmod-deny-guard-census.test.ts b/tests/core/architecture/chmod-deny-guard-census.test.ts
new file mode 100644
index 00000000..fd170d66
--- /dev/null
+++ b/tests/core/architecture/chmod-deny-guard-census.test.ts
@@ -0,0 +1,238 @@
+/**
+ * Every test that drops permission bits to make an access FAIL is gated on
+ * {@link CHMOD_CANNOT_DENY} from `tests/helpers/platform.ts`.
+ *
+ * `chmod` denies nothing on two hosts: root reads and writes through any
+ * mode bits, and Windows maps `chmod` onto the single read-only attribute,
+ * which never removes read access and leaves a directory accepting new
+ * entries. A test that waits for the denial there fails for a reason that
+ * says nothing about the product - which is how a Windows CI run broke on
+ * an unguarded `chmodSync(path, 0o000)`. The helper names that fact once;
+ * this census keeps a new denial fixture from forgetting it.
+ *
+ * ## The rule names files, not call sites
+ *
+ * A test module with a denial passes when its code references the guard
+ * anywhere (`test.skipIf(CHMOD_CANNOT_DENY)`, `describe.skipIf(...)`, an
+ * early `if (CHMOD_CANNOT_DENY) return`). It does not prove the guard sits
+ * on the test that holds the chmod; it makes a new denial in a module that
+ * never thought about the platform fail until it does - a review gate, not
+ * a proof. Gating on `IS_WINDOWS` alone does not pass: it still asserts a
+ * denial root never sees.
+ *
+ * ## What counts as a denial
+ *
+ * A `chmod(` / `chmodSync(` call (bare, `fs.`, `fs.promises.`) whose mode
+ * argument is a numeric literal whose OWNER digit lacks the read or the
+ * write bit: `0o000`, `0o444`, `0o555`, `0o500`, `0o400`, `0o300`,
+ * `0o200`, `0o100`. A mode whose owner digit is 6 or 7 restores access
+ * (the `finally` that undoes the fixture) and is not a denial. Read off
+ * the shared source lexer, so a mention in a comment or a string is not a
+ * call. A mode passed through a variable, or as a string, is not seen;
+ * no test in this tree spells one that way, and {@link denialMode} is
+ * where the form gets added the day one does. Python suites are out of
+ * scope: this lexer reads TypeScript.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+
+import { lexSource } from "../../helpers/source-lexer.ts";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+
+/** The one root the census walks. */
+const SWEPT_ROOT = "tests";
+
+/** The platform fact a denial fixture has to be gated on. */
+const DENY_GUARDS: ReadonlyArray<string> = Object.freeze(["CHMOD_CANNOT_DENY"]);
+
+/** A chmod call in any of its spellings; the `(` ends the match. */
+const CHMOD_CALL = /\bchmod(?:Sync)?\s*\(/g;
+
+/** A numeric mode literal: octal, or plain decimal. */
+const OCTAL_MODE = /^0o([0-7]{1,4})$/;
+const DECIMAL_MODE = /^\d+$/;
+
+/** The owner's read and write bits, shifted into the owner digit. */
+const OWNER_READ_WRITE = 0o600;
+
+interface SourceFile {
+ readonly path: string;
+ readonly text: string;
+}
+
+function readTestTree(): ReadonlyArray<SourceFile> {
+ const files: SourceFile[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else if (entry.name.endsWith(".ts")) {
+ files.push({
+ path: relative(REPO_ROOT, abs).split("\\").join("/"),
+ text: readFileSync(abs, "utf8"),
+ });
+ }
+ }
+ };
+ walk(join(REPO_ROOT, SWEPT_ROOT));
+ return files.toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+}
+
+/**
+ * The top-level arguments of the call whose `(` is at `open`, read off the
+ * `code` view, where a comma or a bracket inside a literal is blanked.
+ */
+function callArguments(code: string, open: number): string[] {
+ const args: string[] = [];
+ let depth = 0;
+ let start = open + 1;
+ for (let i = open; i < code.length; i++) {
+ const ch = code[i];
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
+ else if (ch === ")" || ch === "]" || ch === "}") {
+ depth--;
+ if (depth === 0) {
+ args.push(code.slice(start, i));
+ return args;
+ }
+ } else if (ch === "," && depth === 1) {
+ args.push(code.slice(start, i));
+ start = i + 1;
+ }
+ }
+ return args;
+}
+
+/** The mode a literal argument spells, or null when it is not a literal. */
+function denialMode(arg: string): number | null {
+ const literal = arg.trim();
+ const octal = OCTAL_MODE.exec(literal);
+ if (octal !== null) return Number.parseInt(octal[1]!, 8);
+ if (DECIMAL_MODE.test(literal)) return Number.parseInt(literal, 10);
+ return null;
+}
+
+function isDenial(mode: number): boolean {
+ return (mode & OWNER_READ_WRITE) !== OWNER_READ_WRITE;
+}
+
+function lineAt(text: string, offset: number): number {
+ return text.slice(0, offset).split("\n").length;
+}
+
+/** `path:line 0o…` for every denial chmod in one module. */
+function denialSites(file: SourceFile): string[] {
+ const { code } = lexSource(file.text);
+ const sites: string[] = [];
+ for (const match of code.matchAll(CHMOD_CALL)) {
+ const open = match.index + match[0].length - 1;
+ const mode = denialMode(callArguments(code, open)[1] ?? "");
+ if (mode !== null && isDenial(mode)) {
+ sites.push(
+ `${file.path}:${lineAt(file.text, match.index)} 0o${mode.toString(8).padStart(3, "0")}`,
+ );
+ }
+ }
+ return sites;
+}
+
+function referencesGuard(code: string): boolean {
+ return DENY_GUARDS.some((name) => new RegExp(`\\b${name}\\b`).test(code));
+}
+
+interface CensusResult {
+ /** Denial sites in modules that never reference the guard. */
+ readonly offenders: ReadonlyArray<string>;
+ /** Every module with at least one denial site. */
+ readonly denyingFiles: ReadonlyArray<string>;
+}
+
+function chmodDenyCensus(files: ReadonlyArray<SourceFile>): CensusResult {
+ const offenders: string[] = [];
+ const denyingFiles: string[] = [];
+ for (const file of files) {
+ const sites = denialSites(file);
+ if (sites.length === 0) continue;
+ denyingFiles.push(file.path);
+ if (!referencesGuard(lexSource(file.text).code)) offenders.push(...sites);
+ }
+ return { offenders, denyingFiles };
+}
+
+describe("every chmod-denial test is gated where chmod cannot deny", () => {
+ const census = chmodDenyCensus(readTestTree());
+
+ test("the census actually found the denial fixtures", () => {
+ // A census over an empty set passes for the wrong reason.
+ expect(census.denyingFiles.length).toBeGreaterThan(40);
+ });
+
+ test("no denial fixture sits in a module that never references the guard", () => {
+ expect(census.offenders).toEqual([]);
+ });
+});
+
+/** A synthetic module under the swept root, for the census's own fixtures. */
+function testFile(path: string, text: string): SourceFile {
+ return { path: `tests/${path}`, text };
+}
+
+describe("the chmod-denial census can fail", () => {
+ test.each([
+ ["chmodSync 0o000", `chmodSync(path, 0o000);`],
+ ["chmodSync read-only file", `chmodSync(path, 0o444);`],
+ ["chmodSync read-only directory", `chmodSync(dir, 0o555); // r-x`],
+ ["chmodSync owner r-x", `chmodSync(dir, 0o500);`],
+ ["chmodSync write-execute", `chmodSync(dir, 0o300);`],
+ ["fs.promises.chmod", `await fs.promises.chmod(path, 0o400);`],
+ ["bare chmod", `await chmod(path, 0o200);`],
+ ["decimal mode", `chmodSync(path, 0);`],
+ ])("an unguarded %s is an offender", (_label, line) => {
+ const result = chmodDenyCensus([testFile("new.test.ts", `${line}\n`)]);
+ expect(result.offenders).toEqual([expect.stringMatching(/^tests\/new\.test\.ts:1 0o/)]);
+ });
+
+ test.each([
+ ["a restoring 0o700", `chmodSync(dir, 0o700);`],
+ ["a restoring 0o755", `chmodSync(dir, 0o755);`],
+ ["a restoring 0o600", `chmodSync(path, 0o600);`],
+ ["a group-writable 0o646", `chmodSync(path, 0o646);`],
+ ["a mode passed through a variable", `chmodSync(path, mode);`],
+ ["a mention in a comment", `// chmodSync(path, 0o000) would deny`],
+ ["a mention in a string", `const hint = "chmodSync(path, 0o000)";`],
+ ])("%s is not a denial site", (_label, line) => {
+ expect(chmodDenyCensus([testFile("other.test.ts", `${line}\n`)]).denyingFiles).toEqual([]);
+ });
+
+ test("a module that gates on the guard is cleared", () => {
+ const text = `import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
+test.skipIf(CHMOD_CANNOT_DENY)("unreadable", () => {
+ chmodSync(path, 0o000);
+});
+`;
+ expect(chmodDenyCensus([testFile("gated.test.ts", text)]).offenders).toEqual([]);
+ });
+
+ test("gating on IS_WINDOWS alone does not clear the module", () => {
+ const text = `import { IS_WINDOWS } from "../helpers/platform.ts";
+test.skipIf(IS_WINDOWS)("unreadable", () => {
+ chmodSync(path, 0o000);
+});
+`;
+ expect(chmodDenyCensus([testFile("half.test.ts", text)]).offenders).toEqual([
+ "tests/half.test.ts:3 0o000",
+ ]);
+ });
+
+ test("the guard named only in a comment does not clear the module", () => {
+ const text = `// gated on CHMOD_CANNOT_DENY elsewhere
+chmodSync(path, 0o000);
+`;
+ expect(chmodDenyCensus([testFile("claimed.test.ts", text)]).offenders).toEqual([
+ "tests/claimed.test.ts:2 0o000",
+ ]);
+ });
+});
diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.ts
index 776c03b3..2ede43de 100644
--- a/tests/core/architecture/verdict-vocabulary-census.test.ts
+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts
@@ -414,6 +414,16 @@ import {
NOTE_WRITE_OP,
NOTE_WRITE_OPS,
} from "../../../src/core/brain/notes/write-record.ts";
+import {
+ DISCLOSURE_MODE,
+ DISCLOSURE_MODES,
+ isDisclosureMode,
+} from "../../../src/core/search/disclosure-mode.ts";
+import {
+ FTS_MATCH_MODE,
+ FTS_MATCH_MODES,
+ isFtsMatchMode,
+} from "../../../src/core/search/fts-match-mode.ts";
import { lexCode } from "../../helpers/source-lexer.ts";
import {
TRANSPORT_REACH,
@@ -1298,6 +1308,25 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([
members: NOTE_WRITE_OPS,
guard: isNoteWriteOp,
},
+ {
+ // t_c5326ece. The keyword-lane match breadth a caller selects. The
+ // same list is copied OUT of TypeScript into the brain_search MCP
+ // enum and every refusal message, so a mode added to the object and
+ // missed in the list would be refused by the guard the CLI and the
+ // MCP argument check both call.
+ name: "FTS_MATCH_MODE",
+ values: FTS_MATCH_MODE,
+ members: FTS_MATCH_MODES,
+ guard: isFtsMatchMode,
+ },
+ {
+ // The brain_search result depth. Like the match mode it is copied
+ // out of TypeScript into the MCP enum and both refusal messages.
+ name: "DISCLOSURE_MODE",
+ values: DISCLOSURE_MODE,
+ members: DISCLOSURE_MODES,
+ guard: isDisclosureMode,
+ },
]);
// ---------------------------------------------------------------------------
@@ -1562,7 +1591,7 @@ const SCANNED = scanVocabularies(SOURCE_TREE);
* How many four-piece vocabularies `src/` currently holds. Measured, and
* kept as an equality rather than a floor - see the population test.
*/
-const VOCABULARY_POPULATION = 77;
+const VOCABULARY_POPULATION = 79;
const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));
describe("verdict vocabulary census", () => {
diff --git a/tests/core/brain/capture/telegram-capture.test.ts b/tests/core/brain/capture/telegram-capture.test.ts
index f8a23cca..dd45d757 100644
--- a/tests/core/brain/capture/telegram-capture.test.ts
+++ b/tests/core/brain/capture/telegram-capture.test.ts
@@ -27,6 +27,7 @@ import {
readCatchupWatermark,
} from "../../../../src/core/brain/capture/capture-note.ts";
import { captureDecisionLogPath } from "../../../../src/core/brain/paths.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
const NOW = new Date("2026-07-19T12:00:00Z");
const ALLOW = new Set(["100"]);
@@ -300,3 +301,12 @@ test("every handled update writes exactly one decision to the ledger", () => {
expect(kinds).toEqual(["captured", "rejected-chat"]);
expect(existsSync(captureDecisionLogPath(vault))).toBe(true);
});
+
+test("two capture hosts append to their own decision shards (t_774dea61)", () => {
+ withDeviceId("a", () => handleCaptureUpdate(vault, textUpdate(1, "100", "host a"), baseOpts()));
+ withDeviceId("b", () => handleCaptureUpdate(vault, textUpdate(2, "200", "host b"), baseOpts()));
+ const logDir = join(vault, "Brain", "log");
+ expect(existsSync(join(logDir, "capture-decisions.a.jsonl"))).toBe(true);
+ expect(existsSync(join(logDir, "capture-decisions.b.jsonl"))).toBe(true);
+ expect(existsSync(join(logDir, "capture-decisions.jsonl"))).toBe(false);
+});
diff --git a/tests/core/brain/decisions/receipts.test.ts b/tests/core/brain/decisions/receipts.test.ts
index ed4dd7a8..71ce1b76 100644
--- a/tests/core/brain/decisions/receipts.test.ts
+++ b/tests/core/brain/decisions/receipts.test.ts
@@ -10,7 +10,10 @@ import {
normalizeDecisionSubject,
queryDecisionChangeHistory,
readDecisionChangeReceipts,
+ receiptShardPath,
+ receiptsDir,
} from "../../../../src/core/brain/decisions/receipts.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
let vault: string;
@@ -240,3 +243,12 @@ describe("no receipt on reads", () => {
expect(files.filter((f) => f.startsWith("decision-change")).length).toBe(0);
});
});
+
+test("the receipt shard name is decision-change[.<deviceId>].jsonl, byte for byte", () => {
+ expect(withDeviceId("", () => receiptShardPath(vault))).toBe(
+ join(receiptsDir(vault), "decision-change.jsonl"),
+ );
+ expect(withDeviceId("laptop-01", () => receiptShardPath(vault))).toBe(
+ join(receiptsDir(vault), "decision-change.laptop-01.jsonl"),
+ );
+});
diff --git a/tests/core/brain/doctor-sync-conflict-ledgers.test.ts b/tests/core/brain/doctor-sync-conflict-ledgers.test.ts
index 3a19f391..369e7cc7 100644
--- a/tests/core/brain/doctor-sync-conflict-ledgers.test.ts
+++ b/tests/core/brain/doctor-sync-conflict-ledgers.test.ts
@@ -1,13 +1,13 @@
/**
* `sync-conflict-log` covers every ledger directory (who-wrote-what,
- * Task B / t_1814b9bf).
+ * Task B / t_1814b9bf; extended by t_774dea61).
*
* The per-device shard layout means no reader merges a Syncthing
- * conflict copy - not under `Brain/log/`, and not under any of the five
- * other append-only ledger directories that now shard the same way. One
- * exit, one meaning: "a sync conflict copy exists that no reader
- * merges", with the directory named in the detail so an operator knows
- * where to do the union+dedup merge.
+ * conflict copy - not under `Brain/log/`, not under its audit
+ * subdirectories, and not under any other append-only ledger directory
+ * that now shards the same way. One exit, one meaning: "a sync conflict
+ * copy exists that no reader merges", with the directory named in the
+ * detail so an operator knows where to do the union+dedup merge.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
@@ -15,13 +15,23 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import {
+ HYGIENE_AUDIT_DIR,
+ SECRET_CUSTODY_AUDIT_DIR,
+ SESSION_LIFECYCLE_AUDIT_DIR,
+ WATCHDOG_AUDIT_DIR,
+} from "../../../src/core/brain/audit-dirs.ts";
import { continuityLogDir } from "../../../src/core/brain/continuity/store.ts";
import { runDoctor } from "../../../src/core/brain/doctor.ts";
import { idempotencyLogDir } from "../../../src/core/brain/idempotency-ledger.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { gitStoreDir } from "../../../src/core/brain/git/store.ts";
import { brainStateDirPath } from "../../../src/core/brain/lineage/ledger.ts";
import { metricsDir } from "../../../src/core/brain/metrics.ts";
-import { brainDirs, prefAuditDir } from "../../../src/core/brain/paths.ts";
+import { BRAIN_SKILL_PROPOSALS_REL } from "../../../src/core/brain/path-constants.ts";
+import { brainDirs, hookAuditDir, prefAuditDir } from "../../../src/core/brain/paths.ts";
+import { schemaMutationAuditDir } from "../../../src/core/brain/schema-integrity.ts";
+import { watchdogFallbackAuditDir } from "../../../src/core/brain/watchdog.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
let vault: string;
@@ -64,6 +74,19 @@ describe("sync-conflict sweep across every ledger directory", () => {
["preference audit", prefAuditDir, "pref-alpha"],
["metrics", metricsDir, "index"],
["Brain state", brainStateDirPath, "session-lineage"],
+ [
+ "session-lifecycle audit",
+ (v) => join(brainDirs(v).log, SESSION_LIFECYCLE_AUDIT_DIR),
+ "2026-W24",
+ ],
+ ["hygiene audit", (v) => join(brainDirs(v).log, HYGIENE_AUDIT_DIR), "2026-W24"],
+ ["schema-mutation audit", schemaMutationAuditDir, "2026-W24"],
+ ["secret-custody audit", (v) => join(brainDirs(v).log, SECRET_CUSTODY_AUDIT_DIR), "2026-W24"],
+ ["watchdog audit", (v) => join(brainDirs(v).log, WATCHDOG_AUDIT_DIR), "2026-W24"],
+ ["watchdog audit fallback", watchdogFallbackAuditDir, "2026-W24"],
+ ["hook audit", hookAuditDir, "2026-W24"],
+ ["skill-proposal ledger", (v) => join(v, BRAIN_SKILL_PROPOSALS_REL), "verifier-rejections"],
+ ["preferences", (v) => brainDirs(v).preferences, "pref-alpha.history"],
];
test.each(LEDGERS)("%s: a conflict copy is reported with its directory", (_label, dir, stem) => {
@@ -83,7 +106,7 @@ describe("sync-conflict sweep across every ledger directory", () => {
expect(conflictFindings()).toHaveLength(LEDGERS.length);
});
- test("the six directories are distinct, so no one of them is swept twice", () => {
+ test("the swept directories are distinct, so no one of them is swept twice", () => {
const dirs = LEDGERS.map(([, dir]) => dir(vault));
expect(new Set(dirs).size).toBe(LEDGERS.length);
});
@@ -99,4 +122,54 @@ describe("sync-conflict sweep across every ledger directory", () => {
expect(findings).toHaveLength(1);
expect(findings[0]!.path).toBe(path);
});
+
+ /**
+ * The git store keeps one directory per repository
+ * (`Brain/projects/git/<repo>/`), so the sweep discovers them from the
+ * tree rather than from a fixed list.
+ */
+ test("a conflict copy inside every per-repo git store directory is reported", () => {
+ const planted = ["alpha", "beta"].map((repo) => plant(gitStoreDir(vault, repo), "commits"));
+ const findings = conflictFindings();
+ expect(findings.map((f) => f.path).toSorted()).toEqual(planted.toSorted());
+ });
+
+ /**
+ * Three swept directories also hold files that are not ledgers: the
+ * preference notes, the proposal files at the proposals root and each
+ * repository's state.json. A conflict copy of one of those is still
+ * reported, but never with the row-merge remedy, which is wrong advice
+ * for a note or an atomically replaced JSON file.
+ */
+ const NON_LEDGER: ReadonlyArray<readonly [string, (v: string) => string, string]> = [
+ [
+ "preference note",
+ (v) => brainDirs(v).preferences,
+ "pref-alpha.sync-conflict-20260610-120000-ABCDEFG.md",
+ ],
+ [
+ "proposal file",
+ (v) => join(v, BRAIN_SKILL_PROPOSALS_REL),
+ "proposal-watermark.sync-conflict-20260610-120000-ABCDEFG.json",
+ ],
+ [
+ "git store state",
+ (v) => gitStoreDir(v, "alpha"),
+ "state.sync-conflict-20260610-120000-ABCDEFG.json",
+ ],
+ ];
+
+ test.each(NON_LEDGER)(
+ "%s: a conflict copy is reported without the ledger merge remedy",
+ (_label, dir, name) => {
+ mkdirSync(dir(vault), { recursive: true });
+ const path = join(dir(vault), name);
+ writeFileSync(path, "{}\n", "utf8");
+ const findings = conflictFindings();
+ expect(findings).toHaveLength(1);
+ expect(findings[0]!.path).toBe(path);
+ expect(findings[0]!.message).not.toContain("Merge its rows");
+ expect(findings[0]!.message).toContain("not a ledger shard");
+ },
+ );
});
diff --git a/tests/core/brain/doctor-unreadable-paths.test.ts b/tests/core/brain/doctor-unreadable-paths.test.ts
index 88f36817..a1cc1752 100644
--- a/tests/core/brain/doctor-unreadable-paths.test.ts
+++ b/tests/core/brain/doctor-unreadable-paths.test.ts
@@ -55,7 +55,7 @@ import { resolveNextStep } from "../../../src/core/brain/next-step.ts";
import { brainDirs } from "../../../src/core/brain/paths.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
-import { IS_WINDOWS } from "../../helpers/platform.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
const SKIPPED = DEGRADATION_CODE.vaultWalkEntrySkipped;
@@ -103,9 +103,8 @@ function skipsFor(path: string): ReadonlyArray<DoctorUncertainEntry> {
}
describe("the environment can actually deny a read", () => {
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("a 0o000 directory is unreadable to this runner", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("a 0o000 directory is unreadable to this runner", () => {
const dir = join(tmp, "probe");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -117,17 +116,19 @@ describe("the environment can actually deny a read", () => {
});
describe("the symlink-escape walk", () => {
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("an unreadable directory under Brain/ is named, with the reason", () => {
- const dir = join(brainDirs(vault).inbox, "vaulted");
- mkdirSync(dir, { recursive: true });
- makeUnreadable(dir);
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable directory under Brain/ is named, with the reason",
+ () => {
+ const dir = join(brainDirs(vault).inbox, "vaulted");
+ mkdirSync(dir, { recursive: true });
+ makeUnreadable(dir);
- const entry = skipsFor(dir).find((u) => u.message.includes("symlink"));
- expect(entry).toBeDefined();
- expect(entry!.message).toContain("EACCES");
- });
+ const entry = skipsFor(dir).find((u) => u.message.includes("symlink"));
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain("EACCES");
+ },
+ );
test("it still reports the escaping symlinks it COULD see", () => {
const dir = join(brainDirs(vault).inbox, "vaulted");
@@ -157,9 +158,8 @@ describe("the removed-tool scan", () => {
expect(entry!.message).toContain("ENOTDIR");
});
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("an unreadable skills subdirectory is named", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable skills subdirectory is named", () => {
const dir = join(vault, ".claude", "skills", "private");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -168,23 +168,24 @@ describe("the removed-tool scan", () => {
expect(entry).toBeDefined();
});
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("a Markdown file it cannot open is named rather than skipped", () => {
- const file = join(brainDirs(vault).brain, "notes.md");
- writeFileSync(file, "brain_digest\n", "utf8");
- makeUnreadable(file);
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a Markdown file it cannot open is named rather than skipped",
+ () => {
+ const file = join(brainDirs(vault).brain, "notes.md");
+ writeFileSync(file, "brain_digest\n", "utf8");
+ makeUnreadable(file);
- const entry = uncertain().find((u) => u.path === file && u.message.includes("removed"));
- expect(entry).toBeDefined();
- expect(entry!.message).toContain("EACCES");
- });
+ const entry = uncertain().find((u) => u.path === file && u.message.includes("removed"));
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain("EACCES");
+ },
+ );
});
describe("the orphan-evidence basename sweep", () => {
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable directory makes the basename universe incomplete, and says so",
() => {
const dir = join(vault, "notes");
@@ -236,21 +237,22 @@ describe("the code an [UNSURE] line carries is not itself a dead end", () => {
expect(step!.nextCommand.startsWith("o2b ")).toBe(true);
});
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("the doctor emits exactly that code on an unreadable subtree", () => {
- const dir = join(brainDirs(vault).inbox, "vaulted");
- mkdirSync(dir, { recursive: true });
- makeUnreadable(dir);
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the doctor emits exactly that code on an unreadable subtree",
+ () => {
+ const dir = join(brainDirs(vault).inbox, "vaulted");
+ mkdirSync(dir, { recursive: true });
+ makeUnreadable(dir);
- expect(uncertain().map((u) => u.code)).toContain(SKIPPED);
- });
+ expect(uncertain().map((u) => u.code)).toContain(SKIPPED);
+ },
+ );
});
describe("one unread path is one entry", () => {
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("four sweeps over the same directory report it once", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("four sweeps over the same directory report it once", () => {
const dir = join(brainDirs(vault).inbox, "vaulted");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -260,38 +262,41 @@ describe("one unread path is one entry", () => {
expect(skipsFor(dir).length).toBe(1);
});
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("the surviving entry keeps the most informative consequence", () => {
- const dir = join(brainDirs(vault).inbox, "vaulted");
- mkdirSync(dir, { recursive: true });
- makeUnreadable(dir);
-
- // Of the four clauses written for this path, the basename sweep's is
- // the one that states most about what went unanswered; first-wins
- // would have kept whichever check the registry happens to run first.
- expect(skipsFor(dir)[0]!.message).toContain("basename universe");
- expect(skipsFor(dir)[0]!.message).toContain("EACCES");
- });
-
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)("the stream is capped, so a synced tree cannot flood the payload", () => {
- const parent = brainDirs(vault).inbox;
- for (let i = 0; i < UNCERTAIN_MAX_PER_CODE + 10; i += 1) {
- const dir = join(parent, `locked-${i}`);
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the surviving entry keeps the most informative consequence",
+ () => {
+ const dir = join(brainDirs(vault).inbox, "vaulted");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
- }
- expect(uncertain().filter((u) => u.code === SKIPPED).length).toBe(UNCERTAIN_MAX_PER_CODE);
- });
+ // Of the four clauses written for this path, the basename sweep's is
+ // the one that states most about what went unanswered; first-wins
+ // would have kept whichever check the registry happens to run first.
+ expect(skipsFor(dir)[0]!.message).toContain("basename universe");
+ expect(skipsFor(dir)[0]!.message).toContain("EACCES");
+ },
+ );
+
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the stream is capped, so a synced tree cannot flood the payload",
+ () => {
+ const parent = brainDirs(vault).inbox;
+ for (let i = 0; i < UNCERTAIN_MAX_PER_CODE + 10; i += 1) {
+ const dir = join(parent, `locked-${i}`);
+ mkdirSync(dir, { recursive: true });
+ makeUnreadable(dir);
+ }
+
+ expect(uncertain().filter((u) => u.code === SKIPPED).length).toBe(UNCERTAIN_MAX_PER_CODE);
+ },
+ );
});
describe("a failure on a parent path component", () => {
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable .claude/ does not read as an absent skills directory",
() => {
const claude = join(vault, ".claude");
@@ -321,9 +326,8 @@ describe("a failure on a parent path component", () => {
expect(entry!.message).toMatch(process.platform === "win32" ? /ENOTDIR|ELOOP/ : /ELOOP/);
});
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable vault root is not reported as an un-initialized one",
() => {
makeUnreadable(vault);
@@ -407,9 +411,8 @@ describe("the doctor never dies on an odd path", () => {
expect(runDoctor(vault).trust_verdict).toBeDefined();
});
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable Brain/ still produces findings rather than a throw",
() => {
makeUnreadable(brainDirs(vault).brain);
@@ -423,9 +426,8 @@ describe("the doctor never dies on an odd path", () => {
},
);
- // Windows chmod only toggles the read-only attribute and cannot deny a read
- // (root is not skipped: the 0o000 probe fails loudly for it, by design).
- test.skipIf(IS_WINDOWS)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable Brain/preferences still produces findings rather than a throw",
() => {
const prefs = brainDirs(vault).preferences;
diff --git a/tests/core/brain/doctor/orphan-session-check.test.ts b/tests/core/brain/doctor/orphan-session-check.test.ts
index 6b33533c..047e3ed6 100644
--- a/tests/core/brain/doctor/orphan-session-check.test.ts
+++ b/tests/core/brain/doctor/orphan-session-check.test.ts
@@ -30,7 +30,7 @@ import {
parseSessionRef,
} from "../../../../src/core/brain/doctor/orphan-session-check.ts";
import type { DoctorUncertainEntry } from "../../../../src/core/brain/doctor/report.ts";
-import { IS_WINDOWS } from "../../../helpers/platform.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { brainDirs } from "../../../../src/core/brain/paths.ts";
import { readAllLogRecords } from "../../../../src/core/brain/doctor/records.ts";
@@ -175,7 +175,7 @@ describe("what the walk could not read is uncertainty", () => {
// Windows chmod only toggles the read-only attribute and cannot deny a
// read; the rest of this file passes there vacuously, so only this
// subtree is skipped rather than guarded.
- test.skipIf(IS_WINDOWS)(
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable signals directory reaches the uncertain stream, never silence",
() => {
const dirs = brainDirs(vault);
@@ -191,7 +191,7 @@ describe("what the walk could not read is uncertainty", () => {
},
);
- test.skipIf(IS_WINDOWS)(
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a continuity ledger that cannot be read is uncertainty, not an orphan flood",
() => {
const dirs = brainDirs(vault);
@@ -215,7 +215,7 @@ describe("what the walk could not read is uncertainty", () => {
});
describe("an unreadable log day is uncertainty, not an orphan", () => {
- test.skipIf(IS_WINDOWS)(
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a session whose lifecycle lives in an unreadable day is never flagged",
() => {
const dirs = brainDirs(vault);
diff --git a/tests/core/brain/entities/page-scope.test.ts b/tests/core/brain/entities/page-scope.test.ts
index 33297128..0148acc4 100644
--- a/tests/core/brain/entities/page-scope.test.ts
+++ b/tests/core/brain/entities/page-scope.test.ts
@@ -27,7 +27,7 @@ import {
import { BRAIN_ENTITY_KIND } from "../../../../src/core/brain/entities/types.ts";
import {
IDENTITY_STRENGTH,
- collectRepairCandidates,
+ collectRepairCandidatesWithRefusals,
} from "../../../../src/core/brain/link-graph/repair-lane.ts";
/** A title long enough to clear the repair lane's explicit-reference floor. */
@@ -134,7 +134,7 @@ describe("a quarantined entity page stays out of the link graph", () => {
}
function candidatesNamingTheEntity(): number {
- return collectRepairCandidates(vault).filter(
+ return collectRepairCandidatesWithRefusals(vault).candidates.filter(
(candidate) =>
candidate.strength === IDENTITY_STRENGTH.explicitReference &&
candidate.target.includes("shadowbroker-ledger"),
diff --git a/tests/core/brain/git/store.test.ts b/tests/core/brain/git/store.test.ts
index f032f1f0..aa94d756 100644
--- a/tests/core/brain/git/store.test.ts
+++ b/tests/core/brain/git/store.test.ts
@@ -4,13 +4,23 @@
*/
import { afterEach, beforeEach, expect, test } from "bun:test";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
appendGitRecords,
gitStoreDir,
+ gitStoreRootDir,
listGitCommits,
listGitRepos,
listGitTags,
@@ -18,6 +28,9 @@ import {
writeGitState,
} from "../../../../src/core/brain/git/store.ts";
import type { GitCommitRecord, GitTagRecord } from "../../../../src/core/brain/git/store.ts";
+import { acquireLockSync, LOCK_WAIT_BUDGET_ENV } from "../../../../src/core/brain/sync-lockfile.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let tmp: string;
let vault: string;
@@ -57,6 +70,11 @@ test("gitStoreDir nests under Brain/projects/git/<repo-key>", () => {
expect(gitStoreDir(vault, KEY)).toBe(join(vault, "Brain", "projects", "git", KEY));
});
+test("gitStoreRootDir is Brain/projects/git and the parent of every repo store", () => {
+ expect(gitStoreRootDir(vault)).toBe(join(vault, "Brain", "projects", "git"));
+ expect(gitStoreDir(vault, KEY)).toBe(join(gitStoreRootDir(vault), KEY));
+});
+
test("append + list round-trips commits and tags, oldest-first", () => {
const a = commit("a".repeat(40), { subject: "feat: first" });
const b = commit("b".repeat(40), { subject: "fix: second", files: ["src/b.ts", "docs/x.md"] });
@@ -194,3 +212,119 @@ test("listGitRepos enumerates per-repo stores with their states", () => {
expect(repos[1]!.state!.repoPath).toBe("/work/other");
expect(existsSync(join(vault, "Brain", "projects", "git", KEY, "commits.jsonl"))).toBe(true);
});
+
+test("listGitRepos skips an entry that vanished, a dangling link", () => {
+ appendGitRecords(vault, KEY, [commit("a".repeat(40))]);
+ symlinkSync(join(tmp, "nowhere"), join(gitStoreRootDir(vault), "dangling"));
+ expect(listGitRepos(vault).map((r) => r.key)).toEqual([KEY]);
+});
+
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "listGitRepos surfaces an entry it cannot stat by its error code",
+ () => {
+ appendGitRecords(vault, KEY, [commit("a".repeat(40))]);
+ const root = gitStoreRootDir(vault);
+ // Readable but not searchable: the names list, every stat is refused.
+ chmodSync(root, 0o444);
+ try {
+ expect(() => listGitRepos(vault)).toThrow(/EACCES/);
+ } finally {
+ chmodSync(root, 0o755);
+ }
+ },
+);
+
+test("two devices write their own commits shards and reads merge both (t_774dea61)", () => {
+ const a = commit("c".repeat(40), { subject: "feat: from host a" });
+ const b = commit("d".repeat(40), { subject: "fix: from host b" });
+ withDeviceId("a", () => appendGitRecords(vault, KEY, [a]));
+ withDeviceId("b", () => appendGitRecords(vault, KEY, [b]));
+ const dir = gitStoreDir(vault, KEY);
+ expect(existsSync(join(dir, "commits.a.jsonl"))).toBe(true);
+ expect(existsSync(join(dir, "commits.b.jsonl"))).toBe(true);
+ expect(existsSync(join(dir, "commits.jsonl"))).toBe(false);
+
+ // Cross-device dedup: replaying host a's commit under host b is a no-op
+ // because the dedup read spans every shard.
+ const replay = withDeviceId("b", () => appendGitRecords(vault, KEY, [a]));
+ expect(replay.appended).toBe(0);
+ expect(
+ listGitCommits(vault, KEY)
+ .map((c) => c.subject)
+ .toSorted(),
+ ).toEqual(["feat: from host a", "fix: from host b"]);
+});
+
+test("the append lock is the device's own shard, not the legacy name (t_774dea61)", () => {
+ const dir = gitStoreDir(vault, KEY);
+ mkdirSync(dir, { recursive: true });
+ const previousBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ // Another writer holds the legacy file and device b's shard.
+ const legacy = acquireLockSync(join(dir, "commits.jsonl"));
+ const other = acquireLockSync(join(dir, "commits.b.jsonl"));
+ try {
+ const result = withDeviceId("a", () => appendGitRecords(vault, KEY, [commit("e".repeat(40))]));
+ expect(result.appended).toBe(1);
+
+ const own = acquireLockSync(join(dir, "commits.a.jsonl"));
+ try {
+ expect(() =>
+ withDeviceId("a", () => appendGitRecords(vault, KEY, [commit("f".repeat(40))])),
+ ).toThrow(/lock busy: .*commits\.a\.jsonl\.lock/);
+ } finally {
+ own.release();
+ }
+ } finally {
+ legacy.release();
+ other.release();
+ if (previousBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = previousBudget;
+ }
+});
+
+test("commits from two devices list oldest-first by commit time (t_774dea61)", () => {
+ // Device a ingested the newer range, device b the older one; a sorts
+ // first by shard name, so a name-order merge listed b's old commits last
+ // and a `limit` kept them as the "newest".
+ withDeviceId("a", () =>
+ appendGitRecords(vault, KEY, [
+ commit("1".repeat(40), { subject: "a-new-1", committedAt: "2026-06-03T10:00:00+00:00" }),
+ commit("2".repeat(40), { subject: "a-new-2", committedAt: "2026-06-04T10:00:00+00:00" }),
+ ]),
+ );
+ withDeviceId("b", () =>
+ appendGitRecords(vault, KEY, [
+ commit("3".repeat(40), { subject: "b-old-1", committedAt: "2026-06-01T10:00:00+00:00" }),
+ commit("4".repeat(40), { subject: "b-old-2", committedAt: "2026-06-02T10:00:00+00:00" }),
+ ]),
+ );
+
+ expect(listGitCommits(vault, KEY).map((c) => c.subject)).toEqual([
+ "b-old-1",
+ "b-old-2",
+ "a-new-1",
+ "a-new-2",
+ ]);
+ expect(listGitCommits(vault, KEY, { limit: 1 }).map((c) => c.subject)).toEqual(["a-new-2"]);
+});
+
+test("a commit two devices both ingested before their shards synced lists once (t_774dea61)", () => {
+ // Both devices found the sha absent and wrote it: device b's shard is a
+ // byte copy of device a's, the state a pre-sync race leaves behind.
+ withDeviceId("a", () =>
+ appendGitRecords(vault, KEY, [
+ commit("5".repeat(40), { subject: "both", committedAt: "2026-06-01T10:00:00+00:00" }),
+ commit("6".repeat(40), { subject: "only-a", committedAt: "2026-06-02T10:00:00+00:00" }),
+ ]),
+ );
+ const dir = gitStoreDir(vault, KEY);
+ const firstLine = readFileSync(join(dir, "commits.a.jsonl"), "utf8").split("\n")[0]!;
+ writeFileSync(join(dir, "commits.b.jsonl"), `${firstLine}\n`);
+
+ expect(listGitCommits(vault, KEY).map((c) => c.subject)).toEqual(["both", "only-a"]);
+ expect(listGitCommits(vault, KEY, { limit: 2 }).map((c) => c.subject)).toEqual([
+ "both",
+ "only-a",
+ ]);
+});
diff --git a/tests/core/brain/health/edit-history.test.ts b/tests/core/brain/health/edit-history.test.ts
index 53f73b8c..2b7f66e7 100644
--- a/tests/core/brain/health/edit-history.test.ts
+++ b/tests/core/brain/health/edit-history.test.ts
@@ -9,7 +9,7 @@
*/
import { describe, expect, test, beforeEach, afterEach } from "bun:test";
-import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, rmSync, mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -20,6 +20,7 @@ import {
type EditHistoryEntry,
} from "../../../../src/core/brain/health/edit-history.ts";
import { preferenceHistoryPath } from "../../../../src/core/brain/paths.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
let vault: string;
@@ -110,3 +111,30 @@ describe("renderEditHistory", () => {
expect(renderEditHistory([]).trim().length).toBeGreaterThan(0);
});
});
+
+describe("edit-history per-device shards (t_774dea61)", () => {
+ test("two devices write two shard files and reads merge both, dedupe included", () => {
+ withDeviceId("a", () =>
+ appendEditHistory(vault, "alpha", [entry({ revision: 1, after: "spaces" })]),
+ );
+ withDeviceId("b", () =>
+ appendEditHistory(vault, "alpha", [entry({ revision: 2, after: "tabs again" })]),
+ );
+ // A shard of one device carries no revision 2; a plain read of it
+ // would not dedupe a cross-device replay, so the merged read must
+ // see both files before the dedupe.
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-alpha.history.a.jsonl"))).toBe(
+ true,
+ );
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-alpha.history.b.jsonl"))).toBe(
+ true,
+ );
+
+ const replay = withDeviceId("b", () =>
+ appendEditHistory(vault, "alpha", [entry({ revision: 1, after: "spaces" })]),
+ );
+ expect(replay).toBe(0);
+ const merged = readEditHistory(vault, "alpha");
+ expect(merged.map((e) => e.revision).toSorted()).toEqual([1, 2]);
+ });
+});
diff --git a/tests/core/brain/ingest/ingest.test.ts b/tests/core/brain/ingest/ingest.test.ts
index 0b42450d..ebb50a7e 100644
--- a/tests/core/brain/ingest/ingest.test.ts
+++ b/tests/core/brain/ingest/ingest.test.ts
@@ -19,6 +19,7 @@ import {
upsertEntity,
} from "../../../../src/core/brain/entities/registry.ts";
import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";
+import { manifestPath } from "../../../../src/core/brain/ingest/content-manifest.ts";
import { computePlanId, readCheckpoint } from "../../../../src/core/brain/ingest/checkpoint.ts";
let vault: string;
@@ -52,6 +53,13 @@ function seedSourceFile(rel = INPUT.sourcePath): void {
writeFileSync(abs, "the source bytes\n", "utf8");
}
+/** Write raw bytes as the content manifest, for the corrupted-manifest cases. */
+function writeManifestBytes(bytes: string): void {
+ const path = manifestPath(vault);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, bytes, "utf8");
+}
+
const INPUT = {
sourcePath: "Articles/restaking-primer.md",
summary: "An overview of restaking and its role for validators.",
@@ -180,6 +188,75 @@ describe("ingestSource pre-extract pass (P4, t_ef786747)", () => {
}
});
+ test("a relative import binds to a sibling already in the content manifest", () => {
+ writeCode();
+ mkdirSync(join(vault, "Code"), { recursive: true });
+ writeFileSync(join(vault, "Code", "dom.ts"), "export const h = 1;\n", "utf8");
+ // The sibling lands in the manifest first; the importer's own pass runs
+ // before its own manifest entry is written, so binding needs a prior
+ // ingest of the imported file - exactly the incremental reality.
+ ingestSource(
+ vault,
+ {
+ sourcePath: "Code/dom.ts",
+ summary: "A dom module.",
+ extraction: { entities: [{ category: "concept", name: "Dom" }], relations: [] },
+ },
+ { agent: "claude", now: NOW },
+ );
+ const res = ingestSource(vault, CODE_INPUT, { agent: "claude", now: NOW, preExtract: true });
+ expect(res.preExtract?.extracted).toBe(true);
+ if (res.preExtract?.extracted) {
+ expect(res.preExtract.edges[0]).toEqual({
+ kind: "imports",
+ from: "Code/widget.ts",
+ to: "./dom",
+ resolvedTo: "Code/dom.ts",
+ });
+ }
+ });
+
+ test.each([
+ ["corrupted JSON", "{ not json", /ingest manifest is corrupted JSON/],
+ [
+ "an unsupported schema_version",
+ JSON.stringify({ schema_version: 999, entries: {} }),
+ /ingest manifest schema_version 999 not supported/,
+ ],
+ ])(
+ "a manifest with %s surfaces its own error before anything is written",
+ (_label, bytes, error) => {
+ writeCode();
+ writeManifestBytes(bytes);
+ expect(() =>
+ ingestSource(vault, CODE_INPUT, { agent: "claude", now: NOW, preExtract: true }),
+ ).toThrow(error);
+ // The named manifest error must stop the ingest at the pre-extract read,
+ // not get reported as unreadable source bytes while the page is written.
+ expect(existsSync(join(vault, "Brain", "sources"))).toBe(false);
+ },
+ );
+
+ test("a non-code source never reads the manifest", () => {
+ // Deliberately unseeded, so the ingest itself never reaches the manifest
+ // update either: a corrupted manifest is then visible only to the pass.
+ writeManifestBytes("{ not json");
+ const res = ingestSource(vault, INPUT, { agent: "claude", now: NOW, preExtract: true });
+ expect(res.preExtract?.extracted).toBe(false);
+ if (res.preExtract !== undefined && res.preExtract.extracted === false) {
+ expect(res.preExtract.reason).toContain("unsupported source extension");
+ }
+ });
+
+ test("a code source with no bytes on disk never reads the manifest", () => {
+ writeManifestBytes("{ not json");
+ const res = ingestSource(vault, CODE_INPUT, { agent: "claude", now: NOW, preExtract: true });
+ expect(res.preExtract?.extracted).toBe(false);
+ if (res.preExtract !== undefined && res.preExtract.extracted === false) {
+ expect(res.preExtract.reason).toContain("no readable file bytes");
+ }
+ });
+
test("with the pass off the result carries no seeds and the page is byte-identical", () => {
writeCode();
// First ingest creates the entity + page; a second (idempotent) re-ingest
diff --git a/tests/core/brain/ingest/pre-extract.test.ts b/tests/core/brain/ingest/pre-extract.test.ts
index 2be7d162..3432874f 100644
--- a/tests/core/brain/ingest/pre-extract.test.ts
+++ b/tests/core/brain/ingest/pre-extract.test.ts
@@ -121,3 +121,301 @@ describe("preExtractCodeStructure - unknown languages", () => {
expect(res.edges).toEqual([]);
});
});
+
+describe("preExtractCodeStructure - relative-import binding (t_2356dace)", () => {
+ const INGESTED = new Set([
+ "src/lib/dom.ts",
+ "src/lib/widget.ts",
+ "src/lib/loader.ts",
+ "src/feature/index.ts",
+ "pkg/helpers.py",
+ "pkg/util.py",
+ ]);
+
+ test("a ./ specifier resolving to exactly one ingested file fills resolvedTo", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { h } from "./dom";\n', {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([
+ { kind: "imports", from: "src/lib/widget.ts", to: "./dom", resolvedTo: "src/lib/dom.ts" },
+ ]);
+ });
+
+ test("a ../ specifier binds through extension and index probing", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { f } from "../feature";\n', {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([
+ {
+ kind: "imports",
+ from: "src/lib/widget.ts",
+ to: "../feature",
+ resolvedTo: "src/feature/index.ts",
+ },
+ ]);
+ });
+
+ test("a require of a relative specifier binds the same way", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'const load = require("./loader");\n', {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([
+ {
+ kind: "imports",
+ from: "src/lib/widget.ts",
+ to: "./loader",
+ resolvedTo: "src/lib/loader.ts",
+ },
+ ]);
+ });
+
+ test("a specifier matching no ingested file leaves the seed raw", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { g } from "./ghost";\n', {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([{ kind: "imports", from: "src/lib/widget.ts", to: "./ghost" }]);
+ expect(Object.hasOwn(res.edges[0]!, "resolvedTo")).toBe(false);
+ });
+
+ test("a specifier matching several ingested files leaves the seed raw", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { d } from "./dom";\n', {
+ ingestedFiles: new Set(["src/lib/dom.ts", "src/lib/dom.tsx", "src/lib/dom.js"]),
+ }),
+ );
+ expect(res.edges).toEqual([{ kind: "imports", from: "src/lib/widget.ts", to: "./dom" }]);
+ });
+
+ test("a bare package specifier never binds", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { x } from "react";\n', {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([{ kind: "imports", from: "src/lib/widget.ts", to: "react" }]);
+ });
+
+ test.each([
+ [
+ "a TS/JS specifier",
+ "src/a.ts",
+ 'import { x } from "../../lib/x";\n',
+ "../../lib/x",
+ "lib/x.ts",
+ ],
+ ["a python specifier", "src/a.py", "from ...util import thing\n", "...util", "util.py"],
+ ])("%s climbing above the vault root never binds", (_label, from, source, to, rootFile) => {
+ const res = asSuccess(
+ preExtractCodeStructure(from, source, { ingestedFiles: new Set([rootFile]) }),
+ );
+ expect(res.edges).toEqual([{ kind: "imports", from, to }]);
+ });
+
+ test("a python leading-dot from-import binds to the ingested module file", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("pkg/mod.py", "from .helpers import thing\n", {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([
+ { kind: "imports", from: "pkg/mod.py", to: ".helpers", resolvedTo: "pkg/helpers.py" },
+ ]);
+ });
+
+ test("a python two-dot from-import resolves against the parent directory", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("pkg/sub/mod.py", "from ..util import thing\n", {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ expect(res.edges).toEqual([
+ { kind: "imports", from: "pkg/sub/mod.py", to: "..util", resolvedTo: "pkg/util.py" },
+ ]);
+ });
+
+ test("a python relative import never binds to a TS/JS file of the same name", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("pkg/mod.py", "from .util import thing\n", {
+ ingestedFiles: new Set(["pkg/util.ts"]),
+ }),
+ );
+ expect(res.edges).toEqual([{ kind: "imports", from: "pkg/mod.py", to: ".util" }]);
+ });
+
+ test("a TS/JS relative import never binds to a python file of the same name", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { h } from "./helpers";\n', {
+ ingestedFiles: new Set(["src/lib/helpers.py", "src/lib/helpers/__init__.py"]),
+ }),
+ );
+ expect(res.edges).toEqual([{ kind: "imports", from: "src/lib/widget.ts", to: "./helpers" }]);
+ });
+
+ test("a python relative import binds to a package through its __init__.py", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("pkg/mod.py", "from .sub import thing\n", {
+ ingestedFiles: new Set(["pkg/sub/__init__.py", "pkg/sub/index.py"]),
+ }),
+ );
+ expect(res.edges).toEqual([
+ { kind: "imports", from: "pkg/mod.py", to: ".sub", resolvedTo: "pkg/sub/__init__.py" },
+ ]);
+ });
+
+ test("a python bare-dot import binds to the enclosing package's __init__.py", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("pkg/mod.py", "from . import thing\n", {
+ ingestedFiles: new Set(["pkg/__init__.py", "pkg.py"]),
+ }),
+ );
+ expect(res.edges).toEqual([
+ { kind: "imports", from: "pkg/mod.py", to: ".", resolvedTo: "pkg/__init__.py" },
+ ]);
+ });
+
+ test("a specifier that already carries an extension binds the joined path first", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.tsx", 'import "./widget.css";\n', {
+ ingestedFiles: new Set(["src/lib/widget.css"]),
+ }),
+ );
+ expect(res.edges).toEqual([
+ {
+ kind: "imports",
+ from: "src/lib/widget.tsx",
+ to: "./widget.css",
+ resolvedTo: "src/lib/widget.css",
+ },
+ ]);
+ });
+
+ test("an exact joined-path hit wins over the extension probes", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { v } from "./view.js";\n', {
+ ingestedFiles: new Set(["src/lib/view.js", "src/lib/view.js.ts"]),
+ }),
+ );
+ expect(res.edges).toEqual([
+ {
+ kind: "imports",
+ from: "src/lib/widget.ts",
+ to: "./view.js",
+ resolvedTo: "src/lib/view.js",
+ },
+ ]);
+ });
+
+ test("a call without ingestedFiles leaves every seed byte-identical to today", () => {
+ const withOpt = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { h } from "./dom";\n', {
+ ingestedFiles: INGESTED,
+ }),
+ );
+ const withoutOpt = asSuccess(
+ preExtractCodeStructure("src/lib/widget.ts", 'import { h } from "./dom";\n'),
+ );
+ expect(withoutOpt.edges).toEqual([{ kind: "imports", from: "src/lib/widget.ts", to: "./dom" }]);
+ expect(Object.hasOwn(withoutOpt.edges[0]!, "resolvedTo")).toBe(false);
+ expect(JSON.stringify(withoutOpt)).toBe(
+ JSON.stringify({ ...withOpt, edges: withoutOpt.edges }),
+ );
+ });
+});
+
+describe("preExtractCodeStructure - JSX component usage (t_998aa4e6)", () => {
+ test("a capitalized opening tag in a .tsx source yields a uses edge", () => {
+ const res = asSuccess(
+ preExtractCodeStructure(
+ "src/app/View.tsx",
+ "export function View() {\n return (\n <Widget size={3} />\n );\n}\n",
+ ),
+ );
+ expect(res.edges).toContainEqual({ kind: "uses", from: "src/app/View.tsx", to: "Widget" });
+ });
+
+ test("lowercase-initial DOM and intrinsic tags produce nothing", () => {
+ const res = asSuccess(
+ preExtractCodeStructure(
+ "src/app/View.tsx",
+ "const view = (\n <div><nav><span>hi</span></nav></div>\n);\n",
+ ),
+ );
+ expect(res.edges).toEqual([]);
+ });
+
+ test("member-expression tags produce nothing", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/app/View.tsx", "const view = <Nav.Item active />;\n"),
+ );
+ expect(res.edges).toEqual([]);
+ });
+
+ test("generic type arguments produce nothing", () => {
+ const res = asSuccess(
+ preExtractCodeStructure(
+ "src/app/View.tsx",
+ "const names: Array<Foo> = [];\nconst pair: Pair<Bar, Baz> = pairOf();\n",
+ ),
+ );
+ expect(res.edges).toEqual([]);
+ });
+
+ test.each([
+ ["a trailing-comma arrow generic", "const id = <T,>(x: T) => x;\n"],
+ ["a constrained arrow generic", "const key = <K extends string>(k: K) => k;\n"],
+ ["a generic call after a closing paren", "const v = make()<Foo>(arg);\n"],
+ ["a generic call-signature type alias", "type Fn = <T>(value: T) => T;\n"],
+ ["a generic call-signature annotation", "const id: <U>(x: U) => U = (x) => x;\n"],
+ ])("%s in a .tsx source produces no uses edge", (_label, source) => {
+ const res = asSuccess(preExtractCodeStructure("src/app/View.tsx", source));
+ expect(res.edges).toEqual([]);
+ });
+
+ test.each([
+ ["a bare opening tag", "return <Foo>child</Foo>;\n", "Foo"],
+ ["a self-closing tag with an attribute", "const el = <Foo prop={1} />;\n", "Foo"],
+ [
+ "a tag whose attributes continue on the next line",
+ "return (\n <Foo\n prop={1}\n />\n);\n",
+ "Foo",
+ ],
+ ["a tag opening with a spread attribute", "const el = <Foo {...props} />;\n", "Foo"],
+ ])("%s in a .tsx source still yields its uses edge", (_label, source, name) => {
+ const res = asSuccess(preExtractCodeStructure("src/app/View.tsx", source));
+ expect(res.edges).toEqual([{ kind: "uses", from: "src/app/View.tsx", to: name }]);
+ });
+
+ test("closing tags and fragments produce nothing; a repeated component dedupes", () => {
+ const res = asSuccess(
+ preExtractCodeStructure("src/app/View.tsx", "const view = (<><Widget /><Widget /></>);\n"),
+ );
+ expect(res.edges).toEqual([{ kind: "uses", from: "src/app/View.tsx", to: "Widget" }]);
+ });
+
+ test("a .ts source yields no uses edges even with tag-shaped lines", () => {
+ const res = asSuccess(preExtractCodeStructure("src/app/util.ts", "const el = <Widget />;\n"));
+ expect(res.edges).toEqual([]);
+ });
+
+ test("several components on one line each yield their own edge, sorted", () => {
+ const res = asSuccess(
+ preExtractCodeStructure(
+ "src/app/View.tsx",
+ "const view = <Layout><Header /><Footer /></Layout>;\n",
+ ),
+ );
+ expect(res.edges).toEqual([
+ { kind: "uses", from: "src/app/View.tsx", to: "Footer" },
+ { kind: "uses", from: "src/app/View.tsx", to: "Header" },
+ { kind: "uses", from: "src/app/View.tsx", to: "Layout" },
+ ]);
+ });
+});
diff --git a/tests/core/brain/ledger-shards.test.ts b/tests/core/brain/ledger-shards.test.ts
index c33361ec..d13183ff 100644
--- a/tests/core/brain/ledger-shards.test.ts
+++ b/tests/core/brain/ledger-shards.test.ts
@@ -10,7 +10,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -22,10 +22,12 @@ import {
literalBase,
mergeShardedRows,
parseShardedName,
+ readShardedLines,
resolveAppendShardId,
shardedFileName,
type LedgerShardGrammar,
} from "../../../src/core/brain/ledger-shards.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
const MONTH_GRAMMAR: LedgerShardGrammar = Object.freeze({
base: "\\d{4}-\\d{2}",
@@ -262,3 +264,37 @@ describe("the shard id shape", () => {
expect(LEDGER_SHARD_ID_RE.test("a".repeat(33))).toBe(false);
});
});
+
+describe("readShardedLines", () => {
+ test("merges every shard in name order, legacy file first, skipping blank lines", () => {
+ const shards = join(dir, "lines-x");
+ mkdirSync(shards, { recursive: true });
+ writeFileSync(join(shards, "led.b.jsonl"), '["b1"]\n\n["b2"]\n', "utf8");
+ writeFileSync(join(shards, "led.jsonl"), '["legacy"]\n', "utf8");
+ writeFileSync(join(shards, "led.a.jsonl"), '["a1"]\n', "utf8");
+ // A conflict copy is never a shard.
+ writeFileSync(join(shards, "led.sync-conflict-x.jsonl"), '["conflict"]\n', "utf8");
+
+ const lines = readShardedLines(shards, { base: "led", extensions: ["jsonl"] });
+ expect(lines).toEqual(['["a1"]', '["b1"]', '["b2"]', '["legacy"]']);
+ });
+
+ test("an absent directory lists nothing", () => {
+ expect(
+ readShardedLines(join(dir, "missing-x"), { base: "led", extensions: ["jsonl"] }),
+ ).toEqual([]);
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable directory throws its own error by code", () => {
+ const locked = join(dir, "unreadable-x");
+ mkdirSync(locked, { recursive: true });
+ chmodSync(locked, 0o000);
+ try {
+ expect(() => readShardedLines(locked, { base: "led", extensions: ["jsonl"] })).toThrow(
+ /EACCES/,
+ );
+ } finally {
+ chmodSync(locked, 0o755);
+ }
+ });
+});
diff --git a/tests/core/brain/lineage-ledger-integrity.test.ts b/tests/core/brain/lineage-ledger-integrity.test.ts
index e2d7ac6b..0ed1edd4 100644
--- a/tests/core/brain/lineage-ledger-integrity.test.ts
+++ b/tests/core/brain/lineage-ledger-integrity.test.ts
@@ -45,6 +45,7 @@ import {
} from "../../../src/core/brain/lineage/ledger.ts";
import { verifyLineageLedger } from "../../../src/core/brain/lineage/verify.ts";
import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let tmp: string;
@@ -207,22 +208,24 @@ describe("verifyLineageLedger — reports, never refuses", () => {
expect(verifyLineageLedger(join(tmp, "elsewhere")).exists).toBe(false);
});
- test("an unreadable ledger is reported rather than counted as clean", () => {
- const path = sessionLineageLedgerPath(tmp);
- mkdirSync(dirname(path), { recursive: true });
- writeFileSync(path, `${JSON.stringify({ sid: "s", at: "x", event: "Stop" })}\n`, "utf8");
- chmodSync(path, 0o000);
- try {
- const report = verifyLineageLedger(tmp);
- // Running as root defeats the mode bits; skip rather than assert
- // a permission the environment does not enforce.
- if (report.readable) return;
- expect(report.ok).toBe(false);
- expect(report.notices.some((n) => n.detail.includes("could not be read"))).toBe(true);
- } finally {
- chmodSync(path, 0o644);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable ledger is reported rather than counted as clean",
+ () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, `${JSON.stringify({ sid: "s", at: "x", event: "Stop" })}\n`, "utf8");
+ chmodSync(path, 0o000);
+ try {
+ const report = verifyLineageLedger(tmp);
+ expect(report.readable).toBe(false);
+ expect(report.ok).toBe(false);
+ expect(report.notices.some((n) => n.detail.includes("could not be read"))).toBe(true);
+ } finally {
+ chmodSync(path, 0o644);
+ }
+ },
+ );
test("a line stripped of its chain fields is reported once chained lines exist", () => {
record("s-1", T0);
diff --git a/tests/core/brain/link-graph/alias-index.test.ts b/tests/core/brain/link-graph/alias-index.test.ts
index 5702d8ed..08822ab8 100644
--- a/tests/core/brain/link-graph/alias-index.test.ts
+++ b/tests/core/brain/link-graph/alias-index.test.ts
@@ -1,5 +1,5 @@
/**
- * Unit tests for `buildAliasIndex`. The helper walks Brain
+ * Unit tests for `buildAliasIndex` and `listAliasClaims`. The helper walks Brain
* preferences + retired artifacts, reads their frontmatter
* `aliases:` arrays, and returns a frozen Map keyed by NFC-normalised
* lowercase alias text, valued at the canonical artifact id.
@@ -14,7 +14,10 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { buildAliasIndex } from "../../../../src/core/brain/link-graph/alias-index.ts";
+import {
+ buildAliasIndex,
+ listAliasClaims,
+} from "../../../../src/core/brain/link-graph/alias-index.ts";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
let vault: string;
@@ -234,6 +237,36 @@ describe("buildAliasIndex - collision handling", () => {
});
});
+describe("listAliasClaims", () => {
+ function claimant(topic: string, aliases: string): string {
+ return [
+ "---",
+ "kind: preference",
+ `topic: ${topic}`,
+ "status: confirmed",
+ "principle: x",
+ `aliases: ${aliases}`,
+ "---",
+ ].join("\n");
+ }
+
+ test("keeps every claimant of a colliding alias in the index's order, each once", () => {
+ writePref("pref-bbb", claimant("b", "[shared, Shared]"));
+ writePref("pref-aaa", claimant("a", "[shared]"));
+ writeRetired("ret-ccc", claimant("c", "[shared]"));
+
+ expect(listAliasClaims(vault).get("shared")).toEqual(["pref-aaa", "pref-bbb", "ret-ccc"]);
+ expect(buildAliasIndex(vault).get("shared")).toBe("pref-aaa");
+ });
+
+ test("an alias shadowing an existing canonical id has no claimant", () => {
+ writePref("pref-foo", claimant("foo", "[pref-bar]"));
+ writePref("pref-bar", claimant("bar", "[]"));
+
+ expect(listAliasClaims(vault).has("pref-bar")).toBe(false);
+ });
+});
+
describe("buildAliasIndex - degenerate inputs", () => {
test("empty vault returns empty frozen map", () => {
const idx = buildAliasIndex(vault);
diff --git a/tests/core/brain/link-graph/repair-collect.test.ts b/tests/core/brain/link-graph/repair-collect.test.ts
index 9ab9ecea..6dc3d865 100644
--- a/tests/core/brain/link-graph/repair-collect.test.ts
+++ b/tests/core/brain/link-graph/repair-collect.test.ts
@@ -13,8 +13,9 @@ import { tmpdir } from "node:os";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { appendContinuityRecord } from "../../../../src/core/brain/continuity/store.ts";
import {
+ EXPLICIT_REFERENCE_CONFIDENCE,
IDENTITY_STRENGTH,
- collectRepairCandidates,
+ collectRepairCandidatesWithRefusals,
} from "../../../../src/core/brain/link-graph/repair-lane.ts";
let vault: string;
@@ -29,6 +30,27 @@ afterEach(() => {
rmSync(vault, { recursive: true, force: true });
});
+function writePref(rel: string, body: string): void {
+ const abs = join(vault, "Brain", "preferences", rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, body, "utf8");
+}
+
+/** Preference frontmatter declaring one shared alias, for collision cases. */
+function aliasedPref(topic: string): string {
+ return [
+ "---",
+ "kind: preference",
+ `topic: ${topic}`,
+ "status: confirmed",
+ "principle: shared alias",
+ "aliases: [downstream]",
+ "---",
+ "",
+ "Body.",
+ ].join("\n");
+}
+
function writeNote(rel: string, title: string, body: string): void {
const abs = join(vault, rel);
mkdirSync(join(abs, ".."), { recursive: true });
@@ -39,12 +61,12 @@ function writeNote(rel: string, title: string, body: string): void {
);
}
-describe("collectRepairCandidates explicit references", () => {
+describe("collectRepairCandidatesWithRefusals explicit references", () => {
test("a note that names another note's title without linking it yields an explicit candidate", () => {
writeNote("Notes/alpha.md", "Alpha", "This note discusses Beta in depth.");
writeNote("Notes/beta.md", "Beta", "standalone");
- const candidates = collectRepairCandidates(vault);
+ const { candidates } = collectRepairCandidatesWithRefusals(vault);
const explicit = candidates.find(
(c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.target.includes("beta"),
);
@@ -58,7 +80,7 @@ describe("collectRepairCandidates explicit references", () => {
writeNote("Notes/essay.md", "Essay", "This whole essay is about AI and its many uses.");
writeNote("Notes/ai.md", "AI", "standalone");
- const candidates = collectRepairCandidates(vault);
+ const { candidates } = collectRepairCandidatesWithRefusals(vault);
expect(
candidates.some(
(c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.target.includes("ai"),
@@ -70,14 +92,14 @@ describe("collectRepairCandidates explicit references", () => {
writeNote("Notes/alpha.md", "Alpha", "See [[Notes/beta.md]] and Beta again.");
writeNote("Notes/beta.md", "Beta", "standalone");
- const candidates = collectRepairCandidates(vault);
+ const { candidates } = collectRepairCandidatesWithRefusals(vault);
expect(candidates.some((c) => c.source.includes("alpha") && c.target.includes("beta"))).toBe(
false,
);
});
});
-describe("collectRepairCandidates session continuity", () => {
+describe("collectRepairCandidatesWithRefusals session continuity", () => {
test("two notes co-referenced in one session event yield a continuity candidate", () => {
writeNote("Notes/gamma.md", "Gamma", "standalone");
writeNote("Notes/delta.md", "Delta", "standalone");
@@ -91,7 +113,7 @@ describe("collectRepairCandidates session continuity", () => {
payload: { host: "test" },
});
- const candidates = collectRepairCandidates(vault);
+ const { candidates } = collectRepairCandidatesWithRefusals(vault);
const continuity = candidates.find((c) => c.strength === IDENTITY_STRENGTH.sessionContinuity);
expect(continuity).toBeDefined();
expect(
@@ -101,3 +123,111 @@ describe("collectRepairCandidates session continuity", () => {
).toBe(true);
});
});
+
+describe("collectRepairCandidatesWithRefusals - corpus-wide unique-match binding", () => {
+ test("a title carried by two pages refuses the mention instead of binding to both", () => {
+ writeNote("Notes/one.md", "Alpha", "Platform notes");
+ writeNote("Notes/two.md", "Alpha", "More platform notes");
+ writeNote("Notes/three.md", "Reader", "Reads Alpha every day.");
+
+ const { candidates, refusals } = collectRepairCandidatesWithRefusals(vault);
+ const bound = candidates.filter(
+ (c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.source.includes("three"),
+ );
+ expect(bound).toEqual([]);
+ expect(refusals.map((r) => [r.source, r.target, r.action])).toEqual([
+ [expect.stringContaining("three"), expect.stringContaining("one"), "skip-ambiguous"],
+ [expect.stringContaining("three"), expect.stringContaining("two"), "skip-ambiguous"],
+ ]);
+ expect(refusals.every((r) => r.reason.includes("Alpha"))).toBe(true);
+ });
+
+ test("a carrier mentioning its own ambiguous title is a self-reference, not a refusal", () => {
+ // The unique path reads a page naming its own title as self-reference;
+ // the ambiguous path must not turn the same mention into refusals
+ // pointing at the other carriers.
+ writeNote("Notes/one.md", "Alpha", "Alpha is also documented elsewhere.");
+ writeNote("Notes/two.md", "Alpha", "standalone");
+
+ const { candidates, refusals } = collectRepairCandidatesWithRefusals(vault);
+ expect(candidates).toEqual([]);
+ expect(refusals).toEqual([]);
+ });
+
+ test("a page already linking one carrier of an ambiguous term is not refused", () => {
+ // The unique path never re-proposes an edge the page already has; the
+ // ambiguous path must not refuse a mention the author already resolved.
+ writeNote("Notes/one.md", "Alpha", "Platform notes");
+ writeNote("Notes/two.md", "Alpha", "More platform notes");
+ writeNote("Notes/three.md", "Reader", "Reads Alpha, see [[Notes/one.md]].");
+
+ const { refusals } = collectRepairCandidatesWithRefusals(vault);
+ expect(refusals.filter((r) => r.source.includes("three"))).toEqual([]);
+ });
+
+ test("a uniquely carried title still binds exactly one page", () => {
+ writeNote("Notes/one.md", "Alpha", "standalone");
+ writeNote("Notes/two.md", "Beta", "Mentions Alpha once.");
+
+ const { candidates, refusals } = collectRepairCandidatesWithRefusals(vault);
+ const bound = candidates.find(
+ (c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.source.includes("two"),
+ );
+ expect(bound).toBeDefined();
+ expect(bound!.target).toContain("one");
+ expect(bound!.confidence).toBe(EXPLICIT_REFERENCE_CONFIDENCE);
+ expect(refusals).toEqual([]);
+ });
+
+ test("an alias mention proposes the same explicit candidate a title mention would", () => {
+ writePref("pref-second-order.md", aliasedPref("second-order"));
+ writeNote("Notes/report.md", "Quarterly", "We follow the downstream effect.");
+
+ const { candidates, refusals } = collectRepairCandidatesWithRefusals(vault);
+ const bound = candidates.find(
+ (c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.source.includes("report"),
+ );
+ expect(bound).toBeDefined();
+ expect(bound!.target).toContain("pref-second-order");
+ expect(bound!.confidence).toBe(EXPLICIT_REFERENCE_CONFIDENCE);
+ expect(bound!.reason).toContain("downstream");
+ expect(refusals).toEqual([]);
+ });
+
+ test("an alias claimed by two pages refuses the mention instead of binding to one", () => {
+ writePref("pref-left.md", aliasedPref("left"));
+ writePref("pref-right.md", aliasedPref("right"));
+ writeNote("Notes/report.md", "Quarterly", "We follow the downstream effect.");
+
+ const { candidates, refusals } = collectRepairCandidatesWithRefusals(vault);
+ const bound = candidates.filter(
+ (c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.source.includes("report"),
+ );
+ expect(bound).toEqual([]);
+ expect(refusals.map((r) => [r.source, r.target, r.action])).toEqual([
+ [expect.stringContaining("report"), expect.stringContaining("pref-left"), "skip-ambiguous"],
+ [expect.stringContaining("report"), expect.stringContaining("pref-right"), "skip-ambiguous"],
+ ]);
+ expect(refusals.every((r) => r.reason.includes("downstream"))).toBe(true);
+ });
+
+ test("an alias colliding with a page title refuses the mention", () => {
+ writePref("pref-second-order.md", aliasedPref("second-order"));
+ writeNote("Notes/glossary.md", "Downstream", "The downstream page collects the effects.");
+ writeNote("Notes/report.md", "Quarterly", "We follow the downstream effect.");
+
+ const { candidates, refusals } = collectRepairCandidatesWithRefusals(vault);
+ const bound = candidates.filter(
+ (c) => c.strength === IDENTITY_STRENGTH.explicitReference && c.source.includes("report"),
+ );
+ expect(bound).toEqual([]);
+ // The glossary page naming its own title is a self-reference, so only
+ // the report's (mentioning page, carrying page) pairs are refused.
+ expect(refusals.every((r) => r.action === "skip-ambiguous")).toBe(true);
+ expect(refusals.every((r) => r.reason.includes("Downstream"))).toBe(true);
+ expect(refusals.map((r) => [r.source, r.target])).toEqual([
+ [expect.stringContaining("report"), expect.stringContaining("pref-second-order")],
+ [expect.stringContaining("report"), expect.stringContaining("glossary")],
+ ]);
+ });
+});
diff --git a/tests/core/brain/link-graph/repair-lane.test.ts b/tests/core/brain/link-graph/repair-lane.test.ts
index c2d160f7..eb096750 100644
--- a/tests/core/brain/link-graph/repair-lane.test.ts
+++ b/tests/core/brain/link-graph/repair-lane.test.ts
@@ -21,6 +21,7 @@ import {
RepairConfirmationError,
runRepairLane,
type RepairCandidate,
+ type RepairDecision,
} from "../../../../src/core/brain/link-graph/repair-lane.ts";
let vault: string;
@@ -191,3 +192,46 @@ describe("runRepairLane dry-run vs apply", () => {
expect(second.decisions[0]!.action).toBe("skip-existing");
});
});
+
+describe("runRepairLane collected refusals", () => {
+ test("refusals are reported verbatim, never re-decided, never counted as writes", () => {
+ writeNote("Notes/a.md", "A", "body");
+ writeNote("Notes/b.md", "B", "body");
+ const refusal: RepairDecision = {
+ ...candidate({ source: "Notes/src.md", target: "Notes/x.md", reason: "ambiguous: Alpha" }),
+ action: "skip-ambiguous",
+ };
+ const report = runRepairLane(vault, [candidate({})], { collectedRefusals: [refusal] });
+ expect(report.decisions[0]).toEqual(refusal);
+ expect(report.written).toBe(1);
+ expect(report.decisions.filter((d) => d.action === "skip-ambiguous")).toHaveLength(1);
+ });
+
+ test("refusals do not consume the write cap", () => {
+ writeNote("Notes/a.md", "A", "body");
+ writeNote("Notes/b.md", "B", "body");
+ const refusal: RepairDecision = {
+ ...candidate({ source: "Notes/src.md", target: "Notes/x.md", reason: "ambiguous: Alpha" }),
+ action: "skip-ambiguous",
+ };
+ const report = runRepairLane(vault, [candidate({})], {
+ writeCap: 1,
+ collectedRefusals: [refusal],
+ });
+ expect(report.written).toBe(1);
+ });
+
+ test("refusals are ordered by the candidate order, deterministically", () => {
+ const second: RepairDecision = {
+ ...candidate({ source: "Notes/z.md", target: "Notes/x.md", reason: "ambiguous: Alpha" }),
+ action: "skip-ambiguous",
+ };
+ const first: RepairDecision = {
+ ...candidate({ source: "Notes/a.md", target: "Notes/x.md", reason: "ambiguous: Alpha" }),
+ action: "skip-ambiguous",
+ };
+ const report = runRepairLane(vault, [], { collectedRefusals: [second, first] });
+ expect(report.decisions.map((d) => d.source)).toEqual(["Notes/a.md", "Notes/z.md"]);
+ expect(report.written).toBe(0);
+ });
+});
diff --git a/tests/core/brain/maintenance/maintenance.test.ts b/tests/core/brain/maintenance/maintenance.test.ts
index 09586387..ffd63714 100644
--- a/tests/core/brain/maintenance/maintenance.test.ts
+++ b/tests/core/brain/maintenance/maintenance.test.ts
@@ -7,7 +7,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { appendFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, existsSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -44,6 +44,7 @@ import {
} from "../../../../src/core/brain/recall-telemetry.ts";
import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
const NOW = new Date("2026-06-05T03:30:00Z");
@@ -498,3 +499,70 @@ describe("the consecutive-failure streak", () => {
expect(consecutiveTaskFailures(vault, TASK)).toBe(0);
});
});
+
+describe("maintenance journal per-device shards (t_774dea61)", () => {
+ test("two devices write their own shards; lists merge and the sweep trims only the local shard", () => {
+ appendAs("a", "2026-06-01T10:00:00Z", false);
+ appendAs("b", "2026-06-01T10:01:00Z", true);
+ const derived = join(vault, ".open-second-brain");
+ expect(existsSync(join(derived, "maintenance-runs.a.jsonl"))).toBe(true);
+ expect(existsSync(join(derived, "maintenance-runs.b.jsonl"))).toBe(true);
+ expect(existsSync(join(derived, "maintenance-runs.jsonl"))).toBe(false);
+
+ expect(listJournal(vault)).toHaveLength(2);
+
+ // The cap sweep rewrites only the local device's shard: host b's
+ // shard is trimmed to the cap, host a's rows stay on disk.
+ withDeviceId("b", () => sweepJournal(vault, 1));
+ expect(listJournal(vault)).toHaveLength(2);
+ const bShard = readFileSync(join(derived, "maintenance-runs.b.jsonl"), "utf8")
+ .trim()
+ .split("\n");
+ expect(bShard).toHaveLength(1);
+ expect(readFileSync(join(derived, "maintenance-runs.a.jsonl"), "utf8").trim()).toContain(
+ "host-a",
+ );
+ });
+});
+
+function appendAs(device: string, ts: string, ok: boolean): void {
+ withDeviceId(device, () =>
+ appendJournal(vault, {
+ ts,
+ holder: `host-${device}`,
+ verdict: MAINTENANCE_VERDICT.run,
+ task: LANE_TASK.dream,
+ ok,
+ }),
+ );
+}
+
+describe("maintenance journal merged order across devices (t_774dea61)", () => {
+ test("the merged list is newest-first by timestamp, and the streak walks that order", () => {
+ // Device a's newest failure is newer than device b's success, but a's
+ // shard sorts first by name: a name-order merge put b's success on top
+ // and read the live streak as zero.
+ appendAs("a", "2026-06-01T10:00:00.000Z", false);
+ appendAs("a", "2026-06-01T10:04:00.000Z", false);
+ appendAs("b", "2026-06-01T10:02:00.000Z", true);
+
+ expect(listJournal(vault).map((entry) => entry.ts)).toEqual([
+ "2026-06-01T10:04:00.000Z",
+ "2026-06-01T10:02:00.000Z",
+ "2026-06-01T10:00:00.000Z",
+ ]);
+ expect(consecutiveTaskFailures(vault, LANE_TASK.dream)).toBe(1);
+ });
+
+ test("one shard keeps its own file order even when its timestamps are not monotonic", () => {
+ appendAs("a", "2026-06-01T10:05:00.000Z", true);
+ // A clock stepped back: the row appended later carries the older stamp.
+ appendAs("a", "2026-06-01T10:01:00.000Z", false);
+
+ expect(listJournal(vault).map((entry) => entry.ts)).toEqual([
+ "2026-06-01T10:01:00.000Z",
+ "2026-06-01T10:05:00.000Z",
+ ]);
+ expect(consecutiveTaskFailures(vault, LANE_TASK.dream)).toBe(1);
+ });
+});
diff --git a/tests/core/brain/query-demand.test.ts b/tests/core/brain/query-demand.test.ts
index 5df85a30..25af13bd 100644
--- a/tests/core/brain/query-demand.test.ts
+++ b/tests/core/brain/query-demand.test.ts
@@ -1,5 +1,13 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -14,6 +22,7 @@ import {
recordQueryDemand,
} from "../../../src/core/brain/query-demand.ts";
import { fakeCredential } from "../../helpers/fake-credentials.ts";
+import { withDeviceId } from "../../helpers/device-id.ts";
const SECRET_SHAPED_TERM = fakeCredential("sk-", "abcdef0123456789abcdef0123456789");
@@ -288,3 +297,51 @@ describe("rolling cap", () => {
expect(records.every((r) => r.terms.join(" ") === bucketKey)).toBe(true);
});
});
+
+describe("query-demand per-device shards (t_774dea61)", () => {
+ const INPUT = {
+ query: "how does the auth flow work",
+ at: "2026-07-01T00:00:00.000Z",
+ resultCount: 3,
+ };
+
+ test("two devices write two shard files and reads merge both", () => {
+ withDeviceId("a", () => recordQueryDemand(vault, INPUT));
+ withDeviceId("b", () => recordQueryDemand(vault, INPUT));
+ expect(existsSync(join(vault, "Brain", "log", "query-demand.a.jsonl"))).toBe(true);
+ expect(existsSync(join(vault, "Brain", "log", "query-demand.b.jsonl"))).toBe(true);
+ expect(existsSync(join(vault, "Brain", "log", "query-demand.jsonl"))).toBe(false);
+
+ const records = readQueryDemand(vault);
+ expect(records).toHaveLength(2);
+ });
+
+ test("the empty device id keeps the legacy un-sharded file", () => {
+ withDeviceId("", () => recordQueryDemand(vault, INPUT));
+ expect(existsSync(join(vault, "Brain", "log", "query-demand.jsonl"))).toBe(true);
+ expect(readQueryDemand(vault)).toHaveLength(1);
+ });
+
+ test("compaction after a write on one device caps only that device's shard", () => {
+ const logDir = join(vault, "Brain", "log");
+ mkdirSync(logDir, { recursive: true });
+ const line =
+ JSON.stringify({ ts: INPUT.at, terms: ["auth", "flow"], results: 3, coverage: 0.5 }) + "\n";
+ // Both shards already sit over the byte budget. Only the shard the
+ // write lands on may be rewritten; the peer's file is not this
+ // device's to touch, however large it is.
+ const overBudget = line.repeat(Math.ceil(DEMAND_LOG_MAX_BYTES / line.length) + 1);
+ const ownShard = join(logDir, "query-demand.a.jsonl");
+ const peerShard = join(logDir, "query-demand.b.jsonl");
+ writeFileSync(ownShard, overBudget, "utf8");
+ writeFileSync(peerShard, overBudget, "utf8");
+
+ withDeviceId("a", () => {
+ expect(queryDemandLogPath(vault)).toBe(ownShard);
+ recordQueryDemand(vault, INPUT);
+ });
+
+ expect(statSync(ownShard).size).toBeLessThanOrEqual(DEMAND_LOG_MAX_BYTES);
+ expect(readFileSync(peerShard, "utf8")).toBe(overBudget);
+ });
+});
diff --git a/tests/core/brain/recurrence.test.ts b/tests/core/brain/recurrence.test.ts
index 15fb0b59..b41974b4 100644
--- a/tests/core/brain/recurrence.test.ts
+++ b/tests/core/brain/recurrence.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -9,6 +9,7 @@ import {
listRecurrenceEntries,
purgeRecurrenceSource,
} from "../../../src/core/brain/recurrence.ts";
+import { withDeviceId } from "../../helpers/device-id.ts";
let vault: string;
@@ -111,3 +112,51 @@ describe("recurrence support ledger", () => {
expect(entry).toBeNull();
});
});
+
+describe("recurrence-support per-device shards (t_774dea61)", () => {
+ test("two devices write two shard files and the reader merges both", () => {
+ withDeviceId("a", () =>
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-shared",
+ scope: "project-a",
+ sourceId: "src-a",
+ action: "learn",
+ at: "2026-06-01T10:00:00Z",
+ }),
+ );
+ withDeviceId("b", () =>
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h-shared",
+ scope: "project-b",
+ sourceId: "src-b",
+ action: "learn",
+ at: "2026-06-01T10:01:00Z",
+ }),
+ );
+ expect(existsSync(join(vault, "Brain", "log", "recurrence-support.a.jsonl"))).toBe(true);
+ expect(existsSync(join(vault, "Brain", "log", "recurrence-support.b.jsonl"))).toBe(true);
+ expect(existsSync(join(vault, "Brain", "log", "recurrence-support.jsonl"))).toBe(false);
+
+ const entry = getRecurrenceEntry(vault, "h-shared");
+ expect(entry).not.toBeNull();
+ expect(entry!.supportCount).toBe(2);
+ });
+
+ test("a purge on one device removes support learned earlier on another, whatever the shard names", () => {
+ // Device b learns from src-shared first; device a purges it a day
+ // later. Shard `.a` sorts before `.b`, so a name-order replay ran the
+ // purge before the learn and brought the purged source back.
+ withDeviceId("b", () =>
+ applyRecurrenceEvidence(vault, {
+ contentHash: "h1",
+ scope: "project-a",
+ sourceId: "src-shared",
+ action: "learn",
+ at: "2026-09-01T10:00:00Z",
+ }),
+ );
+ withDeviceId("a", () => purgeRecurrenceSource(vault, "src-shared", "2026-09-02T10:00:00Z"));
+
+ expect(listRecurrenceEntries(vault)).toEqual([]);
+ });
+});
diff --git a/tests/core/brain/runtime-notices.test.ts b/tests/core/brain/runtime-notices.test.ts
index bd7e3b50..8c78daa2 100644
--- a/tests/core/brain/runtime-notices.test.ts
+++ b/tests/core/brain/runtime-notices.test.ts
@@ -10,6 +10,7 @@ import {
renderRuntimeNotices,
} from "../../../src/core/brain/runtime-notices.ts";
import { writeVaultIdentity } from "../../../src/core/brain/vault-identity.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
let configPath: string;
@@ -70,25 +71,13 @@ test("a missing search index yields an index notice", () => {
expect(notices.map((n) => n.code)).toContain("search_index_missing");
});
-test("a read-only vault yields a read-only notice", () => {
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)("a read-only vault yields a read-only notice", () => {
writeConfig("");
seedIndex();
chmodSync(vault, 0o500);
const notices = collectRuntimeNotices(vault, { configPath, env: {} });
- // Skip the assertion if the platform/user still permits the write probe
- // (e.g. running as root ignores mode bits); the notice is best-effort.
- const probe = join(vault, ".probe-write-check");
- let writable = false;
- try {
- writeFileSync(probe, "x");
- rmSync(probe);
- writable = true;
- } catch {
- /* not writable, as intended */
- }
- if (!writable) {
- expect(notices.map((n) => n.code)).toContain("vault_read_only");
- }
+ expect(notices.map((n) => n.code)).toContain("vault_read_only");
});
test("the opt-out env suppresses all notices", () => {
diff --git a/tests/core/brain/schema-integrity.test.ts b/tests/core/brain/schema-integrity.test.ts
index 5eb31d00..3d314789 100644
--- a/tests/core/brain/schema-integrity.test.ts
+++ b/tests/core/brain/schema-integrity.test.ts
@@ -241,6 +241,69 @@ describe("assessSchemaPackIntegrity", () => {
expect(assessSchemaPackIntegrity(vault).status).toBe(SCHEMA_PACK_INTEGRITY.ok);
});
+ test("device shards merge and the newest apply still wins (t_774dea61)", async () => {
+ await seal();
+ const shard = soleShardPath();
+ const sealed = JSON.parse(readFileSync(shard, "utf8").trim()) as {
+ timestamp: string;
+ details: Record<string, unknown>;
+ };
+ const stale = {
+ ...sealed,
+ timestamp: "2020-01-01T00:00:00.000Z",
+ details: { ...sealed.details, [SCHEMA_PACK_DIGEST_FIELD]: "deadbeef" },
+ };
+ // Another device's shard carries an older apply; sorting by name alone
+ // would let the stale record win once the local file sorts later.
+ writeFileSync(shard.replace(".jsonl", ".other.jsonl"), JSON.stringify(stale) + "\n", "utf8");
+
+ const recorded = readRecordedSchemaPackDigest(vault);
+
+ expect(recorded.found).toBe(true);
+ expect(recorded.found && recorded.recorded_at).toBe(sealed.timestamp);
+ expect(assessSchemaPackIntegrity(vault).status).toBe(SCHEMA_PACK_INTEGRITY.ok);
+ });
+
+ test("another device's newer apply in its own shard wins over the local one (t_774dea61)", async () => {
+ await seal();
+ const shard = soleShardPath();
+ const sealed = JSON.parse(readFileSync(shard, "utf8").trim()) as {
+ timestamp: string;
+ details: Record<string, unknown>;
+ };
+ const newer = {
+ ...sealed,
+ timestamp: "2099-01-01T00:00:00.000Z",
+ details: { ...sealed.details, [SCHEMA_PACK_DIGEST_FIELD]: "deadbeef" },
+ };
+ // A reader that looked only at this device's shard would still see the
+ // local apply and report ok; the merged read must pick the peer's.
+ writeFileSync(shard.replace(".jsonl", ".other.jsonl"), JSON.stringify(newer) + "\n", "utf8");
+
+ const recorded = readRecordedSchemaPackDigest(vault);
+
+ expect(recorded.found).toBe(true);
+ expect(recorded.found && recorded.recorded_at).toBe(newer.timestamp);
+ expect(assessSchemaPackIntegrity(vault).status).not.toBe(SCHEMA_PACK_INTEGRITY.ok);
+ });
+
+ test("a sync-conflict copy of an audit week is never parsed as a shard", async () => {
+ await seal();
+ const shard = soleShardPath();
+ // An unreadable copy: if the reader treated conflict copies as shards,
+ // this would flip the whole read to audit-unreadable.
+ writeFileSync(
+ shard.replace(".jsonl", ".sync-conflict-20260930-armadillo.jsonl"),
+ "{ torn\n",
+ "utf8",
+ );
+
+ const recorded = readRecordedSchemaPackDigest(vault);
+
+ expect(recorded.found).toBe(true);
+ expect(assessSchemaPackIntegrity(vault).status).toBe(SCHEMA_PACK_INTEGRITY.ok);
+ });
+
test("a deleted config file is unverified with the config-absent reason", async () => {
await seal();
rmSync(configPath());
diff --git a/tests/core/brain/skill-proposals.test.ts b/tests/core/brain/skill-proposals.test.ts
index 4033547a..7d968b0a 100644
--- a/tests/core/brain/skill-proposals.test.ts
+++ b/tests/core/brain/skill-proposals.test.ts
@@ -14,10 +14,12 @@ import {
acceptSkillProposal,
draftDeclaredSkillProposal,
learnSkillProposals,
+ verifierRejectionLedgerPath,
listPendingSkillProposals,
previewDeclaredSkillProposal,
rejectSkillProposal,
} from "../../../src/core/brain/skill-proposals.ts";
+import { withDeviceId } from "../../helpers/device-id.ts";
let vault: string;
@@ -343,3 +345,14 @@ describe("a declared proposal refuses a taken slug by name", () => {
expect(previewDeclaredSkillProposal(vault, declaration).outcome).toBe("suppressed");
});
});
+
+describe("verifier-rejection ledger shards (t_774dea61)", () => {
+ test("each device names its own rejection shard; the empty id keeps the legacy name", () => {
+ const onA = withDeviceId("a", () => verifierRejectionLedgerPath(vault));
+ const onB = withDeviceId("b", () => verifierRejectionLedgerPath(vault));
+ const legacy = withDeviceId("", () => verifierRejectionLedgerPath(vault));
+ expect(onA.endsWith("verifier-rejections.a.jsonl")).toBe(true);
+ expect(onB.endsWith("verifier-rejections.b.jsonl")).toBe(true);
+ expect(legacy.endsWith("verifier-rejections.jsonl")).toBe(true);
+ });
+});
diff --git a/tests/core/brain/temporal/stale-watch.test.ts b/tests/core/brain/temporal/stale-watch.test.ts
index 6139a089..61d0ec3e 100644
--- a/tests/core/brain/temporal/stale-watch.test.ts
+++ b/tests/core/brain/temporal/stale-watch.test.ts
@@ -15,7 +15,7 @@ import { join } from "node:path";
import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";
import { findStaleEntries } from "../../../../src/core/brain/temporal/stale-watch.ts";
import { BRAIN_TEMPORAL_DEFAULTS } from "../../../../src/core/brain/policy.ts";
-import { IS_WINDOWS } from "../../../helpers/platform.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
import { tempDirs } from "../../../helpers/temp-dir.ts";
const mkTemp = tempDirs();
@@ -111,9 +111,10 @@ describe("findStaleEntries", () => {
expect(out.staleLogFiles[0]!.path).toContain("2025-08-01.jsonl");
});
- // Windows has no directory execute bit for chmod to drop, so the
- // readable-but-unstattable entry cannot be built there.
- test.skipIf(IS_WINDOWS)(
+ // Windows has no directory execute bit for chmod to drop, and root
+ // stats through any mode, so the readable-but-unstattable entry cannot
+ // be built on either (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unstattable log file fails the scan by name rather than vanishing",
() => {
// Read without execute on the log directory: `readdir` still
@@ -128,13 +129,9 @@ describe("findStaleEntries", () => {
const idx = buildTimelineIndex(VAULT, {});
chmodSync(logDir, 0o400);
try {
- // Root ignores the mode bits; only assert the refusal where the
- // construction actually bites.
- if (process.getuid?.() !== 0) {
- expect(() => findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, { now: NOW })).toThrow(
- /findStaleEntries: cannot read the mtime of log file .*d\.jsonl/,
- );
- }
+ expect(() => findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, { now: NOW })).toThrow(
+ /findStaleEntries: cannot read the mtime of log file .*d\.jsonl/,
+ );
} finally {
chmodSync(logDir, 0o700);
}
diff --git a/tests/core/brain/time.test.ts b/tests/core/brain/time.test.ts
index ee8274db..7517b3c4 100644
--- a/tests/core/brain/time.test.ts
+++ b/tests/core/brain/time.test.ts
@@ -17,7 +17,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileAgeMs, msToWholeDays, MS_PER_DAY } from "../../../src/core/brain/time.ts";
-import { IS_WINDOWS } from "../../helpers/platform.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
/** Pinned clock; every expectation below is relative to this instant. */
const NOW_MS = Date.parse("2026-05-29T12:00:00Z");
@@ -85,36 +85,29 @@ describe("fileAgeMs", () => {
}
});
- // Windows has no traversal bit for chmod to remove, so the unstattable
- // child cannot be built there.
- test.skipIf(IS_WINDOWS)("returns null for a file that exists but cannot be stat'ed", () => {
- const dir = makeTempDir();
- // A file is unstattable when its PARENT denies traversal, which is the
- // portable POSIX construction: removing every mode bit from the
- // directory makes `statSync` on a child fail EACCES while the child
- // itself still exists and is a different condition from absence.
- const denied = mkdtempSync(join(dir, "denied-"));
- const victim = join(denied, "victim.md");
- try {
- writeFileSync(victim, "x");
- chmodSync(denied, 0o000);
- let reachable = true;
+ // Windows has no traversal bit for chmod to remove, and root stats
+ // through any mode, so the unstattable child cannot be built on either
+ // (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "returns null for a file that exists but cannot be stat'ed",
+ () => {
+ const dir = makeTempDir();
+ // A file is unstattable when its PARENT denies traversal, which is the
+ // portable POSIX construction: removing every mode bit from the
+ // directory makes `statSync` on a child fail EACCES while the child
+ // itself still exists and is a different condition from absence.
+ const denied = mkdtempSync(join(dir, "denied-"));
+ const victim = join(denied, "victim.md");
try {
- statSync(victim);
- } catch {
- reachable = false;
- }
- // Root ignores the mode bits, so the construction only bites for an
- // unprivileged uid. Assert the real thing when it holds and say
- // plainly why it does not when it cannot, rather than faking it.
- if (reachable) {
- expect(process.getuid?.()).toBe(0);
- } else {
+ writeFileSync(victim, "x");
+ chmodSync(denied, 0o000);
+ // The fixture has to bite before the product is asked about it.
+ expect(() => statSync(victim)).toThrow();
expect(fileAgeMs(victim, NOW_MS)).toBeNull();
+ } finally {
+ chmodSync(denied, 0o700);
+ rmSync(dir, { recursive: true, force: true });
}
- } finally {
- chmodSync(denied, 0o700);
- rmSync(dir, { recursive: true, force: true });
- }
- });
+ },
+ );
});
diff --git a/tests/core/brain/truth/store.test.ts b/tests/core/brain/truth/store.test.ts
index 4d682d65..5a9932b8 100644
--- a/tests/core/brain/truth/store.test.ts
+++ b/tests/core/brain/truth/store.test.ts
@@ -23,6 +23,7 @@ import {
writeTruthState,
} from "../../../../src/core/brain/truth/store.ts";
import { computeTruthState } from "../../../../src/core/brain/truth/fold.ts";
+import { withDeviceId } from "../../../helpers/device-id.ts";
let vault: string;
@@ -208,3 +209,10 @@ describe("sweepClaimEvents", () => {
expect(readTruthState(vault)!.events).toBe(0);
});
});
+
+test("the claim shard name is claims.jsonl or claims.<deviceId>.jsonl, byte for byte", () => {
+ expect(withDeviceId("", () => claimShardPath(vault))).toBe(join(truthDir(vault), "claims.jsonl"));
+ expect(withDeviceId("laptop-01", () => claimShardPath(vault))).toBe(
+ join(truthDir(vault), "claims.laptop-01.jsonl"),
+ );
+});
diff --git a/tests/core/brain/write-batch-vocab.test.ts b/tests/core/brain/write-batch-vocab.test.ts
index b79338e0..ca4e36e6 100644
--- a/tests/core/brain/write-batch-vocab.test.ts
+++ b/tests/core/brain/write-batch-vocab.test.ts
@@ -7,10 +7,11 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { idempotencyLogDir } from "../../../src/core/brain/idempotency-ledger.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { applyWriteBatch, WriteBatchError } from "../../../src/core/brain/write-batch.ts";
@@ -156,3 +157,28 @@ describe("applyWriteBatch mixed all-or-nothing", () => {
expect(existsSync(join(vault, "Notes/First.md"))).toBe(false);
});
});
+
+describe("applyWriteBatch request receipts for log-writing operations (t_b34439d9)", () => {
+ const EVIDENCE_OP = {
+ kind: "apply_evidence",
+ input: { pref_id: "test-first", artifact: "[[src/x.ts]]", result: "applied", agent: "claude" },
+ } as const;
+
+ test("the stored receipt holds a vault-relative log path and a retry rebuilds it under the vault", () => {
+ writePref("test-first");
+ const first = applyWriteBatch(vault, [EVIDENCE_OP], { requestId: "evidence-1" });
+ const firstPath = (first.results[0] as { log_path: string }).log_path;
+ expect(firstPath.startsWith(vault)).toBe(true);
+
+ const ledgerDir = idempotencyLogDir(vault);
+ const stored = readdirSync(ledgerDir)
+ .map((name) => readFileSync(join(ledgerDir, name), "utf8"))
+ .join("");
+ expect(stored).toContain("evidence-1");
+ expect(stored).not.toContain(vault);
+
+ const retry = applyWriteBatch(vault, [EVIDENCE_OP], { requestId: "evidence-1" });
+ expect(retry.receipt.status).toBe("duplicate");
+ expect((retry.results[0] as { log_path: string }).log_path).toBe(firstPath);
+ });
+});
diff --git a/tests/core/brain/write-batch.test.ts b/tests/core/brain/write-batch.test.ts
index 13535837..c8427892 100644
--- a/tests/core/brain/write-batch.test.ts
+++ b/tests/core/brain/write-batch.test.ts
@@ -25,7 +25,7 @@
* is not an update and is unaffected.
*/
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import {
existsSync,
chmodSync,
@@ -39,7 +39,18 @@ import {
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
-import { applyWriteBatch, WriteBatchError } from "../../../src/core/brain/write-batch.ts";
+import {
+ applyWriteBatch,
+ WRITE_BATCH_RECEIPT_STATUS,
+ WriteBatchError,
+ type WriteOperation,
+} from "../../../src/core/brain/write-batch.ts";
+import * as ledger from "../../../src/core/brain/idempotency-ledger.ts";
+import {
+ IdempotencyKeyError,
+ IdempotencyPayloadMismatchError,
+} from "../../../src/core/brain/idempotency-ledger.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
import { listNoteWrites, type NoteWriteRecord } from "../../../src/core/brain/notes/write-log.ts";
import {
NOTE_WRITE_NO_PRIOR,
@@ -602,3 +613,140 @@ describe("applyWriteBatch note-write attribution", () => {
expect(noteWrites()).toEqual([]);
});
});
+
+describe("applyWriteBatch client request receipts (t_b34439d9)", () => {
+ const OPS: ReadonlyArray<WriteOperation> = [
+ {
+ kind: "create_note",
+ path: "Notes/Receipt.md",
+ frontmatter: { title: "Receipt" },
+ content: "written once",
+ },
+ ];
+
+ test("without a request id the result carries no receipt and behavior is unchanged", () => {
+ const res = applyWriteBatch(vault, OPS);
+ expect(res.applied).toBe(1);
+ expect(Object.hasOwn(res, "receipt")).toBe(false);
+ });
+
+ test("a fresh request id applies once with an applied receipt", () => {
+ const res = applyWriteBatch(vault, OPS, { requestId: "req-1" });
+ expect(res.receipt).toEqual({ requestId: "req-1", status: WRITE_BATCH_RECEIPT_STATUS.applied });
+ expect(readFileSync(join(vault, "Notes/Receipt.md"), "utf8")).toContain("written once");
+ });
+
+ test("a repeated id with the same payload returns the retained result as a duplicate", () => {
+ applyWriteBatch(vault, OPS, { requestId: "req-2" });
+ const before = readFileSync(join(vault, "Notes/Receipt.md"), "utf8");
+ const retry = applyWriteBatch(vault, OPS, { requestId: "req-2" });
+ expect(retry.receipt).toEqual({
+ requestId: "req-2",
+ status: WRITE_BATCH_RECEIPT_STATUS.duplicate,
+ });
+ // The retained original receipt, not a fresh application.
+ expect(retry.applied).toBe(1);
+ expect(retry.done).toBe(true);
+ expect(readFileSync(join(vault, "Notes/Receipt.md"), "utf8")).toBe(before);
+ });
+
+ test("a repeated id with a different payload throws and writes nothing", () => {
+ applyWriteBatch(vault, OPS, { requestId: "req-3" });
+ const before = readFileSync(join(vault, "Notes/Receipt.md"), "utf8");
+ expect(() =>
+ applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Other.md", content: "x" }], {
+ requestId: "req-3",
+ }),
+ ).toThrow(IdempotencyPayloadMismatchError);
+ expect(existsSync(join(vault, "Notes/Other.md"))).toBe(false);
+ expect(readFileSync(join(vault, "Notes/Receipt.md"), "utf8")).toBe(before);
+ });
+
+ test("an invalid request id surfaces the ledger's named key error before any write", () => {
+ for (const bad of ["", " ", "x".repeat(257)]) {
+ expect(() => applyWriteBatch(vault, OPS, { requestId: bad })).toThrow(IdempotencyKeyError);
+ }
+ expect(existsSync(join(vault, "Notes/Receipt.md"))).toBe(false);
+ });
+});
+
+describe("applyWriteBatch request receipt integrity (t_b34439d9 audit)", () => {
+ const LOG_OP: ReadonlyArray<WriteOperation> = [
+ { kind: "append_log_line", input: { text: "receipt race line" } },
+ ];
+
+ test("a rival that records the same id with a different payload mid-batch: this call's writes landed and the receipt says so", () => {
+ applyWriteBatch(vault, LOG_OP, { requestId: "race-1" });
+ // The unlocked pre-write consult misses the rival's record, as it does
+ // when a concurrent process records between the consult and the commit.
+ const spy = spyOn(ledger, "lookupKey").mockReturnValueOnce(null);
+ try {
+ const res = applyWriteBatch(
+ vault,
+ [{ kind: "append_log_line", input: { text: "a different line" } }],
+ { requestId: "race-1" },
+ );
+ expect(res.receipt).toEqual({
+ requestId: "race-1",
+ status: WRITE_BATCH_RECEIPT_STATUS.payload_conflict,
+ });
+ expect(res.applied).toBe(1);
+ expect(res.done).toBe(true);
+ const [only] = res.results;
+ expect(only?.kind).toBe("append_log_line");
+ const logged = readFileSync(join(vault, (only as { log_path: string }).log_path), "utf8");
+ expect(logged).toContain("a different line");
+ } finally {
+ spy.mockRestore();
+ }
+ // The id stays bound to the rival's payload: a retry of this call's
+ // operations under it is refused, and writes nothing more.
+ expect(() =>
+ applyWriteBatch(vault, [{ kind: "append_log_line", input: { text: "a different line" } }], {
+ requestId: "race-1",
+ }),
+ ).toThrow(IdempotencyPayloadMismatchError);
+ });
+
+ test("a rival that records the same id and payload mid-batch is named, never reported as applied", () => {
+ applyWriteBatch(vault, LOG_OP, { requestId: "race-2" });
+ const spy = spyOn(ledger, "lookupKey").mockReturnValueOnce(null);
+ try {
+ const res = applyWriteBatch(vault, LOG_OP, { requestId: "race-2" });
+ expect(res.receipt).toEqual({
+ requestId: "race-2",
+ status: WRITE_BATCH_RECEIPT_STATUS.concurrent_duplicate,
+ });
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test("a request id does not collide with a brain_feedback idempotency key of the same text", () => {
+ writeSignal(vault, {
+ topic: "shared-key-topic",
+ signal: "positive",
+ agent: "claude",
+ principle: "Keep keys apart.",
+ created_at: "2026-05-01T10:00:00Z",
+ date: "2026-05-01",
+ slug: "shared-key-topic",
+ idempotency_key: "shared-key",
+ });
+ const res = applyWriteBatch(vault, LOG_OP, { requestId: "shared-key" });
+ expect(res.receipt).toEqual({
+ requestId: "shared-key",
+ status: WRITE_BATCH_RECEIPT_STATUS.applied,
+ });
+ });
+
+ test("a non-array operations value with a request id is refused by name", () => {
+ for (const bad of [null, 42, {}]) {
+ expect(() =>
+ applyWriteBatch(vault, bad as unknown as ReadonlyArray<WriteOperation>, {
+ requestId: "shape-1",
+ }),
+ ).toThrow(WriteBatchError);
+ }
+ });
+});
diff --git a/tests/core/graph/unique-match.test.ts b/tests/core/graph/unique-match.test.ts
new file mode 100644
index 00000000..ae9a152c
--- /dev/null
+++ b/tests/core/graph/unique-match.test.ts
@@ -0,0 +1,43 @@
+/**
+ * The shared exactly-one decision (`resolveUniqueMatch`). Two features in
+ * this wave bind a term to a target only when exactly one candidate
+ * carries it - the repair lane binding a mention term to a corpus page,
+ * pre-extract binding a relative import specifier to an ingested file.
+ * Both must answer ambiguity the same way, so the discipline lives in one
+ * typed resolver instead of two call sites that can drift.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { resolveUniqueMatch } from "../../../src/core/graph/unique-match.ts";
+
+describe("resolveUniqueMatch", () => {
+ test("an empty candidate list resolves to none", () => {
+ expect(resolveUniqueMatch([])).toEqual({ status: "none" });
+ });
+
+ test("a single candidate resolves to unique with that target", () => {
+ expect(resolveUniqueMatch(["Notes/only.md"])).toEqual({
+ status: "unique",
+ target: "Notes/only.md",
+ });
+ });
+
+ test.each([
+ ["two", ["Notes/b.md", "Notes/a.md", "Notes/b.md"], ["Notes/b.md", "Notes/a.md"]],
+ ["three", ["a", "b", "a", "c", "b", "a"], ["a", "b", "c"]],
+ ])(
+ "%s distinct candidates resolve to ambiguous, each once in first-occurrence order",
+ (_count, candidates, matches) => {
+ expect(resolveUniqueMatch(candidates)).toEqual({ status: "ambiguous", matches });
+ },
+ );
+
+ test("a repeated identical candidate is deduped before the decision", () => {
+ // One page naming a term twice must never read as two pages naming it.
+ expect(resolveUniqueMatch(["Notes/same.md", "Notes/same.md"])).toEqual({
+ status: "unique",
+ target: "Notes/same.md",
+ });
+ });
+});
diff --git a/tests/core/reliability.test.ts b/tests/core/reliability.test.ts
index f3ab4d1e..a10cb4a3 100644
--- a/tests/core/reliability.test.ts
+++ b/tests/core/reliability.test.ts
@@ -3,10 +3,20 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { appendAuditRecord } from "../../src/core/reliability/audit.ts";
+import {
+ appendAuditRecord,
+ AUDIT_WEEK_SHARD_GRAMMAR,
+ isoWeekLabel,
+} from "../../src/core/reliability/audit.ts";
+import {
+ JSONL_LEDGER_EXT,
+ parseShardedName,
+ shardedFileName,
+} from "../../src/core/brain/ledger-shards.ts";
import { withFileLock } from "../../src/core/reliability/lock.ts";
import { buildProbeReport } from "../../src/core/reliability/probe.ts";
import { fakeCredential } from "../helpers/fake-credentials.ts";
+import { withDeviceId } from "../helpers/device-id.ts";
const RESEARCH_TYPE = "research";
const LOGGED_KEY = fakeCredential("secret-", "value");
@@ -91,6 +101,36 @@ describe("appendAuditRecord", () => {
expect(lines[0]).not.toContain(LOGGED_KEY);
});
+ test("the device id shards the week file name (t_774dea61)", () => {
+ const auditRoot = join(tmp, "Brain", "log", "device-sharded");
+ const record = {
+ timestamp: "2026-05-30T12:00:00.000Z",
+ actor: "tester",
+ action: "probe",
+ target: "Brain/x",
+ ok: true,
+ };
+ const onA = withDeviceId("a", () =>
+ appendAuditRecord(auditRoot, { ...record, action: "from-a" }),
+ );
+ const onB = withDeviceId("b", () =>
+ appendAuditRecord(auditRoot, { ...record, action: "from-b" }),
+ );
+ expect(onA.endsWith("2026-W22.a.jsonl")).toBe(true);
+ expect(onB.endsWith("2026-W22.b.jsonl")).toBe(true);
+ expect(existsSync(join(auditRoot, "2026-W22.a.jsonl"))).toBe(true);
+ expect(existsSync(join(auditRoot, "2026-W22.b.jsonl"))).toBe(true);
+ expect(existsSync(join(auditRoot, "2026-W22.jsonl"))).toBe(false);
+
+ // The empty device id is the legacy un-sharded file: names and bytes
+ // unchanged, no migration.
+ const legacy = withDeviceId("", () =>
+ appendAuditRecord(auditRoot, { ...record, action: "legacy" }),
+ );
+ expect(legacy.endsWith("2026-W22.jsonl")).toBe(true);
+ expect(existsSync(join(auditRoot, "2026-W22.jsonl"))).toBe(true);
+ });
+
test("rejects invalid timestamps before week bucketing", () => {
expect(() =>
appendAuditRecord(join(tmp, "Brain", "log", "schema-mutations"), {
@@ -130,3 +170,18 @@ describe("buildProbeReport", () => {
]);
});
});
+
+describe("audit week shard grammar", () => {
+ test("the reader grammar parses every name the writer composes, and nothing else", () => {
+ const week = isoWeekLabel(new Date("2026-01-01T12:00:00Z"));
+ for (const shardId of ["", "laptop-01"]) {
+ const name = shardedFileName(week, shardId, JSONL_LEDGER_EXT);
+ expect(parseShardedName(name, AUDIT_WEEK_SHARD_GRAMMAR)).toMatchObject({
+ base: week,
+ shardId,
+ });
+ }
+ expect(parseShardedName(`${week}.md`, AUDIT_WEEK_SHARD_GRAMMAR)).toBeNull();
+ expect(parseShardedName("2026-01.jsonl", AUDIT_WEEK_SHARD_GRAMMAR)).toBeNull();
+ });
+});
diff --git a/tests/core/search/agent-scope-surfaces.test.ts b/tests/core/search/agent-scope-surfaces.test.ts
index b315e249..fd868aa9 100644
--- a/tests/core/search/agent-scope-surfaces.test.ts
+++ b/tests/core/search/agent-scope-surfaces.test.ts
@@ -23,6 +23,7 @@ import { indexVault, resolveSearchConfig, search } from "../../../src/core/searc
import { SearchError, type ResolvedSearchConfig } from "../../../src/core/search/types.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
const OWNER_A = "agent-a";
const OWNER_B = "agent-b";
@@ -168,22 +169,26 @@ test("a deleted owner-tagged file is hidden from another owner, not shared", asy
expect(refused!.message).toBe(`chunk not found: ${foreign}`);
});
-test("an unreadable owner-tagged file is hidden from another owner", async () => {
- const target = join(vault, "notes", "owned-a.md");
- const foreign = await chunkIdFor("notes/owned-a.md");
- chmodSync(target, 0o000);
- try {
- const scoped = await search(config, { query: QUERY, limit: 20, agentScope: OWNER_B });
- expect(scoped.results.map((r) => r.path)).not.toContain("notes/owned-a.md");
- const refused = await expandHit(config, { chunkId: foreign, agentScope: OWNER_B }).then(
- () => null,
- (e: unknown) => e as SearchError,
- );
- expect(refused).toBeInstanceOf(SearchError);
- } finally {
- chmodSync(target, 0o644);
- }
-});
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable owner-tagged file is hidden from another owner",
+ async () => {
+ const target = join(vault, "notes", "owned-a.md");
+ const foreign = await chunkIdFor("notes/owned-a.md");
+ chmodSync(target, 0o000);
+ try {
+ const scoped = await search(config, { query: QUERY, limit: 20, agentScope: OWNER_B });
+ expect(scoped.results.map((r) => r.path)).not.toContain("notes/owned-a.md");
+ const refused = await expandHit(config, { chunkId: foreign, agentScope: OWNER_B }).then(
+ () => null,
+ (e: unknown) => e as SearchError,
+ );
+ expect(refused).toBeInstanceOf(SearchError);
+ } finally {
+ chmodSync(target, 0o644);
+ }
+ },
+);
test("an unscoped call still serves a deleted file's indexed chunk", async () => {
const chunkId = await chunkIdFor("notes/owned-a.md");
diff --git a/tests/core/search/fts.test.ts b/tests/core/search/fts.test.ts
index 090190aa..82c03cad 100644
--- a/tests/core/search/fts.test.ts
+++ b/tests/core/search/fts.test.ts
@@ -1,7 +1,8 @@
import { test, expect, beforeEach, afterEach } from "bun:test";
import { Database } from "bun:sqlite";
-import { buildFtsMatch, runFtsQuery } from "../../../src/core/search/fts.ts";
+import { buildExpandedFtsMatch, buildFtsMatch, runFtsQuery } from "../../../src/core/search/fts.ts";
+import { FTS_MATCH_MODE } from "../../../src/core/search/fts-match-mode.ts";
import { Store } from "../../../src/core/search/store.ts";
import { createTempVault, makeConfig } from "../../helpers/search-fixtures.ts";
@@ -163,3 +164,42 @@ test("runFtsQuery rebuilds an empty desynced FTS table once", async () => {
expect(hits[0]?.documentId).toBe(d2);
await readStore.close();
});
+
+test("match mode any OR-joins the quoted tokens (t_c5326ece)", () => {
+ expect(buildFtsMatch("alpha beta", { matchMode: FTS_MATCH_MODE.any })).toBe('"alpha" OR "beta"');
+});
+
+test("caller-typed operator tokens stay dropped in both modes", () => {
+ expect(buildFtsMatch("alpha AND beta")).toBe('"alpha" "beta"');
+ expect(buildFtsMatch("alpha AND beta", { matchMode: FTS_MATCH_MODE.any })).toBe(
+ '"alpha" OR "beta"',
+ );
+});
+
+test("the default mode is byte-identical, including empty and single-token cases", () => {
+ expect(buildFtsMatch("alpha")).toBe('"alpha"');
+ expect(buildFtsMatch("")).toBe("");
+ expect(buildFtsMatch("alpha beta")).toBe('"alpha" "beta"');
+});
+
+test("expanded composition in any mode ORs the flat group with the expansion terms", () => {
+ expect(buildExpandedFtsMatch("alpha beta", ["gamma"], { matchMode: FTS_MATCH_MODE.any })).toBe(
+ '("alpha" OR "beta") OR "gamma"',
+ );
+ expect(buildExpandedFtsMatch("alpha beta", ["gamma"])).toBe('("alpha" "beta") OR "gamma"');
+});
+
+test("runFtsQuery with matchMode any keeps the single-term document", async () => {
+ // Only Notes/alpha.md (d1) carries both terms ("fox" and "nights"); in
+ // the default all-mode it is the only hit, and any-mode keeps Other/beta.md (d2).
+ const { store, d1, d2 } = await fixture();
+ try {
+ const strict = runFtsQuery(store, "fox nights", { limit: 10 });
+ const widened = runFtsQuery(store, "fox nights", { limit: 10, matchMode: FTS_MATCH_MODE.any });
+ expect(strict.some((h) => h.documentId === d2)).toBe(false);
+ expect(widened.some((h) => h.documentId === d2)).toBe(true);
+ expect(widened.some((h) => h.documentId === d1)).toBe(true);
+ } finally {
+ await store.close();
+ }
+});
diff --git a/tests/core/search/query-cache.test.ts b/tests/core/search/query-cache.test.ts
index 49905217..74c27f35 100644
--- a/tests/core/search/query-cache.test.ts
+++ b/tests/core/search/query-cache.test.ts
@@ -58,3 +58,15 @@ test("a local outcome cannot be served to a caller that established nothing", ()
buildCacheKey(opts({ transportReach: "local" }), "p", "fp"),
);
});
+
+test("an any-mode search keys apart from the strict default", () => {
+ expect(buildCacheKey(opts({ query: "alpha beta", matchMode: "any" }), "p", "fp")).not.toBe(
+ buildCacheKey(opts({ query: "alpha beta" }), "p", "fp"),
+ );
+});
+
+test("an explicit all mode keys identically to an absent mode", () => {
+ expect(buildCacheKey(opts({ query: "alpha beta", matchMode: "all" }), "p", "fp")).toBe(
+ buildCacheKey(opts({ query: "alpha beta" }), "p", "fp"),
+ );
+});
diff --git a/tests/core/search/search.test.ts b/tests/core/search/search.test.ts
index 4918e4c4..ed0fa003 100644
--- a/tests/core/search/search.test.ts
+++ b/tests/core/search/search.test.ts
@@ -5,6 +5,7 @@ import { indexVault } from "../../../src/core/search/indexer.ts";
import { search } from "../../../src/core/search/search.ts";
import { parseStructuredRecallQueryDocument } from "../../../src/core/search/structured-query.ts";
import { SearchError } from "../../../src/core/search/types.ts";
+import { FTS_MATCH_MODE, type FtsMatchMode } from "../../../src/core/search/fts-match-mode.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
@@ -380,3 +381,28 @@ test("limit truncates results", async () => {
const out = await search(cfg, { query: "repeated", limit: 5 });
expect(out.results.length).toBe(5);
});
+
+test("matchMode any widens the keyword lane; the default all stays exact (t_c5326ece)", async () => {
+ writeMd(vault, "Notes/both.md", "# Both\n\nchimera basilisk together in one lair.");
+ writeMd(vault, "Notes/one.md", "# One\n\nA lone chimera wanders here.");
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+ const strict = await search(cfg, { query: "chimera basilisk", limit: 10 });
+ const widened = await search(cfg, {
+ query: "chimera basilisk",
+ limit: 10,
+ matchMode: FTS_MATCH_MODE.any,
+ });
+ expect(strict.results.some((h) => h.path.includes("one.md"))).toBe(false);
+ expect(widened.results.some((h) => h.path.includes("one.md"))).toBe(true);
+ expect(widened.results.some((h) => h.path.includes("both.md"))).toBe(true);
+});
+
+test("an unknown matchMode is refused, not treated as the default", async () => {
+ writeMd(vault, "Notes/both.md", "# Both\n\nchimera basilisk together in one lair.");
+ const cfg = makeConfig({ vault, dbPath });
+ await indexVault(cfg);
+ expect(
+ search(cfg, { query: "chimera", matchMode: "sometimes" as unknown as FtsMatchMode }),
+ ).rejects.toThrow(SearchError);
+});
diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.ts
index ada355f8..7bcb0d48 100644
--- a/tests/core/state/surfaces.test.ts
+++ b/tests/core/state/surfaces.test.ts
@@ -30,7 +30,7 @@
import { afterEach, describe, expect, test } from "bun:test";
import { selfHealUpgradeMarkerPath } from "../../../src/core/maintenance/self-heal-upgrade-state.ts";
-import { existsSync, mkdirSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdirSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { dirname, join, resolve, sep } from "node:path";
import {
@@ -96,6 +96,7 @@ import {
STATE_TIERS,
type StateSurfaceId,
} from "../../../src/core/state/surfaces.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
import { tempDirs } from "../../helpers/temp-dir.ts";
const mkTemp = tempDirs();
@@ -647,3 +648,80 @@ describe("one value, two renderings", () => {
expect(text).not.toContain("nothing has created it");
});
});
+
+function logDir(vault: string): string {
+ return join(vault, "Brain", "log");
+}
+
+describe("sharded ledger surfaces (t_774dea61)", () => {
+ test("a fixed-name ledger surface is present when only a device shard exists", () => {
+ const vault = tempVault();
+ mkdirSync(logDir(vault), { recursive: true });
+ const shard = join(logDir(vault), "query-demand.device-x.jsonl");
+ writeFileSync(shard, "{}\n", "utf8");
+
+ const report = reportFor(vault, STATE_SURFACE_ID.queryDemandLedger);
+
+ expect(report.reachability.state).toBe(STATE_REACHABILITY.present);
+ expect(report.reachability.path).toBe(shard);
+ });
+
+ test("the legacy name alone still reads present at its own path; neither reads absent", () => {
+ const vault = tempVault();
+ mkdirSync(logDir(vault), { recursive: true });
+ const legacy = join(logDir(vault), "query-demand.jsonl");
+ writeFileSync(legacy, "{}\n", "utf8");
+ const present = reportFor(vault, STATE_SURFACE_ID.queryDemandLedger).reachability;
+ expect(present.state).toBe(STATE_REACHABILITY.present);
+ expect(present.path).toBe(legacy);
+
+ const empty = tempVault();
+ mkdirSync(logDir(empty), { recursive: true });
+ expect(reportFor(empty, STATE_SURFACE_ID.queryDemandLedger).reachability.state).toBe(
+ STATE_REACHABILITY.absent,
+ );
+ expect(reportFor(tempVault(), STATE_SURFACE_ID.queryDemandLedger).reachability.state).toBe(
+ STATE_REACHABILITY.absent,
+ );
+ });
+
+ test("a conflict copy alone is not a shard and does not make the surface present", () => {
+ const vault = tempVault();
+ mkdirSync(logDir(vault), { recursive: true });
+ writeFileSync(join(logDir(vault), "recurrence-support.sync-conflict-x.jsonl"), "{}\n", "utf8");
+ expect(reportFor(vault, STATE_SURFACE_ID.recurrenceLedger).reachability.state).toBe(
+ STATE_REACHABILITY.absent,
+ );
+ });
+
+ test("the maintenance journal and the lineage ledger read their device shards too", () => {
+ const vault = tempVault();
+ const journal = join(vault, ".open-second-brain", "maintenance-runs.device-x.jsonl");
+ const lineage = join(vault, "Brain", ".state", "session-lineage.device-x.jsonl");
+ for (const path of [journal, lineage]) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "{}\n", "utf8");
+ }
+
+ expect(reportFor(vault, STATE_SURFACE_ID.maintenanceJournal).reachability.path).toBe(journal);
+ expect(reportFor(vault, STATE_SURFACE_ID.lineageLedger).reachability.path).toBe(lineage);
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a ledger directory that cannot be listed is unchecked by its code, never absent",
+ () => {
+ const vault = tempVault();
+ mkdirSync(logDir(vault), { recursive: true });
+ // Traversable but not listable: the legacy stat answers ENOENT, the
+ // shard listing answers EACCES.
+ chmodSync(logDir(vault), 0o300);
+ try {
+ const verdict = reportFor(vault, STATE_SURFACE_ID.captureDecisionLog).reachability;
+ expect(verdict.state).toBe(STATE_REACHABILITY.unchecked);
+ expect(verdict.reason).toContain("EACCES");
+ } finally {
+ chmodSync(logDir(vault), 0o700);
+ }
+ },
+ );
+});
diff --git a/tests/helpers/device-id.ts b/tests/helpers/device-id.ts
new file mode 100644
index 00000000..1adad192
--- /dev/null
+++ b/tests/helpers/device-id.ts
@@ -0,0 +1,22 @@
+/**
+ * Run `run` with `O2B_DEVICE_ID` set to `deviceId`, then put the previous
+ * value back (or remove the variable when it was absent), whatever `run`
+ * did.
+ *
+ * Per-device ledger shards are named from this variable, so a test that
+ * writes as two devices switches it several times. One helper owns the
+ * save/set/restore: a hand-written restore that is missed or wrong leaks
+ * the device id into every later test in the same bun process.
+ * `tests/setup.ts` pins the suite-wide default to the empty string (the
+ * un-sharded legacy name); pass `""` here to select that name explicitly.
+ */
+export function withDeviceId<T>(deviceId: string, run: () => T): T {
+ const previous = process.env["O2B_DEVICE_ID"];
+ process.env["O2B_DEVICE_ID"] = deviceId;
+ try {
+ return run();
+ } finally {
+ if (previous === undefined) delete process.env["O2B_DEVICE_ID"];
+ else process.env["O2B_DEVICE_ID"] = previous;
+ }
+}
diff --git a/tests/hooks/recall-inject-decision-model.test.ts b/tests/hooks/recall-inject-decision-model.test.ts
index 91edb92d..c96b2c58 100644
--- a/tests/hooks/recall-inject-decision-model.test.ts
+++ b/tests/hooks/recall-inject-decision-model.test.ts
@@ -154,6 +154,11 @@ async function runHook(env: Record<string, string> = {}): Promise<HookRun> {
VAULT_DIR: vault,
OPEN_SECOND_BRAIN_CONFIG: configPath,
OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED: "true",
+ // The spawned hook does not run the test preload, so without this it
+ // would mint a device id into each rewritten config and spread its
+ // audit records over several week shards; "last record" below needs
+ // the single legacy week file the preload pins in-process.
+ O2B_DEVICE_ID: "",
...env,
},
});
diff --git a/tests/mcp/agent-scope-matrix.test.ts b/tests/mcp/agent-scope-matrix.test.ts
index 394006d1..45020825 100644
--- a/tests/mcp/agent-scope-matrix.test.ts
+++ b/tests/mcp/agent-scope-matrix.test.ts
@@ -85,6 +85,7 @@ import {
probeLabel,
type ProbeCall,
} from "../helpers/tool-probe-catalogue.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";
@@ -412,19 +413,23 @@ test("second_brain_query excludes another owner's pages from the listing", async
* page, so without the walk's diagnostic sink an owner-tagged page becomes
* shared the moment its file stops being readable.
*/
-test("second_brain_query hides a page it cannot read from a scoped caller", async () => {
- const target = join(vault, "notes", "owned-a.md");
- chmodSync(target, 0o000);
- try {
- const scoped = JSON.parse(
- await call("second_brain_query", { limit: 500, agent_scope: OWNER_B }),
- );
- expect(pagePaths(scoped)).not.toContain("notes/owned-a.md");
- expect(pagePaths(scoped)).toContain("notes/shared.md");
- } finally {
- chmodSync(target, 0o644);
- }
-});
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "second_brain_query hides a page it cannot read from a scoped caller",
+ async () => {
+ const target = join(vault, "notes", "owned-a.md");
+ chmodSync(target, 0o000);
+ try {
+ const scoped = JSON.parse(
+ await call("second_brain_query", { limit: 500, agent_scope: OWNER_B }),
+ );
+ expect(pagePaths(scoped)).not.toContain("notes/owned-a.md");
+ expect(pagePaths(scoped)).toContain("notes/shared.md");
+ } finally {
+ chmodSync(target, 0o644);
+ }
+ },
+);
test("brain_search_by_source excludes another owner's derived pages", async () => {
const sourceFile = "sources/paper.md";
diff --git a/tests/mcp/brain-write-batch.test.ts b/tests/mcp/brain-write-batch.test.ts
index a32467fe..fa9f7958 100644
--- a/tests/mcp/brain-write-batch.test.ts
+++ b/tests/mcp/brain-write-batch.test.ts
@@ -15,7 +15,7 @@
* any operation commits.
*/
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import {
existsSync,
mkdirSync,
@@ -38,8 +38,9 @@ import { BRAIN_LOG_EVENT_KIND } from "../../src/core/brain/types.ts";
import { WRITE_BATCH_TOOLS } from "../../src/mcp/brain/write-batch-tools.ts";
import { NOTES_TOOLS } from "../../src/mcp/brain/notes-tools.ts";
import { MAX_BATCH_OPERATIONS } from "../../src/core/brain/write-batch.ts";
+import * as ledger from "../../src/core/brain/idempotency-ledger.ts";
import { PAGE_LINT_KEY } from "../../src/core/brain/page-lint.ts";
-import { MCPError } from "../../src/mcp/protocol.ts";
+import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
/**
@@ -552,3 +553,103 @@ describe("brain_write_batch - mtime stability on byte-identical rewrites", () =>
expect(readFileSync(join(vault, "Notes/Appended.md"), "utf8")).toContain("more");
});
});
+
+describe("brain_write_batch request receipts (t_b34439d9)", () => {
+ const OPS = [{ op: "create_note", path: "Notes/Receipted.md", content: "written once" }];
+
+ test("a request_id returns a receipt, and a retry returns the retained duplicate", async () => {
+ const first = (await tool.handler(ctx, {
+ operations: OPS,
+ request_id: "req-42",
+ })) as Record<string, unknown>;
+ expect(first["request_id"]).toBe("req-42");
+ expect(first["receipt"]).toBe("applied");
+ expect(first["applied"]).toBe(1);
+
+ const retry = (await tool.handler(ctx, {
+ operations: OPS,
+ request_id: "req-42",
+ })) as Record<string, unknown>;
+ expect(retry["request_id"]).toBe("req-42");
+ expect(retry["receipt"]).toBe("duplicate");
+ // The retained original receipt: the batch reports what the FIRST call
+ // applied, and nothing new lands.
+ expect(retry["applied"]).toBe(1);
+ expect(existsSync(join(vault, "Notes/Receipted.md"))).toBe(true);
+ });
+
+ test("a request_id omitted leaves the payload without receipt fields", async () => {
+ const res = (await tool.handler(ctx, { operations: OPS })) as Record<string, unknown>;
+ expect(Object.hasOwn(res, "request_id")).toBe(false);
+ expect(Object.hasOwn(res, "receipt")).toBe(false);
+ });
+
+ test("a concurrent duplicate recorded mid-batch reaches the caller by its own status", async () => {
+ const LOG_OPS = [{ op: "append_log_line", text: "concurrent receipt line" }];
+ await tool.handler(ctx, { operations: LOG_OPS, request_id: "req-race" });
+ // The unlocked consult misses the rival's record, as under a concurrent call.
+ const spy = spyOn(ledger, "lookupKey").mockReturnValueOnce(null);
+ try {
+ const res = (await tool.handler(ctx, {
+ operations: LOG_OPS,
+ request_id: "req-race",
+ })) as Record<string, unknown>;
+ expect(res["receipt"]).toBe("concurrent_duplicate");
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test("a concurrent record of the same id with another payload: this call's writes landed and the receipt says so", async () => {
+ await tool.handler(ctx, {
+ operations: [{ op: "append_log_line", text: "the rival line" }],
+ request_id: "req-conflict",
+ });
+ const spy = spyOn(ledger, "lookupKey").mockReturnValueOnce(null);
+ try {
+ const res = (await tool.handler(ctx, {
+ operations: OPS,
+ request_id: "req-conflict",
+ })) as Record<string, unknown>;
+ expect(res["receipt"]).toBe("payload_conflict");
+ expect(res["applied"]).toBe(1);
+ expect(res["done"]).toBe(true);
+ expect(String(res["receipt_note"])).toMatch(/writes of this call landed/);
+ expect(existsSync(join(vault, "Notes/Receipted.md"))).toBe(true);
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ test.each([
+ ["a number", 7],
+ ["an empty string", ""],
+ ["whitespace", " "],
+ ["an over-long id", "x".repeat(300)],
+ ])("request_id as %s is INVALID_PARAMS before any write", async (_label, requestId) => {
+ let thrown: unknown = null;
+ try {
+ await tool.handler(ctx, { operations: OPS, request_id: requestId });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(MCPError);
+ expect((thrown as MCPError).code).toBe(INVALID_PARAMS);
+ expect((thrown as MCPError).message).toMatch(/request_id|idempotency key/);
+ expect(existsSync(join(vault, "Notes/Receipted.md"))).toBe(false);
+ });
+
+ test("a duplicate retry lints nothing: the call wrote no page", async () => {
+ const first = (await tool.handler(ctx, { operations: OPS, request_id: "req-lint" })) as Record<
+ string,
+ unknown
+ >;
+ const retry = (await tool.handler(ctx, { operations: OPS, request_id: "req-lint" })) as Record<
+ string,
+ unknown
+ >;
+ expect(retry["receipt"]).toBe("duplicate");
+ expect(PAGE_LINT_KEY in first).toBe(true);
+ expect(PAGE_LINT_KEY in retry).toBe(false);
+ });
+});
diff --git a/tests/mcp/error-redaction.test.ts b/tests/mcp/error-redaction.test.ts
index 911f38ec..65a77b90 100644
--- a/tests/mcp/error-redaction.test.ts
+++ b/tests/mcp/error-redaction.test.ts
@@ -17,7 +17,7 @@ import { join } from "node:path";
import { redactErrorForCaller } from "../../src/mcp/error-redaction.ts";
import { JSONRPC_VERSION, MCPServer } from "../../src/mcp/index.ts";
-import { IS_WINDOWS } from "../helpers/platform.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
describe("redactErrorForCaller", () => {
const vault = join(homedir(), "vaults", "main");
@@ -79,7 +79,7 @@ describe("the server's error channels", () => {
expect(response.error!.message).not.toContain(tmp);
});
- test.skipIf(IS_WINDOWS)(
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a tool error at remote reach redacts a path outside the vault; at local it does not",
async () => {
// An unreadable o2b config makes the write tool throw a plain Error
diff --git a/tests/mcp/ingest-tool.test.ts b/tests/mcp/ingest-tool.test.ts
index d1ff0eca..7a2c8a37 100644
--- a/tests/mcp/ingest-tool.test.ts
+++ b/tests/mcp/ingest-tool.test.ts
@@ -134,6 +134,27 @@ describe("brain_ingest_source", () => {
});
});
+ test("pre_extract names a bound import target in snake_case, like every other key", async () => {
+ mkdirSync(join(vault, "Code"), { recursive: true });
+ writeFileSync(join(vault, "Code", "dom.ts"), "export const h = 1;\n", "utf8");
+ writeFileSync(join(vault, "Code", "widget.ts"), 'import { h } from "./dom";\n', "utf8");
+ // The imported file must already be in the content manifest to bind.
+ await handler(ctx, {
+ source_path: "Code/dom.ts",
+ summary: "A dom module.",
+ entities: [{ category: "concept", name: "Dom" }],
+ });
+ const res = (await handler(ctx, {
+ source_path: "Code/widget.ts",
+ summary: "A widget.",
+ entities: [{ category: "concept", name: "Widget" }],
+ pre_extract: true,
+ })) as Record<string, unknown>;
+ expect((res["pre_extract"] as { edges: unknown[] }).edges).toEqual([
+ { kind: "imports", from: "Code/widget.ts", to: "./dom", resolved_to: "Code/dom.ts" },
+ ]);
+ });
+
test("without pre_extract the response omits the seeds field (byte-identical)", async () => {
const res = (await handler(ctx, {
source_path: "Articles/eth.md",
diff --git a/tests/mcp/search-description.test.ts b/tests/mcp/search-description.test.ts
new file mode 100644
index 00000000..883e98c9
--- /dev/null
+++ b/tests/mcp/search-description.test.ts
@@ -0,0 +1,27 @@
+/**
+ * The `brain_search` when-to-search cue (t_cb1e9d3d): the tool description
+ * carries exactly one sentence naming `brain_recall_gate` as the classifier
+ * to consult before widening recall - calibration for the agent reading the
+ * tool list, nothing more. No fan-out counts and no parallel-search
+ * language: the description must not promise machinery it does not have.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";
+
+const SEARCH_DESCRIPTION = SEARCH_TOOLS.find((t) => t.name === "brain_search")!.description;
+
+describe("brain_search when-to-search cue", () => {
+ test("the description names brain_recall_gate exactly once", () => {
+ expect(SEARCH_DESCRIPTION).toContain("brain_recall_gate");
+ expect(SEARCH_DESCRIPTION.split("brain_recall_gate")).toHaveLength(2);
+ });
+
+ test("the cue names widening recall, with no fan-out or parallel-search language", () => {
+ expect(/widening recall/i.test(SEARCH_DESCRIPTION)).toBe(true);
+ expect(/parallel/i.test(SEARCH_DESCRIPTION)).toBe(false);
+ expect(/fan-out/i.test(SEARCH_DESCRIPTION)).toBe(false);
+ expect(/\d+\s+search(es|es per)/i.test(SEARCH_DESCRIPTION)).toBe(false);
+ });
+});
diff --git a/tests/mcp/search-disclosure-mode.test.ts b/tests/mcp/search-disclosure-mode.test.ts
new file mode 100644
index 00000000..0cc035b4
--- /dev/null
+++ b/tests/mcp/search-disclosure-mode.test.ts
@@ -0,0 +1,84 @@
+/**
+ * MCP `disclosure` on `brain_search`: the result-depth modes come from one
+ * vocabulary, the schema enum is that list, and any refused value - however
+ * long or whatever its type - is INVALID_PARAMS naming the accepted modes.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ DEFAULT_DISCLOSURE_MODE,
+ DISCLOSURE_MODES,
+} from "../../src/core/search/disclosure-mode.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";
+import { MCPError } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { writeMd } from "../helpers/search-fixtures.ts";
+
+const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search")!;
+
+let tmp: string;
+let ctx: ServerContext;
+
+beforeEach(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-disclosure-"));
+ const vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const configPath = join(tmp, "config.yaml");
+ writeMd(vault, "Brain/notes/lair.md", "# Lair\n\nA chimera sleeps in the lair.");
+ await indexVault(resolveSearchConfig({ vault, configPath }));
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+interface SearchResponse {
+ readonly results: ReadonlyArray<unknown>;
+ readonly cards?: ReadonlyArray<unknown>;
+}
+
+async function run(args: Record<string, unknown>): Promise<SearchResponse> {
+ return (await tool.handler(ctx, args)) as unknown as SearchResponse;
+}
+
+describe("disclosure mode vocabulary", () => {
+ test("full is the default", () => {
+ expect(DEFAULT_DISCLOSURE_MODE).toBe("full");
+ });
+});
+
+describe("brain_search disclosure", () => {
+ test("the schema declares the public full|cards enum", () => {
+ const schema = tool.inputSchema.properties as Record<string, { enum?: string[] }>;
+ expect(schema["disclosure"]?.enum).toEqual(["full", "cards"]);
+ });
+
+ test("cards returns layer-1 cards instead of full results", async () => {
+ const out = await run({ query: "chimera", disclosure: "cards" });
+ expect(out.results).toEqual([]);
+ expect(out.cards?.length).toBeGreaterThan(0);
+ });
+
+ test("any refused value, however long or typed, names the accepted modes", async () => {
+ const refusal = `argument 'disclosure' must be one of ${DISCLOSURE_MODES.join(", ")}`;
+ const errors = await Promise.all(
+ ["x".repeat(40), "sometimes", 7].map((bad) =>
+ run({ query: "chimera", disclosure: bad }).then(
+ () => null,
+ (exc: unknown) => exc,
+ ),
+ ),
+ );
+ for (const error of errors) {
+ expect(error).toBeInstanceOf(MCPError);
+ expect((error as Error).message).toContain(refusal);
+ }
+ });
+});
diff --git a/tests/mcp/search-match-mode.test.ts b/tests/mcp/search-match-mode.test.ts
new file mode 100644
index 00000000..8b21298b
--- /dev/null
+++ b/tests/mcp/search-match-mode.test.ts
@@ -0,0 +1,77 @@
+/**
+ * MCP `match_mode` on `brain_search` (t_c5326ece): the enum is validated at
+ * the boundary - anything but `all` / `any` is INVALID_PARAMS - and a valid
+ * `any` actually widens the keyword lane instead of being dropped.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { FTS_MATCH_MODES } from "../../src/core/search/fts-match-mode.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";
+import { INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { writeMd } from "../helpers/search-fixtures.ts";
+
+const tool = SEARCH_TOOLS.find((t) => t.name === "brain_search")!;
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+let ctx: ServerContext;
+
+beforeEach(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-match-mode-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ writeMd(vault, "Brain/notes/both.md", "# Both\n\nchimera basilisk together in one lair.");
+ writeMd(vault, "Brain/notes/one.md", "# One\n\nA lone chimera wanders here.");
+ await indexVault(resolveSearchConfig({ vault, configPath }));
+ ctx = { vault, configPath, repoRoot: null };
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+interface SearchResponse {
+ readonly results: ReadonlyArray<{ readonly path: string }>;
+}
+
+async function run(args: Record<string, unknown>): Promise<SearchResponse> {
+ return (await tool.handler(ctx, args)) as unknown as SearchResponse;
+}
+
+describe("brain_search match_mode", () => {
+ test("the schema declares the public all|any enum", () => {
+ const schema = tool.inputSchema.properties as Record<string, { enum?: string[] }>;
+ expect(schema["match_mode"]?.enum).toEqual(["all", "any"]);
+ });
+
+ test("any reaches the keyword lane and keeps the single-term document", async () => {
+ const widened = await run({ query: "chimera basilisk", limit: 10, match_mode: "any" });
+ expect(widened.results.some((h) => h.path.includes("one.md"))).toBe(true);
+ });
+
+ test.each([["sometimes"], ["x".repeat(40)], [7]])(
+ "match_mode %p is INVALID_PARAMS naming the accepted modes",
+ async (bad) => {
+ let thrown: unknown = null;
+ try {
+ await run({ query: "chimera", match_mode: bad });
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(MCPError);
+ expect((thrown as MCPError).code).toBe(INVALID_PARAMS);
+ expect((thrown as MCPError).message).toContain(
+ `must be one of ${FTS_MATCH_MODES.join(", ")}`,
+ );
+ },
+ );
+});
diff --git a/tests/scripts/hermes-plugin-scan.test.ts b/tests/scripts/hermes-plugin-scan.test.ts
new file mode 100644
index 00000000..e023b3f0
--- /dev/null
+++ b/tests/scripts/hermes-plugin-scan.test.ts
@@ -0,0 +1,99 @@
+/**
+ * `scripts/hermes-plugin-scan.ts` - the pinned scanner fetch.
+ *
+ * The CI gate fetches Hermes' scanner modules from the GitHub contents API.
+ * A shared runner can hit that API's rate limit (HTTP 429) or a transient
+ * server error; the fetch retries those a bounded number of times with
+ * backoff, honours a `Retry-After` header, and otherwise surfaces the last
+ * status by name. A stubbed fetch and sleep keep the tests off the network.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ GUARD_FETCH_ATTEMPTS,
+ GUARD_FETCH_BASE_DELAY_MS,
+ fetchGuardFile,
+ type GuardFetchDeps,
+} from "../../scripts/hermes-plugin-scan.ts";
+
+const PATH = "tools/skills_guard.py";
+const BODY = new TextEncoder().encode("print('guard')\n");
+
+function stubFetch(responses: Array<() => Response>): {
+ fetch: GuardFetchDeps["fetch"];
+ calls: () => number;
+} {
+ let calls = 0;
+ const fetchImpl = (async () => {
+ const next = responses[Math.min(calls, responses.length - 1)]!;
+ calls += 1;
+ return next();
+ }) satisfies GuardFetchDeps["fetch"];
+ return { fetch: fetchImpl, calls: () => calls };
+}
+
+function recordingSleep(): {
+ sleep: (ms: number) => Promise<void>;
+ delays: number[];
+} {
+ const delays: number[] = [];
+ return {
+ delays,
+ sleep: async (ms: number) => {
+ delays.push(ms);
+ },
+ };
+}
+
+const status = (code: number, headers?: Record<string, string>) => () =>
+ new Response("rate limited", { status: code, headers });
+const ok = () => new Response(BODY, { status: 200 });
+
+describe("fetchGuardFile", () => {
+ test("a rate-limited fetch is retried with exponential backoff until it succeeds", async () => {
+ const stub = stubFetch([status(429), status(429), ok]);
+ const clock = recordingSleep();
+ const data = await fetchGuardFile(PATH, {
+ fetch: stub.fetch,
+ sleep: clock.sleep,
+ });
+ expect(new TextDecoder().decode(data)).toBe("print('guard')\n");
+ expect(stub.calls()).toBe(3);
+ expect(clock.delays).toEqual([GUARD_FETCH_BASE_DELAY_MS, GUARD_FETCH_BASE_DELAY_MS * 2]);
+ });
+
+ test("a Retry-After header in seconds sets the wait", async () => {
+ const stub = stubFetch([status(429, { "Retry-After": "7" }), ok]);
+ const clock = recordingSleep();
+ await fetchGuardFile(PATH, { fetch: stub.fetch, sleep: clock.sleep });
+ expect(clock.delays).toEqual([7000]);
+ });
+
+ test("a server error is retried like a rate limit", async () => {
+ const stub = stubFetch([status(503), ok]);
+ const clock = recordingSleep();
+ await fetchGuardFile(PATH, { fetch: stub.fetch, sleep: clock.sleep });
+ expect(stub.calls()).toBe(2);
+ });
+
+ test("exhausted attempts throw the last status by name", async () => {
+ const stub = stubFetch([status(429)]);
+ const clock = recordingSleep();
+ await expect(fetchGuardFile(PATH, { fetch: stub.fetch, sleep: clock.sleep })).rejects.toThrow(
+ new RegExp(`${PATH}@[0-9a-f]{40}: HTTP 429 after ${GUARD_FETCH_ATTEMPTS} attempts`),
+ );
+ expect(stub.calls()).toBe(GUARD_FETCH_ATTEMPTS);
+ expect(clock.delays).toHaveLength(GUARD_FETCH_ATTEMPTS - 1);
+ });
+
+ test("a client error other than 429 is not retried", async () => {
+ const stub = stubFetch([status(404)]);
+ const clock = recordingSleep();
+ await expect(fetchGuardFile(PATH, { fetch: stub.fetch, sleep: clock.sleep })).rejects.toThrow(
+ /HTTP 404 after 1 attempt/,
+ );
+ expect(stub.calls()).toBe(1);
+ expect(clock.delays).toEqual([]);
+ });
+});
diff --git a/uv.lock b/uv.lock
index 1783e9aa..b93f2d89 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.62.0"
+version = "1.63.0"
source = { editable = "." }