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: note-change truth maintenance for links, index freshness and entity anchoring (#268)
Serg Eroshe9e5798204842
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex bdc04eea..404354ea 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.88.0",+ "version": "1.89.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 1602759b..4f9dadd0 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.88.0",+ "version": "1.89.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8bbac216..ca2b4bf1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,24 @@ 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.89.0] - 2026-10-19++Open Second Brain 1.89.0 makes the derived truth follow the note write. A rename or move rewrites the inbound links it touches to the shortest spelling that still resolves, repairs the bare-name links its carrier-count change would silently repoint, and claims one detached search-index refresh the moment the write lands, so the staleness window starts closing at the write instead of at the next search. Entity anchoring matches the spelling a fact actually uses - "Ada Lovelace" anchors a registry entity reachable as "ada-lovelace" - while a leading-edge word-boundary rule stops the matcher from anchoring inside other words without silencing the inflected forms a token boundary admits. And the anchors a fact carries can follow its source page's outbound links: the anchoring kernel accepts caller-resolved link-derived ids, and a fifth maintenance lane task, `relink`, re-anchors the extracted signals already stored - every lane pass reports what the task would add, and the stored lines change only when the run asks for it.++### Fixed++- **Entity anchoring matches the spelling a fact uses, and stops matching inside other words.** The anchoring kernels compared literal normalized substrings: a fact saying "Ada Lovelace" never anchored an entity whose forms are "ada-lovelace" or "people/ada_lovelace", while a short form anchored inside any word that contained it - "Canada" anchored "Ada". Both sides of every comparison now expand through one pure match-form generator: runs of space, hyphen and underscore are interchangeable, so the spaced, hyphenated, underscored and slug-prefixed spellings of a name are one match class; a slug-prefixed form also matches at its path-segment boundary, the segment prefix being registry decoration rather than part of the mentioned name, and the tail spelling is minted only when that prefix is one of the registry's entity-type folders - the same vocabulary the registry mints entity ids and the merge guard's guarded categories from - so `people/ada_lovelace` answers `Ada Lovelace` while a slash-bearing form like `Warner/Chappell` never anchors through a bare `Chappell`; and an occurrence anchors only when no letter or digit sits directly before it - the leading edge - while the trailing side stays open, a trailing character being an inflection until proven otherwise, so the Russian accusative `Ивана`, the German genitive `Annas` and a Korean particle run like `김철수는` anchor again; the adjacency of a script written without word spaces (Han, kana, Thai, Lao, Khmer, Myanmar) suspends the requirement, because there adjacency carries no boundary information, and a leading Hangul letter still blocks, Korean attaching no prefixes. The leading edge is what preserves the precision fix: the fold still never plants a mid-word hit literal matching did not already have - `Canada` never anchors `Ada`. Forms are precomputed once per capture and each text expands once, not once per entity; identity keys are untouched - two spellings can remain two entities and one match class - and the merge guard and the contamination check adopt the shared rule verbatim, so the guard that vetoes a merge cannot disagree with the anchoring that fed it.+- **A rename can no longer silently repoint the bare-name links it never rewrote.** A bare spelling resolves only while exactly one nested note carries it, so a rename that brings a second carrier into the vault - another note moved onto a basename a unique bare spelling already resolved to - turned every `[[spelling]]` aimed at the note that never moved into a link that resolves to neither, and nothing said so: the rewrite pass only touched links that named the moved note. Those third-party links are now repaired in the same pass, retargeted to the minimal unambiguous spelling of their pre-rename target through the same chooser and resolution ladder as the main rewrite; a repair that would write the spelling it already has is dropped, and everything unprovable stays untouched - a spelling several notes carried before the move was already ambiguous, a spelling with no carrier was already dangling, and a top-level note keeps owning its bare spelling through the exact-path rung whatever the nested count becomes.++### Changed++- **Inbound wikilinks a relocation rewrites come out no longer than the vault still needs.** The rewrite preserved each link's original spelling form, so a full-path link was rewritten to the new full path even where the bare basename would have resolved to the same note. Every old spelling of the source now collapses onto the one shortest form that still resolves to the destination under the store's own read-time resolution ladder - exact path first, then a bare basename (a top-level note owns its bare spelling outright, whatever nested notes also carry it), then a bare basename carried by exactly one nested note - so `[[Projects/Old]]` comes out `[[New]]` when `New` is unambiguous and `[[Projects/New]]` only when it is not. The chooser mirrors the index's resolution rung for rung, so a spelling it calls minimal is a spelling search resolves to the same document; an ambiguous spelling is never an answer - it falls through to the next-longer form - and ambiguous basenames stay withheld exactly as before.++### Added++- **An applied note write claims one detached index refresh, and the receipt names the claim and, on a refusal, the reason.** The derived search index was only as fresh as its last indexing pass: a rename's receipt said so honestly, and the window stayed open until the next search happened to freshen on read. Applied note writes now claim one detached, claim-guarded incremental refresh through the freshen-on-read machinery - create, content edit and append alongside the four lifecycle operations (rename, move, archive, delete; a batch write's operations do not claim yet) - forced past the freshness interval because the write just aged the stamp, so the window starts closing at the write itself. The claim is the reader path's, verbatim: the same claim file, so a write's refresh and a reader's freshen exclude each other, and a write arriving while a run holds the claim starts nothing of its own but leaves a durable pending marker, which the running pass settles with one extra bounded incremental pass before it releases the claim - bounded at one, never a loop, so a write landing mid-refresh is picked up by that pass instead of staying stale for a whole interval. It is a report, not an invariant: `claimed` says a run is in flight, never that it has landed, and every refusal - `search_freshen_interval_s: 0`, another run holding the claim, no index to refresh, a failed spawn - answers `not_claimed` with the freshen machinery's own reason surfaced beside the token: `index_refresh_reason` on the create, update and append results, `refresh_reason` on the lifecycle receipts (the CLI's JSON and the MCP result, with the CLI's prose rendering it in parentheses beside the token), so a refusal names which refusal it was; the index evidence's next command remains the way the index reconciles. The CLI and the MCP note-lifecycle results carry the token beside the index evidence, the create and update receipts carry it under the same vocabulary, and both now expose the rewritten spellings the pass applied.+- **Link-derived fact anchors, and a `relink` lane task that reports the re-anchoring the stored signals need and applies it on request.** A fact extracted from a source page anchored only to the entity names its own sentence used, so a page about an entity it linked but never named wrote signals that never reached that entity's recall surface. The anchoring kernel unions caller-resolved link-derived entity ids into the stored `entities:` line ahead of the text-derived anchors, the first body-order link leading when both mechanisms match the same fact: a page-sourced caller maps the page's outbound wikilinks through a resolver that answers the entity id (with or without the `.md` suffix), the entity page's own vault path, the slug-prefixed spelling folded and case-folded the way ids are minted, and a frontmatter alias no other visible entity claims - a directory-prefixed spelling answers only as that path rather than by basename, an alias two visible entities claim stays unresolved instead of first-wins, the captured link target is trimmed before the rungs answer it, the pages the caller's reach refuses are dropped before any id is produced, and the resolver answers empty rather than throwing when nothing resolves; a session-sourced capture passes nothing and writes byte-identical signals. Write-time attachment has no shipped caller yet - the extraction call exposes the seam and nothing threads it on the write path - so the path extracted signals actually gain link-derived anchors through is the maintenance lane: a fifth lane task, `relink`, recomputes the anchors of the extracted signals already stored with the shipped matchers and the same resolver, and unions them into the stored line additively. The resolution binds at the reach of each signal itself - a remotely readable signal only receives ids whose entity and source pages are readable at remote reach, a local-only signal keeps the lane's reach, a withheld page is skipped - acts only on server-stamped extracted signals, never on a caller-supplied pointer, and the rewrite touches only the extractor's own raw shape: a codec-compressed raw, a drifted page and a Raw holding anything but the extractor's one `entities:` line are skipped, never written. An anchor already stored is never removed, a signal without a Raw section is counted by neither arm because the rewrite could not store the addition, and the default arm is a dry run that writes nothing, not even the skip-audit log the shared anchorable build stamps on the write path. Every lane pass reports per source page what the task would add, and the stored lines are rewritten only when the run asks for it with `--relink-apply`, or `relink_apply` over MCP, each addition written only where the signal's own reach allows it, never calling a model.+## [1.88.0] - 2026-10-17Open Second Brain 1.88.0 repairs split entity pages behind a preview-and-apply gate, folds the write ledger into one destination-keyed view, and catches an agent up on the log lines its peers appended while it was away. `brain entity merge` plans the repair, echoes the plan's hash and applies only when the live vault still produces the plan the caller read - the dropped page archived behind a recovery point, its name kept as an alias on the survivor. `o2b brain writes destinations` and the new `brain_write_destinations` tool answer which destinations the recorded writes touched, across both recorded write kinds, each row saying what its rows cover. An opt-in SessionStart lane hands the agent the log lines other agents appended since its last look on this device. Every lane that injects memory at session start now neutralizes what it hands over and frames it under the clause that says what the span is - records for the foreign lanes, binding working-style guidance for the memory lanes - and note listings order the same on every host, "note 2" before "note 10". Exports speak OKF v0.2 beside the Open Second Brain dialect while the importer accepts both, and Hermes discovers the memory provider through a declared package entry point.@@ -8647,6 +8665,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.89.0]: https://github.com/itechmeat/open-second-brain/compare/v1.88.0...v1.89.0[1.88.0]: https://github.com/itechmeat/open-second-brain/compare/v1.87.0...v1.88.0[1.87.0]: https://github.com/itechmeat/open-second-brain/compare/v1.86.2...v1.87.0[1.86.2]: https://github.com/itechmeat/open-second-brain/compare/v1.86.1...v1.86.2diff --git a/docs/architecture.md b/docs/architecture.mdindex d8a2a625..36563b23 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -265,7 +265,7 @@ writes it, and they act only on a path the caller named.Three architectural invariants:-- **Filesystem-first.** No database, no daemon. Every artifact is plain Markdown with YAML frontmatter; backup is `cp -r` or `tar`. Background work is started only by agent activity and exits when done: the search index is refreshed by a short detached run a stale read starts (freshen on read), never by a resident process.+- **Filesystem-first.** No database, no daemon. Every artifact is plain Markdown with YAML frontmatter; backup is `cp -r` or `tar`. Background work is started only by agent activity and exits when done: the search index is refreshed by a short detached run a stale read starts (freshen on read) - an applied note-lifecycle write claims one the same way - never by a resident process.- **Deterministic core.** The `dream` algorithm is a pure function of inputs (signals, preferences, log, configuration, current time). No LLM calls inside the core. Semantic merging, if needed, is delegated to external agents via the same CLI / MCP surface. External judgment (the bench judge, the hygiene conflict resolver) goes through one sanctioned fail-open boundary: the operator-configured command bridge (`src/core/reliability/command-bridge.ts`).- **Pre-run snapshot + atomic per-file writes.** Each `dream` run takes a `.snapshots/<run_id>.tar.zst` before any state change (streamed through a staging file, and published under its final name only once complete); per-file writes go through `fs-atomic` (temp + rename). Combined with retention of the most-recent N snapshots, this gives reversible, audit-friendly mutation.diff --git a/docs/brainstorm/note-change-truth-maintenance/cli-output/claude.md b/docs/brainstorm/note-change-truth-maintenance/cli-output/claude.mdnew file mode 100644index 00000000..2b262f67--- /dev/null+++ b/docs/brainstorm/note-change-truth-maintenance/cli-output/claude.md@@ -0,0 +1,38 @@+### Variant 1: Detached refresh claims, contract-preserving write side+- **Approach**: After an applied `noteLifecycle` write, the lifecycle path reuses the freshen machinery (the `FRESHEN_CLAIM_FILE` single-runner claim, backoff state, a `decideFreshen`-style pure decision) through the same deferred dynamic import `readIndexEvidence` already established, spawning one detached low-priority incremental `indexVault` run; `IndexEvidence` gains a "refresh claimed" reporting arm so the honesty contract is upgraded rather than inverted - the index stays a reported fact and the report now names the run converging it. The rewrite policy extends `retargetsFor` and `decideBasename` with a pure minimal-spelling ladder over the already-scanned population (emit the shortest of full-path/suffix-less/basename spellings that resolves to exactly one note under the store's exact-one rule), plus a third-party repair arm that fires only when the rename provably changes a bare link's resolution (pinning it to the minimal spelling of its single pre-rename target), while `decideBasename`'s ambiguous withholding stays untouched. Separator tolerance lands inside the pure kernel as a separator-insensitive occurrence matcher in `anchorEntityForms` (form spaces match runs of space, hyphen or underscore in the haystack; slug-prefixed occurrences match at a `/`-segment boundary), keeping `normalizeEntityName` identity keys unchanged so registry duplicate refusal, doctor lints and search alias expansion see no identity change. Link-derived attachment is threaded through `opts`: extraction callers resolve the source page's outbound links server-side from note bytes and pass candidate entity ids into `decomposeAtomicFacts`, and a relink verb recomputes anchors for stored facts through the same kernel and lexicon (`resolveEntityLexicon`) with the new matcher, writing only additional anchors at no model cost.+- **Trade-offs**:+ - Pro: honors the acyclic-import ratchet with the exact precedent (`readIndexEvidence`) the tree already endorses; no new static edges, no new dependencies.+ - Pro: honesty contract preserved and strengthened; behavior-preserving defaults hold (ambiguous basenames still withheld, repair only under provable rules, `MIN_ANCHOR_FORM_LENGTH` still gates matching).+ - Pro: kernel stays pure text; relink is deterministic, model-free, and testable with plain bun test in a temp vault.+ - Con: the detached run still takes time, so a read issued immediately after a write can beat the run and answer stale - a narrower window than today, but not zero.+ - Con: the minimal-spelling ladder duplicates, in pure form, resolution semantics the index store also implements, so the two must be kept aligned by shared fixtures.+ - Con: separator-insensitive matching widens anchor recall, so some facts gain anchors literal matching never gave them; precision needs explicit test coverage.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Maintained invariant index with identity-level fold+- **Approach**: Define a write-to-index port (interface plus no-op default) in the Brain tree, implemented by the search barrel and injected at the MCP/CLI seam so no static edge exists, and have every applied lifecycle write synchronously update just the touched document's rows in the links table under the existing writer lock and guarded-write rules; `IndexEvidence` becomes a maintained-invariant report ("current" or "degraded") and the module doc's honesty contract is rewritten. Minimal-spelling rewriting and third-party repair then resolve against the index's stored links table via `resolveLinkTargets` as the single authority, eliminating the duplicated ladder because rewrite, repair and reporting read one source. Separator folding moves into `normalizeEntityName` itself, making "foo-bar", "foo bar" and "foo_bar" one identity everywhere at once (duplicate refusal, alias resolution, search alias expansion, anchoring), with a one-time migration re-keying stored identities and a relink pass riding the same migration. Link-derived attachment becomes a maintained page-to-entity edge written by extraction alongside anchors and backfilled by the migration, so relink is a materialization of an invariant rather than a verb.+- **Trade-offs**:+ - Pro: strongest truth guarantee - no staleness window after a write, and no read-side freshen special cases for writes.+ - Pro: one resolution authority for rewrite, repair and reporting; no ladder drift.+ - Pro: separator tolerance arrives globally, so recall, dedup and search all agree on identity.+ - Con: puts an index write on the critical path of every guarded note write; index failure must degrade the lifecycle result without failing it, which is new machinery on the hottest path.+ - Con: needs port/injection discipline to stay inside the ratchet, plus writer-lock contention with the freshen daemon and the watch daemon.+ - Con: the identity fold changes duplicate refusal and stored keys - the wave's largest blast radius - and the "reported fact, not maintained invariant" contract is deliberately abandoned, with carve-outs still needed because deletes rewrite nothing.+- **Complexity**: large+- **Risk**: high++### Variant 3: Convergence-on-read with a shared resolution layer+- **Approach**: The lifecycle path only records a durable dirty marker (a note-change stamp beside `FRESHEN_STATE_FILE`, written through the same deferred dynamic import), and `decideFreshen` is extended so a dirty marker makes any read immediately due, bypassing `search_freshen_interval_s`; `IndexEvidence` reports "converges on next read" instead of bare stale plus `next_command`. A single pure resolution module is factored out and shared by the rewrite pass, dangling-wikilink listing and unlinked mentions: it computes minimal resolving spellings over a walked population and applies the proven-safe third-party repair rule, so resolution and rewriting cannot disagree. Separator tolerance lives in that shared layer and in the anchoring gate as match-time folding, leaving stored identities untouched. Link-derived attachment is a read-time projection over the links table plus stored fact texts, exposed through the claim-graph projection, with a relink verb that materializes the projection into stored anchors deterministically and without a model.+- **Trade-offs**:+ - Pro: write path stays minimal - one tiny marker write, no index coupling, no ratchet pressure beyond the existing deferred import.+ - Pro: the shared resolution layer is the wave's best structural payoff: one ladder behind rewrite, dangling listing and unlinked mentions permanently.+ - Pro: no migration of stored rows; folding and projected attachment are pure additions.+ - Con: the first read after a write still answers from the stale index while the detached run completes - exactly the window card t_c256d428 targets survives in weakened form.+ - Con: freshness semantics become conditional (interval OR dirty) and spread across read sites, diluting the single-result honesty story.+ - Con: read-time attachment means anchored recall differs between paths that materialize and paths that project unless every consumer adopts the projection.+- **Complexity**: medium+- **Risk**: medium++### Recommended: Variant 1+**Rationale**: It is the only variant that starts closing the staleness window at the moment it is created - the write itself claims the refresh - while keeping the module's hard-won honesty contract intact: the index remains a reported fact and the report simply gains the claim. It respects every structural invariant with precedents already in the tree, using the deferred dynamic import the ratchet already tolerates, the freshen claim-file pattern for detached single-runner refresh, and a pure kernel that gains a matcher rather than new identity semantics, so no stored-key migration touches the registry, doctor or search alias expansion. Variant 2 buys a stronger invariant at the cost of an index write on the guarded-write critical path, an injection seam, and the wave's largest migration blast radius, while Variant 3 leaves the very post-write staleness window the spine targets and disperses freshness semantics across read sites. Variant 1's duplicated minimal-spelling ladder is its main liability, and it is containable with the plain bun test fixtures and shared resolution fixtures the project already standardizes on.diff --git a/docs/brainstorm/note-change-truth-maintenance/cli-output/prompt.md b/docs/brainstorm/note-change-truth-maintenance/cli-output/prompt.mdnew file mode 100644index 00000000..c7025cf4--- /dev/null+++ b/docs/brainstorm/note-change-truth-maintenance/cli-output/prompt.md@@ -0,0 +1 @@+consultant prompt (phase 0): three architectural variants for the four-card wave note-change truth maintenance; task bodies in task-bodies.md; project context: Open Second Brain, TypeScript on Bun, kernel never calls a model, acyclic-import ratchet, no new runtime dependencies; required output format: exactly 3 variants (Approach/Trade-offs/Complexity/Risk) plus one Recommendation.diff --git a/docs/brainstorm/note-change-truth-maintenance/cli-output/task-bodies.md b/docs/brainstorm/note-change-truth-maintenance/cli-output/task-bodies.mdnew file mode 100644index 00000000..ea5d5029--- /dev/null+++ b/docs/brainstorm/note-change-truth-maintenance/cli-output/task-bodies.md@@ -0,0 +1,56 @@+===== t_c256d428 (priority 3) [upstream:iwe] Keep backlinks and link resolution current as notes change+**Source**: https://github.com/iwe-org/iwe/releases/tag/iwe-v0.27.0+**Repo**: iwe-org/iwe (1086 stars)+**Released**: iwe-v0.27.0 (2026-10-16T11:20:03Z)+## What+When a note is created, moved or deleted, every link and backlink that mentions it should keep resolving without anyone re-saving or re-indexing the linking note. Open Second Brain's brain_backlinks aggregator already recomputes live, but the derived search index that backs link resolution, dangling-wikilink listing and unlinked mentions goes stale after a brain_note_lifecycle write and stays stale until a manual reindex (the tool reports next_command instead of refreshing).+## Why useful for Open Second Brain+Agents rename and reorganize vault notes constantly through brain_note_lifecycle; a stale index makes recall and hygiene queries answer from pre-move addresses and reports links as dangling that are not. Resolution against the current document set removes a manual `o2b search index` step from every reorganization flow and removes the window where the agent reasons over outdated graph answers.+## Status in Open Second Brain+- **Verdict**: present_weaker+- **Evidence**: live side: src/core/brain/backlinks.ts:15-17 ("The index is recomputed on demand (no on-disk cache)") served by brain_backlinks at src/mcp/brain/query-tools.ts:518. Stale side: src/core/brain/notes/lifecycle.ts:31-33 ("the derived index still holds the old path until something re-indexes"); readIndexEvidence at src/core/brain/notes/lifecycle.ts:573-598 returns INDEX_EVIDENCE.stale with nextCommand: REINDEX_COMMAND, surfaced as index.state/next_command in src/mcp/brain/lifecycle-file-tools.ts:86-88; index-backed resolution is SQL over stored rows at src/core/search/store/links.ts:108 (resolveLinkTargets). The only freshness mechanism is the opt-in daemon `o2b search watch` (src/cli/search/verbs/watch.ts:1-7).+## Notes+Upstream change is internal to liwe (links resolved against current documents on every read) plus the workspace/inlayHint/refresh LSP notification; the transferable idea is auto-refreshing (or live-resolving) the derived index after note file changes. Slot-in: trigger the existing incremental indexVault pass at the end of an applied noteLifecycle, or resolve search-layer links live the way buildBacklinkIndex does.++===== t_5914c4c1 (priority 3) [upstream:iwe] Rewrite inbound wikilinks on rename with minimal, target-safe spellings+**Source**: https://github.com/iwe-org/iwe/releases/tag/iwe-v0.27.0+**Repo**: iwe-org/iwe (1086 stars)+**Released**: iwe-v0.27.0 (2026-10-16T11:20:03Z)+## What+A rename or move should leave links that still resolve untouched, rewrite the rest to the shortest spelling that resolves (not the full path), and repair third-party bare-name links that would silently start pointing at the renamed note. Open Second Brain's brain_note_lifecycle rewrites inbound links but preserves each link's spelling form (path links stay full-path), and it withholds ambiguous bare-basename rewrites entirely, leaving them unresolved, rather than repairing links whose target silently changes.+## Why useful for Open Second Brain+Rename and move are the note operations agents get wrong most often; tidier rewritten spellings keep vaults grep- and Obsidian-friendly after agent reorganizations, and repairing would-be-retargeted links keeps references pointing at what the author meant instead of stranding them as unresolvable basenames that every later tool must special-case.+## Status in Open Second Brain+- **Verdict**: present_weaker+- **Evidence**: retargetsFor at src/core/brain/notes/lifecycle.ts:1161-1174 rewrites path-form spellings to path-form (form-preserving, never shortest); decideBasename at src/core/brain/notes/lifecycle.ts:702-720 returns BASENAME_REWRITE.ambiguous and withholds the bare-basename rewrite when the destination basename is already carried elsewhere, per the rationale at lifecycle.ts:40-48 (an ambiguous basename resolves to nothing by the exact-one ladder). Tool surface: src/mcp/brain/lifecycle-file-tools.ts:351 ("Rewrites [[links]]"). not found - any shortest-resolving-name spelling policy: rg -i "shortest" over src matches only src/core/brain/wikilink.ts:86 (fence-run logic, unrelated); not found - any rewrite of third-party links to preserve targets across an ambiguous rename.+## Notes+Open Second Brain's withholding stance is a deliberate safety choice; upstream instead actively fixes the third-party link so it keeps its target. Both behaviors (shortest-form output, retarget repair) are small, well-scoped extensions of retargetsFor/decideBasename.++===== t_8c72a23e (priority 3) [upstream:gbrain] Entity resolution that skips retired pages, follows successors and normalizes alias spellings+**Source**: https://github.com/garrytan/gbrain/releases/tag/v0.60.283.0+**Repo**: garrytan/gbrain (18439 stars)+**Released**: v0.60.283.0 (2026-10-17T09:47:19Z)+## What+When extraction writes facts about a person or company, upstream never lets a fuzzy or name-word guess land on a retired or superseded page, resolves a direct reference to a retired page through its superseded_by or merged_into chain to the live page, and matches aliases whether the name words are joined by spaces, hyphens, underscores or a slug directory prefix.+## Why useful for Open Second Brain+Open Second Brain anchors extracted facts to entity ids at write time, so an anchoring or recall path that could pick a retired alias page would silently pool facts on a dead record. Separator-tolerant alias matching matters because vault prose writes one name as "Ada Lovelace", "ada-lovelace" and "ada_lovelace", and today those are three distinct identities.+## Status in Open Second Brain+- **Verdict**: present_weaker+- **Evidence**: Retired-page exclusion already holds: src/core/brain/entities/status-scope.ts:14-15 restricts identity-holding to active records and the same canonical scope gates every name and alias resolution; src/core/brain/atomic-facts.ts:129-133 skips entities outside canonical scope before matching; src/core/brain/link-graph/alias-index.ts:90 reserves retired canonical names. Gaps: src/core/brain/entities/canonical.ts:5-8 normalizes only NFC, case, whitespace and quote variants, so separator-joined spellings stay distinct; src/core/brain/lifecycle/tombstone.ts:104 and :229-235 store the superseded_by pointer but no resolution path follows it automatically - it is reachable only through the claim-graph projection (src/core/brain/claim-graph.ts:277, exposed as the replaced operation at src/mcp/brain/knowledge-tools.ts:862).+## Notes+The collected release body is truncated mid-sentence in the itemized alias-matching section (cut at "a folded hi"), so the exact fold list beyond space, hyphen and underscore was not judgeable. Adjacent board card t_fd842db0 covers excluding non-content files from ambiguous link resolution, a different half of resolution hygiene.++===== t_681e498a (priority 3) [upstream:gbrain] Conversation facts anchored to the entity pages they reference, with relink+**Source**: https://github.com/garrytan/gbrain/releases/tag/v0.60.284.0+**Repo**: garrytan/gbrain (18439 stars)+**Released**: v0.60.284.0 (2026-10-17T10:14:19Z)+## What+Facts extracted from meeting and conversation pages upstream now attach to the person or company the page links even when the fact sentence itself does not name them, and a local relink pass attaches historically stored facts the same way at no model cost.+## Why useful for Open Second Brain+Open Second Brain anchors extracted assertions only when a normalized name or alias form literally appears in the anchor text, so a meeting note that refers to a person as "she" or "the founder" leaves the fact unanchored, and there is no bulk way to re-anchor stored facts after aliases improve.+## Status in Open Second Brain+- **Verdict**: present_weaker+- **Evidence**: src/core/brain/atomic-facts.ts:124-134 anchorEntities matches only normalized name and alias forms against the assertion text and only for entities in canonical scope. not found - no link-derived or page-level fact attachment and no bulk relink of stored facts to entities (rg -i 'relink' over src and tests: only note-move inode relinking at src/core/brain/destructive-sites.ts:423 and src/core/brain/notes/lifecycle.ts:807).+## Notes+Adjacent board card t_13ca52c4 covers meeting attendance determination (attendee versus merely mentioned), a different precision problem from fact-to-entity attachment. A link-derived attachment pass must re-derive links server-side from note bytes, per the kernel invariant that server-derived facts outrank caller-supplied claims.+diff --git a/docs/brainstorm/note-change-truth-maintenance/design.md b/docs/brainstorm/note-change-truth-maintenance/design.mdnew file mode 100644index 00000000..64c75d68--- /dev/null+++ b/docs/brainstorm/note-change-truth-maintenance/design.md@@ -0,0 +1,56 @@+# Note-change truth maintenance - derived knowledge follows note writes++**Status:** draft+**Author:** orchestrator (via feature-release-playbook, host-mode wave cycle-20261019)+**Audience:** implementation+**Kanban cards:** t_c256d428, t_5914c4c1, t_8c72a23e, t_681e498a++## Problem statement++When a note is created, renamed or deleted, everything derived from it quietly diverges: the derived search index keeps the old path until the next search happens to notice (freshen-on-read heals it within about a minute of a later read, and only then); inbound wikilinks are rewritten preserving their original spelling form, so links grow longer than they need to be and ambiguous bare names are withheld entirely; extracted facts anchor to entity pages only through literal normalized substrings, so "Ada Lovelace" in a fact never anchors a page reachable as "ada-lovelace", and a fact extracted from a page that links an entity never attaches to that entity unless the sentence names it.++## Scope++- F1 (t_5914c4c1): on rename/move, inbound wikilinks are rewritten to the minimal spelling that still resolves to the destination under the store's exact-one rule; third-party bare-name links whose resolution the rename provably changes are repaired to the unambiguous spelling of their pre-rename target. Ambiguous-basename withholding stays.+- F2 (t_c256d428, reshaped by premise verification): an applied note lifecycle write spawns one detached, claim-guarded incremental index refresh (the freshen-on-read pattern, force-claimed), so the staleness window starts closing at the write instead of at the next search. The index stays a reported fact: the honesty contract sentences are updated to describe the claim, not to declare an invariant.+- F3 (t_8c72a23e residue): separator-tolerant alias matching in the two anchoring kernels: anchor forms match runs of space, hyphen or underscore in the haystack, and slug-prefixed forms match at a path-segment boundary. Identity keys (normalizeEntityName) are untouched.+- F4 (t_681e498a): link-derived fact attachment: extraction callers resolve the source page's outbound links server-side and pass candidate entity ids into the extraction call; the kernel unions them into the text-derived anchors (first body-order entity link wins as primary; all matches anchor, matching today's multi-name behavior). A fifth maintenance lane task recomputes anchors for page-sourced signals additively (never removes), dry-run by default, local reach only.++## Out of scope++- Following superseded_by/merged_into chains in anchoring (refuted: write-side anchoring already filters ENTITY_STATUS_SCOPE.canonical; recall already follows successor chains at post-rank.ts:179-201).+- Any write-to-index hook on the synchronous write path (Variant 2 rejected: index write on the guarded-write critical path).+- Turning IndexEvidence into a maintained invariant; changing normalizeEntityName identity keys; any stored-key migration.+- Source-kind expansions, search-language changes, unlinked-mentions indexing (it is a live directory walk, not index-backed).++## Chosen approach++Variant 1 of the consultant's three ("Detached refresh claims, contract-preserving write side"), agreed by the orchestrator: the wave starts closing the staleness window at the write while preserving the module's honesty contract; the acyclic-import ratchet is honored through the deferred dynamic import readIndexEvidence already established (lifecycle.ts:569-576); the anchoring kernel stays pure text and gains match forms, not new identity semantics; link-derived attachment is threaded by callers into the existing persistence shape (`entities:` ids), so no new store.++## Design decisions++1. Freshness: reuse freshen claim/state/child argv verbatim (freshen.ts:166-214); add a force path bypassing the interval gate (MaybeFreshenOptions); the spawn happens inside noteLifecycle before finish via an injectable spawn seam (pattern: search.ts:444); `search_freshen_interval_s: 0` disables the post-write refresh as it disables freshen-on-read; the spawn is fire-and-forget and never fails the write.+2. Minimal spelling: a pure chooser `minimalSpellingFor(destinationRel, knownFiles)` hosted as a core/brain leaf beside link-graph/format-wikilink.ts. Predicate: the shortest of basename / suffix-less / full relPath whose exact-one resolution over the walked file population equals the destination, mirroring RESOLVED_LINK_TARGET_SQL's rungs (store/links.ts:62-70). Rung 2 lets a top-level basename win over a nested one; the chooser encodes that rule, and shared fixtures pin chooser and ladder agreement.+3. Third-party repair: the pre-rename counting probe (.files, lifecycle.ts:920-924) gives carrier counts; post-state is derivable (the rename moves exactly one carrier). When a bare spelling's carrier count goes 1 -> 2 (or more), links using it are retargeted to the minimal unambiguous spelling of the pre-rename target. Only provable changes are repaired; everything else stays.+4. Separator tolerance: new pure match-form generator in canonical.ts beside foldQuoteVariantsByClass, applied to BOTH the needle and the haystack at match time (folding only the needle matches nothing); forms Set-deduped; MIN_ANCHOR_FORM_LENGTH still gates; twins (merge-guard.ts:59-75, contamination.ts:53-57) updated in the same commit to stay in sync.+5. Link-derived attachment: callers (ingestSource, the page-sourced decompose path) read the source page's outbound wikilinks from bytes (extractWikilinks, order-preserving), map them to canonical entity ids server-side, and pass the ordered id list into the extraction call; the kernel unions link-derived ids after text matches. Primary entity = first body-order entity link (precedent: ingest summary ordering). Withheld entity pages are dropped before attachment (link-candidates precedent: drop before counting), and anchors stay subject to read-time visibility as today.+6. Relink: fifth LANE_TASK in the unattended maintenance lane (lane.ts:208-242), MAINTENANCE_LANE_REACH=local, additive-only anchor writes over page-sourced signals, dry-run report by default with an apply flag (doctor repair-lane precedent), never calls a model.++## File changes++- src/core/brain/notes/lifecycle.ts (freshness spawn seam, retargetsFor minimal spellings, repair arm, contract doc sentences)+- src/core/search/freshen.ts (force option, spawn-seam export)+- src/core/brain/link-graph/ (new minimal-spelling chooser leaf + fixtures)+- src/core/brain/page-dedup.ts (shared rewrite helpers if the repair arm needs them)+- src/cli/brain/verbs/note-lifecycle.ts, src/mcp/brain/lifecycle-file-tools.ts (report fields)+- src/core/brain/entities/canonical.ts (match-form generator), src/core/brain/atomic-facts.ts, src/core/brain/fact-extract.ts (kernels), src/core/brain/truth/merge-guard.ts, src/core/brain/truth/contamination.ts (twins)+- src/core/brain/ingest/ingest.ts, src/cli/brain/verbs/facts.ts, src/core/brain/intake/extract-intake.ts (caller threading)+- src/core/brain/maintenance/lane.ts + new relink task file+- tests/ mirroring each of the above; docs touched by osb-pr-prepare's docs lane.++## Risks and open questions++- The chooser duplicates resolution semantics in pure form; alignment is pinned by shared fixtures, and a drift test compares chooser output against a temp-vault index build.+- The post-write refresh narrows but does not close the staleness window (a read between write and refresh completion still answers stale); the report now names the pending claim.+- Separator folding widens anchor recall; precision coverage is explicit in the test plan (no test pins mid-word false positives today, "ada" already matches "canada" - folding must not make that worse).+- Lane 3's optional parameter on the extraction call lands after Lane 2's kernel commits (file overlap on fact-extract.ts).diff --git a/docs/brainstorm/note-change-truth-maintenance/plan.md b/docs/brainstorm/note-change-truth-maintenance/plan.mdnew file mode 100644index 00000000..46e4dfb8--- /dev/null+++ b/docs/brainstorm/note-change-truth-maintenance/plan.md@@ -0,0 +1,82 @@+# Note-change truth maintenance - implementation plan++Lanes are file-disjoint except where a Depends on names an upstream lane; the+extraction-call parameter (D2) lands after Lane 2's kernel commits. Every task:+failing test first, implement to green, refactor green, one conventional commit,+formatted and linted before the commit. Test runs use a throwaway HOME.++## Lane 1 - links and index freshness (F1 + F2)++### Task A1: minimal-spelling chooser+- **Files**: src/core/brain/link-graph/minimal-spelling.ts (new), tests/core/brain/link-graph/minimal-spelling.test.ts (new)+- **Acceptance**: `minimalSpellingFor(destinationRel, knownFiles)` returns the shortest of basename / suffix-less / full relPath whose exact-one resolution over knownFiles equals the destination; top-level basename beats nested (ladder rung 2); ambiguity returns the next-longer form, never a wrong one. Unit tests over nested and top-level populations.+- **Depends on**: none++### Task A2: ladder-agreement fixture+- **Files**: tests/core/brain/link-graph/minimal-spelling.test.ts (extended)+- **Acceptance**: a fixture builds a temp vault, indexes it, and asserts the chooser's spelling resolves through the store ladder (resolveLinkTargets) to the same document for every population shape in A1.+- **Depends on**: A1++### Task A3: retargetsFor emits minimal spellings+- **Files**: src/core/brain/notes/lifecycle.ts, tests/core/brain/notes/note-lifecycle.test.ts, tests/core/brain/notes/note-lifecycle-defects.test.ts+- **Acceptance**: on rename, a full-path inbound link is rewritten to the minimal resolving spelling; report field rewrittenSpellings records old->new form; deliberately updated pins: spelling-form preservation (note-lifecycle.test.ts:88-114) now asserts minimality; ambiguous destination still withholds (defects.test.ts:191-210 keeps its no-repair assertion only where the repair rule does not fire).+- **Depends on**: A1++### Task A4: third-party bare-name repair+- **Files**: src/core/brain/notes/lifecycle.ts, tests/core/brain/notes/note-lifecycle-defects.test.ts+- **Acceptance**: when a rename moves a bare spelling's carrier count from exactly one to several, existing links with that bare spelling are retargeted to the minimal unambiguous spelling of the pre-rename target; the pre-state comes from the counting probe; unprovable cases stay untouched; defects.test.ts:279-303 self-reference counting still holds.+- **Depends on**: A3++### Task A5: freshen force path+- **Files**: src/core/search/freshen.ts, tests/core/search/freshen.test.ts+- **Acceptance**: MaybeFreshenOptions gains force (bypasses the interval gate, keeps claim exclusivity, backoff and the writer-lock probe); interval 0 with force still refuses (config off means off); existing decideFreshen pins stay green.+- **Depends on**: none++### Task A6: post-write detached refresh+- **Files**: src/core/brain/notes/lifecycle.ts, tests/core/brain/notes/note-lifecycle.test.ts, tests/core/brain/notes/note-lifecycle-defects.test.ts+- **Acceptance**: an applied lifecycle write (move and delete arms) spawns one detached refresh through an injectable spawn seam via the deferred dynamic import; claim exclusivity prevents doubles; spawn failures never fail the write; contract doc sentences (lifecycle.ts:26-33) describe the claim; readIndexEvidence pins stay green; tests run with the freshen-off env and assert the seam was called with the force option.+- **Depends on**: A5, A4 (same file, sequential in-lane)++### Task A7: CLI/MCP report shapes+- **Files**: src/cli/brain/verbs/note-lifecycle.ts, src/mcp/brain/lifecycle-file-tools.ts, tests/cli/brain-note-lifecycle.test.ts, tests/mcp/note-lifecycle.test.ts+- **Acceptance**: the CLI and MCP results expose the new rewritten spellings and the refresh-claimed marker; shape tests updated.+- **Depends on**: A6++## Lane 2 - separator-tolerant anchoring (F3)++### Task B1: match-form generator+- **Files**: src/core/brain/entities/canonical.ts, tests/core/brain/entities/entities.canonical.test.ts+- **Acceptance**: a pure generator beside foldQuoteVariantsByClass expands one normalized form into separator-variant match forms (space/hyphen/underscore runs interchangeable; slug-prefixed form also matches at a path-segment boundary); MIN length rules preserved; identity keys untouched (quote-variant-fold and topic-key-quote-classes byte-stability pins stay green).+- **Depends on**: none++### Task B2: kernels adopt folded matching+- **Files**: src/core/brain/atomic-facts.ts, src/core/brain/fact-extract.ts, tests/core/brain/atomic-facts.test.ts, tests/core/brain/fact-extract.anchoring.test.ts, tests/core/truth/stated-claims.test.ts+- **Acceptance**: anchorEntityForms and entityAnchors match folded forms with both sides folded, Set-deduped, forms precomputed once per call; "ada lovelace" in text anchors "ada-lovelace" and "people/ada_lovelace" forms; existing exact-form pins extended, not weakened; precision cases ("canada" never anchors "ada") asserted explicitly.+- **Depends on**: B1++### Task B3: twins in sync+- **Files**: src/core/brain/truth/merge-guard.ts, src/core/brain/truth/contamination.ts, tests/core/brain/truth/merge-guard.test.ts, tests/core/brain/truth/contamination.test.ts+- **Acceptance**: the two inline re-implementations use the same generator; their tests updated in the same commit.+- **Depends on**: B2++## Lane 3 - link-derived attachment and relink (F4)++### Task C1: page-link to entity resolver+- **Files**: src/core/brain/intake/page-entity-links.ts (new), tests/core/brain/intake/page-entity-links.test.ts (new)+- **Acceptance**: given source page bytes and an entity-index accessor, returns the ordered list of canonical entity ids the page links to (extractWikilinks order), dropping withheld pages before returning (link-candidates precedent), and returns empty (never throws) when nothing resolves.+- **Depends on**: none++### Task C2: callers thread link-derived ids+- **Files**: src/core/brain/fact-extract.ts (optional parameter only), src/core/brain/ingest/ingest.ts, src/cli/brain/verbs/facts.ts, tests/core/brain/fact-extract.anchoring.test.ts (extended), tests/core/brain/ingest tests+- **Acceptance**: page-sourced extraction paths resolve link-derived entity ids server-side and pass them in; the persisted `entities:` union contains text-derived plus link-derived ids; a fact from a page linking an entity without naming it gains the anchor; first body-order link is the primary when both mechanisms match; session-sourced extraction without a page passes nothing and is unchanged. Depends on Lane 2's fact-extract.ts commits (kernel union site).+- **Depends on**: C1, B2++### Task C3: relink lane task+- **Files**: src/core/brain/maintenance/lane.ts, src/core/brain/maintenance/relink-anchors-task.ts (new), tests/core/brain/maintenance/relink-anchors.test.ts (new)+- **Acceptance**: fifth LANE_TASK recomputes anchors for page-sourced signals with the shipped rules, additive-only (existing anchors never removed), dry-run report by default with an apply flag, local reach only, never calls a model; lane registration test extended; report includes per-source added-anchor counts.+- **Depends on**: C2++## Integration++- **Integrator**: full gates on the merged branch (fmt, lint, mirrors, sync-version check, openclaw bundle with the CI Bun, targeted suites), disjoint-file ownership respected throughout; commit per atomic unit with `git commit --only <paths>`.+- **Acceptance for the wave**: every new test fails on the pre-fix code where applicable (regression discipline), full bun test suite green locally, no new runtime dependencies, acyclic-import ratchet green (deferred import only).diff --git a/docs/brainstorm/note-change-truth-maintenance/variants.md b/docs/brainstorm/note-change-truth-maintenance/variants.mdnew file mode 100644index 00000000..03360e70--- /dev/null+++ b/docs/brainstorm/note-change-truth-maintenance/variants.md@@ -0,0 +1,46 @@+# Variants considered (consultant output verbatim)++The consultant brainstorm ran per the feature-release-playbook phase 0; the consultant prompt is cli-output/prompt.md and its reply is cli-output/claude.md.++### Variant 1: Detached refresh claims, contract-preserving write side+- **Approach**: After an applied `noteLifecycle` write, the lifecycle path reuses the freshen machinery (the `FRESHEN_CLAIM_FILE` single-runner claim, backoff state, a `decideFreshen`-style pure decision) through the same deferred dynamic import `readIndexEvidence` already established, spawning one detached low-priority incremental `indexVault` run; `IndexEvidence` gains a "refresh claimed" reporting arm so the honesty contract is upgraded rather than inverted - the index stays a reported fact and the report now names the run converging it. The rewrite policy extends `retargetsFor` and `decideBasename` with a pure minimal-spelling ladder over the already-scanned population (emit the shortest of full-path/suffix-less/basename spellings that resolves to exactly one note under the store's exact-one rule), plus a third-party repair arm that fires only when the rename provably changes a bare link's resolution (pinning it to the minimal spelling of its single pre-rename target), while `decideBasename`'s ambiguous withholding stays untouched. Separator tolerance lands inside the pure kernel as a separator-insensitive occurrence matcher in `anchorEntityForms` (form spaces match runs of space, hyphen or underscore in the haystack; slug-prefixed occurrences match at a `/`-segment boundary), keeping `normalizeEntityName` identity keys unchanged so registry duplicate refusal, doctor lints and search alias expansion see no identity change. Link-derived attachment is threaded through `opts`: extraction callers resolve the source page's outbound links server-side from note bytes and pass candidate entity ids into `decomposeAtomicFacts`, and a relink verb recomputes anchors for stored facts through the same kernel and lexicon (`resolveEntityLexicon`) with the new matcher, writing only additional anchors at no model cost.+- **Trade-offs**:+ - Pro: honors the acyclic-import ratchet with the exact precedent (`readIndexEvidence`) the tree already endorses; no new static edges, no new dependencies.+ - Pro: honesty contract preserved and strengthened; behavior-preserving defaults hold (ambiguous basenames still withheld, repair only under provable rules, `MIN_ANCHOR_FORM_LENGTH` still gates matching).+ - Pro: kernel stays pure text; relink is deterministic, model-free, and testable with plain bun test in a temp vault.+ - Con: the detached run still takes time, so a read issued immediately after a write can beat the run and answer stale - a narrower window than today, but not zero.+ - Con: the minimal-spelling ladder duplicates, in pure form, resolution semantics the index store also implements, so the two must be kept aligned by shared fixtures.+ - Con: separator-insensitive matching widens anchor recall, so some facts gain anchors literal matching never gave them; precision needs explicit test coverage.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Maintained invariant index with identity-level fold+- **Approach**: Define a write-to-index port (interface plus no-op default) in the Brain tree, implemented by the search barrel and injected at the MCP/CLI seam so no static edge exists, and have every applied lifecycle write synchronously update just the touched document's rows in the links table under the existing writer lock and guarded-write rules; `IndexEvidence` becomes a maintained-invariant report ("current" or "degraded") and the module doc's honesty contract is rewritten. Minimal-spelling rewriting and third-party repair then resolve against the index's stored links table via `resolveLinkTargets` as the single authority, eliminating the duplicated ladder because rewrite, repair and reporting read one source. Separator folding moves into `normalizeEntityName` itself, making "foo-bar", "foo bar" and "foo_bar" one identity everywhere at once (duplicate refusal, alias resolution, search alias expansion, anchoring), with a one-time migration re-keying stored identities and a relink pass riding the same migration. Link-derived attachment becomes a maintained page-to-entity edge written by extraction alongside anchors and backfilled by the migration, so relink is a materialization of an invariant rather than a verb.+- **Trade-offs**:+ - Pro: strongest truth guarantee - no staleness window after a write, and no read-side freshen special cases for writes.+ - Pro: one resolution authority for rewrite, repair and reporting; no ladder drift.+ - Pro: separator tolerance arrives globally, so recall, dedup and search all agree on identity.+ - Con: puts an index write on the critical path of every guarded note write; index failure must degrade the lifecycle result without failing it, which is new machinery on the hottest path.+ - Con: needs port/injection discipline to stay inside the ratchet, plus writer-lock contention with the freshen daemon and the watch daemon.+ - Con: the identity fold changes duplicate refusal and stored keys - the wave's largest blast radius - and the "reported fact, not maintained invariant" contract is deliberately abandoned, with carve-outs still needed because deletes rewrite nothing.+- **Complexity**: large+- **Risk**: high++### Variant 3: Convergence-on-read with a shared resolution layer+- **Approach**: The lifecycle path only records a durable dirty marker (a note-change stamp beside `FRESHEN_STATE_FILE`, written through the same deferred dynamic import), and `decideFreshen` is extended so a dirty marker makes any read immediately due, bypassing `search_freshen_interval_s`; `IndexEvidence` reports "converges on next read" instead of bare stale plus `next_command`. A single pure resolution module is factored out and shared by the rewrite pass, dangling-wikilink listing and unlinked mentions: it computes minimal resolving spellings over a walked population and applies the proven-safe third-party repair rule, so resolution and rewriting cannot disagree. Separator tolerance lives in that shared layer and in the anchoring gate as match-time folding, leaving stored identities untouched. Link-derived attachment is a read-time projection over the links table plus stored fact texts, exposed through the claim-graph projection, with a relink verb that materializes the projection into stored anchors deterministically and without a model.+- **Trade-offs**:+ - Pro: write path stays minimal - one tiny marker write, no index coupling, no ratchet pressure beyond the existing deferred import.+ - Pro: the shared resolution layer is the wave's best structural payoff: one ladder behind rewrite, dangling listing and unlinked mentions permanently.+ - Pro: no migration of stored rows; folding and projected attachment are pure additions.+ - Con: the first read after a write still answers from the stale index while the detached run completes - exactly the window card t_c256d428 targets survives in weakened form.+ - Con: freshness semantics become conditional (interval OR dirty) and spread across read sites, diluting the single-result honesty story.+ - Con: read-time attachment means anchored recall differs between paths that materialize and paths that project unless every consumer adopts the projection.+- **Complexity**: medium+- **Risk**: medium++### Recommended: Variant 1+**Rationale**: It is the only variant that starts closing the staleness window at the moment it is created - the write itself claims the refresh - while keeping the module's hard-won honesty contract intact: the index remains a reported fact and the report simply gains the claim. It respects every structural invariant with precedents already in the tree, using the deferred dynamic import the ratchet already tolerates, the freshen claim-file pattern for detached single-runner refresh, and a pure kernel that gains a matcher rather than new identity semantics, so no stored-key migration touches the registry, doctor or search alias expansion. Variant 2 buys a stronger invariant at the cost of an index write on the guarded-write critical path, an injection seam, and the wave's largest migration blast radius, while Variant 3 leaves the very post-write staleness window the spine targets and disperses freshness semantics across read sites. Variant 1's duplicated minimal-spelling ladder is its main liability, and it is containable with the plain bun test fixtures and shared resolution fixtures the project already standardizes on.++## Orchestrator decision++Variant 1 adopted. Rationale: it is the only variant that closes the staleness window from the write side while preserving the index-evidence honesty contract, honors the acyclic-import ratchet with the readIndexEvidence precedent, and keeps the anchoring kernel pure without an identity-key migration. Variant 2's synchronous index write on the guarded-write critical path and stored-key migration are the largest blast radius in the tree for this wave's value; Variant 3 leaves the post-write window the spine targets and splits freshness semantics across read sites.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 38f4a550..c6678683 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -481,7 +481,7 @@ o2b brain session-describe Count raw turns and deterministic summary depths fo2b brain session-expand Expand a session recall node to immediate sources and paginated raw turn content (since v0.29.0)o2b brain session-summary write|get|list a session-scoped structured digest (request/decisions/learnings/next_steps) (since v1.11.0)o2b brain idea-lineage Trace how a derived artifact was reached: observation -> synthesis -> conclusion over continuity sourceRefs or belief-evolution (since v1.11.0)-o2b brain note-lifecycle <rename|move|archive|delete> <path> [<to>] [--apply] [--confirm] [--expect N] [--strict] [--json] - note-FILE lifecycle; source and destination both go through the create-note path envelope. Dry-run without --apply; delete also needs --confirm. A relocation rewrites inbound [[wikilinks]] vault-wide (both path spellings always, the bare basename only when exactly one note carries it) and the receipt names how stale the search index still is; delete rewrites nothing, reports the references it strands, and returns a recoverability verdict saying the archive it took does not cover a note outside Brain/+o2b brain note-lifecycle <rename|move|archive|delete> <path> [<to>] [--apply] [--confirm] [--expect N] [--strict] [--json] - note-FILE lifecycle; source and destination both go through the create-note path envelope. Dry-run without --apply; delete also needs --confirm. A relocation rewrites inbound [[wikilinks]] vault-wide to the minimal spelling that still resolves to the destination (the bare basename only when exactly one note carries it; a bare name the rename turns from unique to ambiguous is repaired to the unambiguous spelling of its pre-rename target) and the receipt names how stale the search index still is and whether the write claimed the detached refresh; delete rewrites nothing, reports the references it strands, and returns a recoverability verdict saying the archive it took does not cover a note outside Brain/o2b brain scaffold-stub list [--limit N] [--json] | write <target> [--path <p>] [--source <s>...] [--if-exists refuse|skip] [--apply] [--json] - unresolved wikilink targets. list reads them from the search index and refuses with a state and a next_command when that index is missing or only partially resolved, never printing an empty list for an index nobody finished resolving; write materialises a stub whose title is the target and whose body links back to its sources. A target that already resolves, or names several notes, is refusedo2b brain note-history Decompose a note's git history into episodic phases split on a commit-time gap (since v1.11.0)o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence; --approval-digest <hex> seals the plan - non-interactive --apply must carry the digest a prior --dry-run printed and then lands exactly the approved plan or nothing (a stale digest refuses with a re-run remedy), an entry whose name cannot land a parseable tag skips as a named row instead of aborting, and a digest paired with --dry-run refuses@@ -656,7 +656,7 @@ o2b brain label <path> --suggest [--dimensions a,b] - read-only ado2b brain attr <path> <field>=<value> | --remove <field> | --show - per-type attribute fields; an undeclared field error lists the declared fields WITH descriptionso2b brain tiers check | restore <path> [--field F] --apply | accept <path> [--field F] - staged repair for identity-tier frontmatter hand-editso2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] | list | rm <name> | run <name> -- <command...> | lock | unlock [--passphrase-from-env SRC] | export --out FILE [--passphrase-from-env SRC] | import FILE [--replace] [--passphrase-from-env SRC] [--vault <path>] - capability-gated custody; the value enters via stdin, never argv. `unlock` wraps the keyfile under a passphrase (read from stdin or --passphrase-from-env, never argv) and holds the key for this process only; `lock` clears that holder; `export` writes every entry as one passphrase-encrypted bundle to `--out` (values re-encrypted, names and env-var mappings travel in the clear past the shared egress redactor); `import` restores a bundle, refusing names the store already holds unless --replace-o2b brain maintenance run [--force] [--retry <task|custom:name>] [--force-cost] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] - quiet-window lease-guarded lane for dream, reindex, bridges, clusters and declared custom tasks+o2b brain maintenance run [--force] [--retry <task|custom:name>] [--force-cost] [--relink-apply] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] - quiet-window lease-guarded lane for dream, reindex, bridges, clusters, relink and declared custom tasks; the relink task previews the anchor additions it would make and rewrites the stored signal pages only with --relink-applyo2b brain maintenance run --cron-template [--interval N] [--format cron|systemd] [--window H-H --tz ZONE] - print the cron or systemd recipe that schedules the lane (default interval 1h); prints and installs nothing```@@ -670,7 +670,7 @@ Since v1.72.0 the spend is priced honestly. The banner prints `price unknown` inSince v1.65.0 the lane prints its own schedule and can carry an install's own upkeep. `o2b brain maintenance run --cron-template` prints a script (`~/.local/bin/osb-maintenance-<hash>.sh`, where `<hash>` is the first 8 hex characters of the SHA-256 of the resolved vault path, so each vault gets its own script, Hermes job and systemd units and re-rendering for the same vault keeps the name) and its scheduler lines - a crontab line and the Hermes form by default, a systemd user timer with `--format systemd` - with `--interval <N>m|h|d` defaulting to `1h`: the gates decide whether work happens and a gate skip exits 0, so an hourly schedule plus `--window` is the intended pattern. The script embeds the resolved vault, runs `o2b brain maintenance run --vault '<vault>' --json`, stays silent on exit 0 and prints the captured JSON and keeps the exit code otherwise. The rendered script calls `o2b` by name, so it expects `o2b` on the scheduler's PATH: cron jobs and systemd user services start with a minimal PATH, so add the install directory (usually `~/.local/bin`) to that PATH. The verb returns before the lease, the gates, the journal and the metrics, so printing a recipe leaves no trace. A bad interval, window or format, `--interval` or `--format` without `--cron-template`, a lane-run flag (`--force`, `--retry`, `--force-cost`, `--busy-minutes`, `--busy-threshold`, `--agent`, `--progress`, `--json`) beside `--cron-template`, and `status --cron-template` exit 2.-Custom lane tasks (since v1.65.0) put an install's own upkeep under the lane's window, busy, pressure, lease and streak gates. They are declared in the machine config file, never in the vault: `maintenance_custom_<name>: <command>`, optionally `maintenance_custom_<name>_cwd: <absolute dir>` (default the running user's home directory; the vault is allowed when named) and `maintenance_custom_<name>_timeout_seconds: <N>` (default 120; a whole number from 1 to 1200). The lease is taken once per pass for 30 minutes, so the declared custom timeouts together stay within 1200 s, which leaves 600 s for the built-in tasks; in name order, a task whose timeout would take the sum past 1200 s is refused by name, and the full 8 tasks fit at the default. Declared tasks run only with the master switch `maintenance_custom_tasks: true` (env `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS`, default off; `0` turns it off on one host). Each runs as `custom:<name>`, where `<name>` matches `^[a-z][a-z0-9-]{0,31}$` (no underscores, so the suffixes stay unambiguous, and no task can be named `tasks`), after the four built-in tasks and stale-first with them; at most 8 are declared. The command runs through `sh -c` (`cmd.exe /d /s /c` on Windows) with stdin closed, stdout discarded and `O2B_VAULT` set. Its environment is this process's minus every variable whose name declares a credential (`*_API_KEY`, `*_TOKEN`, `*_SECRET`, `*PASSWORD*` and the other names the redactor treats as secrets); `PATH`, `HOME`, `LANG`, `LC_*`, `TZ`, `TMPDIR` and `O2B_VAULT` are always kept, and a command that needs a key reads it from its own configuration. The default working directory is not the vault because the vault syncs and is writable through the MCP write tools, and on Windows a bare command name resolves in the working directory first; use absolute executable paths. A `_cwd` that does not exist fails the task as `custom task <name>: cwd does not exist: <path>`. A non-zero exit is reported as `exit <N>: <stderr tail>`, redacted and capped at 4096 bytes. The task's outcome is its shell's exit status: it does not wait for processes the command left in the background, but those still belong to the task, and on POSIX the command's whole process group is killed (SIGTERM, then SIGKILL a second later) when the timeout elapses or the o2b process exits, whichever is first, also after the shell has exited (on Windows `taskkill /T /F` kills the tree while the shell runs). Past its timeout the run is journaled as timed out, and unlike a built-in task, a custom task's timeout counts toward its `failure_streak_limit` and exits 1 rather than 6, so a command that always hangs is refused like one that always fails. A shell that exits before its timeout keeps its exit status even when a background process still holds its stderr at the deadline. `--retry custom:<name>` (MCP `retry_tasks`) attempts a refused custom task alone; an undeclared name is refused with the registered list. A bad declaration (a bad name, an empty command, an out-of-range timeout, a relative `_cwd`, a suffix key without its command, a ninth task, a timeout over the budget) is named on stderr as `custom task refused: <reason>` (MCP `custom_task_errors`) and the valid ones still run; `status` says `custom tasks declared but maintenance_custom_tasks is off` while the switch is off, or `custom tasks declared but OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS turns them off` when the env override did it. A custom task never calls a model on the lane's behalf and records no spend receipt, and the lane cannot police spend or side effects inside an operator's own command. No MCP parameter can add, edit or read a command. The config reader strips one pair of matching surrounding quotes from a value, so a command that starts and ends with the same quote character loses them; wrap such a command in single quotes (`maintenance_custom_tidy: '"/opt/my tool" --flag "x"'`).+Custom lane tasks (since v1.65.0) put an install's own upkeep under the lane's window, busy, pressure, lease and streak gates. They are declared in the machine config file, never in the vault: `maintenance_custom_<name>: <command>`, optionally `maintenance_custom_<name>_cwd: <absolute dir>` (default the running user's home directory; the vault is allowed when named) and `maintenance_custom_<name>_timeout_seconds: <N>` (default 120; a whole number from 1 to 1200). The lease is taken once per pass for 30 minutes, so the declared custom timeouts together stay within 1200 s, which leaves 600 s for the built-in tasks; in name order, a task whose timeout would take the sum past 1200 s is refused by name, and the full 8 tasks fit at the default. Declared tasks run only with the master switch `maintenance_custom_tasks: true` (env `OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS`, default off; `0` turns it off on one host). Each runs as `custom:<name>`, where `<name>` matches `^[a-z][a-z0-9-]{0,31}$` (no underscores, so the suffixes stay unambiguous, and no task can be named `tasks`), after the five built-in tasks and stale-first with them; at most 8 are declared. The command runs through `sh -c` (`cmd.exe /d /s /c` on Windows) with stdin closed, stdout discarded and `O2B_VAULT` set. Its environment is this process's minus every variable whose name declares a credential (`*_API_KEY`, `*_TOKEN`, `*_SECRET`, `*PASSWORD*` and the other names the redactor treats as secrets); `PATH`, `HOME`, `LANG`, `LC_*`, `TZ`, `TMPDIR` and `O2B_VAULT` are always kept, and a command that needs a key reads it from its own configuration. The default working directory is not the vault because the vault syncs and is writable through the MCP write tools, and on Windows a bare command name resolves in the working directory first; use absolute executable paths. A `_cwd` that does not exist fails the task as `custom task <name>: cwd does not exist: <path>`. A non-zero exit is reported as `exit <N>: <stderr tail>`, redacted and capped at 4096 bytes. The task's outcome is its shell's exit status: it does not wait for processes the command left in the background, but those still belong to the task, and on POSIX the command's whole process group is killed (SIGTERM, then SIGKILL a second later) when the timeout elapses or the o2b process exits, whichever is first, also after the shell has exited (on Windows `taskkill /T /F` kills the tree while the shell runs). Past its timeout the run is journaled as timed out, and unlike a built-in task, a custom task's timeout counts toward its `failure_streak_limit` and exits 1 rather than 6, so a command that always hangs is refused like one that always fails. A shell that exits before its timeout keeps its exit status even when a background process still holds its stderr at the deadline. `--retry custom:<name>` (MCP `retry_tasks`) attempts a refused custom task alone; an undeclared name is refused with the registered list. A bad declaration (a bad name, an empty command, an out-of-range timeout, a relative `_cwd`, a suffix key without its command, a ninth task, a timeout over the budget) is named on stderr as `custom task refused: <reason>` (MCP `custom_task_errors`) and the valid ones still run; `status` says `custom tasks declared but maintenance_custom_tasks is off` while the switch is off, or `custom tasks declared but OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS turns them off` when the env override did it. A custom task never calls a model on the lane's behalf and records no spend receipt, and the lane cannot police spend or side effects inside an operator's own command. No MCP parameter can add, edit or read a command. The config reader strips one pair of matching surrounding quotes from a value, so a command that starts and ends with the same quote character loses them; wrap such a command in single quotes (`maintenance_custom_tidy: '"/opt/my tool" --flag "x"'`).### Link and recall intelligence (since v0.45.0)diff --git a/docs/hermes-cron.md b/docs/hermes-cron.mdindex b31c8f07..fe596600 100644--- a/docs/hermes-cron.md+++ b/docs/hermes-cron.md@@ -78,7 +78,7 @@ When `--silent-if-empty` is set and the window has no changes, the command write`dream` is itself idempotent — running it on top of an unchanged Brain is a no-op (no log entry written, no snapshot taken). The chained form is safe at any cadence.-The alternative to a hand-chained dream job is the maintenance lane, which runs dream, reindex, bridges and clusters under one lease and only inside its window: `o2b brain maintenance run --vault /path/to/vault --cron-template` prints a script and the `hermes cron create` line that schedules it (hourly by default; `--interval`, `--window H-H --tz ZONE` narrow it). The script is silent when the lane succeeds or a gate skips, and prints the lane's JSON report when a task failed, timed out or was refused, so Hermes delivers only the runs that need attention. Since v1.76.0 the keyword index needs no scheduled reindex: freshen on read keeps it current while agents work (see "Freshen on read" in `docs/cli-reference.md`), so a scheduled reindex is only worth keeping to compute embeddings periodically. Every recipe this CLI prints - the maintenance lane, `o2b search reindex --cron-template` and `o2b partner codegraph resync --cron-template` - also prints a systemd user timer with `--format systemd`, for a host where Hermes does not own the schedule.+The alternative to a hand-chained dream job is the maintenance lane, which runs dream, reindex, bridges, clusters and relink under one lease and only inside its window; the relink task previews the anchor additions it would make to the stored signals and reports them, rewriting the stored lines only when the lane line carries `--relink-apply`: `o2b brain maintenance run --vault /path/to/vault --cron-template` prints a script and the `hermes cron create` line that schedules it (hourly by default; `--interval`, `--window H-H --tz ZONE` narrow it). The script is silent when the lane succeeds or a gate skips, and prints the lane's JSON report when a task failed, timed out or was refused, so Hermes delivers only the runs that need attention. Since v1.76.0 the keyword index needs no scheduled reindex: freshen on read keeps it current while agents work (see "Freshen on read" in `docs/cli-reference.md`), so a scheduled reindex is only worth keeping to compute embeddings periodically. Every recipe this CLI prints - the maintenance lane, `o2b search reindex --cron-template` and `o2b partner codegraph resync --cron-template` - also prints a systemd user timer with `--format systemd`, for a host where Hermes does not own the schedule.## Discipline report (daily logging-discipline sanity-check)diff --git a/docs/mcp.md b/docs/mcp.mdindex e9b2b5ea..78440562 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -122,9 +122,10 @@ for progress and entirely absent for one that did not.minutes is `brain_dream`, `brain_bridges`, `brain_clusters` and`brain_maintenance`. Index management verbs (`index`, `reindex`,`check`) are deliberately not exposed over MCP, so they are not on this-list. `brain_maintenance` is a dispatcher over the other four-operations and forwards the sink to each task, so its events name the-task that emitted them (`dream`, `reindex`, `bridges`, `clusters`) rather+list. `brain_maintenance` is a dispatcher over the lane's built-in+tasks and forwards the sink to each task, so its events name the+task that emitted them (`dream`, `reindex`, `bridges`, `clusters`,+`relink`) ratherthan the lane. Two more reach a consolidation pass without carrying itsname and report on the same terms: `brain_brief` with `view: "operator"`,whose operator summary runs a dry-run pass, and@@ -154,7 +155,7 @@ release because nothing checked it; its replacement is checked.| `brain_dream` (`step`) | one step (`scan` or `heal-enrich`), not a pass | `dream` — a step is part of a dream pass, so it draws on that budget. Checked per file and per directory in `scan`, and per page in each of `heal-enrich`'s two loops, plus around the two phases that cross no boundary of their own — the vault listing (checkpoint after it only) and the one-shot title/alias phrase build (before and after). So it stops within one page **plus** whichever of those two is running, not within one page flat | yes, under the step's own stage (`scan` / `heal-enrich`) || `brain_bridges` (`discover`) | `bridges` | `bridges` | yes || `brain_clusters` (`run`) | `clusters` | `clusters` | yes |-| `brain_maintenance` (`run`) | the four built-ins plus declared custom tasks (since v1.65.0), sequentially; since v1.64.0 the reindex task stays keyword-only unless config `maintenance_embeddings` is `true`; then it requests the embedding phase when the resolved semantic config can reach a provider, announcing the predicted spend and receipting the completed pass (additive `spend` block: `banner` estimate, `receipt` with model, tokens, `estimated_usd` and whether `force_cost` overrode a refusing gate) | one fresh guard per task; a tripped task is a `timed_out` row, not an aborted call | yes, in its tasks' voices |+| `brain_maintenance` (`run`) | the five built-ins plus declared custom tasks (since v1.65.0), sequentially; since v1.64.0 the reindex task stays keyword-only unless config `maintenance_embeddings` is `true`; then it requests the embedding phase when the resolved semantic config can reach a provider, announcing the predicted spend and receipting the completed pass (additive `spend` block: `banner` estimate, `receipt` with model, tokens, `estimated_usd` and whether `force_cost` overrode a refusing gate); since v1.89.0 the relink task previews the anchor additions it would make and rewrites the stored signal pages only under `relink_apply`, its per-source report riding the result as an additive `relink` block either way | one fresh guard per task; a tripped task is a `timed_out` row, not an aborted call | yes, in its tasks' voices || `brain_brief` (`view: "operator"`) | `dream`, dry run | `dream` | yes || `brain_review_candidates` | `dream`, dry run | `dream` | yes |@@ -403,7 +404,7 @@ flags for a narrower per-process full server.| `brain_session_expand` | Expand a raw or summary session recall node to immediate sources and paginated raw turn content. | `id` || `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — || `brain_create_note` | Write an actual vault note file (path + frontmatter + content) atomically inside the vault. Distinct from `brain_note` (log append); refuses traversal, the Brain root, excluded paths, any destination outside the declared write binding, and — by default — clobbering. Opt-in: `if_exists: "skip"` returns `outcome: "skipped"` instead of creating, `strict` validates the document before writing and reports coded violations, and `template` + `template_variables` render the body through a closed two-construct grammar (`{{name}}` substitution; `{{#name}}…{{/name}}` presence sections and list iteration with `{{.}}`). Unknown placeholders are left intact. | `path` |-| `brain_note_lifecycle` | Note-FILE lifecycle, dispatched on `action`: `rename` (new filename, same directory), `move` (new directory, same filename), `archive` (displaces the note under `Archive/`, mirroring its path), `delete` (removes it). Both the source and the destination go through the same nine-step path envelope `brain_create_note` uses, so a destination cannot reach where a create could not. Dry-run unless `apply: true`; `delete` additionally requires `confirm: true` and honours `expect` / `strict` over the inbound-reference count. A relocation rewrites inbound `[[links]]` vault-wide - both path spellings always, the bare basename only when exactly one note carries it - and the result names what it rewrote, what it withheld and how stale the search index still is (`references.index`). A delete rewrites nothing, reports the references it strands, and returns a `recoverability` verdict saying the archive it took does not cover a note living outside `Brain/`. | `action`, `path` |+| `brain_note_lifecycle` | Note-FILE lifecycle, dispatched on `action`: `rename` (new filename, same directory), `move` (new directory, same filename), `archive` (displaces the note under `Archive/`, mirroring its path), `delete` (removes it). Both the source and the destination go through the same nine-step path envelope `brain_create_note` uses, so a destination cannot reach where a create could not. Dry-run unless `apply: true`; `delete` additionally requires `confirm: true` and honours `expect` / `strict` over the inbound-reference count. A relocation rewrites inbound `[[links]]` vault-wide to the minimal spelling that still resolves to the destination - a bare basename only when exactly one note carries it, and a bare name the rename turns from unique to ambiguous repaired to the unambiguous spelling of its pre-rename target - and the result names the rewritten spellings, what it withheld, how stale the search index still is (`references.index`) and whether the write claimed the detached refresh (`references.refresh`). A delete rewrites nothing, reports the references it strands, and returns a `recoverability` verdict saying the archive it took does not cover a note living outside `Brain/`. | `action`, `path` || `brain_scaffold_stub` | Unresolved wikilink targets. `action: "list"` reads them from the search index and REFUSES - `state` plus a `next_command` - when that index is missing, unreadable or only partially resolved, rather than reporting zero: an empty list from an index nobody finished resolving is a clean bill of health for a vault nobody measured. `action: "write"` materialises a stub for one target through the same `createNote` envelope and `if_exists` semantics as `brain_create_note` - its title is the target the link spelled and its body links back to the `sources` documents, each of which must be an existing Markdown note inside the vault or the call is refused with `unknown_source` - so nothing the stub cites is invented, though whether a cited document really carries the reference is `action: "list"`'s claim, read from the index, not this write's. A target that already resolves, or that names more than one note, is refused with its candidates. Dry-run unless `apply: true`. | `action` || `brain_file_context` | Given a file path, surface prior vault work that mentions it (decisions, bug notes, refactor history) by querying the index with path-derived terms. Size gate skips trivial files. Read-only; no LLM. | `file_path` || `brain_session_summary` | Session-scoped structured digest over request/decisions/learnings/next_steps: `write` stores agent-extracted categories, `get` returns a session's latest digest, `list` returns all. Append-only, deduped; an all-empty digest is rejected. | `operation` |@@ -2331,6 +2332,7 @@ format characters), when it contains NUL, or when it exceeds the cap.finding. `brain_doctor` reports `merge-chain-dangling` warnings for a`merged_into:` pointer whose canonical resolves to no file - reportingonly, with the repair named as the content judgement it is.+- Since v1.89.0 `brain_maintenance` (`run`) also dispatches the lane's fifth built-in task, `relink`, which recomputes the entity anchors of the page-sourced signals already stored with the shipped matchers and the page-link resolver. The task previews by contract: it reports per source page what it would add - the result carries that report as an additive `relink` block whenever the task ran, on the CLI JSON payload and here alike - and it rewrites the stored `entities:` lines only when the call passes `relink_apply` (`--relink-apply` on the CLI), which routes the run through the same write guard every lane write answers to. A dry run writes nothing, including the skip-audit log the shared anchorable build stamps on the apply arm; a signal without a Raw section is counted by neither arm.- Since v1.65.0 `brain_maintenance` (`run`) also runs the custom lane tasksan install declares in its machine config (`maintenance_custom_<name>`,behind the default-off `maintenance_custom_tasks` switch), after the fourdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 583b9cac..3f0db615 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.88.0",+ "version": "1.89.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 18dab273..fcaf8cca 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.88.0",+ "version": "1.89.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 1db974eb..d8f79a58 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.88.0"+version: "1.89.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 58ded91e..7682a66c 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.88.0",+ "version": "1.89.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 1db974eb..d8f79a58 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.88.0"+version: "1.89.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 16179c21..91014d96 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"# `hermes_agent.memory_providers` group, not a CLI script.[project]name = "open-second-brain"-version = "1.88.0"+version = "1.89.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 77cd1a8a..83441465 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -35,7 +35,7 @@ const RECALL_CHANNEL_CHOICES = RECALL_CHANNELS.join("|");*/export const MAINTENANCE_USAGE ="usage: o2b brain maintenance run [--force] [--retry <task|custom:name>] [--window H-H] [--tz ZONE] " +- "[--busy-minutes N] [--busy-threshold N] [--force-cost] [--progress] " ++ "[--busy-minutes N] [--busy-threshold N] [--force-cost] [--relink-apply] [--progress] " +"| run --cron-template [--interval N] [--format cron|systemd] [--window H-H --tz ZONE] " +"| status [--limit N] [--vault <path>] [--json]";@@ -752,7 +752,9 @@ export const VERB_HELP: Record<string, string> = {"maintenance.failure_streak_limit times in a row is REFUSED by name\n" +"(exit 7) while the others still run; --retry <task> attempts that one\n" +"task with every gate still in force, and --force bypasses the soft\n" +- "gates and every refusal, never the lease. Every attempt - including\n" ++ "gates and every refusal, never the lease. The relink task previews\n" ++ "the anchor additions it would make; --relink-apply rewrites the\n" ++ "stored signal pages. Every attempt - including\n" +"gate refusals - lands in a bounded journal; status renders lease +\n" +"journal. Custom tasks are shell commands declared in the machine\n" +"config (maintenance_custom_<name>), run only with\n" +diff --git a/src/cli/brain/verbs/maintenance.ts b/src/cli/brain/verbs/maintenance.tsindex 1d23a738..bc1e7f18 100644--- a/src/cli/brain/verbs/maintenance.ts+++ b/src/cli/brain/verbs/maintenance.ts@@ -7,7 +7,10 @@* bridges, and clusters stale-first; --force bypasses the soft gates* and every streak refusal but never the lease, while --retry <task>* (repeatable) bypasses the streak refusal for that task alone and- * leaves every gate in force. The reindex pass stays keyword-only+ * leaves every gate in force. The relink task previews the anchor+ * additions it would make and rewrites the stored signal pages only+ * under --relink-apply; either way its per-source report rides the run+ * result. The reindex pass stays keyword-only* unless `maintenance_embeddings` opts the lane into the embedding phase* and the resolved config can reach a provider: then the pass announces* its predicted spend before it runs, receipts what the phase actually@@ -52,6 +55,7 @@ import {} from "../../../core/brain/maintenance/custom-tasks.ts";import { isCustomLaneTask } from "../../../core/brain/maintenance/custom-task-id.ts";import { buildLaneTasks } from "../../../core/brain/maintenance/lane-tasks.ts";+import type { RelinkAnchorsReport } from "../../../core/brain/maintenance/relink-anchors-task.ts";import { resolveAgentName } from "../../../core/config.ts";import { CronTemplateError, parseRecipeFormat } from "../../cron-recipe.ts";import {@@ -124,6 +128,7 @@ const RUN_ONLY_FLAGS = ["force","retry","force-cost",+ "relink-apply","busy-minutes","busy-threshold","agent",@@ -166,6 +171,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {progress: { type: "boolean" },json: { type: "boolean" },"force-cost": { type: "boolean" },+ "relink-apply": { type: "boolean" },"cron-template": { type: "boolean" },interval: { type: "string" },format: { type: "string" },@@ -373,6 +379,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {searchConfig,now,forceCost: flags["force-cost"] === true,+ relinkApply: flags["relink-apply"] === true,safeguardFor: laneSafeguard,signal: interrupt.signal,...laneProgress,@@ -417,6 +424,10 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {// The run-level spend block: the banner this run announced and the// receipt its reindex pass returned, both absent when nothing spent.const spend = lane.reindex.spendBlock(result.tasks);+ // The relink pass's report: the preview on the default arm, the+ // changes under --relink-apply. Absent while the task has not run+ // (a gate skip, a refusal), so a skipped lane reports no numbers.+ const relink = lane.relinkReport();if (asJson) {okJson({verdict: result.verdict,@@ -426,6 +437,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {// so the two surfaces cannot disagree about what a skip says....(result.capacity !== undefined ? { capacity: result.capacity } : {}),...(spend !== undefined ? { spend } : {}),+ ...(relink !== undefined ? { relink } : {}),});} else {ok(`maintenance: ${result.verdict}`);@@ -433,6 +445,9 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {ok(` capacity: ${result.capacity.tier} - ${result.capacity.remedy}`);}for (const t of result.tasks) ok(` ${renderTaskLine(t)}`);+ if (relink !== undefined) {+ ok(` relink: ${renderRelinkLine(relink)}`);+ }}// A stopped lane is reported as stopped, not as four failures. The// lane catches each task's abort and journals it, so without this the@@ -559,6 +574,19 @@ export function formatSpendBanner(preview: EmbeddingSpendPreview, gateUsd: numbe);}+/**+ * One line for the relink pass's report, under the task rows. The verb+ * says which arm ran: without `--relink-apply` the numbers are the+ * preview's, and the sentence must not read as though signal pages+ * changed.+ */+export function renderRelinkLine(report: RelinkAnchorsReport): string {+ const arm = report.apply+ ? `added ${report.anchorsAdded} anchor(s) to ${report.signalsChanged} signal(s)`+ : `would add ${report.anchorsAdded} anchor(s) to ${report.signalsChanged} signal(s)`;+ return `${arm} across ${report.perSource.length} source page(s)`;+}+/** A repeatable flag's values; a flag never passed is an empty list. */function stringArrayFlag(raw: unknown): string[] {return Array.isArray(raw)diff --git a/src/cli/brain/verbs/note-lifecycle.ts b/src/cli/brain/verbs/note-lifecycle.tsindex be6ef914..6dca0f2f 100644--- a/src/cli/brain/verbs/note-lifecycle.ts+++ b/src/cli/brain/verbs/note-lifecycle.ts@@ -58,6 +58,10 @@ function renderJson(res: NoteLifecycleResult): Record<string, unknown> {files_scanned: res.references.filesScanned,inbound_files: [...res.references.inboundFiles],files_rewritten: res.references.filesRewritten,+ rewritten_spellings: res.references.rewrittenSpellings.map((s) => ({+ from: s.from,+ to: s.to,+ })),rewrite_failures: res.references.rewriteFailures.map((f) => ({path: f.path,reason: f.reason,@@ -68,6 +72,13 @@ function renderJson(res: NoteLifecycleResult): Record<string, unknown> {last_indexed_at: res.references.index.lastIndexedAt,next_command: res.references.index.nextCommand,},+ // `claimed` says a detached refresh run is IN FLIGHT, never that it+ // has landed; every other value names why nothing was started, and+ // `refresh_reason` spells that reason - the freshen machinery's own+ // skip token, or the error it raised - so `not_claimed` is never+ // the whole answer a caller receives.+ refresh: res.references.refresh,+ refresh_reason: res.references.refreshReason,},cascade:res.cascade === null@@ -84,7 +95,8 @@ function renderJson(res: NoteLifecycleResult): Record<string, unknown> {* The human line. It names the index state and the command that fixes it* on every run, because the operator reading a terminal is exactly the* person who has to decide whether the search index still describes the- * vault they just changed.+ * vault they just changed - and it names whether the write claimed the+ * detached refresh, so "claimed" is never read as "already caught up".*/function renderText(res: NoteLifecycleResult): string {const where = res.to === null ? res.from : `${res.from} -> ${res.to}`;@@ -122,6 +134,11 @@ function renderText(res: NoteLifecycleResult): string {"\n" +` search index: ${refs.index.state}` +(refs.index.lastIndexedAt === null ? "" : ` since ${refs.index.lastIndexedAt}`) ++ // The reason rides the token in prose too: an operator reading a+ // terminal is exactly the person who has to tell a deliberate+ // config-off from a held claim or a broken spawn.+ `; refresh: ${refs.refresh}` ++ (refs.refreshReason === null ? "" : ` (${refs.refreshReason})`) +`; next: ${refs.index.nextCommand}`);}@@ -169,6 +186,12 @@ export async function cmdBrainNoteLifecycle(argv: string[]): Promise<number> {deleteLinked: flags["delete-linked"] === true,expect: expectCount,strict: flags["strict"] === true,+ // The post-write refresh resolves through the config file this+ // invocation already resolved the vault from, the same rule the+ // search verbs read (`--config`, else the default): a non-default+ // config's index path and freshen settings are the ones the claim+ // reads and the child spawns with.+ refreshConfigPath: config,});if (flags["json"] === true) okJson(renderJson(res));else ok(renderText(res));diff --git a/src/cli/interrupt.ts b/src/cli/interrupt.tsindex 337b6826..c0c1541c 100644--- a/src/cli/interrupt.ts+++ b/src/cli/interrupt.ts@@ -125,6 +125,7 @@ const YIELDS_TO_EVENT_LOOP: Readonly<Record<Operation, boolean>> = Object.freeze[OPERATION.bridges]: false,[OPERATION.clusters]: false,[OPERATION.architect]: false,+ [OPERATION.relink]: false,[OPERATION.reindex]: true,[OPERATION.maintenance]: true,// The session sweep is synchronous end to end: the walk and the hashdiff --git a/src/cli/search/verbs/indexing.ts b/src/cli/search/verbs/indexing.tsindex eb177873..4bf7efe4 100644--- a/src/cli/search/verbs/indexing.ts+++ b/src/cli/search/verbs/indexing.ts@@ -10,7 +10,11 @@ import { setPriority } from "node:os";import { dirname } from "node:path";import { formatDegradationNotice } from "../../../core/integrity/degradation.ts";-import { recordFreshenOutcome, releaseFreshen } from "../../../core/search/freshen.ts";+import {+ recordFreshenOutcome,+ releaseFreshen,+ settleFreshenPending,+} from "../../../core/search/freshen.ts";import {createSafeguard,resolveSafeguardTimeoutMs,@@ -236,6 +240,17 @@ export async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<numbe* records its outcome and backoff in the per-device state file, and* releases the claim it was handed whatever happens. Nothing is printed:* every stream of a detached child is ignored.+ *+ * Before the claim goes, a run whose main pass COMPLETED settles the+ * pending-write marker ({@link settleFreshenPending}): a write that+ * landed while this run held the claim queued itself there, and this+ * run's fresh stamp would otherwise suppress freshen-on-read until the+ * next interval with the write still unindexed. The settle runs at most+ * ONE extra incremental pass, and it never keeps the claim past its own+ * end - the release below happens in every arm. A run whose main pass+ * did not complete (a config that never resolved, a lock it did not+ * get, a pass that threw) touched no files, so it leaves the marker for+ * the next run, which is the caller that can provably cover it.*/async function runFreshenChild(flags: SearchVerbFlags,@@ -247,9 +262,31 @@ async function runFreshenChild(} catch {// Not permitted here (or not supported): run at normal priority.}+ // The scan-start instant the settle is judged against: anything the+ // pass actually read was on disk after this.const startedAt = Date.now();let cfg: ResolvedSearchConfig | undefined;let stateDir = stateDirFlag;+ // Whether the MAIN pass completed. Only a run whose main pass+ // completed may settle the pending marker: the settle's covered+ // branch clears markers at or before this run's scan start, and a run+ // that never scanned would clear markers it cannot have covered. The+ // documented rule is the other one - a caller that cannot run a pass+ // (a config that never resolved, a lock it did not get, a pass that+ // threw) leaves the marker exactly as it stands for the next run.+ let mainPassCompleted = false;+ const runIncrementalPass = async (): Promise<void> => {+ if (cfg === undefined || stateDir === undefined) return;+ const passStartedAt = Date.now();+ const stats = await indexVault(cfg, {+ embeddings: cfg.freshen?.embeddings === true,+ });+ recordFreshenOutcome(cfg.vault, stateDir, {+ outcome: "completed",+ durationMs: Date.now() - passStartedAt,+ changed: stats.added + stats.updated + stats.deleted,+ });+ };try {cfg = resolveConfig(flags);stateDir ??= dirname(cfg.dbPath);@@ -261,6 +298,7 @@ async function runFreshenChild(durationMs: Date.now() - startedAt,changed: stats.added + stats.updated + stats.deleted,});+ mainPassCompleted = true;return 0;} catch (e) {// Another writer holds the index (a manual run, the watcher, the@@ -275,7 +313,29 @@ async function runFreshenChild(}return 1;} finally {- if (stateDir !== undefined) releaseFreshen(stateDir, token);+ if (stateDir !== undefined) {+ if (mainPassCompleted) {+ const extraStartedAt = Date.now();+ try {+ await settleFreshenPending(stateDir, startedAt, runIncrementalPass);+ } catch (e) {+ // The extra pass is best-effort: a failure in it is recorded+ // like any run failure, at its real duration, and an+ // uncovered marker survives for the next run to cover and+ // clear. A lock it did not get is the benign skip the main+ // pass treats it as - recording it as a failure would push+ // the backoff up for another writer's ordinary run.+ if (!(e instanceof SearchError && e.code === "INDEX_LOCKED") && cfg !== undefined) {+ recordFreshenOutcome(cfg.vault, stateDir, {+ outcome: "failed",+ durationMs: Date.now() - extraStartedAt,+ error: e instanceof Error ? e.message : String(e),+ });+ }+ }+ }+ releaseFreshen(stateDir, token);+ }}}diff --git a/src/core/brain/atomic-facts.ts b/src/core/brain/atomic-facts.tsindex 773d1b08..e79499b9 100644--- a/src/core/brain/atomic-facts.ts+++ b/src/core/brain/atomic-facts.ts@@ -11,7 +11,10 @@*/import {+ MIN_ANCHOR_FORM_LENGTH,entityMatchForms,+ matchFormVariants,+ matchVariantsOccurIn,normalizeEntityName,type EntityLexiconHandle,type ValidateEntityLabelOptions,@@ -124,20 +127,26 @@ export function splitSentences(text: string): string[] {return out.map((s) => s.trim()).filter((s) => s !== "");}-/** Minimum normalised form length that participates in substring matching. */-const MIN_ANCHOR_FORM_LENGTH = 3;-/*** The occurrence-anchoring kernel (truth-correctable-time-aware,- * task 4): the quality-gated normalized match forms that literally- * occur in `text`. Candidate labels pass through the quality gate+ * task 4): the quality-gated normalized match forms that occur in+ * `text`. Candidate labels pass through the quality gate* (sanitize decoration, then normalize, drop structurally-invalid* forms) before matching, and forms shorter than- * {@link MIN_ANCHOR_FORM_LENGTH} never participate. Pure: no I/O, no- * registry - so this layer never resolves the lexicon itself. The one- * kernel every occurrence-anchoring caller shares - the assertion- * decomposer and the agent-stated claim verdicts both anchor through- * it, and each vault-aware caller resolves the SAME store-learned+ * {@link MIN_ANCHOR_FORM_LENGTH} never participate. Since F3+ * (note-change truth maintenance) the occurrence test itself is+ * separator-tolerant: both the form AND the haystack fold through+ * {@link matchFormVariants} to their canonical (space) joins - runs of+ * space, hyphen and underscore are interchangeable, a folder-prefixed+ * form also matches at a path-segment boundary - and every occurrence+ * must have a clean leading edge (a no-space-script neighbour suspends+ * the requirement), so the fold never plants a mid-word hit nothing+ * anchored before (`canada` never anchors `ada`). The returned forms are+ * still the gate's normalized forms, never the expanded variants. Pure:+ * no I/O, no registry - so this layer never resolves the lexicon itself.+ * The one kernel every occurrence-anchoring caller shares - the+ * assertion decomposer and the agent-stated claim verdicts both anchor+ * through it, and each vault-aware caller resolves the SAME store-learned* lexicon through `resolveEntityLexicon` and threads it in here* (recall-quality M6), so no path can drift back to anchoring a form* the creation gate refuses. `opts` threads the admission vocabularies@@ -151,9 +160,18 @@ export function anchorEntityForms(opts: ValidateEntityLabelOptions = {},): ReadonlyArray<string> {const haystack = normalizeEntityName(text);+ // The haystack folds to its one canonical-join variant ONCE per call,+ // not once per form: the same hoist entityAnchors makes, so a decompose+ // pass over an assertion x entity grid tokenizes the text once per+ // call instead of per form per entity. Identical verdicts -+ // `matchFormOccursIn` is exactly this comparison with the expansion+ // inlined.+ const haystackVariants = matchFormVariants(haystack);return Object.freeze(entityMatchForms(forms, opts).filter(- (f) => f.length >= MIN_ANCHOR_FORM_LENGTH && haystack.includes(f),+ (f) =>+ f.length >= MIN_ANCHOR_FORM_LENGTH &&+ matchVariantsOccurIn(matchFormVariants(f), haystackVariants),),);}@@ -171,12 +189,20 @@ function anchorEntities(opts: ValidateEntityLabelOptions = {},): string[] {if (entities.length === 0) return [];+ // The text tokenizes ONCE for the whole entity loop (M2, PR 268+ // review): folding the haystack once per entity through+ // `anchorEntityForms` re-derived the identical variant per iteration.+ // The verdict is the same per-entity comparison, minus the re-fold.+ const haystackVariants = matchFormVariants(normalizeEntityName(text));const ids: string[] = [];for (const entity of entities) {if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;- if (anchorEntityForms(text, [entity.name, ...entity.aliases], opts).length > 0) {- ids.push(entity.id);- }+ const anchored = entityMatchForms([entity.name, ...entity.aliases], opts).some(+ (f) =>+ f.length >= MIN_ANCHOR_FORM_LENGTH &&+ matchVariantsOccurIn(matchFormVariants(f), haystackVariants),+ );+ if (anchored) ids.push(entity.id);}return ids.toSorted();}diff --git a/src/core/brain/entities/canonical.ts b/src/core/brain/entities/canonical.tsindex f12eedbb..8e73d804 100644--- a/src/core/brain/entities/canonical.ts+++ b/src/core/brain/entities/canonical.ts@@ -132,6 +132,247 @@ export function foldQuoteVariantsByClass(raw: string): string {);}+/**+ * The separators whose RUNS are interchangeable at match time, folded to+ * the one canonical join. Space, hyphen and underscore only: a+ * `notes/link-candidates.ts` basename is a slug, so those three are the+ * spellings one token sequence answers to in this store; dot and slash+ * carry structure (`Node.js`, a path) and are never folded.+ */+const MATCH_SEPARATOR_RUN_RE = /[-_ ]+/;++/**+ * Minimum normalized form length that participates in substring matching.+ * The anchoring kernels gate the FULL forms they compare with this floor,+ * and {@link matchFormVariants} gates the slug tail it emits - the tail is+ * an emitted needle in its own right, and an unfloored one would anchor+ * standalone words no full form ever matched (`AC/DC` must not mint `dc`).+ * One constant here so the kernels and the generator cannot drift.+ */+export const MIN_ANCHOR_FORM_LENGTH = 3;++/**+ * The entity-type folders of the canonical entity registry: the category+ * slugs entity pages (`Brain/entities/<category>/<id>.md`) and entity ids+ * (`ent-<category>-<slug>`) are minted from. Declared here - the leaf+ * kernel every anchoring consumer shares - so the registry names its own+ * folder vocabulary exactly once and every reader derives from the one+ * list: {@link matchFormVariants} gates the slug tail on it, and the+ * merge guard's default guarded categories ARE this list (re-exported+ * there under its guard-facing name).+ */+export const ENTITY_TYPE_FOLDERS: ReadonlyArray<string> = Object.freeze([+ "people",+ "person",+ "org",+ "organization",+ "organisation",+ "company",+ "team",+]);++/** Set form of {@link ENTITY_TYPE_FOLDERS} for the tail gate's lookups. */+const ENTITY_TYPE_FOLDER_SET: ReadonlySet<string> = new Set(ENTITY_TYPE_FOLDERS);++/**+ * Fold a string's separator runs to the ONE canonical join: the tokens+ * the string splits into, joined by single spaces (the tokens keep their+ * slashes and dots - only the three foldable separators run together).+ * Edge separator runs vanish with their empty edge tokens, exactly as+ * they always did.+ */+function canonicalMatchJoin(s: string): string {+ return s+ .split(MATCH_SEPARATOR_RUN_RE)+ .filter((token) => token !== "")+ .join(" ");+}++/**+ * Expand one ALREADY-NORMALIZED match form into the match variants the+ * anchoring kernels compare with (note-change truth maintenance, F3;+ * grid reduced per M2 of the PR 268 review). At most TWO variants:+ *+ * - The form's CANONICAL JOIN ({@link canonicalMatchJoin}): runs of+ * space, hyphen and underscore (in any mix) fold to one space, so+ * `ada lovelace`, `ada-lovelace`, `ada_lovelace` and+ * `ada -_ lovelace` all expand to the one same variant. The kernels+ * fold the needle AND the haystack through the same function, and+ * one space-joined comparison answers for the whole variant class:+ * tokens never contain separators, every join character counts as a+ * non-word neighbour at the leading edge, and both the old grid and+ * the folded one compare token sequences - so the fold is verdict-+ * equivalent, at one scan instead of nine.+ * - When the form's LAST `/`-segment (the slug itself) has a registry+ * entity-type folder for its parent segment ({@link+ * ENTITY_TYPE_FOLDERS} - the categories entity pages and ids are+ * minted from; the parent SEGMENT gates, so the registry's deeper+ * spellings `entities/people/ada_lovelace` and+ * `Brain/entities/people/ada_lovelace` mint the tail too), the+ * CANONICAL JOIN of that segment, so `people/ada_lovelace` also+ * occurs in a text that only says `ada lovelace`. The segment prefix+ * is registry+ * decoration, not part of the mentioned name - and because the tail+ * is an emitted needle in its own right, the tail meets+ * {@link MIN_ANCHOR_FORM_LENGTH}, the same floor the kernels apply+ * to full forms (`AC/DC` emits no `dc` for a standalone word to+ * match). The FULL form is never floored or gated here: gating it+ * stays the caller's call, unchanged. A slash after any other prefix+ * carries no registry decoration - "Warner/Chappell" is one name+ * with a slash in it, not a directory path - so `Warner/Chappell`+ * mints no `chappell` and `Sony/ATV` no `atv` (M1, PR 268 review).+ *+ * The output is deterministic (the folded full form first, the folded+ * tail after) and never empty for a non-empty separator-free form of at+ * least {@link MIN_ANCHOR_FORM_LENGTH}. Deliberately NOT part of+ * identity: the input is never re-normalized, `normalizeEntityName` is+ * untouched, and nothing this returns may be persisted - identity keys+ * keep their separators, which is exactly why two spellings can be two+ * identities and one match class. Pure: no I/O, no state.+ */+export function matchFormVariants(form: string): string[] {+ const out: string[] = [];+ const full = canonicalMatchJoin(form);+ if (full === "") return out;+ out.push(full);+ const lastSlash = form.lastIndexOf("/");+ if (lastSlash >= 0) {+ // The gate is the slug's OWN parent segment - the category folder an+ // entity page's id sits in - not the whole prefix before the slash:+ // a form that still carries the registry's deeper path+ // (`Brain/entities/people/ada_lovelace`) has `people` as its+ // immediate parent and mints its tail the same as the bare+ // `people/ada_lovelace`, while `Warner/Chappell` has `warner` there+ // and mints nothing (M1, PR 268 review).+ const prefix = form.slice(0, lastSlash);+ const folder = prefix.slice(prefix.lastIndexOf("/") + 1).toLowerCase();+ if (ENTITY_TYPE_FOLDER_SET.has(folder)) {+ const tail = canonicalMatchJoin(form.slice(lastSlash + 1));+ if (tail.length >= MIN_ANCHOR_FORM_LENGTH) out.push(tail);+ }+ }+ return out;+}++/**+ * A letter or digit in ANY script: the word characters a match must not+ * sit inside. The fold is deliberately NOT on this list - a separator is+ * exactly where one token ends and the next begins, so `ada` may anchor+ * inside `ada-lovelace` but never inside `canada`.+ */+const MATCH_WORD_CHAR_RE = /[\p{L}\p{N}]/u;++/**+ * The scripts written WITHOUT word spaces - Han, Hiragana, Katakana,+ * Thai, Lao, Khmer, Myanmar. In a run of such text every letter touches+ * a letter, so a LEADING letter is not evidence of a mid-word hit the+ * way it is in a spaced script: `田中太郎` never occurs in+ * `鈴木花子と田中太郎` at a word boundary, and a boundary rule applied+ * there verbatim would have silenced every CJK mention the pre-rule+ * literal `includes` matching anchored. For a leading neighbour from one+ * of these scripts the boundary requirement is therefore suspended - the+ * script keeps its literal behavior back, spaced scripts keep the rule+ * (a Latin neighbour blocks even inside otherwise-CJK text). Korean is+ * deliberately NOT on this list: it writes spaces between words, so a+ * leading Hangul letter keeps blocking - Korean attaches no prefixes,+ * and `박철수` must not anchor `철수`.+ */+const NO_SPACE_SCRIPT_RE =+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;++/**+ * True when `codePoint` belongs to a script written without word spaces+ * (see {@link NO_SPACE_SCRIPT_RE}): a leading neighbour from one of+ * these scripts never blocks an occurrence, because adjacency there+ * carries no word-boundary information.+ */+function boundaryNotRequiredForScripts(codePoint: string): boolean {+ return NO_SPACE_SCRIPT_RE.test(codePoint);+}++function isHighSurrogate(code: number): boolean {+ return code >= 0xd800 && code <= 0xdbff;+}++function isLowSurrogate(code: number): boolean {+ return code >= 0xdc00 && code <= 0xdfff;+}++/**+ * The code point ending just before index `i`, or null at the string+ * edge. Steps over a surrogate pair so an astral letter comes back+ * whole rather than as a lone (always non-word) code unit.+ */+function codePointBefore(s: string, i: number): string | null {+ if (i <= 0) return null;+ const start =+ i >= 2 && isLowSurrogate(s.charCodeAt(i - 1)) && isHighSurrogate(s.charCodeAt(i - 2))+ ? i - 2+ : i - 1;+ return s.slice(start, i);+}++/**+ * True when `variant` occurs in one folded haystack string with a clean+ * LEADING edge: some occurrence of it has no letter or digit directly+ * before it - UNLESS that neighbour belongs to a script written without+ * word spaces (see {@link NO_SPACE_SCRIPT_RE}), whose adjacency suspends+ * the requirement. The trailing side is unchecked (H1, PR 268 review):+ * every language that attaches endings to a name with no space - Russian+ * `Ивана`, the German genitive `Annas`, a Korean particle run like+ * `김철수는` - lost those mentions under a two-sided rule, and a+ * trailing character is an inflection until proven otherwise. The+ * leading-side rule is what keeps the separator fold from planting+ * mid-word hits nothing anchored before (`canada` never anchors `ada`:+ * the letter before the hit blocks it, folded spellings included); an+ * occurrence beside a separator or the string edge is a token edge and+ * anchors.+ */+function variantOccursAtWordBoundary(variant: string, haystack: string): boolean {+ // An empty variant occurs everywhere and nowhere - refuse it rather+ // than let a boundary-less occurrence anchor.+ if (variant === "") return false;+ let at = haystack.indexOf(variant);+ while (at >= 0) {+ const before = codePointBefore(haystack, at);+ const blockedBefore =+ before !== null && MATCH_WORD_CHAR_RE.test(before) && !boundaryNotRequiredForScripts(before);+ if (!blockedBefore) return true;+ at = haystack.indexOf(variant, at + 1);+ }+ return false;+}++/**+ * True when ANY of the needle's match variants occurs with a clean+ * leading edge in ANY of the haystack's match variants - the one+ * comparison the anchoring kernels and their twins share. Both arrays+ * come from {@link matchFormVariants}: the needle's variants are+ * precomputed by the caller where it already precomputes forms, and the+ * haystack's variants are expanded once per text, never once per entity.+ * Pure: no I/O.+ */+export function matchVariantsOccurIn(+ formVariants: ReadonlyArray<string>,+ haystackVariants: ReadonlyArray<string>,+): boolean {+ return formVariants.some((variant) =>+ haystackVariants.some((haystack) => variantOccursAtWordBoundary(variant, haystack)),+ );+}++/**+ * One-shot convenience over {@link matchFormVariants} and+ * {@link matchVariantsOccurIn}: does the single normalized form `form`+ * occur, separator-folded and leading-edge-checked, in the normalized+ * haystack text? For callers that match one form at a time; a caller+ * holding precomputed variant lists calls {@link matchVariantsOccurIn}+ * directly so the haystack expands once, not once per form.+ */+export function matchFormOccursIn(form: string, normalizedHaystack: string): boolean {+ return matchVariantsOccurIn(matchFormVariants(form), matchFormVariants(normalizedHaystack));+}+/*** The kernel's shape pass, WITHOUT the quote fold: NFC, trim, collapse* whitespace runs, lowercase. Separated from {@link normalizeEntityName}diff --git a/src/core/brain/fact-extract.ts b/src/core/brain/fact-extract.tsindex 9e4c279c..4bc11ba6 100644--- a/src/core/brain/fact-extract.ts+++ b/src/core/brain/fact-extract.ts@@ -37,7 +37,10 @@ import { brainDirsForWrite } from "./paths.ts";import type { DedupIndexEntry } from "./dedup-hash.ts";import { buildEntityIndex } from "./entities/index-builder.ts";import {+ MIN_ANCHOR_FORM_LENGTH,entityMatchForms,+ matchFormVariants,+ matchVariantsOccurIn,normalizeEntityName,sanitizeEntityLabel,validateEntityLabel,@@ -238,6 +241,25 @@ export interface RouteFactsInput {* drops it at read; `0` (the default) stamps nothing, byte-identical.*/readonly ambientTtlDays?: number;+ /**+ * Link-derived entity ids the CALLER resolved from this capture's+ * source page, in the page's first-occurrence (body) order+ * (note-change truth maintenance, F4). The kernel unions them into+ * every signal this capture writes: link-derived ids first - the+ * first body-order link leads the persisted `entities:` line, so it+ * is the primary anchor when both mechanisms match the same fact -+ * followed by the text-derived ids that are not already present.+ *+ * The resolution and its withholding are the CALLER's job, done+ * server-side before this call: a page-sourced caller maps the page's+ * outbound wikilinks through the page-link resolver, which drops+ * withheld entity pages before any id is produced. This kernel takes+ * the ids as given - it reads no pages, resolves no links and never+ * widens the list on its own. A session-sourced capture passes+ * nothing (or an empty list), which is byte-identical to before this+ * parameter existed; a dry run forecasts unchanged either way.+ */+ readonly linkDerivedEntityIds?: ReadonlyArray<string>;}export interface RouteFactsResult {@@ -269,10 +291,13 @@ export interface RouteFactsResult {/** Max length of the redacted fact text carried onto a `durability-skip` log. */const DURABILITY_LOG_TEXT_MAX_LEN = 200;-/** Minimum normalised form length that participates in substring matching. */-const MIN_ANCHOR_FORM_LENGTH = 3;--/** A registry entity reduced to its clean, matchable label forms. */+/**+ * A registry entity reduced to its clean, matchable label forms, each+ * expanded once into its separator-variant match forms (note-change truth+ * maintenance, F3) and the expansion Set-deduped. Precomputed HERE - once+ * per capture, not once per fact - so the per-fact kernel never re-derives+ * a variant.+ */export interface AnchorableEntity {readonly id: string;readonly forms: ReadonlyArray<string>;@@ -316,9 +341,18 @@ export function buildAnchorables(// Fall through: entityMatchForms drops the junk name form itself, so a// valid alias still yields an anchorable form.}- const forms = entityMatchForms([entity.name, ...entity.aliases], { lexicon }).filter(- (f) => f.length >= MIN_ANCHOR_FORM_LENGTH,- );+ // Match-variant expansion (F3) happens ONCE here, per capture: the+ // gate-filtered normalized forms fold to their canonical-join match+ // variants (at most the full form plus a folder-prefixed tail).+ // MIN_ANCHOR_FORM_LENGTH still gates the ORIGINAL forms - an+ // expansion never rescues a short one.+ const forms = [+ ...new Set(+ entityMatchForms([entity.name, ...entity.aliases], { lexicon })+ .filter((f) => f.length >= MIN_ANCHOR_FORM_LENGTH)+ .flatMap((f) => matchFormVariants(f)),+ ),+ ];if (forms.length === 0) continue;out.push({ id: entity.id, forms });}@@ -327,20 +361,49 @@ export function buildAnchorables(/*** Resolve canonical-entity anchors for a fact: every anchorable registry- * entity whose normalised label form appears in the fact text. The- * canonicalization kernel is the comparison boundary, so facts and the- * registry compare like with like.+ * entity whose match forms occur in the fact text. The canonicalization+ * kernel is the comparison boundary, so facts and the registry compare+ * like with like - and since F3 (note-change truth maintenance) both+ * sides fold: the haystack folds through {@link matchFormVariants} once+ * per fact, each entity's precomputed variants are compared through the+ * shared leading-edge rule ({@link matchVariantsOccurIn}), so a spaced+ * text anchors a hyphenated or folder-prefixed form while the fold never+ * plants a mid-word hit nothing anchored before.*/function entityAnchors(anchorables: ReadonlyArray<AnchorableEntity>, factText: string): string[] {if (anchorables.length === 0) return [];- const haystack = normalizeEntityName(factText);+ const haystackVariants = matchFormVariants(normalizeEntityName(factText));const ids: string[] = [];for (const entity of anchorables) {- if (entity.forms.some((f) => haystack.includes(f))) ids.push(entity.id);+ if (matchVariantsOccurIn(entity.forms, haystackVariants)) ids.push(entity.id);}return ids;}+/**+ * The persisted anchor union for one capture: the caller's link-derived+ * ids first, in the body order they arrived (the first body-order link+ * is the primary when both mechanisms match the same fact), then the+ * text-derived anchors the kernel found, deduped across the two+ * mechanisms. Absent or empty link ids answer the text anchors verbatim,+ * so a session-sourced capture is byte-identical to before the parameter+ * existed.+ */+function unionAnchors(+ linkDerived: ReadonlyArray<string> | undefined,+ textAnchors: ReadonlyArray<string>,+): ReadonlyArray<string> {+ if (linkDerived === undefined || linkDerived.length === 0) return textAnchors;+ const out: string[] = [];+ const seen = new Set<string>();+ for (const id of [...linkDerived, ...textAnchors]) {+ if (seen.has(id)) continue;+ seen.add(id);+ out.push(id);+ }+ return out;+}+/*** Write extracted facts as `source_type: extracted` signals. Facts* that name a registered canonical entity (or alias) carry the@@ -489,7 +552,7 @@ export function routeExtractedFacts(vault: string, input: RouteFactsInput): Routwithheld++;continue;}- const anchors = entityAnchors(anchorables, fact.text);+ const anchors = unionAnchors(input.linkDerivedEntityIds, entityAnchors(anchorables, fact.text));const topic = `fact-${fact.family}`;try {const result = writeSignal(diff --git a/src/core/brain/intake/page-entity-links.ts b/src/core/brain/intake/page-entity-links.tsnew file mode 100644index 00000000..7bf976ed--- /dev/null+++ b/src/core/brain/intake/page-entity-links.ts@@ -0,0 +1,198 @@+/**+ * Page-link to entity resolver (note-change truth maintenance, F4/C1).+ *+ * A source page that cites an entity page carries more than its prose:+ * its outbound wikilinks name the records the page is about. This module+ * turns those links into the ordered list of canonical entity ids the+ * page links to, so an extraction caller can resolve them server-side+ * and hand the ids to the anchoring kernel - link-derived attachment+ * without pulling the link graph into the kernel itself.+ *+ * ## The accessor is injected, and it owns withholding+ *+ * The pure half ({@link pageEntityLinks}) knows nothing about vaults or+ * indexes: it extracts the wikilinks in first-occurrence order+ * (`extractWikilinks`, which masks code regions and skips media) and maps+ * each target through the injected accessor. A target the accessor leaves+ * unresolved contributes nothing, and a target it refuses is IDENTICAL TO+ * ABSENT - the link-candidates convention, applied before the list is+ * returned, so a withheld entity page is never leaked as an id and never+ * even counts. Which pages are withheld is the caller's question, not this+ * module's: the accessor is where a reach rule or an owner scope binds.+ *+ * {@link entityLinkResolver} is the production accessor over a vault's+ * entity index. It resolves through the spellings a wikilink to an entity+ * page can actually carry, in ladder order:+ *+ * 1. the entity id itself, with or without the `.md` suffix+ * (`[[ent-people-ada-lovelace]]`, `[[ent-people-ada-lovelace.md]]`);+ * 2. the page's own vault path, with or without `.md`+ * (`[[Brain/entities/people/...]]`) - a spelling that carries a+ * directory prefix answers ONLY as that path, never by basename+ * alone, because the vault's own link resolution dangles on a+ * prefixed spelling that names no page and so must this resolver;+ * 3. the slug-prefixed spelling `[[people/ada-lovelace]]` - each path+ * segment lowercased and its separator runs folded the way the+ * anchoring kernel's separator-tolerant spelling folds them, so+ * what the matcher admits and what the resolver maps agree on one+ * rule. The fold is the matcher's, not the full id-minting+ * slugify: a character only slugify folds (a period, an+ * apostrophe) stays as written and the spelling dangles, exactly+ * as the vault's own link resolution dangles on it. The rung is+ * defined on the category/slug form a directory prefix carries -+ * a spelling without one never reaches it;+ * 4. a frontmatter alias, through the index's own alias vocabulary -+ * except an alias more than one visible canonical entity claims:+ * the index records that claim as a duplicate-alias conflict and+ * answers it to no one, and a resolver that picked a first winner+ * would turn an ambiguous link into a confident wrong anchor.+ *+ * Every rung answers the TRIMMED target: the shared wikilink extractor+ * captures the text between the brackets untrimmed, so the whitespace a+ * link carries is not part of the spelling the author wrote. The `.md`+ * suffix is the one tolerance beyond that: entity ids and paths are+ * answered case-sensitively, because a link is matched by its exact+ * stored spelling the same way every other link read in this codebase+ * matches, and a case-insensitive id map would resolve spellings the+ * vault's own link resolution refuses.+ *+ * A bare entity NAME is deliberately not a rung: name-in-text matching is+ * the anchoring kernel's job, and a link spelling the vault's own link+ * resolution would dangle on stays dangling here too. Records outside the+ * canonical scope (archived, quarantined, unparsable) resolve to nothing,+ * exactly like absent pages, and a page the `visible` predicate refuses is+ * dropped before any of its spellings can answer. An index that cannot+ * build resolves nothing and never throws - a broken registry must not+ * turn every page into a failed read, and it must not invent anchors+ * either.+ */++import { relative, sep } from "node:path";++import { extractWikilinks } from "../../vault.ts";+import { normalizeEntityName } from "../entities/canonical.ts";+import { buildEntityIndex } from "../entities/index-builder.ts";+import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "../entities/status-scope.ts";++/**+ * May this wikilink target be attached as a canonical entity id? Answers+ * the id, or `undefined` when the target does not resolve to an entity+ * page the caller may attach - absent, non-entity, out of canonical+ * scope, or withheld by the caller's reach rule.+ */+export type EntityLinkAccessor = (target: string) => string | undefined;++/**+ * The ordered canonical entity ids `content` links to, in+ * `extractWikilinks` first-occurrence order, deduped across spellings+ * that resolve to one id. A target that resolves to nothing contributes+ * nothing - including one whose accessor raises, because a link the+ * resolver cannot answer is an unresolved link, not a failed page. Never+ * throws; nothing to resolve answers an empty list.+ */+export function pageEntityLinks(content: string, resolve: EntityLinkAccessor): string[] {+ const ids: string[] = [];+ const seen = new Set<string>();+ for (const target of extractWikilinks(content)) {+ let id: string | undefined;+ try {+ id = resolve(target);+ } catch {+ id = undefined;+ }+ if (id === undefined || seen.has(id)) continue;+ seen.add(id);+ ids.push(id);+ }+ return ids;+}++export interface EntityLinkResolverOptions {+ /**+ * May the caller read the entity page at this VAULT-RELATIVE path?+ * REQUIRED, with no default: a predicate nobody wrote must not read as+ * "everything is visible", because the resolver indexes every+ * canonical-scope entity it can see, and the anchor list naming an+ * entity page the reader cannot read IS the disclosure. A caller+ * already running at the vault's own reach (a local maintenance lane,+ * the local CLI) passes `() => true` - the decision stays visible at+ * the call site, and a caller deriving the list for a narrower reader+ * binds its rule here. A refused page is dropped before the list is+ * returned, so the refused id is not merely hidden but absent.+ */+ readonly visible: (rel: string) => boolean;+}++/**+ * The production {@link EntityLinkAccessor} over `vault`'s entity index,+ * built once per call. Canonical-scope records only; a page the caller's+ * `visible` predicate refuses is dropped before answering, under every+ * spelling it answers to - and before counting as an alias claimant,+ * since a refused page is identical to absent and cannot make a visible+ * entity's alias ambiguous. An alias two visible entities claim is+ * dropped for both, the index's own duplicate-alias rule mirrored over+ * the population this accessor may name. Never throws: an index that+ * cannot build answers `undefined` for every target, which is the one+ * answer that cannot leak a record a broken walk cannot see.+ */+export function entityLinkResolver(+ vault: string,+ opts: EntityLinkResolverOptions,+): EntityLinkAccessor {+ let index: ReturnType<typeof buildEntityIndex>;+ try {+ index = buildEntityIndex(vault);+ } catch {+ return () => undefined;+ }+ const byId = new Map<string, string>();+ const byPath = new Map<string, string>();+ const aliasClaims = new Map<string, Set<string>>();+ for (const entity of index.entities) {+ if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;+ const rel = relative(vault, entity.path).split(sep).join("/");+ if (!opts.visible(rel)) continue;+ byId.set(entity.id, entity.id);+ // The page's own vault path, with and without the `.md` suffix: the+ // only directory-prefixed spellings that answer (rung 2).+ byPath.set(rel, entity.id);+ byPath.set(rel.replace(/\.md$/i, ""), entity.id);+ for (const alias of entity.aliases) {+ const normalized = normalizeEntityName(alias);+ if (!normalized) continue;+ const claimants = aliasClaims.get(normalized) ?? new Set<string>();+ claimants.add(entity.id);+ aliasClaims.set(normalized, claimants);+ }+ }+ // Contested aliases answer no one; uncontested ones answer their one+ // claimant, deterministically.+ const byAlias = new Map<string, string>();+ for (const [normalized, claimants] of aliasClaims) {+ if (claimants.size !== 1) continue;+ byAlias.set(normalized, claimants.values().next().value!);+ }+ return (target) => {+ const trimmed = target.trim();+ if (byId.has(trimmed)) return trimmed;+ const stripped = trimmed.replace(/\.md$/i, "");+ const asPath = byPath.get(stripped);+ if (asPath !== undefined) return asPath;+ if (!stripped.includes("/") && byId.has(stripped)) return stripped;+ // A bare spelling's rungs end here. The fold below is the+ // slug-prefixed spelling's rung, defined on the category/slug form+ // a directory prefix carries; folded over a bare name it would+ // mint the id's own slug out of "People Ada Lovelace" or+ // "people_ada_lovelace" - bare entity NAMEs, which are deliberately+ // not a rung - and resolve spellings the vault's own link+ // resolution dangles on. Case-varying a bare id stays unresolved+ // for the same reason: ids are answered case-sensitively.+ if (!stripped.includes("/")) return byAlias.get(normalizeEntityName(trimmed));+ const slugPrefixed = `ent-${stripped+ .split("/")+ .map((segment) => segment.toLowerCase().replace(/[-_ ]+/g, "-"))+ .join("-")}`;+ if (byId.has(slugPrefixed)) return slugPrefixed;+ return byAlias.get(normalizeEntityName(trimmed));+ };+}diff --git a/src/core/brain/link-graph/minimal-spelling.ts b/src/core/brain/link-graph/minimal-spelling.tsnew file mode 100644index 00000000..29d2dda3--- /dev/null+++ b/src/core/brain/link-graph/minimal-spelling.ts@@ -0,0 +1,110 @@+/**+ * The minimal-spelling chooser for inbound wikilink retargets.+ *+ * A note relocation has to rewrite the links that named it, and a+ * rewrite that preserves each link's original FORM writes longer links+ * than the vault still needs: `[[Projects/Old]]` becomes+ * `[[Projects/New]]` when `[[New]]` would have resolved to the same+ * note. The chooser answers one question, purely and without I/O:+ * what is the shortest spelling that STILL resolves, under the store's+ * own resolution rules, to exactly this note?+ *+ * The rules are not invented here. They mirror the read-time resolution+ * ladder of `src/core/search/store/links.ts` (RESOLVED_LINK_TARGET_SQL,+ * lines 62-70), rung for rung, so a spelling this chooser calls minimal+ * is a spelling the index itself resolves to the same document:+ *+ * - exact path: `spelling` (or `spelling + ".md"`) is a document path;+ * - bare basename, top-level first: a top-level `New.md` OWNS the bare+ * `New` spelling through the exact-path rung, whatever nested notes+ * also carry the basename - so for a nested destination a shared+ * top-level name makes the bare spelling a WRONG answer, and the+ * chooser falls through;+ * - bare basename, nested, exactly one: the ladder's basename rung+ * resolves only when the count of nested carriers is exactly one.+ *+ * Shortest-first over basename, suffix-less relPath, full relPath. An+ * ambiguous spelling is never a stop: it falls through to the+ * next-longer form, because a spelling two documents share resolves, by+ * the ladder's own rule, to neither. If nothing resolves to the+ * destination - the destination is not in the population at all - the+ * full relPath is returned rather than any shorter guess, so a caller+ * that writes the answer writes an over-qualified link and never a+ * broken one.+ *+ * Aliases are deliberately not modeled: the chooser judges a walked+ * file population, and alias resolution lives in the index's+ * `doc_aliases` table, which no walk carries. A spelling only an alias+ * could resolve gets a longer form, which is the honest answer for a+ * population-based judgement.+ */++/**+ * `Projects/Old.md` -> `Old`, matching the store's `documentBasename`.+ * The suffix test is CASE-SENSITIVE on purpose: the ladder's basename+ * rung joins against the stored `documents.basename`, which strips a+ * trailing `.md` and nothing else, so `Old.MD` keeps that basename and+ * the bare spelling `Old` dangles - a candidate this chooser must never+ * produce, however much shorter it reads.+ */+function basenameOf(relPath: string): string {+ const last = relPath.split("/").at(-1) ?? relPath;+ return last.endsWith(".md") ? last.slice(0, -".md".length) : last;+}++/** `Projects/Old.md` -> `Projects/Old`. */+function withoutMarkdownSuffix(relPath: string): string {+ return relPath.toLowerCase().endsWith(".md") ? relPath.slice(0, -".md".length) : relPath;+}++/**+ * What the ladder resolves `spelling` to over `files`, or `null` when it+ * resolves to nothing. The exact rung mirrors the ladder's COALESCE+ * order: a document named `spelling` VERBATIM answers before a document+ * named `spelling + ".md"` - and the append is UNCONDITIONAL, exactly+ * like the ladder's `target_path || '.md'` rung, so a spelling that+ * already ends in `.md` in some case (`x.Md`) still tries the appended+ * form (`x.Md.md`) instead of jumping straight to the basename rung.+ * Only then the unambiguous nested-basename rung, whose carriers+ * exclude top-level documents because a top-level carrier would have+ * owned the spelling outright one rung earlier.+ */+function resolveOverFiles(+ spelling: string,+ files: ReadonlyArray<string>,+): string | "ambiguous" | null {+ const asIs = files.filter((rel) => rel === spelling);+ if (asIs.length > 0) return asIs.length === 1 ? asIs[0]! : "ambiguous";+ const appended = files.filter((rel) => rel === `${spelling}.md`);+ if (appended.length > 0) return appended.length === 1 ? appended[0]! : "ambiguous";+ if (spelling.includes("/")) return null;+ const nested = files.filter((rel) => rel.includes("/") && basenameOf(rel) === spelling);+ if (nested.length === 1) return nested[0]!;+ if (nested.length > 1) return "ambiguous";+ return null;+}++/**+ * The shortest of basename / suffix-less relPath / full relPath whose+ * exact-one resolution over `knownFiles` equals `destinationRel`.+ *+ * `knownFiles` is the population a vault walk produced - vault-relative+ * paths with the `.md` suffix, the same list a retarget pass reports as+ * the files it read. For a relocation the caller derives the POST-move+ * population (the walked list minus the old path plus the new one);+ * the chooser never sees a half state.+ */+export function minimalSpellingFor(+ destinationRel: string,+ knownFiles: ReadonlyArray<string>,+): string {+ const candidates = [+ basenameOf(destinationRel),+ withoutMarkdownSuffix(destinationRel),+ destinationRel,+ ];+ for (const spelling of candidates) {+ if (resolveOverFiles(spelling, knownFiles) === destinationRel) return spelling;+ }+ return destinationRel;+}diff --git a/src/core/brain/maintenance/lane-tasks.ts b/src/core/brain/maintenance/lane-tasks.tsindex fe17362f..39cfa390 100644--- a/src/core/brain/maintenance/lane-tasks.ts+++ b/src/core/brain/maintenance/lane-tasks.ts@@ -36,6 +36,7 @@ import {} from "./custom-tasks.ts";import { LANE_TASK, type LaneTask, type LaneTaskId, type MaintenanceTask } from "./lane.ts";import { createLaneReindex, type LaneReindex } from "./reindex-task.ts";+import { runRelinkAnchors, type RelinkAnchorsReport } from "./relink-anchors-task.ts";export interface LaneTaskBuildOptions {readonly vault: string;@@ -44,6 +45,15 @@ export interface LaneTaskBuildOptions {readonly now: Date;/** Bypass a positive embedding cost gate for this run (`--force-cost`). */readonly forceCost: boolean;+ /**+ * Apply the relink pass: rewrite the changed signal pages' anchor+ * lines. Absent or false, the lane's relink task is the dry run - it+ * reports what it would add and writes nothing - because every other+ * pass an unattended lane runs through a cron produces no new writes+ * without an explicit ask. The apply arm carries the run's own+ * vault-identity write guard.+ */+ readonly relinkApply?: boolean;/** One fresh deadline per built-in task, called when that task starts. */readonly safeguardFor: (operation: LaneTask) => Safeguard;readonly signal?: AbortSignal;@@ -58,11 +68,24 @@ export interface LaneTaskSet {/** Every registered identity, in registration order. */readonly taskNames: ReadonlyArray<LaneTaskId>;readonly custom: CustomTaskResolution;+ /**+ * The relink pass's report for the run dispatched through this set, or+ * `undefined` while the task has not completed: the preview on the+ * default arm, the changes on the apply arm. Read after+ * `runMaintenance` resolves, beside the task rows - the same shape the+ * reindex spend block rides, because a task's report belongs to the+ * run, not to a task row's receipt field.+ */+ relinkReport(): RelinkAnchorsReport | undefined;}export function buildLaneTasks(opts: LaneTaskBuildOptions): LaneTaskSet {const { vault, now, searchConfig, safeguardFor } = opts;const laneProgress = opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {};+ // The relink report is captured by the task body and read by the+ // caller after the run: `undefined` until the task completes, and+ // undefined again never - a set builds one run's tasks.+ let relinkReport: RelinkAnchorsReport | undefined;// Spend is opt-in (`maintenance_embeddings`): the reindex builder decides// whether the pass may embed, announces the predicted spend inside the// task and receipts what the phase priced.@@ -149,6 +172,25 @@ export function buildLaneTasks(opts: LaneTaskBuildOptions): LaneTaskSet {}},},+ // The anchor-relink pass (note-change truth maintenance) closes the+ // lane: it reads the signal tree and the entity index only, so it+ // needs no store. It PREVIEWS by contract - `relinkApply` hands it+ // the apply arm, and absent that flag the report is what would change+ // and no signal page is rewritten. Either way the pass's report is+ // captured below and surfaced through `relinkReport()`, so neither+ // front door runs the pass blind. The pass never calls a model and+ // returns no spend receipt.+ {+ name: LANE_TASK.relink,+ run: async () => {+ relinkReport = runRelinkAnchors(vault, {+ now,+ apply: opts.relinkApply === true,+ safeguard: safeguardFor(LANE_TASK.relink),+ ...laneProgress,+ });+ },+ },];const custom = resolveCustomTasks(opts.configPath);const customTasks = custom.specs.map((spec) =>@@ -158,5 +200,11 @@ export function buildLaneTasks(opts: LaneTaskBuildOptions): LaneTaskSet {}),);const tasks = [...builtIns, ...customTasks];- return { tasks, reindex, taskNames: tasks.map((task) => task.name), custom };+ return {+ tasks,+ reindex,+ taskNames: tasks.map((task) => task.name),+ custom,+ relinkReport: () => relinkReport,+ };}diff --git a/src/core/brain/maintenance/lane.ts b/src/core/brain/maintenance/lane.tsindex e7dd410c..15ca477a 100644--- a/src/core/brain/maintenance/lane.ts+++ b/src/core/brain/maintenance/lane.ts@@ -225,6 +225,7 @@ export const LANE_TASK = Object.freeze({reindex: OPERATION.reindex,bridges: OPERATION.bridges,clusters: OPERATION.clusters,+ relink: OPERATION.relink,} as const);export type LaneTask = (typeof LANE_TASK)[keyof typeof LANE_TASK];@@ -239,6 +240,7 @@ export const LANE_TASKS: ReadonlyArray<LaneTask> = Object.freeze([LANE_TASK.reindex,LANE_TASK.bridges,LANE_TASK.clusters,+ LANE_TASK.relink,]);/**diff --git a/src/core/brain/maintenance/relink-anchors-task.ts b/src/core/brain/maintenance/relink-anchors-task.tsnew file mode 100644index 00000000..afffc23c--- /dev/null+++ b/src/core/brain/maintenance/relink-anchors-task.ts@@ -0,0 +1,768 @@+/**+ * The relink maintenance lane task (note-change truth maintenance, F4/C3).+ *+ * Anchors are facts of attachment: a signal whose `entities:` line omits+ * an entity it is about never reaches that entity's recall surface. The+ * anchoring kernel accepts caller-resolved link-derived ids beside the+ * text-derived ones, but that parameter is an extension seam - no shipped+ * extraction caller resolves its source page's links yet - so the+ * extraction callers write text-derived anchors only, and every signal+ * stored before and since holds just what its own text named. This pass+ * is the seam's shipped consumer: it walks the signal pages, and for+ * every PAGE-SOURCED signal (one whose `source:` pointer resolves to a+ * vault page) it recomputes the anchors with the shipped rules and unions+ * them into the stored line.+ *+ * ## The recomputation uses the shipped matchers, never new ones+ *+ * Text anchors come from the same build the capture path builds, matched+ * through the capture path's own occurrence rule: the fact text+ * normalized once and expanded through {@link matchFormVariants}, each+ * entity's precomputed variants tested with {@link matchVariantsOccurIn}+ * - the exact comparison `routeExtractedFacts` performs, so a form this+ * pass adds is exactly a form the extractor itself would attach today.+ * Link-derived ids come from the page-link resolver+ * ({@link ../intake/page-entity-links.ts}), the same resolver a+ * page-sourced extraction caller would use. The resolver's `visible`+ * predicate binds at the reach the SIGNAL ITSELF is readable at, not at+ * the lane's: a signal any remote-reach reader can list only ever+ * receives ids whose entity page and source page are readable at that+ * reach, because an id written into a listable signal is disclosed to+ * every reader that can list it - and this pass never removes an anchor,+ * so the disclosure would be permanent. The TEXT-derived matches answer+ * to the same per-signal predicate: the anchorable list is built at the+ * lane's reach, and a match against it unfiltered would write a private+ * entity's id into a remotely readable signal just the same. A signal+ * reserved against remote reads keeps {@link MAINTENANCE_LANE_REACH}:+ * the lane is a local repair pass, and what it heals for a local-only+ * page never leaves the host.+ *+ * ## Server-stamped sources only+ *+ * The pass also acts only on signals whose `source:` the SERVER derived -+ * `source_type: extracted`, the stamp every extraction caller writes. A+ * `brain_feedback` caller supplied its own pointer (a `live` signal+ * carries no source_type at all - absence IS the live stamp), and an+ * inline author marker is author-written the same way; a caller-chosen+ * page must not choose which entity ids attach, because the card's+ * invariant is that server-derived facts outrank caller-supplied claims.+ * Those signals are out of the pass's scope entirely: the pass never+ * reads their pointers, and they are counted by neither arm - the same+ * answer a signal whose pointer names no page gets.+ *+ * ## Additive only, and dry-run by default+ *+ * An anchor already stored is never removed, even when the recompute+ * would not produce it: the pass heals narrow anchor lists, it does not+ * second-guess wide ones (an id that outlived its entity is the doctor's+ * finding, not this pass's deletion). Absent {@link RelinkAnchorsOptions.apply}+ * the pass reports what it WOULD add and writes nothing - including the+ * `entity-anchor-skip` audit the shared anchorable build appends for a+ * junk-named entity: the dry run builds its anchorables through the same+ * gate, floor and variant expansion with the logging held back, because a+ * preview that wrote the log would not be a preview. With `apply` the+ * changed signal pages are rewritten in place through the atomic writer,+ * the stored ids first and the added ones appended, and the audit is+ * stamped exactly as the capture path stamps it. The rewrite's only safe+ * home is the extractor's own raw shape: one `entities: <ids>` line,+ * exactly what `routeExtractedFacts` writes for a fact that anchored. An+ * in-scope signal whose Raw holds anything else is carrying prose - a+ * verbatim quote - and a line-level rewrite there overwrote the quote's+ * own `entities:` line, spliced an anchor line into a quote, or landed+ * mid-quote past a heading; such a signal is skipped ENTIRELY, counted in+ * `signalsSkippedRawShape`, never written. A signal whose raw reads as+ * absent (no `## Raw` section, or the legacy placeholder) is not a shape+ * failure - the extractor writes no raw at all for a fact that anchored+ * nothing - and the rewrite's own support decides below whether the+ * anchor has a home, so a page without the section stays counted by+ * neither arm: a dry run never reports an addition no apply could make.+ * The same hold-out covers a codec-compressed section: the bytes on disk+ * hold the reversible compressed form, whose collapsed whitespace runs+ * can hide the `entities:` line from a line-level rewrite, so the pass+ * skips those signals outright rather than write a line the next parse+ * never reads - the gate the raw-shape check subsumes for prose sections,+ * kept for the shaped raw a codec stores. The apply arm writes against+ * the bytes it read (`expectBefore`): a page edited or moved between the+ * read and the rename fails the write instead of losing that edit, and+ * the next pass retries. The byte gates are re-run on those bytes too+ * ({@link decideRawRewrite}): a page edited between the parse and the+ * apply read is judged by what it now IS, not what the parse saw, so a+ * Raw turned quote or codec in that window is skipped like any other.+ *+ * The pass never calls a model: the recomputation is a file walk, an+ * index build and pure matching, bounded by the caller's safeguard like+ * every other lane task.+ */++import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";+import { join, relative, sep } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { ensureInsideVault } from "../../path-safety.ts";+import { MAINTENANCE_LANE_REACH, TRANSPORT_REACH } from "../../graph/transport-reach.ts";+import type { TransportReach } from "../../graph/transport-reach.ts";+import { isPathReadableAtReach, type FrontmatterCache } from "../../search/result-filters.ts";+import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import { buildEntityIndex } from "../entities/index-builder.ts";+import {+ entityMatchForms,+ matchFormVariants,+ matchVariantsOccurIn,+ MIN_ANCHOR_FORM_LENGTH,+ normalizeEntityName,+} from "../entities/canonical.ts";+import { resolveEntityLexicon } from "../entities/lexicon.ts";+import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "../entities/status-scope.ts";+import { brainDirs } from "../paths.ts";+import { progressCounter, type ProgressSink } from "../progress.ts";+import { parseSignal } from "../signal.ts";+import { BRAIN_SIGNAL_SOURCE_TYPE } from "../types.ts";+import type { Safeguard } from "../safeguard.ts";+import { OPERATION } from "../safeguard.ts";+import {+ entityLinkResolver,+ pageEntityLinks,+ type EntityLinkAccessor,+} from "../intake/page-entity-links.ts";+import { buildAnchorables, type AnchorableEntity } from "../fact-extract.ts";++/** One source page's rollup in the relink report. */+export interface RelinkSourceReport {+ /** The vault-relative path the signal's source pointer resolved to. */+ readonly source: string;+ /** Page-sourced signals citing this page. */+ readonly signals: number;+ /** Anchors this pass adds (or would add) for those signals. */+ readonly anchorsAdded: number;+}++/** What one relink pass found (and, on `apply`, changed). */+export interface RelinkAnchorsReport {+ /** False for the default dry run: the report describes a would-be pass. */+ readonly apply: boolean;+ /** Every `sig-*.md` page the walk opened in the inbox and processed trees. */+ readonly signalsScanned: number;+ /** Pages that could not be parsed; counted, never fatal. */+ readonly signalsUnreadable: number;+ /**+ * In-scope signals (`source_type: extracted`) whose `source:` pointer+ * resolved to at least one vault page at the signal's own reach.+ */+ readonly signalsPageSourced: number;+ /**+ * In-scope signals skipped because their Raw section is not the+ * extractor's own single `entities:` line shape - counted, never+ * written: the rewrite's only safe home is the shape+ * `routeExtractedFacts` itself writes, and anything else in `## Raw`+ * is a quote the pass has no business editing.+ */+ readonly signalsSkippedRawShape: number;+ /** Signals with at least one anchor to add - rewritten on `apply`. */+ readonly signalsChanged: number;+ /** Total anchors added (or would be added) across every signal. */+ readonly anchorsAdded: number;+ /** Per-source rollup, sorted by source path. */+ readonly perSource: ReadonlyArray<RelinkSourceReport>;+}++export interface RelinkAnchorsOptions {+ /**+ * Injected clock; on the apply arm it stamps the skip-audit log events+ * the shared anchorable build emits, exactly as the capture path stamps+ * them. The dry run writes nothing and needs no stamp.+ */+ readonly now: Date;+ /**+ * Rewrite the changed signal pages. Absent or false (the default) the+ * pass is a dry run: the report says what would change and no byte is+ * written. The doctor repair-lane precedent: preview first, mutate on+ * an explicit ask.+ */+ readonly apply?: boolean;+ /** Safeguard budget handed down by the lane; checkpoints between files. */+ readonly safeguard?: Safeguard;+ /** Progress stream for the signal walk, when the caller has one. */+ readonly onProgress?: ProgressSink;+}++/** Largest source page this pass reads, matching the inline walk's cap. */+const SOURCE_PAGE_MAX_BYTES = 1_048_576;++/** The raw-section placeholder a signal with no stored raw content carries. */+const RAW_PLACEHOLDER = "_(not provided)_";++/**+ * The dry run's quiet twin of the capture path's anchorable build+ * (`buildAnchorables`): the same quality gate, the same length floor and+ * the same separator-variant expansion, minus the `entity-anchor-skip`+ * log events the shared build appends for a junk-named entity - those are+ * writes, and a preview must not write. The apply arm calls the shared+ * build, so the audit trail is stamped exactly where bytes change; the+ * two builds compute the same forms, which is what the dry/apply+ * agreement pin in the task's suite holds.+ */+function buildAnchorablesQuietly(+ vault: string,+ index: ReturnType<typeof buildEntityIndex>,+): AnchorableEntity[] {+ const lexicon = resolveEntityLexicon(vault);+ const out: AnchorableEntity[] = [];+ for (const entity of index.entities) {+ if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;+ // The capture build's own form rule, verbatim: gate each label, keep+ // the forms at or above the length floor, expand each once into its+ // separator variants, Set-deduped in the generator's order. A+ // junk-named entity still anchors on its valid alias forms here,+ // exactly as it does on the capture path.+ const forms = [+ ...new Set(+ entityMatchForms([entity.name, ...entity.aliases], { lexicon })+ .filter((f) => f.length >= MIN_ANCHOR_FORM_LENGTH)+ .flatMap((f) => matchFormVariants(f)),+ ),+ ];+ if (forms.length === 0) continue;+ out.push({ id: entity.id, forms });+ }+ return out;+}++/** The `entities:` ids of a raw section, in stored order; empty when absent. */+function storedAnchorIds(raw: string | undefined): string[] {+ if (raw === undefined) return [];+ for (const line of raw.split(/\r?\n/)) {+ if (line.startsWith("entities:")) {+ return line+ .slice("entities:".length)+ .split(",")+ .map((id) => id.trim())+ .filter((id) => id.length > 0);+ }+ }+ return [];+}++/**+ * Is `raw` EXACTLY the shape the extractor writes - one `entities: <ids>`+ * line, nothing else? The rewrite's only safe home. `storedAnchorIds`+ * trusts the first `entities:` line it finds, and a Raw section holding+ * author prose - a verbatim quote - can carry such a line as its own+ * words: rewriting there overwrote the quote's text, spliced an anchor+ * line into it, or landed mid-quote past a heading the parser reads past+ * and the line-rewrite stops at. A single line, `entities: `-prefixed,+ * parsing to at least one id: anything else skips the signal (counted,+ * never written), and the section stays byte-identical.+ */+function isExtractorRawShape(raw: string): boolean {+ if (raw.includes("\n") || raw.includes("\r")) return false;+ if (!raw.startsWith("entities: ")) return false;+ return storedAnchorIds(raw).length > 0;+}++/**+ * The signal page rewritten with `nextLine` as its `entities:` line, or+ * `undefined` when the page has no `## Raw` section to rewrite in. The+ * stored line is replaced in place; a section without one gains the line+ * in place of the placeholder, or appended after its last content.+ */+export function rewriteRawEntitiesLine(contents: string, nextLine: string): string | undefined {+ const lines = contents.split("\n");+ const rawIdx = lines.findIndex((line) => line.trim() === "## Raw");+ if (rawIdx < 0) return undefined;+ let end = lines.length;+ for (let i = rawIdx + 1; i < lines.length; i++) {+ if (lines[i]!.startsWith("## ")) {+ end = i;+ break;+ }+ }+ for (let i = rawIdx + 1; i < end; i++) {+ if (lines[i]!.startsWith("entities:")) {+ lines[i] = nextLine;+ return lines.join("\n");+ }+ }+ for (let i = rawIdx + 1; i < end; i++) {+ if (lines[i]!.trim() === RAW_PLACEHOLDER) {+ lines[i] = nextLine;+ return lines.join("\n");+ }+ }+ let insertAt = end;+ for (let i = end - 1; i > rawIdx; i--) {+ if (lines[i]!.trim() !== "") {+ insertAt = i + 1;+ break;+ }+ }+ lines.splice(insertAt, 0, nextLine);+ return lines.join("\n");+}++/**+ * The Raw section the BYTES carry - the span the parser itself reads+ * (everything after the `## Raw` heading through EOF, the schema's one+ * section), trimmed, or `undefined` when the bytes hold no such heading+ * or only blank lines. The drift re-check below re-runs the shape gate+ * on this span, so the gate and the parse-time gate judge the same+ * bytes: a heading after `## Raw` is part of the section - multi-line,+ * not the extractor's shape - and answers `unsafe-shape` here exactly+ * as the parse gate would, instead of being cut off and the remainder+ * mistaken for a rewritable one-liner.+ */+function rawSectionBytes(contents: string): string | undefined {+ const lines = contents.split("\n");+ const rawIdx = lines.findIndex((line) => line.trim() === "## Raw");+ if (rawIdx < 0) return undefined;+ const section = lines+ .slice(rawIdx + 1)+ .join("\n")+ .trim();+ return section.length > 0 ? section : undefined;+}++/**+ * True when the bytes' frontmatter carries the `_raw_codec` marker: the+ * body on disk is the reversible COMPRESSED form, whatever it spells.+ * The parse-time codec gate reads the same marker from the parsed+ * frontmatter; the drift re-check reads it from the raw bytes because+ * the parse's copy can go stale.+ */+function hasRawCodecMarker(contents: string): boolean {+ const lines = contents.split("\n");+ if (lines[0]?.trim() !== "---") return false;+ const close = lines.findIndex((line, i) => i > 0 && line.trim() === "---");+ if (close < 0) return false;+ return lines.slice(1, close).some((line) => line.trim().startsWith("_raw_codec:"));+}++/** What the byte-level drift re-check decided about one signal page. */+export type RawRewriteDecision =+ | {+ readonly action: "rewrite";+ readonly next: string;+ /** The ids the rewrite actually appends - not one of them was stored. */+ readonly appended: ReadonlyArray<string>;+ }+ | { readonly action: "no-home" }+ | { readonly action: "codec" }+ | { readonly action: "unsafe-shape" };++const NO_REWRITE_HOME: RawRewriteDecision = Object.freeze({ action: "no-home" } as const);++/**+ * Decide the raw-line rewrite against the bytes a fresh read just+ * returned - the drift re-check for the window between the pass's+ * `parseSignal` (whose bytes every gate above judged) and this read. A+ * page edited in that window would otherwise have the rewrite run on+ * bytes no gate checked: a Raw turned prose - a verbatim quote - is the+ * overwrite the shape gate exists to prevent, and a line rebuilt from+ * the parse's stored ids would drop an id the edit stored. The decision+ * re-runs the SAME hold-outs, with the parse gates' own semantics, on+ * the rewrite's own bytes: a codec marker beside a real section is the+ * parse-time codec gate's answer (`codec` - skipped like that gate,+ * counted by neither arm); a section that is neither the extractor's+ * one-line shape nor a fillable placeholder (nor absent) is+ * `unsafe-shape` and the caller skips the signal entirely, counted where+ * the parse-time shape gate counts; a page with no Raw section at all is+ * `no-home`; anything else rewrites with the ids the bytes themselves+ * store, so an edit that widened the list keeps its ids, one that+ * withdrew them is not resurrected, and one that already stored a+ * computed id makes `appended` - not the parse's additions - the truth+ * about what this rewrite adds. The caller still writes through+ * `expectBefore`, so an edit landing after this read fails the write+ * instead of being discarded.+ */+export function decideRawRewrite(before: string, added: ReadonlyArray<string>): RawRewriteDecision {+ const bytesRaw = rawSectionBytes(before);+ // The codec gate, on the marker the bytes themselves carry - but only+ // where the parse gate fires too: `rawCodec` is true for a marker AND+ // a real section, so a marker over an absent or placeholder section is+ // not a codec page and falls through to the shape logic below, where+ // the old flow already answered it. The compression is out of the line+ // rewrite's reach even where the compressed SPELLING happens to read+ // as the extractor's one line - the collapse that hid the section's+ // real content is the whole reason the gate skips codec pages.+ if (hasRawCodecMarker(before) && bytesRaw !== undefined && bytesRaw !== RAW_PLACEHOLDER) {+ return { action: "codec" };+ }+ if (bytesRaw !== undefined && bytesRaw !== RAW_PLACEHOLDER && !isExtractorRawShape(bytesRaw)) {+ return { action: "unsafe-shape" };+ }+ const byteStored =+ bytesRaw === undefined || bytesRaw === RAW_PLACEHOLDER ? [] : storedAnchorIds(bytesRaw);+ const appended = added.filter((id) => !byteStored.includes(id));+ if (appended.length === 0) {+ // Every id the pass computed is already on the page - a concurrent+ // edit stored it after the parse. Nothing to add, nothing to count:+ // the truthful answer is the same no-op the no-home path gives.+ return NO_REWRITE_HOME;+ }+ const nextLine = `entities: ${[...byteStored, ...appended].join(", ")}`;+ // `rewriteRawEntitiesLine` is a pure string fold and never throws.+ const next = rewriteRawEntitiesLine(before, nextLine);+ return next === undefined ? NO_REWRITE_HOME : { action: "rewrite", next, appended };+}++/** The wikilink target inside a signal `source:` entry, without the alias tail. */+function sourceRefOf(entry: string): string | undefined {+ const match = /^\[\[([^\]]+)\]\]$/.exec(entry.trim());+ if (match === null) return undefined;+ const target = match[1]!.split("|")[0]!.trim();+ return target.length > 0 ? target : undefined;+}++/** True when `path` exists as a regular file - a directory is not a page. */+function isRegularFile(path: string): boolean {+ try {+ return statSync(path).isFile();+ } catch {+ return false;+ }+}++/** The absolute page path a source ref names, or `undefined`. */+function resolveSourcePage(vault: string, ref: string): string | undefined {+ let inside: string;+ try {+ inside = ensureInsideVault(join(vault, ref), vault);+ } catch {+ return undefined;+ }+ // Only a regular file resolves. A directory that happens to share the+ // page's name must not swallow the ref: the pass reads the page the+ // author linked, so the `.md` form is tried before the ref is given up+ // as unresolved.+ if (isRegularFile(inside)) return inside;+ const withMd = `${inside}.md`;+ return isRegularFile(withMd) ? withMd : undefined;+}++/**+ * Recompute the entity anchors of every page-sourced signal in the+ * vault. Dry-run by default; see the module and options documentation.+ */+export function runRelinkAnchors(vault: string, opts: RelinkAnchorsOptions): RelinkAnchorsReport {+ const apply = opts.apply === true;+ // Vault-identity write guard (context-integrity-gates, Unit J).+ // A dry run reports would-be additions and writes nothing.+ if (apply) assertVaultIdentityForWrite(vault);+ const agent = "maintenance";+ const now = opts.now;+ const reachCache: FrontmatterCache = new Map();+ // Reach-matched resolution: the visible predicate a signal's+ // attachments bind is the one at the reach the SIGNAL ITSELF is+ // readable at, not the lane's. A signal any remote-reach reader can+ // list must never receive an id whose entity page - or whose source+ // page - that reader cannot open: the id would sit in a file the+ // reader can list, and this pass never removes an anchor, so the+ // disclosure would be permanent. A local-only signal keeps the lane's+ // reach: the pass is a local repair pass, and what it heals for a+ // local-only page never leaves the host.+ const visibleAt =+ (reach: TransportReach) =>+ (rel: string): boolean =>+ isPathReadableAtReach(vault, rel, reach, reachCache);+ const laneVisible = visibleAt(MAINTENANCE_LANE_REACH);+ const remoteVisible = visibleAt(TRANSPORT_REACH.remote);+ // Vault-relative form of an absolute path. Derived with `relative`+ // rather than a length-based slice so a caller that handed down a+ // non-normalized vault root (a trailing separator, a redundant segment)+ // still yields the same relative paths as the normalized spelling.+ const relOf = (abs: string): string => relative(vault, abs).split(sep).join("/");++ let index: ReturnType<typeof buildEntityIndex>;+ try {+ index = buildEntityIndex(vault);+ } catch {+ index = { entities: [], byKey: new Map(), byAlias: new Map(), conflicts: [] };+ }+ // The apply arm builds through the capture path's own build and stamps+ // its skip audit; the dry run builds quietly, because a preview must+ // not write - not even a log event.+ const anchorables = apply+ ? buildAnchorables(vault, index, agent, now)+ : buildAnchorablesQuietly(vault, index);+ // Each anchorable's own page, so the TEXT-derived half can answer the+ // same per-signal visible predicate the link-derived half resolves+ // through: the anchorable list is built at the lane's reach and holds+ // every canonical entity the lane can see, and a match against it+ // without this filter wrote a private entity's id into a signal any+ // remote-reach reader can list - the leak the resolver's predicate+ // already closed for links, entering through the text arm instead.+ // Canonical scope, the same population the two builds admit, so every+ // matchable id resolves here.+ const entityRelById = new Map<string, string>();+ for (const entity of index.entities) {+ if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;+ entityRelById.set(entity.id, relOf(entity.path));+ }+ // One resolver per reach, built on first use: each resolves through+ // its own view of the entity index (a page the predicate refuses is+ // dropped before any spelling can answer), and a vault with no+ // page-sourced signal in scope pays for neither. The link-derived ids+ // cache beside them, keyed per reach - the same source page answers a+ // remote-readable signal with its visible links and a local-only+ // signal with all of them, so one shared map would let whichever+ // signal read the page first decide for the other.+ let laneResolver: EntityLinkAccessor | undefined;+ let remoteResolver: EntityLinkAccessor | undefined;+ const laneLinkIds = new Map<string, ReadonlyArray<string>>();+ const remoteLinkIds = new Map<string, ReadonlyArray<string>>();++ const progress = progressCounter(OPERATION.relink, opts.onProgress);+ const perSource = new Map<string, { signals: number; anchorsAdded: number }>();+ let scanned = 0;+ let unreadable = 0;+ let pageSourced = 0;+ let skippedRawShape = 0;+ let changed = 0;+ let addedTotal = 0;++ // Listed first, so the walk is ONE stage with the whole denominator+ // (both trees) - a per-directory start would reset the counter an+ // operator is watching mid-stage.+ const dirs = [brainDirs(vault).inbox, brainDirs(vault).processed];+ const batches: Array<{ dir: string; names: string[] }> = [];+ for (const dir of dirs) {+ if (!existsSync(dir)) continue;+ try {+ batches.push({+ dir,+ names: readdirSync(dir)+ .filter((n) => n.startsWith("sig-") && n.endsWith(".md"))+ .toSorted(),+ });+ } catch {+ continue;+ }+ }+ progress.start(+ "signals",+ batches.reduce((sum, batch) => sum + batch.names.length, 0),+ );+ for (const { dir, names } of batches) {+ for (const name of names) {+ opts.safeguard?.checkpoint();+ const path = join(dir, name);+ scanned++;+ progress.advance("signals");+ let signal;+ try {+ signal = parseSignal(path);+ } catch {+ unreadable++;+ continue;+ }+ // Server-stamped sources only: the pass acts on signals whose+ // `source:` the SERVER derived - `source_type: extracted`, the+ // stamp every extraction caller writes. A `brain_feedback` caller+ // supplied its own pointer (a `live` signal carries no source_type+ // at all - absence IS the live stamp), and an inline author marker+ // is author-written the same way; a caller-chosen page must not+ // choose which entity ids attach, so the pass never reads those+ // pointers. Out of the pass's scope entirely: counted by neither+ // arm, the same answer a signal whose pointer names no page gets.+ if (signal.source_type !== BRAIN_SIGNAL_SOURCE_TYPE.extracted) continue;+ // Every source pointer that resolves to a real page in this vault+ // AT THE SIGNAL'S OWN REACH. A session pointer names no page and+ // resolves to nothing, which is exactly the out-of-scope answer; a+ // page the signal's reach withholds is identical to absent, so a+ // remotely readable signal is never fed the links of a page its+ // readers cannot open. Deduped: two pointers to one page are one+ // source - it is read once and counted once.+ const remotelyReadable = isPathReadableAtReach(+ vault,+ relOf(path),+ TRANSPORT_REACH.remote,+ reachCache,+ );+ const visible = remotelyReadable ? remoteVisible : laneVisible;+ const linkResolver = remotelyReadable+ ? (remoteResolver ??= entityLinkResolver(vault, { visible: remoteVisible }))+ : (laneResolver ??= entityLinkResolver(vault, { visible: laneVisible }));+ // The per-page id cache of THIS signal's reach: one stat + read ++ // parse per DISTINCT source page, not per signal - the inbox+ // commonly holds several signals citing the same page, and the+ // page's link-derived ids cannot change mid-pass. A page that+ // cannot be read (or is oversized) caches an empty list - the same+ // contributes-no-links answer the uncached path gave.+ const linkIdsByPage = remotelyReadable ? remoteLinkIds : laneLinkIds;+ const sources = [+ ...new Set(+ (signal.source ?? []).flatMap((entry) => {+ const ref = sourceRefOf(entry);+ if (ref === undefined) return [];+ const resolved = resolveSourcePage(vault, ref);+ if (resolved === undefined) return [];+ const rel = relOf(resolved);+ return visible(rel) ? [resolved] : [];+ }),+ ),+ ].map((abs) => ({ abs, rel: relOf(abs) }));+ if (sources.length === 0) continue;+ pageSourced++;++ // A codec-compressed raw section is out of the rewrite's reach,+ // like a page without a Raw section: `raw` above is the EXPANDED+ // text, but the bytes on disk hold the compressed form, where a+ // collapsed whitespace run can merge the `entities:` line into the+ // line above it - a byte-level rewrite would append a second line+ // the next parse never reads. Counted by neither arm: a dry run+ // never reports an addition no apply could make, and run-to-run+ // numbers stay idempotent.+ if (signal.rawCodec === true) continue;++ // The rewrite's only safe home is the extractor's own raw shape:+ // one `entities: <ids>` line, exactly what `routeExtractedFacts`+ // writes for a fact that anchored. An in-scope signal whose Raw+ // holds anything else is carrying prose - a verbatim quote - and a+ // line-level rewrite there overwrote the quote's own `entities:`+ // line, spliced an anchor line into a quote, or landed mid-quote+ // past a heading (the parser reads the section to EOF; the rewrite+ // stopped at the first `## ` line). Skipped ENTIRELY, counted,+ // never written; the check runs on the PARSED raw - the expanded+ // text for a codec signal - and the codec gate above still owns+ // the byte form, since a shaped raw compressed on disk is just as+ // out of the byte-level rewrite's reach as before. A signal whose+ // raw reads as absent (no `## Raw` section, or the legacy+ // placeholder) is not a shape failure: the extractor writes no raw+ // at all for a fact that anchored nothing, and the rewrite's own+ // support decides below whether one can be filled.+ if (signal.raw !== undefined && !isExtractorRawShape(signal.raw)) {+ skippedRawShape++;+ continue;+ }+ // The apply arm re-runs this same gate on the bytes it actually+ // rewrites ({@link decideRawRewrite}): the parse's bytes can go+ // stale before the write, and the rewrite trusts only its own+ // read.++ const stored = storedAnchorIds(signal.raw);+ const added: string[] = [];+ const push = (id: string): void => {+ if (!stored.includes(id) && !added.includes(id)) added.push(id);+ };+ // Text-derived first, through the capture path's own comparison, so a+ // form the extractor would anchor today is the form this pass adds.+ // The match runs UNCONDITIONALLY: a signal whose Raw section holds+ // only the placeholder still earns its text-derived anchors - the+ // placeholder is exactly the line the rewrite can fill - and only+ // the WRITE below waits on the rewrite's support. Each match is+ // then filtered through THIS signal's visible predicate - the same+ // one the source pointers passed above: the anchorables were built+ // at the lane's reach, so a remotely readable signal whose+ // principle names a private entity would otherwise store that+ // entity's id, the disclosure the link half's reach binding+ // already refuses.+ const haystackVariants = matchFormVariants(normalizeEntityName(signal.principle));+ for (const anchorable of anchorables) {+ if (!matchVariantsOccurIn(anchorable.forms, haystackVariants)) continue;+ const entityRel = entityRelById.get(anchorable.id);+ if (entityRel === undefined || !visible(entityRel)) continue;+ push(anchorable.id);+ }+ // Then link-derived, in body order, from each resolvable source page.+ for (const source of sources) {+ const rollup = perSource.get(source.rel) ?? { signals: 0, anchorsAdded: 0 };+ rollup.signals++;+ perSource.set(source.rel, rollup);+ let ids = linkIdsByPage.get(source.abs);+ if (ids === undefined) {+ try {+ ids =+ statSync(source.abs).size > SOURCE_PAGE_MAX_BYTES+ ? []+ : pageEntityLinks(readFileSync(source.abs, "utf8"), linkResolver);+ } catch {+ // A source page that cannot be read contributes no links; the+ // signal's stored anchors are untouched either way.+ ids = [];+ }+ linkIdsByPage.set(source.abs, ids);+ }+ for (const id of ids) push(id);+ }+ if (added.length === 0) continue;+ let before: string | null = null;+ try {+ before = readFileSync(path, "utf8");+ } catch {+ before = null;+ }+ // The gates above judged the bytes the PARSE read; these are the+ // bytes the rewrite would touch. A page edited between the parse+ // and this read would have the rewrite run on bytes no gate+ // checked, and a line rebuilt from the parse's `stored` would drop+ // an id the edit stored. The decision re-runs the shape gate on+ // the rewrite's own bytes and rebuilds the stored half from them;+ // `expectBefore` still pins these bytes to the rename below.+ const decision = before === null ? NO_REWRITE_HOME : decideRawRewrite(before, added);+ if (decision.action === "codec") {+ // The parse-time codec gate's answer, on the truth bytes:+ // skipped, counted by neither arm - the same page condition gets+ // the same report numbers whatever the timing.+ continue;+ }+ if (decision.action === "unsafe-shape") {+ // The same hold-out as the parse-time gate, on the truth bytes:+ // skipped ENTIRELY, counted, never written. The next pass reads+ // the page as it now stands and answers the same way.+ skippedRawShape++;+ continue;+ }+ // No `## Raw` section in the bytes (an unreadable page lands here+ // as `null` and reads the same): the anchor has no home on this+ // page, so no arm counts it - a dry run never reports an addition+ // no apply could make, and run-to-run numbers stay idempotent.+ if (decision.action === "no-home") continue;+ const next = decision.next;+ // The appended half, not the computed `added`, is what this+ // rewrite actually adds: a concurrent edit that stored some or all+ // of `added` between the parse and the read made the rest of the+ // count a no-op write - and a dry run must never report an+ // addition the apply arm would not make.+ const appended = decision.appended;+ changed++;+ addedTotal += appended.length;+ for (const source of sources) {+ const rollup = perSource.get(source.rel)!;+ rollup.anchorsAdded += appended.length;+ }+ if (!apply) continue;+ try {+ // The bytes read above are the write's expectation, re-checked+ // immediately before the rename: an edit that lands between the+ // read and the write fails here instead of being discarded, and+ // a concurrent move fails instead of recreating the page at its+ // old path. The rollback below covers the drift failure too -+ // the signal is reported by its absence, and the next pass+ // recomputes the same additions, idempotently.+ atomicWriteFileSync(path, next, { expectBefore: before });+ } catch {+ // A page that cannot be rewritten is reported by its absence: the+ // next pass recomputes the same additions, idempotently.+ changed--;+ addedTotal -= appended.length;+ for (const source of sources) {+ const rollup = perSource.get(source.rel)!;+ rollup.anchorsAdded -= appended.length;+ }+ }+ }+ }+ progress.finish();++ return {+ apply,+ signalsScanned: scanned,+ signalsUnreadable: unreadable,+ signalsPageSourced: pageSourced,+ signalsSkippedRawShape: skippedRawShape,+ signalsChanged: changed,+ anchorsAdded: addedTotal,+ perSource: [...perSource.entries()]+ .map(([source, counts]) => ({ source, ...counts }))+ .toSorted((a, b) => a.source.localeCompare(b.source)),+ };+}diff --git a/src/core/brain/notes/index-refresh.ts b/src/core/brain/notes/index-refresh.tsnew file mode 100644index 00000000..9c87f583--- /dev/null+++ b/src/core/brain/notes/index-refresh.ts@@ -0,0 +1,335 @@+/**+ * The index-freshness evidence a note write reports, and the post-write+ * refresh claim it starts.+ *+ * This is `notes/lifecycle.ts`'s refresh half, lifted into a module of+ * its own so a SECOND write surface can claim the same detached refresh:+ * note creation and content edits go through writers that cannot import+ * the lifecycle module without a cycle (the lifecycle already imports+ * their path envelope), and the claim - the vocabulary, the evidence+ * read, the deferred search imports, the refusal reason - is one thing+ * that must not come to mean two.+ *+ * The search imports are deferred for the reason+ * `notes/lifecycle.ts` documents: the search barrel reaches back into+ * the Brain tree, and a static edge from a Brain note writer into it is+ * the shape the acyclic-import ratchet exists to keep out.+ */++import { existsSync } from "node:fs";+import { dirname } from "node:path";++import { requireNextStep } from "../next-step.ts";+import { SEARCH_INDEX_MISSING_CODE } from "../diagnostics.ts";++// ----- How stale the derived index is ---------------------------------------++/**+ * The state of the search index at the moment a write call finished.+ *+ * There is no `current` member and that is a result, not an omission:+ * the refresh an applied write claims is detached, so at the instant+ * this evidence is read no run has landed yet - an index that exists is+ * stale with respect to a write that just happened, every time.+ * Declaring a member nothing can produce would be inviting a reader to+ * believe a write might have refreshed the index; the claim that a run+ * is IN FLIGHT travels on the report beside this evidence, never inside+ * it.+ *+ * `unchanged` is the plan-only counterpart, and it exists because that+ * argument has a premise: an index goes stale with respect to a write+ * THAT HAPPENED. A plan moved no byte and rewrote no spelling, so the+ * index describes the vault exactly as well after the call as before it,+ * and reporting `stale` there was a false statement about the one field+ * this vocabulary's honesty rests on. It is deliberately not named+ * `current`: the claim is only that THIS call did not age the index,+ * never that some earlier write did not.+ */+export const INDEX_EVIDENCE = Object.freeze({+ /** An index exists; its last pass predates this call and names the old path. */+ stale: "stale",+ /** An index exists and this call wrote nothing, so it is no staler. */+ unchanged: "unchanged",+ /** No index at the configured path, so it held no evidence either way. */+ absent: "absent",+ /** An index exists and could not be opened, or records no run instant. */+ unreadable: "unreadable",+} as const);++/** Closed union over {@link INDEX_EVIDENCE}. */+export type IndexEvidenceState = (typeof INDEX_EVIDENCE)[keyof typeof INDEX_EVIDENCE];++/** Membership list, in declaration order. */+export const INDEX_EVIDENCE_STATES: ReadonlyArray<IndexEvidenceState> = Object.freeze(+ Object.values(INDEX_EVIDENCE),+);++/** The parameter is `unknown`: the value arrives as an untyped payload. */+export function isIndexEvidenceState(value: unknown): value is IndexEvidenceState {+ return (+ typeof value === "string" && (INDEX_EVIDENCE_STATES as ReadonlyArray<string>).includes(value)+ );+}++// ----- What a write did about a detached refresh -----------------------------++/**+ * What a write did about a detached refresh of the derived index.+ *+ * Two tokens, and the difference between them is the honesty claim. A+ * write that CLAIMED a refresh has started the same claim-guarded+ * detached run the freshen-on-read path starts, and that run - not this+ * call - will bring the index around. `not_claimed` covers every case+ * where nothing was started; WHY nothing was started travels beside it+ * as {@link PostWriteRefreshClaim.refreshReason}, so a deliberate+ * config-off is never indistinguishable from a broken spawn. In every+ * refusal case the index evidence's next command remains the way the+ * index actually gets reconciled, which is exactly why the claim must+ * never read as a guarantee.+ */+export const INDEX_REFRESH = Object.freeze({+ /** A detached refresh run was started for this write and holds the freshen claim. */+ claimed: "claimed",+ /** No refresh was started; the reason is on `refresh_reason` beside this token. */+ notClaimed: "not_claimed",+} as const);++/** Closed union over {@link INDEX_REFRESH}. */+export type IndexRefresh = (typeof INDEX_REFRESH)[keyof typeof INDEX_REFRESH];++/** Membership list, in declaration order. */+export const INDEX_REFRESHES: ReadonlyArray<IndexRefresh> = Object.freeze(+ Object.values(INDEX_REFRESH),+);++/** The parameter is `unknown`: the value arrives as an untyped payload. */+export function isIndexRefresh(value: unknown): value is IndexRefresh {+ return typeof value === "string" && (INDEX_REFRESHES as ReadonlyArray<string>).includes(value);+}++/** What the derived index knows, and how old that knowledge is. */+export interface IndexEvidence {+ readonly state: IndexEvidenceState;+ /**+ * ISO instant of the index's last pass; `null` unless the index+ * reported one, which is the `stale` and `unchanged` states.+ */+ readonly lastIndexedAt: string | null;+ /** The registered command that makes the index agree with the vault again. */+ readonly nextCommand: string;+}++/**+ * The command that reconciles the derived index with the vault. Resolved+ * from the diagnostics registry rather than written here, so the string+ * an operator is handed is the same one every other index advisory names,+ * and a registry rename fails at import instead of inside the advisory it+ * was meant to explain.+ */+const REINDEX_COMMAND = requireNextStep(SEARCH_INDEX_MISSING_CODE).nextCommand;++/**+ * Read the derived index's freshness. Never throws: this is evidence+ * ABOUT the operation, and an unreadable index must not fail a write+ * that already succeeded - it must be reported as unreadable, which is a+ * different answer from "no stale references exist".+ *+ * `wrote` is what separates {@link INDEX_EVIDENCE.stale} from+ * {@link INDEX_EVIDENCE.unchanged}: the staleness claim is about what+ * THIS call did to the vault, so a plan-only run - which moved nothing+ * and rewrote nothing - cannot have aged an index and must not say it+ * did. The other two states are facts about the index file itself and+ * read the same either way.+ */+export async function readIndexEvidence(+ vault: string,+ wrote: boolean,+ configPath?: string,+): Promise<IndexEvidence> {+ try {+ const { resolveSearchConfig } = await import("../../search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } = await import("../../search/store.ts");+ const config = resolveSearchConfig({+ vault,+ ...(configPath !== undefined ? { configPath } : {}),+ });+ if (!existsSync(config.dbPath)) {+ return Object.freeze({+ state: INDEX_EVIDENCE.absent,+ lastIndexedAt: null,+ nextCommand: REINDEX_COMMAND,+ });+ }+ const store = await Store.open(config, { mode: "read" });+ try {+ const last = store.getState(LAST_INDEXED_AT_STATE_KEY);+ if (last === null) {+ return Object.freeze({+ state: INDEX_EVIDENCE.unreadable,+ lastIndexedAt: null,+ nextCommand: REINDEX_COMMAND,+ });+ }+ return Object.freeze({+ state: wrote ? INDEX_EVIDENCE.stale : INDEX_EVIDENCE.unchanged,+ lastIndexedAt: last,+ nextCommand: REINDEX_COMMAND,+ });+ } finally {+ await store.close();+ }+ } catch {+ return Object.freeze({+ state: INDEX_EVIDENCE.unreadable,+ lastIndexedAt: null,+ nextCommand: REINDEX_COMMAND,+ });+ }+}++/** What a write's refresh claim did, and - refused - why. */+export interface PostWriteRefreshClaim {+ /** `claimed` says a run is IN FLIGHT, never that it has landed. */+ readonly refresh: IndexRefresh;+ /**+ * Why nothing was started: the freshen machinery's own skip token+ * (`off`, `backoff`, `writer_lock`, `claimed`, `no_index`,+ * `spawn_failed`), or the message of an error it raised. `null` when a+ * run was started, and when no claim was attempted at all (a plan-only+ * run refused nothing). Read from THIS call's own decision object -+ * never from state another call or another vault could have written.+ */+ readonly refreshReason: string | null;+}++/** The claim-shaped answer for an index this call did not age or cannot refresh. */+const NO_INDEX_CLAIM: PostWriteRefreshClaim = Object.freeze({+ refresh: INDEX_REFRESH.notClaimed,+ // The machinery's own token for an index with nothing to refresh: an+ // absent index and an unreadable one both hold no stamp to force past,+ // and both are already on the report with the command that rebuilds+ // or reconciles them.+ refreshReason: "no_index",+});++/**+ * Try to claim one detached refresh of the derived index on behalf of a+ * write that just happened - the freshen-on-read machinery, forced past+ * the freshness gate because the stamp is now older than the vault it+ * describes. The claim protocol is the reader path's, verbatim: the+ * same claim file, so a lifecycle refresh and a reader-triggered+ * freshen exclude each other, and a second write that arrives while the+ * first run still holds the claim starts nothing.+ *+ * Everything that can refuse is allowed to, and every refusal and every+ * failure lands on {@link INDEX_REFRESH.notClaimed} with ITS REASON on+ * {@link PostWriteRefreshClaim.refreshReason}: the write already+ * happened, the refresh is best-effort by design, and the report's next+ * command reconciles the index whatever became of the spawn. `spawn` is+ * the injected test seam; absent, the child is the real detached run.+ * `now` is the caller's injected clock: passed through as the decision's+ * `nowMs`, so the freshness and backoff judgements are made on the same+ * instant the rest of the run is reproducible against. `configPath` is+ * the config file the CALLER resolved its own world through - the CLI's+ * `--config`, the MCP server's config path - so the claim reads the same+ * index and spawns the child with the same freshen settings the rest of+ * the invocation used; absent, the config resolves from the environment+ * alone, exactly as a caller that passed no config path resolves+ * everything else. There is no+ * freshness floor against the write's own instant: the index stamp marks+ * when a run FINISHED, and a run that finished after the write began may+ * have scanned before the write landed, so a stamp cannot prove the+ * index has seen the write - a floor built on it would silently drop the+ * one refresh the write needs. Back-to-back applied writes spawn one run+ * each; the claim machinery itself - exclusivity, backoff, the+ * writer-lock probe - caps them.+ */+export async function claimPostWriteRefresh(+ vault: string,+ index: IndexEvidence,+ spawn?: (argv: string[]) => void,+ now?: Date,+ configPath?: string,+): Promise<PostWriteRefreshClaim> {+ // Stale is the only state that describes an index this call aged. An+ // absent index holds nothing to refresh, an unreadable one has no+ // stamp to force past, and both are already on the report with the+ // command that rebuilds or reconciles them.+ if (index.state !== INDEX_EVIDENCE.stale) return NO_INDEX_CLAIM;+ try {+ const { resolveSearchConfig } = await import("../../search/index.ts");+ const { FRESHEN_SKIP, markFreshenPending, maybeFreshenIndex } =+ await import("../../search/freshen.ts");+ const config = resolveSearchConfig({+ vault,+ ...(configPath !== undefined ? { configPath } : {}),+ });+ const decision = maybeFreshenIndex(config, {+ lastIndexedAt: index.lastIndexedAt,+ force: true,+ ...(spawn !== undefined ? { spawn } : {}),+ ...(now !== undefined ? { nowMs: now.getTime() } : {}),+ });+ if (decision !== "spawned") {+ // A refusal is a stated reason, not a thrown one: the freshen+ // machinery answers with a skip token - `spawn_failed` among them+ // - so the throwing arm below never ran for a spawn that failed+ // inside it. Every refusal now names itself on the result that+ // carries it, so `not_claimed` is never the whole answer.+ //+ // `claimed` and `writer_lock` are the two refusals that are a+ // QUEUE, not a dead end: a run is in flight either way.+ // `claimed` is the freshen claim held while the child runs - its+ // fresh stamp would otherwise suppress freshen-on-read for a whole+ // interval. `writer_lock` is the SAME run while it holds the index+ // writer lock - the bulk of its pass - where the lock probe+ // answers before the claim is ever consulted; a write that took+ // the lock's answer home unmarked would be exactly the mid-refresh+ // drop the marker exists to prevent. (A lock held by a NON-freshen+ // writer - a manual index - leaves the marker for the next freshen+ // child, whose scan start is later than the marker's instant, so+ // its settle drops it as covered.) The marker beside the freshen+ // state says a write is pending since this instant; the child+ // compares it with its scan start before releasing the claim and+ // runs one bounded extra pass when it is newer. Every other+ // refusal has no run to inform, and an off config has a run to NOT+ // inform - neither marks.+ if (decision === FRESHEN_SKIP.claimed || decision === FRESHEN_SKIP.writerLock) {+ markFreshenPending(dirname(config.dbPath), now?.getTime() ?? Date.now());+ }+ return Object.freeze({+ refresh: INDEX_REFRESH.notClaimed,+ refreshReason: decision,+ });+ }+ return Object.freeze({ refresh: INDEX_REFRESH.claimed, refreshReason: null });+ } catch (err) {+ // The token stays `not_claimed` - the report's vocabulary does not+ // grow a third member for a branch nothing can act on - but the+ // failure is no longer swallowed whole: the message lands on the+ // result, so a broken freshen path can be named by the report that+ // hit it.+ return Object.freeze({+ refresh: INDEX_REFRESH.notClaimed,+ refreshReason: err instanceof Error ? err.message : String(err),+ });+ }+}++/**+ * The whole claim for a write path that does not already hold index+ * evidence: read it, then claim. Note creation and content edits land+ * here - the claim needs the same stale-gate and stamp input the+ * lifecycle's own writes assemble, and one read is the difference+ * between every write surface reporting the same refusal reason and each+ * guessing its own.+ */+export async function claimNoteWriteRefresh(+ vault: string,+ spawn?: (argv: string[]) => void,+ now?: Date,+ configPath?: string,+): Promise<PostWriteRefreshClaim> {+ const index = await readIndexEvidence(vault, true, configPath);+ return claimPostWriteRefresh(vault, index, spawn, now, configPath);+}diff --git a/src/core/brain/notes/lifecycle.ts b/src/core/brain/notes/lifecycle.tsindex fe234c54..bcd5e8c3 100644--- a/src/core/brain/notes/lifecycle.ts+++ b/src/core/brain/notes/lifecycle.ts@@ -26,24 +26,30 @@* A rename that reports success and stops is a lie, and it is worth being* precise about which lie. The Brain backlink index (`backlinks.ts`) is a* full scan and Brain-scoped. The vault-wide `links` table is only as- * fresh as the last `indexVault` pass, and there is no write-to-index- * hook anywhere in this codebase. So a rename can truthfully say only- * this: of the Markdown files it READ during this call, these are the- * ones whose `[[...]]` spellings it rewrote - and the derived index still- * holds the old path until something re-indexes.+ * fresh as the last `indexVault` pass. An applied relocation or delete+ * now CLAIMS one detached, claim-guarded refresh of that index - the+ * freshen-on-read machinery run at force - so the window in which the+ * index still holds the old paths starts closing at the write itself,+ * and the claim rides the report beside the evidence. The claim is not+ * an invariant: until the detached run lands, a search can still answer+ * from the old paths. So a rename can truthfully say only this: of the+ * Markdown files it READ during this call, these are the ones whose+ * `[[...]]` spellings it rewrote, and the derived index holds the old+ * path until the claimed run - or the command on the report - lands.** Three consequences are load-bearing and each is reported rather than* assumed:*- * - the bare-basename spelling `[[Old]]` is rewritten only when- * exactly one note in the scanned population carries the OLD- * basename and none carries the new one. Two notes named `Old.md` in- * different folders make `[[Old]]` a reference to whichever one- * Obsidian resolves, and rewriting it would re-point a link that- * never pointed here; a note already named `New.md` elsewhere makes- * `[[New]]` ambiguous the moment the rename lands, and by this- * project's own ladder an ambiguous basename resolves to nothing at- * all. The verdict token says which of the three happened.+ * - the bare-basename spelling `[[Old]]` is rewritten whenever it+ * uniquely resolved to the source before the move - the source is+ * the basename's only carrier, or the source is top-level and owns+ * the spelling through the exact-path rung - and the rewrite aims at+ * the minimal spelling of the destination, which is unambiguous by+ * construction whatever note count the move creates. Two nested+ * notes named `Old.md` in different folders still withhold it:+ * there `[[Old]]` named whichever one Obsidian resolves, and+ * rewriting it would re-point a link that never pointed here. The+ * verdict token says which of the three happened.* - the search index's state travels back on the result as an* {@link IndexEvidence}, with the instant of its last pass and the* command that makes it agree with the vault again.@@ -155,10 +161,9 @@ import { pathCovers } from "../../vault-scope/defaults.ts";import { assertExpectedCount } from "../count-guard.ts";import { DERIVATION_SCAN_SCOPE, traceNoteDerivations } from "../source-cleanup.ts";import { BRAIN_LOG_REL, BRAIN_ROOT_REL } from "../path-constants.ts";-import { requireNextStep } from "../next-step.ts";-import { SEARCH_INDEX_MISSING_CODE } from "../diagnostics.ts";import { classifyRecoverability, type RecoverabilityVerdict } from "../gates/recoverability.ts";import { retargetWikilinks, type WikilinkRetarget } from "../page-dedup.ts";+import { minimalSpellingFor } from "../link-graph/minimal-spelling.ts";import { withDestructiveSnapshot } from "../snapshot-gate.ts";import { BRAIN_SNAPSHOT_REASON } from "../types.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";@@ -213,11 +218,21 @@ export function isNoteLifecycleAction(value: unknown): value is NoteLifecycleAct* construction.*/export const BASENAME_REWRITE = Object.freeze({- /** Exactly one note carried the basename, so the spelling was rewritten. */+ /**+ * The bare spelling uniquely resolved to the source before the move,+ * so it was rewritten - onto the minimal spelling of the destination,+ * which is unambiguous by construction whatever the destination+ * basename's carrier count became.+ */applied: "applied",/** The basename did not change, so no bare spelling needed rewriting. */notNeeded: "not_needed",- /** Another note carries the same basename; rewriting could re-point its links. */+ /**+ * The bare spelling never uniquely named the source: a nested source+ * with several same-basename carriers resolved, by the ladder's+ * basename rung, to whichever one the resolver picked, and rewriting+ * it could re-point a link that never pointed here.+ */ambiguous: "ambiguous",} as const);@@ -235,62 +250,35 @@ export function isBasenameRewrite(value: unknown): value is BasenameRewrite {}// ----- How stale the derived index is ---------------------------------------+//+// The vocabulary, the evidence read and the refresh claim live in+// `./index-refresh.ts` - lifted out of this module so the note create and+// content-update writers could claim the SAME refresh without importing+// the lifecycle back (this module already imports their path envelope,+// and a second copy of the claim is how two surfaces come to report two+// different refusals). This module re-exports the vocabulary unchanged:+// every report this module builds answers in the same tokens it always+// answered in, with the refusal's reason now on the report itself.-/**- * The state of the search index at the moment this call finished.- *- * There is no `current` member and that is a result, not an omission: no- * write path in this codebase updates the `links` table, so an index that- * exists is stale with respect to a relocation that just happened, by- * construction. Declaring a member nothing can produce would be inviting- * a reader to believe a rename might have refreshed the index.- *- * `unchanged` is the plan-only counterpart, and it exists because that- * argument has a premise: an index goes stale with respect to a- * relocation THAT HAPPENED. A run with `apply: false` moved no byte and- * rewrote no spelling, so the index describes the vault exactly as well- * after the call as before it, and reporting `stale` there was a false- * statement about the one field this module's honesty rests on. It is- * deliberately not named `current`: the claim is only that THIS call did- * not age the index, never that some earlier write did not.- */-export const INDEX_EVIDENCE = Object.freeze({- /** An index exists; its last pass predates this call and names the old path. */- stale: "stale",- /** An index exists and this call wrote nothing, so it is no staler. */- unchanged: "unchanged",- /** No index at the configured path, so it held no evidence either way. */- absent: "absent",- /** An index exists and could not be opened, or records no run instant. */- unreadable: "unreadable",-} as const);--/** Closed union over {@link INDEX_EVIDENCE}. */-export type IndexEvidenceState = (typeof INDEX_EVIDENCE)[keyof typeof INDEX_EVIDENCE];--/** Membership list, in declaration order. */-export const INDEX_EVIDENCE_STATES: ReadonlyArray<IndexEvidenceState> = Object.freeze(- Object.values(INDEX_EVIDENCE),-);+export {+ INDEX_EVIDENCE_STATES,+ INDEX_REFRESHES,+ isIndexEvidenceState,+ isIndexRefresh,+ type IndexEvidenceState,+ type IndexRefresh,+ type PostWriteRefreshClaim,+} from "./index-refresh.ts";+export { INDEX_EVIDENCE, INDEX_REFRESH, readIndexEvidence, type IndexEvidence };-/** See {@link isNoteLifecycleAction} for why the parameter is `unknown`. */-export function isIndexEvidenceState(value: unknown): value is IndexEvidenceState {- return (- typeof value === "string" && (INDEX_EVIDENCE_STATES as ReadonlyArray<string>).includes(value)- );-}--/** What the derived index knows, and how old that knowledge is. */-export interface IndexEvidence {- readonly state: IndexEvidenceState;- /**- * ISO instant of the index's last pass; `null` unless the index- * reported one, which is the `stale` and `unchanged` states.- */- readonly lastIndexedAt: string | null;- /** The registered command that makes the index agree with the vault again. */- readonly nextCommand: string;-}+import {+ claimPostWriteRefresh,+ INDEX_EVIDENCE,+ INDEX_REFRESH,+ readIndexEvidence,+ type IndexEvidence,+ type IndexRefresh,+} from "./index-refresh.ts";/*** What a lifecycle call did to the vault's inbound references, and on@@ -334,6 +322,22 @@ export interface NoteReferenceReport {readonly basename: BasenameRewrite;/** How fresh the derived index is with respect to this call. */readonly index: IndexEvidence;+ /**+ * Whether this write started the detached index refresh. `claimed`+ * says a run is IN FLIGHT, never that it has landed - the index+ * evidence beside it still describes the index as this call left it.+ */+ readonly refresh: IndexRefresh;+ /**+ * Why `refresh` is `not_claimed`: the freshen machinery's own skip+ * token, or the message of an error it raised. `null` when a run was+ * started, and when no claim was attempted (a plan-only run refused+ * nothing). Rendered on every report, so `not_claimed` never has to be+ * guessed at - a deliberate config-off reads differently from a+ * `writer_lock`, a held claim or a broken spawn, and in a multi-vault+ * server the reason is THIS call's own decision, never another vault's.+ */+ readonly refreshReason: string | null;}/**@@ -439,10 +443,28 @@ export interface NoteLifecycleInput {* rejects is reported as a vault without it would be, and a cascade* never deletes it. The link rewrite of an applied relocation still* edits it, so the readers who can see it are not left with links to a- * path that no longer exists. Absent, every file counts (the CLI, which- * reads the vault directly).+ * path that no longer exists - and the same holds for a bare-name+ * repair derived from a page it rejects: the repair runs, but names no+ * pair in `rewrittenSpellings`. Absent, every file counts (the CLI,+ * which reads the vault directly).*/readonly readable?: (rel: string) => boolean;+ /**+ * Test seam: replaces the detached spawn of the post-write index+ * refresh, the same seam shape the freshen-on-read callers inject.+ * Absent, the spawn is the real detached one, and a short-lived CLI+ * process is not its parent for long - which is why the child is+ * detached in the first place.+ */+ readonly refreshSpawn?: (argv: string[]) => void;+ /**+ * The config file the post-write refresh resolves the search config+ * through - the caller's `--config` (or the MCP server's config path),+ * so the claim reads the same index and spawns the child with the same+ * freshen settings the rest of the invocation used. Absent, the config+ * resolves from the environment alone.+ */+ readonly refreshConfigPath?: string;}export interface NoteLifecycleResult {@@ -509,15 +531,6 @@ const VAULT_ROOT_REL = "";*/const APPEND_ONLY_REL: ReadonlyArray<string> = Object.freeze([BRAIN_LOG_REL]);-/**- * The command that reconciles the derived index with the vault. Resolved- * from the diagnostics registry rather than written here, so the string- * an operator is handed is the same one every other index advisory names,- * and a registry rename fails at import instead of inside the advisory it- * was meant to explain.- */-const REINDEX_COMMAND = requireNextStep(SEARCH_INDEX_MISSING_CODE).nextCommand;-/** The `.md` suffix, matched case-insensitively by the path envelope. */const MARKDOWN_SUFFIX = ".md";@@ -553,62 +566,6 @@ function spellingsOf(relPath: string): ReadonlyArray<string> {return [relPath, withoutSuffix(relPath), basenameOf(relPath)];}-/**- * Read the derived index's freshness. Never throws: this is evidence- * ABOUT the operation, and an unreadable index must not fail a relocation- * that already succeeded - it must be reported as unreadable, which is a- * different answer from "no stale references exist".- *- * `wrote` is what separates {@link INDEX_EVIDENCE.stale} from- * {@link INDEX_EVIDENCE.unchanged}: the staleness claim is about what- * THIS call did to the vault, so a plan-only run - which moved nothing- * and rewrote nothing - cannot have aged an index and must not say it- * did. The other two states are facts about the index file itself and- * read the same either way.- *- * The import is deferred because the search barrel reaches back into the- * Brain tree, and a static edge from a Brain note writer into it is the- * shape the acyclic-import ratchet exists to keep out.- */-async function readIndexEvidence(vault: string, wrote: boolean): Promise<IndexEvidence> {- try {- const { resolveSearchConfig } = await import("../../search/index.ts");- const { LAST_INDEXED_AT_STATE_KEY, Store } = await import("../../search/store.ts");- const config = resolveSearchConfig({ vault });- if (!existsSync(config.dbPath)) {- return Object.freeze({- state: INDEX_EVIDENCE.absent,- lastIndexedAt: null,- nextCommand: REINDEX_COMMAND,- });- }- const store = await Store.open(config, { mode: "read" });- try {- const last = store.getState(LAST_INDEXED_AT_STATE_KEY);- if (last === null) {- return Object.freeze({- state: INDEX_EVIDENCE.unreadable,- lastIndexedAt: null,- nextCommand: REINDEX_COMMAND,- });- }- return Object.freeze({- state: wrote ? INDEX_EVIDENCE.stale : INDEX_EVIDENCE.unchanged,- lastIndexedAt: last,- nextCommand: REINDEX_COMMAND,- });- } finally {- await store.close();- }- } catch {- return Object.freeze({- state: INDEX_EVIDENCE.unreadable,- lastIndexedAt: null,- nextCommand: REINDEX_COMMAND,- });- }-}-/*** Resolve the destination this action implies, running it through the* same envelope as the source. Returns `null` for a delete, which has no@@ -681,7 +638,7 @@ function resolveDestination(}/**- * Decide what to do about the bare `[[Basename]]` spelling, from the+ * Decide what to do about the bare `[[Old]]` spelling, from the* population the rewrite would act on.** `files` is the list the counting pass just walked, which is exactly the@@ -689,15 +646,22 @@ function resolveDestination(* answer from a second walk under a second rule set is how the count and* the rewrite would come to disagree.*- * BOTH basenames are counted, and the destination side is the half that- * was missing. `[[Old]]` is safe to rewrite only when it names exactly- * one note before the rename AND `[[New]]` names exactly one after it.- * With `A/Old.md` and `B/New.md` both present, renaming `A/Old.md` to- * `A/New.md` used to report `applied` and produce two `[[New]]` links -- * and by this project's own resolution ladder (`store/links.ts:66-69`- * resolves a bare basename only when the count is exactly one) the- * rewritten link then resolved to NEITHER note. Withholding is the only- * answer that leaves a working link working.+ * The question is whether `[[Old]]` uniquely resolved to the SOURCE+ * before the move, because that is the link this operation would+ * otherwise strand. The rewrite target is no longer the bare new+ * basename but {@link minimalSpellingFor}'s answer over the post-move+ * population, which is unambiguous by construction - so the DESTINATION+ * side of the old count, which withheld the rewrite whenever any other+ * note carried the destination basename, no longer withholds anything:+ * with `A/Old.md`, `B/Foo.md` and a third page's `[[Old]]`, renaming+ * `A/Old.md` to `A/Foo.md` rewrites the link to `[[A/Foo]]`, which+ * resolves to the same note `[[Old]]` did. What still withholds is a+ * bare spelling that never uniquely named the source: a NESTED source+ * with several same-basename carriers answered, by the ladder's+ * basename rung, to whichever one Obsidian picked - rewriting it would+ * re-point a link that never pointed here - while a TOP-LEVEL source+ * owns its bare spelling outright through the exact-path rung whatever+ * the nested count.*/function decideBasename(files: ReadonlyArray<string>,@@ -708,11 +672,8 @@ function decideBasename(const to = basenameOf(destinationRel);if (from === to) return BASENAME_REWRITE.notNeeded;const carriersOfFrom = files.filter((rel) => basenameOf(rel) === from).length;- // The destination does not exist yet, so every carrier of its basename- // is a DIFFERENT note that will still be there afterwards - one is- // already one too many.- const carriersOfTo = files.filter((rel) => basenameOf(rel) === to).length;- return carriersOfFrom > 1 || carriersOfTo > 0+ const sourceIsTopLevel = directoryOf(sourceRel) === "";+ return carriersOfFrom > 1 && !sourceIsTopLevel? BASENAME_REWRITE.ambiguous: BASENAME_REWRITE.applied;}@@ -860,7 +821,9 @@ function relocateBytes(* before the count guard runs; the count guard runs before any byte* moves; and the index evidence is read at the END, so the instant it* reports is the one a caller comparing it against the relocation will- * actually reason about.+ * actually reason about, with the refresh claim trailing it - the claim+ * starts a detached run, and the evidence must stay the description of+ * the index as this call left it.*/export async function noteLifecycle(vault: string,@@ -922,17 +885,42 @@ export async function noteLifecycle(spellingsOf(source.relPath).map((from) => ({ from })),{ root: VAULT_ROOT_REL, apply: false },);+ const reported = (rel: string): boolean => input.readable?.(rel) ?? true;+ const basename =+ destination === null+ ? BASENAME_REWRITE.notNeeded+ : decideBasename(probe.files, source.relPath, destination.relPath);+ const mainRetargets =+ destination === null ? [] : mainRetargetsFor(probe.files, source, destination, basename);+ const repairs =+ destination === null ? [] : bareNameRepairs(probe.files, source.relPath, destination.relPath);+ // The repair pass writes files the moved note's own spellings can+ // never match: a file mentioning ONLY the contested bare basename+ // matches none of them, yet the repair rewrites it. Its spellings+ // therefore run through a match-only probe of their own, and the+ // files they hit join `inbound_files` and the count guard - the plan+ // names every file the apply will write, and `--expect` counts the+ // same set. A delete has no destination and so no repairs; the union+ // below is its plain probe then.+ const repairMatched =+ repairs.length > 0+ ? retargetWikilinks(+ vault,+ repairs.map((r) => ({ from: r.from })),+ { root: VAULT_ROOT_REL, apply: false },+ ).matched+ : [];+ const matched = [...new Set([...probe.matched, ...repairMatched])].toSorted();// A delete drops its own file, so a reference living inside it strands// nothing and is not counted. A relocation REWRITES its own file when// the note names its own old path, so that file is one of the writes// `--expect` guards and has to be in the number.// A file the caller may not read is absent from every list and count// below; see `NoteLifecycleInput.readable`.- const reported = (rel: string): boolean => input.readable?.(rel) ?? true;const inboundFiles = (action === NOTE_LIFECYCLE_ACTION.delete- ? probe.matched.filter((rel) => rel !== source.relPath)- : probe.matched+ ? matched.filter((rel) => rel !== source.relPath)+ : matched).filter(reported);const filesScanned = probe.files.filter(reported).length;@@ -955,13 +943,6 @@ export async function noteLifecycle(matchList: guarded,});- const basename =- destination === null- ? BASENAME_REWRITE.notNeeded- : decideBasename(probe.files, source.relPath, destination.relPath);-- const retargets = destination === null ? [] : retargetsFor(source, destination, basename);-let snapshot: NoteLifecycleResult["snapshot"] = null;let rewritten: ReadonlyArray<string> = [];let rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }> = [];@@ -1011,6 +992,14 @@ export async function noteLifecycle(},);snapshot = Object.freeze({ runId: gated.snapshot.runId, path: gated.snapshot.path });+ const index = await readIndexEvidence(vault, true, input.refreshConfigPath);+ const claim = await claimPostWriteRefresh(+ vault,+ index,+ input.refreshSpawn,+ input.now,+ input.refreshConfigPath,+ );return finish(action,source.relPath,@@ -1024,7 +1013,9 @@ export async function noteLifecycle([],[],basename,- await readIndexEvidence(vault, true),+ index,+ claim.refresh,+ claim.refreshReason,cascade,);}@@ -1043,13 +1034,41 @@ export async function noteLifecycle(// error propagated and the caller got no result at all - no `from`,// no `to`, no evidence - leaving a half-applied rename// indistinguishable from one that never started.- const pass = retargetWikilinks(vault, retargets, {+ //+ // TWO passes, in this order. The repairs go FIRST, over each file's+ // original link texts: a repair's `from` is the destination's own+ // bare basename, which is exactly what the destination-collapsing+ // pass rewrites links TO, so chaining the two rule sets through one+ // ordered reduce let the repair rule consume the spellings the main+ // pass had just written - repointing the renamed note's own inbound+ // links at the third-party note the repair belonged to. With the+ // repairs ahead of the main pass, each original link is rewritten by+ // the one rule that names it and no rule ever sees another rule's+ // output. Both passes obey the same never-rewrite scope.+ const repairPass =+ repairs.length > 0+ ? retargetWikilinks(vault, repairs, {+ root: VAULT_ROOT_REL,+ apply: true,+ neverRewrite: APPEND_ONLY_REL,+ })+ : null;+ const mainPass = retargetWikilinks(vault, mainRetargets, {root: VAULT_ROOT_REL,apply: true,neverRewrite: APPEND_ONLY_REL,});- rewritten = pass.rewritten.filter(reported);- rewriteFailures = pass.failed.filter((failure) => reported(failure.path));+ rewritten = [...new Set([...(repairPass?.rewritten ?? []), ...mainPass.rewritten])]+ .toSorted()+ .filter(reported);+ const failureByPath = new Map<string, string>();+ for (const failure of [...(repairPass?.failed ?? []), ...mainPass.failed]) {+ if (!failureByPath.has(failure.path)) failureByPath.set(failure.path, failure.reason);+ }+ rewriteFailures = [...failureByPath]+ .filter(([rel]) => reported(rel))+ .map(([path, reason]) => ({ path, reason }))+ .toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));}// The MOVE destroys nothing - the bytes are reachable under the@@ -1077,6 +1096,22 @@ export async function noteLifecycle(},});+ const index = await readIndexEvidence(vault, apply, input.refreshConfigPath);+ // The refresh claim trails the evidence read on purpose: the evidence+ // must describe the index as this call left it, and the claim starts a+ // DETACHED run that will not have landed by any instant this call can+ // observe. A plan-only run aged nothing and claims nothing - and+ // refused nothing, so its reason is null rather than a borrowed token.+ const claim = apply+ ? await claimPostWriteRefresh(+ vault,+ index,+ input.refreshSpawn,+ input.now,+ input.refreshConfigPath,+ )+ : { refresh: INDEX_REFRESH.notClaimed, refreshReason: null };+return finish(action,source.relPath,@@ -1087,10 +1122,23 @@ export async function noteLifecycle(filesScanned,inboundFiles,rewritten.length,- retargets.flatMap((r) => (r.to === undefined ? [] : [{ from: r.from, to: r.to }])),+ // A bare-name repair derived from a page the caller may not read is+ // applied (the readers who can see that page keep a working link)+ // but names no pair, exactly like the rewrites inside withheld+ // pages: the report answers as a vault without the page would. The+ // main pairs are derived solely from the paths this call was given,+ // so no pair of theirs can name a page the caller chose not to see.+ // The repairs are listed first because they are applied first.+ [...repairs, ...mainRetargets].flatMap((r) =>+ r.to === undefined || (r.carrierRel !== undefined && !reported(r.carrierRel))+ ? []+ : [{ from: r.from, to: r.to }],+ ),rewriteFailures,basename,- await readIndexEvidence(vault, apply),+ index,+ claim.refresh,+ claim.refreshReason,cascade,);}@@ -1153,22 +1201,112 @@ function planCascade(}/**- * The spellings this relocation will actually rewrite. The bare basename- * is included only when {@link decideBasename} cleared it, so the+ * The walked population as the relocation leaves it: the source path+ * gone, the destination present. Every judgement about the POST state -+ * the minimal destination spelling, the basename carrier counts - is+ * derived from this list rather than from a second walk, so the decision+ * and the rewrite pass can never see two different vaults.+ */+function postRelocationPopulation(+ files: ReadonlyArray<string>,+ sourceRel: string,+ destinationRel: string,+): ReadonlyArray<string> {+ return [...files.filter((rel) => rel !== sourceRel), destinationRel].toSorted();+}++/**+ * One retarget pair plus, for a bare-name repair, the third-party page+ * the pair was derived from. The carrier travels with the pair so the+ * report can ask the caller's reach predicate about the page a withheld+ * carrier would otherwise name - the pair itself spells only a basename+ * and a minimal spelling, and the spelling derived from a page the+ * caller may not read must contribute no reported pair.+ */+type AnnotatedRetarget = WikilinkRetarget & { readonly carrierRel?: string };++/**+ * The bare-name spellings this rename PROVABLY breaks for links that+ * never mentioned it, and the spelling each should carry instead.+ *+ * The casualty is the bare spelling whose carrier count the move turns+ * from exactly one into several: before it, the ladder's+ * unique-carrier rung resolved that spelling to one note; after it,+ * there are two carriers and the spelling resolves to NEITHER - the+ * rename silently broke a third-party link. Those links are repaired to+ * the minimal unambiguous spelling of their PRE-rename target, the+ * chooser applied to the note that never moved. Everything else stays+ * untouched, because nothing is provable about it: a spelling carried+ * by several notes before the move was already ambiguous, a spelling+ * with no carrier was already dangling (adopting it would be a guess),+ * and a single TOP-LEVEL carrier keeps owning its spelling through the+ * exact-path rung whatever the nested count becomes - which is why the+ * repair target is computed through the same chooser and ladder as the+ * main rewrite, and why a repair that comes out identical to the+ * spelling it would "repair" is dropped as a no-op. The pre-state is+ * the counting probe's walked population; the post-state is derived,+ * the move relocating exactly one carrier.+ */+function bareNameRepairs(+ files: ReadonlyArray<string>,+ sourceRel: string,+ destinationRel: string,+): ReadonlyArray<AnnotatedRetarget> {+ const from = basenameOf(sourceRel);+ const to = basenameOf(destinationRel);+ const post = postRelocationPopulation(files, sourceRel, destinationRel);+ const repairs: AnnotatedRetarget[] = [];+ for (const spelling of new Set([from, to])) {+ const preCarriers = files.filter((rel) => basenameOf(rel) === spelling);+ const delta = (spelling === to ? 1 : 0) - (spelling === from ? 1 : 0);+ if (preCarriers.length !== 1 || preCarriers.length + delta < 2) continue;+ const repairedTo = minimalSpellingFor(preCarriers[0]!, post);+ if (repairedTo !== spelling) {+ repairs.push({ from: spelling, to: repairedTo, carrierRel: preCarriers[0]! });+ }+ }+ return repairs;+}++/**+ * The destination-collapsing spellings of this relocation, aimed at the+ * MINIMAL spelling the destination resolves under once the move has+ * landed ({@link minimalSpellingFor} over the post-move population):+ * every old spelling of the source collapses onto the one shortest form+ * that stays unambiguous, so `[[Projects/Old]]` comes out `[[New]]`+ * when `New` is unique and `[[Projects/New]]` only when it is not. A+ * link comes out no longer than the vault still needs, and never+ * longer than it went in. The bare basename of the SOURCE is included+ * only when {@link decideBasename} cleared it, so the* `rewrittenSpellings` a caller reads back is the list that was applied* and not the list that was considered.+ *+ * The repairs {@link bareNameRepairs} derives are NOT in this list, and+ * that is the point: a repair's `from` is the destination's own bare+ * basename - exactly what these pairs rewrite links TO - so one ordered+ * reduce over both would let the repair rule consume the spellings the+ * main pass had just written, repointing the renamed note's own inbound+ * links at the repaired third-party note. The repairs run as a pass of+ * their own, FIRST, over each file's original link texts, so one rule's+ * output is never another rule's input. The separate pass obeys the+ * same never-rewrite scope as this one.*/-function retargetsFor(+function mainRetargetsFor(+ files: ReadonlyArray<string>,source: ResolvedNoteTarget,destination: ResolvedNoteTarget,basename: BasenameRewrite,-): ReadonlyArray<WikilinkRetarget> {- const pairs: WikilinkRetarget[] = [- { from: source.relPath, to: destination.relPath },- { from: withoutSuffix(source.relPath), to: withoutSuffix(destination.relPath) },+): ReadonlyArray<AnnotatedRetarget> {+ const to = minimalSpellingFor(+ destination.relPath,+ postRelocationPopulation(files, source.relPath, destination.relPath),+ );+ const pairs: AnnotatedRetarget[] = [+ { from: source.relPath, to },+ { from: withoutSuffix(source.relPath), to },];if (basename === BASENAME_REWRITE.applied) {- pairs.push({ from: basenameOf(source.relPath), to: basenameOf(destination.relPath) });+ pairs.push({ from: basenameOf(source.relPath), to });}return Object.freeze(pairs);}@@ -1188,6 +1326,8 @@ function finish(rewriteFailures: ReadonlyArray<{ readonly path: string; readonly reason: string }>,basename: BasenameRewrite,index: IndexEvidence,+ refresh: IndexRefresh,+ refreshReason: string | null,cascade: NoteDeleteCascade | null,): NoteLifecycleResult {return Object.freeze({@@ -1206,6 +1346,11 @@ function finish(rewriteFailures: Object.freeze([...rewriteFailures]),basename,index,+ refresh,+ // Rendered on every report, null included: a caller reading the+ // field is reading an answer (nothing was refused, or nothing was+ // attempted) rather than inferring one from an absent key.+ refreshReason,}),});}diff --git a/src/core/brain/safeguard.ts b/src/core/brain/safeguard.tsindex 26b90788..fb0661c6 100644--- a/src/core/brain/safeguard.ts+++ b/src/core/brain/safeguard.ts@@ -62,6 +62,8 @@ export const OPERATION = Object.freeze({reindex: "reindex",bridges: "bridges",clusters: "clusters",+ /** The anchor-relink maintenance pass (note-change truth maintenance). */+ relink: "relink",maintenance: "maintenance",architect: "architect",sessions: "sessions",@@ -75,6 +77,7 @@ export const OPERATIONS: ReadonlyArray<Operation> = Object.freeze([OPERATION.reindex,OPERATION.bridges,OPERATION.clusters,+ OPERATION.relink,OPERATION.maintenance,OPERATION.architect,OPERATION.sessions,diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex b659f423..6f87fbfd 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -715,6 +715,14 @@ export function parseSignal(path: string, options: ParseSignalOptions = {}): Bra}const raw =rawSection !== undefined && rawCodec === CODEC_VERSION ? expand(rawSection) : rawSection;+ // Read the marker back beside the expanded `raw` (additive optional):+ // `raw` alone cannot tell a byte-level rewriter that the section on+ // disk is the compressed form, and a rewriter that edits the file's+ // bytes while its anchor reads come from the expanded text would write+ // a line the next parse never reads. A mismatched marker already threw+ // above, so true here means exactly "expanded on read, compressed on+ // disk".+ const storedCodec = rawCodec === CODEC_VERSION && rawSection !== undefined;// Capture-extension optional fields. Absence stays as `undefined`// on the returned object — never coerced to a default, so callers@@ -778,6 +786,7 @@ export function parseSignal(path: string, options: ParseSignalOptions = {}): Bra...(scope !== undefined ? { scope } : {}),...(source !== undefined ? { source } : {}),...(raw !== undefined ? { raw } : {}),+ ...(storedCodec ? { rawCodec: true } : {}),...(source_type !== undefined ? { source_type } : {}),...(schema_type !== undefined ? { schema_type } : {}),...(dedup_hash !== undefined ? { dedup_hash } : {}),diff --git a/src/core/brain/truth/contamination.ts b/src/core/brain/truth/contamination.tsindex 41f5c4e1..bbf5a445 100644--- a/src/core/brain/truth/contamination.ts+++ b/src/core/brain/truth/contamination.ts@@ -8,7 +8,12 @@* mentions Bob.*/-import { normalizeEntityName } from "../entities/canonical.ts";+import {+ MIN_ANCHOR_FORM_LENGTH,+ matchFormVariants,+ matchVariantsOccurIn,+ normalizeEntityName,+} from "../entities/canonical.ts";import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "../entities/status-scope.ts";/**@@ -55,9 +60,44 @@ export interface ContaminationInput {readonly entities: ReadonlyArray<ContaminationEntityLike>;}-function mentions(haystack: string, entity: ContaminationEntityLike): boolean {- const forms = [entity.name, ...entity.aliases].map((f) => normalizeEntityName(f));- return forms.some((f) => f.length >= 3 && haystack.includes(f));+/**+ * One entity's inclusion-test inputs, precomputed: every normalized form,+ * each already expanded into its match variants, so an entity is+ * tokenized ONCE per check no matter how many texts it is tested against.+ * The length floor is not applied here - `mentions` gates each form at+ * every use, so a short form costs one variant expansion and answers no.+ */+interface PreparedEntity {+ readonly entity: ContaminationEntityLike;+ readonly forms: ReadonlyArray<readonly [string, ReadonlyArray<string>]>;+}++function prepareEntity(entity: ContaminationEntityLike): PreparedEntity {+ const forms = [entity.name, ...entity.aliases].map((f) => {+ const normalized = normalizeEntityName(f);+ return [normalized, matchFormVariants(normalized)] as const;+ });+ return { entity, forms };+}++/**+ * The inclusion test behind the check - the twins' copy of+ * fact-extraction's anchoring rule, kept verbatim through the one+ * canonical match-form rule ({@link matchVariantsOccurIn}) since F3+ * (note-change truth maintenance): both sides fold to their canonical+ * (space) joins, a folder-prefixed form matching at the path-segment+ * boundary, and every occurrence leading-edge-checked (a no-space-script+ * neighbour suspends the requirement), so the fold never plants a+ * mid-word hit nothing anchored before. Takes the entity ALREADY+ * prepared through {@link prepareEntity} and a haystack ALREADY expanded+ * through {@link matchFormVariants} - each side tokenizes once, the+ * same hoist `entityAnchors` makes, not once per entity per source.+ */+function mentions(haystackVariants: ReadonlyArray<string>, prepared: PreparedEntity): boolean {+ return prepared.forms.some(+ ([form, variants]) =>+ form.length >= MIN_ANCHOR_FORM_LENGTH && matchVariantsOccurIn(variants, haystackVariants),+ );}/**@@ -69,15 +109,20 @@ export function checkEntityContamination(input: ContaminationInput): Contaminatiif (input.entities.length === 0 || input.conclusion.trim() === "") {return Object.freeze({ clean: true, violations: Object.freeze([]) });}- const conclusion = normalizeEntityName(input.conclusion);- const sources = input.sources.map((s) => normalizeEntityName(s));+ // Each text expands through its match variants exactly once, up+ // front, and each entity's forms are prepared exactly once: identical+ // verdicts, the grid of entities x texts never re-tokenizes either+ // side.+ const conclusionVariants = matchFormVariants(normalizeEntityName(input.conclusion));+ const sourceVariants = input.sources.map((s) => matchFormVariants(normalizeEntityName(s)));+ const prepared = input.entities.map(prepareEntity);const violations: ContaminationViolation[] = [];- for (const entity of input.entities) {- if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;- if (!mentions(conclusion, entity)) continue;- const cited = sources.some((source) => mentions(source, entity));- if (!cited) violations.push(Object.freeze({ entityId: entity.id, name: entity.name }));+ for (const p of prepared) {+ if (!entityStatusInScope(p.entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;+ if (!mentions(conclusionVariants, p)) continue;+ const cited = sourceVariants.some((variants) => mentions(variants, p));+ if (!cited) violations.push(Object.freeze({ entityId: p.entity.id, name: p.entity.name }));}violations.sort((a, b) => (a.entityId < b.entityId ? -1 : a.entityId > b.entityId ? 1 : 0));return Object.freeze({diff --git a/src/core/brain/truth/merge-guard.ts b/src/core/brain/truth/merge-guard.tsindex 6adef6c0..c09de5dd 100644--- a/src/core/brain/truth/merge-guard.ts+++ b/src/core/brain/truth/merge-guard.ts@@ -9,19 +9,24 @@* anchors) merges exactly as today.*/-import { normalizeEntityName } from "../entities/canonical.ts";+import {+ ENTITY_TYPE_FOLDERS,+ MIN_ANCHOR_FORM_LENGTH,+ matchFormVariants,+ matchVariantsOccurIn,+ normalizeEntityName,+} from "../entities/canonical.ts";import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "../entities/status-scope.ts";-/** Categories guarded by default: people and organisations. */-export const GUARDED_ENTITY_CATEGORIES: ReadonlyArray<string> = Object.freeze([- "people",- "person",- "org",- "organization",- "organisation",- "company",- "team",-]);+/**+ * Categories guarded by default: people and organisations. The registry's+ * own entity-type folder vocabulary ({@link ENTITY_TYPE_FOLDERS} - the+ * categories entity ids are minted from), re-exported under its+ * guard-facing name so the two can never drift: the same list that+ * mints entity folders guards entity merges and gates the matcher's+ * slug tail.+ */+export const GUARDED_ENTITY_CATEGORIES: ReadonlyArray<string> = ENTITY_TYPE_FOLDERS;/** The slice of a registry entity the guard needs. */export interface GuardEntityLike {@@ -50,22 +55,38 @@ export interface MergeGuardVerdict {/*** Anchor a text against guarded entities: every active entity whose- * normalized name or alias appears in the normalized text. The same- * inclusion rule as fact-extraction's `entityAnchors`, restricted to- * the guarded categories.+ * normalized name or alias occurs in the normalized text. The same+ * inclusion rule as fact-extraction's `entityAnchors`, restricted to the+ * guarded categories - shared verbatim since F3 (note-change truth+ * maintenance) through the one canonical match-form rule+ * ({@link matchVariantsOccurIn}): both sides fold to their canonical+ * (space) joins, a folder-prefixed form matching at the path-segment+ * boundary, and every occurrence leading-edge-checked, so the fold never+ * plants a mid-word hit nothing anchored before. The haystack expands+ * ONCE per call - the same hoist `entityAnchors` makes, not once per+ * form per entity - while an entity's forms normalize together first and+ * expand inside the short-circuiting `.some`, so each form's variants+ * are built at most once per entity and only for an entity already in+ * scope (an out-of-scope entity's labels never reach the matcher).*/function guardedAnchors(text: string,entities: ReadonlyArray<GuardEntityLike>,categories: ReadonlySet<string>,): string[] {- const haystack = normalizeEntityName(text);+ const haystackVariants = matchFormVariants(normalizeEntityName(text));const ids: string[] = [];for (const entity of entities) {if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;if (!categories.has(entity.category.toLowerCase())) continue;- const forms = [entity.name, ...entity.aliases].map((f) => normalizeEntityName(f));- if (forms.some((f) => f.length >= 3 && haystack.includes(f))) ids.push(entity.id);+ const anchored = [entity.name, ...entity.aliases]+ .map((f) => normalizeEntityName(f))+ .some(+ (f) =>+ f.length >= MIN_ANCHOR_FORM_LENGTH &&+ matchVariantsOccurIn(matchFormVariants(f), haystackVariants),+ );+ if (anchored) ids.push(entity.id);}return ids.toSorted();}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 6dc118b4..77f2a92a 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -873,6 +873,18 @@ export interface BrainSignal {readonly principle: string;/** Optional free-form raw body following the frontmatter. */readonly raw?: string;+ /**+ * True when the raw body is stored codec-compressed on disk (the+ * `_raw_codec` marker, v0.22.0): `raw` above is the section's+ * EXPANDED text, while the bytes on disk hold its reversible+ * compressed form. A reader that rewrites a signal page from its file+ * bytes must not treat the compressed section as verbatim text - a+ * collapsed whitespace run can merge the `entities:` line into the+ * line above it, so a byte-level rewrite would append a second line a+ * later parse never reads. Absent (equivalently false) on every+ * default verbatim signal.+ */+ readonly rawCodec?: boolean;/*** Origin of the signal (§9 / §16). Absent on signals written by* older OSB versions — downstream code must treat undefined asdiff --git a/src/core/search/freshen.ts b/src/core/search/freshen.tsindex 74d4ef62..75ceafb5 100644--- a/src/core/search/freshen.ts+++ b/src/core/search/freshen.ts@@ -16,7 +16,7 @@* lock probe and one exclusive create.*/import { randomUUID } from "node:crypto";-import { readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";+import { linkSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { appendMetric } from "../brain/metrics.ts";@@ -31,6 +31,26 @@ export const FRESHEN_CLAIM_FILE = "freshen.claim";/** The child's outcome, failure streak and backoff. */export const FRESHEN_STATE_FILE = "freshen-state.json";+/**+ * The pending-write marker a forced refresh claim leaves when a run is+ * already in flight (`freshen-pending.json`, beside the state file) -+ * the claim held, or the index writer lock probed held, which is the+ * same run mid-pass. The claim's exclusivity means exactly one run is in flight, and+ * that run may have scanned past the write before it landed - its stamp+ * cannot prove it saw the write, and until the next interval its+ * freshness suppresses freshen-on-read. The marker is the queue: the+ * child reads it before releasing the claim and runs one bounded extra+ * incremental pass when the marker is newer than its scan start. See+ * {@link settleFreshenPending}.+ */+export const FRESHEN_PENDING_FILE = "freshen-pending.json";++/** A write waiting for a pass that can provably cover it. */+export interface FreshenPending {+ /** Milliseconds since the epoch: when the pending write landed. */+ readonly since: number;+}+/*** Metrics surface for background runs. A row is written only when a run* changed the index or failed: an idle machine would otherwise append one@@ -263,6 +283,203 @@ export function releaseFreshen(dir: string, token: string): void {}}+/**+ * Record that a write landed at `nowMs` and is waiting for a pass that+ * can provably cover it. Always overwrites with the newest instant: the+ * marker must never name an instant older than the youngest uncovered+ * write, or a pass would clear it while the newer write is still+ * missing. Best-effort, like every other piece of freshen bookkeeping -+ * a marker that cannot be written costs the write its second pass, not+ * the write itself.+ */+export function markFreshenPending(dir: string, nowMs: number): void {+ try {+ atomicWriteFileSync(+ join(dir, FRESHEN_PENDING_FILE),+ JSON.stringify({ since: nowMs } satisfies FreshenPending) + "\n",+ );+ } catch {+ // Best effort: the next forced claim re-marks.+ }+}++/** The pending marker at an arbitrary path, or `null` when torn or absent. */+function readPendingAt(path: string): FreshenPending | null {+ try {+ const parsed = JSON.parse(readFileSync(path, "utf8")) as {+ since?: unknown;+ };+ if (typeof parsed.since !== "number" || !Number.isFinite(parsed.since)) return null;+ return { since: parsed.since };+ } catch {+ return null;+ }+}++/** The pending marker, or `null` when there is none or it is torn. */+export function readFreshenPending(dir: string): FreshenPending | null {+ return readPendingAt(join(dir, FRESHEN_PENDING_FILE));+}++/** Drop the pending marker. An absent marker is nothing to fail a run over. */+export function clearFreshenPending(dir: string): void {+ try {+ unlinkSync(join(dir, FRESHEN_PENDING_FILE));+ } catch {+ // Already gone.+ }+}++/** A marker taken off its path by {@link takeFreshenPending}, held for the settle. */+export interface TakenFreshenPending {+ /** The marker as it stood on the path, or `null` when its file was torn. */+ readonly pending: FreshenPending | null;+ /**+ * Put the taken marker back. A writer that re-marked while the settle+ * held this take keeps the path: the link answers that atomically+ * (EEXIST means the path is occupied again), and the newer instant+ * supersedes the taken one, the marker naming the YOUNGEST uncovered+ * write.+ */+ restore(): void;+ /** Drop the taken marker: the pass that ran covered it. */+ drop(): void;+}++/**+ * Take the pending marker off its path atomically, so the settle can+ * judge and clear it without racing the writers that mark between the+ * settle's read and its unlink - the one window a plain+ * read-then-clear leaves open, and exactly the lost write the marker+ * exists to prevent. The rename moves whatever stands at the path NOW+ * (a later writer's marker can only land after it), and `restore` puts+ * the take back unless a newer marker claimed the path in between.+ * `null` when there was no marker to take.+ */+export function takeFreshenPending(dir: string): TakenFreshenPending | null {+ const path = join(dir, FRESHEN_PENDING_FILE);+ const held = `${path}.${randomUUID()}.settle`;+ try {+ renameSync(path, held);+ } catch {+ return null; // No marker (or the directory refused): nothing queued.+ }+ const pending = readPendingAt(held);+ return {+ pending,+ restore: () => {+ try {+ linkSync(held, path);+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== "EEXIST") {+ // A filesystem without hard links (EPERM, ENOTSUP, EXDEV on+ // network and exFAT mounts): the exclusive put-back is+ // unavailable there, so the take goes back by plain rename -+ // the small window where a writer's newer marker could be+ // replaced is the price of not destroying the marker outright.+ try {+ renameSync(held, path);+ return;+ } catch {+ // rename(2) replaces an occupied destination on every+ // platform this runs on, so reaching here is a genuine I/O+ // failure, not an occupied path: the take cannot be put+ // back and is dropped below - the same best-effort loss a+ // marker that cannot be written already names.+ }+ }+ }+ unlinkQuietly(held);+ },+ drop: () => {+ unlinkQuietly(held);+ },+ };+}++/**+ * The freshen child's settle, run before it releases the claim.+ *+ * A forced write that arrived while THIS run held the claim left a+ * marker naming the instant its write landed. The run's own pass covers+ * everything up to its scan start, so:+ *+ * - a marker at or before the scan start is covered - clear it;+ * - a newer marker is not: run ONE more incremental pass - the bound+ * is one extra pass, never a loop - and take the marker only once+ * the pass has finished, clearing it when it still names an instant+ * the extra pass's own scan start covers. A still-newer marker (a+ * write landing during the extra pass) survives for the next run,+ * which covers and clears it the same way;+ * - a caller that cannot run a pass (a config that never resolved)+ * leaves the marker exactly as it stands.+ *+ * The marker is READ before any pass runs and TAKEN only after - never+ * the other way round. A take that outran its pass handed a killed or+ * thrown-away child a marker stranded in the take's hold file, where+ * nothing reads it again: the write stood unqueued and unmarked. With+ * the pass running against a marker that never left its path, a child+ * that dies mid-pass leaves the queue exactly as it found it, and the+ * take's hold window shrinks to the judge-and-clear after the pass -+ * where {@link takeFreshenPending}'s restore still answers a writer+ * that re-marked with newer work, superseding the take rather than+ * being unlinked by this settle. A pass that throws covered nothing and+ * the marker was never taken, so it stands for the next run.+ *+ * Returns whether the extra pass ran. Throws only what `runPass`+ * throws, and the caller decides how a failed extra pass is reported.+ */+export async function settleFreshenPending(+ dir: string,+ scanStartedAtMs: number,+ runPass: (() => Promise<void>) | null,+): Promise<boolean> {+ // Read without taking: the marker stays on its own path through every+ // fallible step below, so a child that dies at any of them leaves the+ // queue standing for the next run.+ const pending = readFreshenPending(dir);+ if (pending === null) return false;+ if (pending.since <= scanStartedAtMs) {+ // This run's scan began after the pending write: the pass that just+ // finished covered it. The take judges what stands NOW, so a writer+ // that re-marked between the read and this take keeps its newer+ // marker - only a still-covered marker is dropped.+ const covered = takeFreshenPending(dir);+ if (covered !== null) {+ if (covered.pending !== null && covered.pending.since <= scanStartedAtMs) {+ covered.drop();+ } else {+ covered.restore();+ }+ }+ return false;+ }+ if (runPass === null) {+ // No pass to run: the marker stands untouched for the next run.+ return false;+ }+ const secondStart = Date.now();+ // A pass that throws propagates with the marker still on its path -+ // it covered nothing, and that standing marker is the truthful queue.+ await runPass();+ const taken = takeFreshenPending(dir);+ if (taken === null) return true;+ if (taken.pending !== null && taken.pending.since <= secondStart) {+ // The extra pass started after the marker's instant, so it covered+ // the pending write - and the marker goes with it. A marker that+ // outlived its own coverage would push every later run into an+ // extra pass forever.+ taken.drop();+ } else {+ // The write landed after the extra pass's scan start: this run+ // cannot prove it saw the write, so the marker survives for the+ // next run - superseded, not merged, if a writer re-marked during+ // the pass.+ taken.restore();+ }+ return true;+}+function str(v: unknown): string | null {return typeof v === "string" ? v : null;}@@ -347,6 +564,17 @@ export interface MaybeFreshenOptions {readonly lastIndexedAt: string | null;/** A read-only open (cross-vault, recall sources): never write there. */readonly readOnly?: boolean;+ /**+ * Skip the freshness gate and spawn whenever the remaining guards+ * allow. This is the post-write shape: the caller just changed the+ * vault, so the stamp is due by definition and comparing it against+ * the interval would answer the wrong question. Config off still+ * means off (`intervalSeconds <= 0` refuses whatever the flag says),+ * an index that was never stamped stays self-heal's, and the claim+ * exclusivity, the failure backoff and the writer-lock probe all+ * stand exactly as on the interval path.+ */+ readonly force?: boolean;readonly nowMs?: number;/** Test seam: replaces the detached spawn. */readonly spawn?: (argv: string[]) => void;@@ -371,17 +599,38 @@ export function maybeFreshenIndex(lastIndexedAt: opts.lastIndexedAt,intervalSeconds: freshen.intervalSeconds,};- // Every search lands here: decide on the index stamp alone first and- // read the state file for the backoff only once the index is due.- const due = decideFreshen({ ...input, backoffUntilMs: null });- if (due.action === "skip") return due.reason;- const backoffUntil = readFreshenState(dir).backoffUntil;- const backoffMs = backoffUntil === null ? Number.NaN : Date.parse(backoffUntil);- const decision = decideFreshen({- ...input,- backoffUntilMs: Number.isFinite(backoffMs) ? backoffMs : null,- });- if (decision.action === "skip") return decision.reason;+ if (opts.force === true) {+ // The freshness comparison is the one gate force exists to skip;+ // everything else decides for the same reasons as on the interval+ // path. The stamp check doubles as the self-heal boundary: an+ // index that was never stamped is rebuilt there, not here.+ if (opts.lastIndexedAt === null) return FRESHEN_SKIP.noIndex;+ // No freshness floor on the stamp: the stamp marks when a run+ // FINISHED, and a run that finished after the write began may well+ // have scanned before the write landed - its stamp cannot prove it+ // saw the write. A forced run that skipped on such a stamp would+ // leave the write unindexed until the next interval or the next+ // write, silently. The collapse the floor promised is the claim+ // machinery's: a run already in flight holds the claim, so a write+ // landing during it starts nothing. Back-to-back applied writes+ // spawn one run each, capped by that exclusivity and the failure+ // backoff - the price of every run provably covering its write.+ const backoffUntil = readFreshenState(dir).backoffUntil;+ const backoffMs = backoffUntil === null ? Number.NaN : Date.parse(backoffUntil);+ if (Number.isFinite(backoffMs) && backoffMs > nowMs) return FRESHEN_SKIP.backoff;+ } else {+ // Every search lands here: decide on the index stamp alone first and+ // read the state file for the backoff only once the index is due.+ const due = decideFreshen({ ...input, backoffUntilMs: null });+ if (due.action === "skip") return due.reason;+ const backoffUntil = readFreshenState(dir).backoffUntil;+ const backoffMs = backoffUntil === null ? Number.NaN : Date.parse(backoffUntil);+ const decision = decideFreshen({+ ...input,+ backoffUntilMs: Number.isFinite(backoffMs) ? backoffMs : null,+ });+ if (decision.action === "skip") return decision.reason;+ }if (isWriterLockHeld(config.dbPath)) return FRESHEN_SKIP.writerLock;const claim = tryClaimFreshen(dir, nowMs);if (!("token" in claim)) return claim.skip;diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex 0984d49c..c45cc629 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -350,7 +350,7 @@ async function toolBrainSecrets(* Advertised bound for `retry_tasks`: the widest list any install can* need, the built-ins plus the custom-task cap. The handler refuses* against the tasks THIS install registered, which can be fewer; naming- * more tasks than the lane dispatches is a mistake, not a request.+ * more tasks than the lane has is a mistake, not a request.** The `maxItems` this feeds into the schema is ADVERTISEMENT, not* enforcement - nothing in the request path validates a JSON Schema.@@ -362,6 +362,26 @@ async function toolBrainSecrets(*/const MAX_RETRY_TASKS = LANE_TASKS.length + CUSTOM_TASK_MAX;+/**+ * An optional boolean argument, read through one rule. `true` passes as+ * itself, and so does the string `"true"` - clients commonly round-trip+ * booleans as strings, and a literal `=== true` read turned that spelling+ * into a preview that still reported `verdict: ok`, the caller never the+ * wiser. `false` and `"false"` answer `false`; absence and `null` answer+ * `undefined` (the caller's default applies). Every OTHER value - `"yes"`,+ * `1`, a nested object - is an INVALID_PARAMS refusal naming the argument,+ * the same shape `coerceBoolOptional` throws for a non-boolean: refused,+ * never silently demoted to the argument's default.+ */+function coerceOptionalBool(args: Record<string, unknown>, key: string): boolean | undefined {+ const raw = args[key];+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === "boolean") return raw;+ if (raw === "true") return true;+ if (raw === "false") return false;+ throw new MCPError(INVALID_PARAMS, `argument '${key}' must be a boolean`);+}+/** The refusal of a lane run below local reach; it names nothing in the vault. */export const MAINTENANCE_RUN_LOCAL_ONLY = "brain_maintenance: run executes at local reach only";@@ -483,7 +503,12 @@ async function toolBrainMaintenance(...(ctx.configPath ? { configPath: ctx.configPath } : {}),searchConfig,now,- forceCost: args["force_cost"] === true,+ // One boolean rule per call: force_cost rides the same coercion+ // relink_apply does, so the string spelling applies and a junk value+ // is refused by name instead of silently spending the caller's+ // default.+ forceCost: coerceOptionalBool(args, "force_cost") === true,+ relinkApply: coerceOptionalBool(args, "relink_apply") === true,safeguardFor: laneSafeguard,...(onProgress ? { onProgress } : {}),});@@ -518,6 +543,10 @@ async function toolBrainMaintenance(});// The run-level spend block, the CLI JSON payload's shape.const spend = lane.reindex.spendBlock(result.tasks);+ // The relink pass's report: the preview on the default arm, the changes+ // under relink_apply - the same block the CLI JSON payload carries, so+ // the two front doors cannot disagree about what the pass would add.+ const relink = lane.relinkReport();return {verdict: result.verdict,tasks: result.tasks,@@ -526,6 +555,7 @@ async function toolBrainMaintenance(// cannot disagree about what a skip says....(result.capacity !== undefined ? { capacity: result.capacity } : {}),...(spend !== undefined ? { spend } : {}),+ ...(relink !== undefined ? { relink } : {}),// Named, never dropped: a refused declaration journals nothing, and// the valid tasks still ran....(lane.custom.errors.length > 0 ? { custom_task_errors: lane.custom.errors } : {}),@@ -610,7 +640,7 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_maintenance",description:- "Quiet-window, lease-guarded maintenance lane: run executes dream, reindex, bridges, clusters and declared custom:<name> tasks behind window, busy, pressure, capacity and streak gates; status renders lease and journal. Reindex embeds only with config maintenance_embeddings.",+ "Quiet-window, lease-guarded maintenance lane: run executes dream, reindex, bridges, clusters, relink and declared custom:<name> tasks behind window, busy, pressure, capacity and streak gates; status renders lease and journal. Reindex embeds only with config maintenance_embeddings.",inputSchema: {type: "object",properties: {@@ -635,6 +665,11 @@ export const ADMIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([description:"Bypass a positive embedding cost gate for this run's reindex (run); recorded on the spend receipt when it overrode a gate that would have refused.",},+ relink_apply: {+ type: "boolean",+ description:+ "Apply the relink pass (run): rewrite the changed signal pages' entity anchor lines. Default false previews the per-source additions and writes nothing.",+ },busy_minutes: {type: "integer",minimum: 1,diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.tsindex fdde5ba4..0e49c426 100644--- a/src/mcp/brain/lifecycle-file-tools.ts+++ b/src/mcp/brain/lifecycle-file-tools.ts@@ -90,6 +90,14 @@ function renderResult(res: NoteLifecycleResult): Record<string, unknown> {last_indexed_at: res.references.index.lastIndexedAt,next_command: res.references.index.nextCommand,},+ // `claimed` says a detached refresh run is IN FLIGHT, never that it+ // has landed; every other value names why nothing was started, and+ // `refresh_reason` spells that reason - the freshen machinery's own+ // skip token, or the error it raised - so `not_claimed` is never+ // the whole answer a caller receives. Read from THIS call's own+ // decision, never from state another vault could have written.+ refresh: res.references.refresh,+ refresh_reason: res.references.refreshReason,},// `null` when no cascade was asked for, which is a different answer// from a cascade that found nothing. Rendered on every response so a@@ -139,6 +147,9 @@ async function toolBrainNoteLifecycle(// A note the caller may not read at its reach is refused exactly// as a missing one.readable: readableAtContextReach(ctx),+ // The post-write refresh resolves through the server's own config+ // path, like every other search-resolving call in this file.+ ...(ctx.configPath !== null ? { refreshConfigPath: ctx.configPath } : {}),});return renderResult(res);} catch (err) {@@ -370,7 +381,7 @@ export const LIFECYCLE_FILE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze{name: TOOL,description:- "Note-file lifecycle. action: rename renames in place; move changes the directory; archive displaces the note under Archive/; delete removes it, and delete_linked extends that to files whose frontmatter derives them from it alone. Dry-run unless apply; delete needs confirm. Rewrites [[links]].",+ "Note-file lifecycle: rename, move, archive (displaces the note under Archive/), delete. Dry-run unless apply; delete needs confirm. Rewrites inbound [[wikilinks]] to the minimal spelling that still resolves; applied writes claim a detached index refresh (references.refresh: claimed, not landed).",inputSchema: {type: "object",properties: {diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.tsindex 1941e6b1..608fbdf7 100644--- a/src/mcp/brain/notes-tools.ts+++ b/src/mcp/brain/notes-tools.ts@@ -62,6 +62,10 @@ import { resolveNearDuplicateWriteWideningEnabled } from "../../core/config.ts";import { ROUTE_STAGE, timeStage, timeStageSync } from "../../core/route-scope.ts";import { resolveSearchConfig } from "../../core/search/index.ts";import type { ResolvedSearchConfig } from "../../core/search/types.ts";+import {+ claimNoteWriteRefresh,+ type PostWriteRefreshClaim,+} from "../../core/brain/notes/index-refresh.ts";import {WRITE_PATH_ADVISORY_KEY,type WritePathAdvisoryField,@@ -331,6 +335,19 @@ async function toolBrainCreateNote(...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),});}+ // An APPLIED create claims the same detached index refresh a+ // lifecycle write claims: the card names created notes among the+ // writes that must resolve without a reindex, and the PR says a+ // create claims. Fire-and-forget, never failing the write it+ // follows; a skip or a staged create authored nothing at the target,+ // so neither claims and neither carries the marker. The claim+ // resolves through the SERVER's own config path - the same file+ // every other search-resolving call in this file reads - so a+ // non-default config's index path and freshen settings are the ones+ // the evidence reads and the child spawns with.+ const claim = res.created+ ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)+ : null;return await noteWriteResult(ctx, res.created ? [res.path] : [], {created: res.created,outcome: res.outcome,@@ -340,6 +357,7 @@ async function toolBrainCreateNote(// has no write to attribute and no null that could be mistaken for// a lost one....(res.outcome === "created" ? auditFields(res) : {}),+ ...(claim !== null ? refreshClaimFields(claim) : {}),});} catch (err) {// Almost every CreateNoteError is a client-input fault (bad path,@@ -437,11 +455,22 @@ async function toolBrainUpdateNote(// one fact, one source. A skipped update wrote no bytes, so it names no// page for the lint and carries no audit half - the same shape a// skipped create spells.+ //+ // An APPLIED update - a content edit, frontmatter or both - claims the+ // same detached index refresh the lifecycle's writes claim, with the+ // marker on the receipt under the same vocabulary. A byte-identical+ // re-apply wrote nothing, so it claims nothing and carries no marker.+ // The claim resolves through the server's own config path, like every+ // other search-resolving call here.+ const claim = result.updated+ ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)+ : null;return noteWriteResult(ctx, result.updated ? [result.path] : [], {updated: result.updated,path: result.path,...(result.updated ? auditFields(result) : {}),...pathAdvisoryFields(result),+ ...(claim !== null ? refreshClaimFields(claim) : {}),});}@@ -459,11 +488,22 @@ async function toolBrainAppendNote(const result = runSingleWrite(ctx, op, "brain_append_note");// Skipped-append receipts follow the skipped-update shape: no bytes// landed, so no page to lint and no audit half to mistake.+ //+ // An APPLIED append wrote body bytes, so it is a content edit and+ // claims the same detached index refresh the update claims - the one+ // note-write surface left claiming nothing, and the only one whose+ // receipt contradicted the "a content edit claims" line. The claim+ // resolves through the server's own config path, like every other+ // search-resolving call here.+ const claim = result.appended+ ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)+ : null;return noteWriteResult(ctx, result.appended ? [result.path] : [], {appended: result.appended,path: result.path,...(result.appended ? auditFields(result) : {}),...pathAdvisoryFields(result),+ ...(claim !== null ? refreshClaimFields(claim) : {}),});}@@ -484,6 +524,23 @@ function auditFields(audit: NoteWriteAudit): Record<string, unknown> {};}+/**+ * The refresh-claim marker a landed create or content edit carries on+ * its receipt, in the same vocabulary the note-lifecycle tool renders:+ * `index_refresh` is `claimed` (a detached run is IN FLIGHT, never+ * landed) or `not_claimed`, and `index_refresh_reason` spells why+ * nothing was started - the freshen machinery's own skip token, or the+ * error it raised. Both keys render together or not at all: a write+ * that authored no bytes claims nothing, and its receipt is+ * byte-identical to the one that shipped before this field existed.+ */+function refreshClaimFields(claim: PostWriteRefreshClaim): Record<string, unknown> {+ return {+ index_refresh: claim.refresh,+ index_refresh_reason: claim.refreshReason,+ };+}+/*** The absolute-path advisory a kernel result computed over the call's* authored content, passed through under its own key. Byte-identical-@@ -626,7 +683,7 @@ export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_create_note",description:- "Create an actual vault note file (path + frontmatter + content), written atomically inside the vault. Distinct from brain_note, which only appends a log line. Refuses path traversal, the Brain root, vault-scope-excluded paths, writes outside the declared write binding, and by default clobbering.",+ "Create an actual vault note file (path + frontmatter + content), written atomically inside the vault. Distinct from brain_note, which only appends a log line. Refuses traversal, the Brain root, excluded paths, bad write bindings, default clobbering. An applied create claims a detached index refresh.",inputSchema: {type: "object",properties: {@@ -676,7 +733,7 @@ export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_update_note",description:- "Update an existing vault note: merge frontmatter keys and/or replace the body, written atomically. A missing target is refused. Reuses the create-note safety envelope: path traversal, the Brain root, vault-scope-excluded paths, and writes outside the declared write binding are refused.",+ "Update an existing vault note: merge frontmatter keys and/or replace the body, atomically; a missing target is refused. Reuses the create-note safety envelope: traversal, the Brain root, excluded paths, bad write bindings. An applied update claims a detached index refresh.",inputSchema: {type: "object",properties: {@@ -708,7 +765,7 @@ export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_append_note",description:- "Append Markdown text to the body of an existing vault note, written atomically. A missing target is refused. Reuses the create-note safety envelope: path traversal, the Brain root, vault-scope-excluded paths, and writes outside the declared write binding are refused.",+ "Append Markdown text to an existing vault note's body, written atomically. A missing target is refused. Reuses the create-note safety envelope: traversal, the Brain root, excluded paths, and writes outside the declared write binding are refused. An applied append claims a detached index refresh.",inputSchema: {type: "object",properties: {diff --git a/src/mcp/coerce.ts b/src/mcp/coerce.tsindex 1a19848f..639fd0da 100644--- a/src/mcp/coerce.ts+++ b/src/mcp/coerce.ts@@ -176,9 +176,9 @@ export const RECALL_SCORES_SCHEMA = Object.freeze({* hard-keyed on it, one layer softer. Both now say the key of the tool they* are attached to.*- * The sentence is budgeted for the LONGEST key it will be handed:- * `PROPERTY_DESCRIPTION_MAX` is 160 and `registry-guard` grants no- * exemptions, so prose that fits under `scores` can still overflow under+ * The sentence is budgeted for the LONGEST key it will be handed: the+ * cap is `PROPERTY_DESCRIPTION_MAX` (registry-guard, which grants no+ * exemptions), so prose that fits under `scores` can still overflow under* `recall_scores`. Six characters of key are six characters of budget.*/export function matchQualitySchema(scoresKey: string): Readonly<Record<string, unknown>> {diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 40c0cc73..08736707 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -49,7 +49,13 @@import type { ToolDefinition } from "./tool-contract.ts";export const TOOL_DESCRIPTION_MAX = 300;-export const PROPERTY_DESCRIPTION_MAX = 160;+// The retry_tasks description enumerates the known lane tasks, so a fifth+// task's registration (note-change truth maintenance) grew the measured+// length; the cap moved with the population rather than shortening the text+// that names what an operator may retry. The maintenance parity census+// imports this constant and measures against it, so the cap and the census+// cannot drift.+export const PROPERTY_DESCRIPTION_MAX = 168;/*** Shortest reason that can justify a preview-budget exemption. Sits withdiff --git a/tests/cli/brain-clusters.test.ts b/tests/cli/brain-clusters.test.tsindex 92ad4cde..f03955fd 100644--- a/tests/cli/brain-clusters.test.ts+++ b/tests/cli/brain-clusters.test.ts@@ -112,7 +112,7 @@ test("maintenance lane executes the bridges and clusters tasks", async () => {};expect(parsed.verdict).toBe("run");const names = parsed.tasks.map((t) => t.name);- expect(names).toEqual(["dream", "reindex", "bridges", "clusters"]);+ expect(names).toEqual(["dream", "reindex", "bridges", "clusters", "relink"]);expect(parsed.tasks.every((t) => t.ok)).toBe(true);// The lane's reindex built the index, so both passes left a metric.expect(listMetrics(vault, { surface: "bridge_discovery" })).toHaveLength(1);diff --git a/tests/cli/brain-maintenance.test.ts b/tests/cli/brain-maintenance.test.tsindex dcc5180b..fc5aec17 100644--- a/tests/cli/brain-maintenance.test.ts+++ b/tests/cli/brain-maintenance.test.ts@@ -5,7 +5,16 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ appendFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";@@ -30,6 +39,8 @@ import {MAINTENANCE_VERDICT,} from "../../src/core/brain/maintenance/journal.ts";import { listMetrics } from "../../src/core/brain/metrics.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { writeFrontmatterAtomic } from "../../src/core/vault.ts";import { currentLease, MAINTENANCE_LEASE_NAME } from "../../src/core/brain/maintenance/lease.ts";import { MAINTENANCE_EMBEDDINGS_ENV } from "../../src/core/config.ts";import {@@ -879,3 +890,124 @@ describe("the spend surface end to end", () => {},);});++describe("the relink arm is opt-in", () => {+ /**+ * A bootstrapped fixture vault holding one canonical entity, one source+ * page that links it, and one page-sourced signal that names nothing:+ * the exact shape the relink pass heals. Returns the signal's path.+ */+ function writeRelinkFixture(): string {+ const entitiesDir = join(vault, "Brain", "entities", "people");+ mkdirSync(entitiesDir, { recursive: true });+ const now = new Date().toISOString();+ writeFrontmatterAtomic(+ join(entitiesDir, "ent-people-ada-lovelace.md"),+ {+ kind: "brain-entity",+ entity_id: "ent-people-ada-lovelace",+ category: "people",+ name: "Ada Lovelace",+ status: "active",+ created_at: now,+ updated_at: now,+ tags: ["brain", "brain/entity"],+ },+ "# Ada Lovelace",+ { overwrite: true },+ );+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(+ join(vault, "notes", "meeting.md"),+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ "utf8",+ );+ writeSignal(vault, {+ topic: "relink-surface",+ signal: "positive",+ agent: "tester",+ principle: "the review concluded with five follow-ups",+ created_at: now,+ date: now.slice(0, 10),+ slug: "relink-surface",+ scope: "writing",+ source: ["[[notes/meeting.md]]"],+ // The pass's in-scope stamp: relink reads only server-derived+ // sources, so the fixture signal is extraction-written.+ source_type: "extracted",+ dedup_hash: `relink-surface-${now}`,+ // The placeholder Raw section: the shape a signal stored without a+ // verbatim quote carries, and the line the relink rewrite can fill.+ raw: "_(not provided)_",+ });+ const signalPath = join(vault, "Brain", "inbox");+ const name = readdirSync(signalPath).find((f) => f.startsWith("sig-") && f.endsWith(".md"));+ if (name === undefined) throw new Error("fixture signal was not written");+ return join(signalPath, name);+ }++ test("without the flag the lane's relink task previews: it reports and writes nothing", async () => {+ await initVault();+ const signalPath = writeRelinkFixture();+ const before = readFileSync(signalPath, "utf8");++ const run = await runCli(["brain", "maintenance", "run", "--vault", vault, "--json"], {+ env: baseEnv(),+ });+ expect(run.returncode).toBe(0);+ const payload = JSON.parse(run.stdout) as {+ relink?: {+ apply: boolean;+ signalsPageSourced: number;+ anchorsAdded: number;+ perSource: Array<{ source: string; signals: number; anchorsAdded: number }>;+ };+ };+ // The unattended lane runs the relink pass as a preview and carries+ // its report beside the task rows.+ expect(payload.relink?.apply).toBe(false);+ expect(payload.relink?.signalsPageSourced).toBe(1);+ expect(payload.relink?.anchorsAdded).toBe(1);+ expect(payload.relink?.perSource).toEqual([+ { source: "notes/meeting.md", signals: 1, anchorsAdded: 1 },+ ]);+ expect(readFileSync(signalPath, "utf8")).toBe(before);+ });++ test("--relink-apply rewrites the stored lines and the report says what changed", async () => {+ await initVault();+ const signalPath = writeRelinkFixture();++ const run = await runCli(+ ["brain", "maintenance", "run", "--relink-apply", "--vault", vault, "--json"],+ { env: baseEnv() },+ );+ expect(run.returncode).toBe(0);+ const payload = JSON.parse(run.stdout) as {+ relink?: { apply: boolean; signalsChanged: number; anchorsAdded: number };+ tasks: Array<{ name: string; ok: boolean }>;+ };+ expect(payload.relink?.apply).toBe(true);+ expect(payload.relink?.signalsChanged).toBe(1);+ expect(payload.relink?.anchorsAdded).toBe(1);+ expect(readFileSync(signalPath, "utf8")).toContain("entities: ent-people-ada-lovelace");+ });++ test("the preview arm names its report in the human output too", async () => {+ await initVault();+ writeRelinkFixture();++ const run = await runCli(["brain", "maintenance", "run", "--vault", vault], {+ env: baseEnv(),+ });+ expect(run.returncode).toBe(0);+ expect(run.stdout).toContain("relink: would add 1 anchor(s) to 1 signal(s)");+ });++ test("--relink-apply is a lane-run flag: the recipe refuses it", async () => {+ const refused = await recipe(["--relink-apply"]);+ expect(refused.returncode).toBe(MAINTENANCE_EXIT.usage);+ expect(refused.stderr).toContain("--relink-apply");+ expect(listJournal(vault, MAINTENANCE_JOURNAL_CAP)).toEqual([]);+ });+});diff --git a/tests/cli/brain-note-lifecycle.test.ts b/tests/cli/brain-note-lifecycle.test.tsindex 963c3569..dc40b672 100644--- a/tests/cli/brain-note-lifecycle.test.ts+++ b/tests/cli/brain-note-lifecycle.test.ts@@ -68,16 +68,50 @@ test("rename moves the note and reports the index freshness in its receipt", asyconst body = JSON.parse(res.stdout) as {applied: boolean;to: string;- references: { files_rewritten: number; index: { state: string; next_command: string } };+ references: {+ files_rewritten: number;+ rewritten_spellings: Array<{ from: string; to: string }>;+ index: { state: string; next_command: string };+ refresh: string;+ refresh_reason: string | null;+ };};expect(body.applied).toBe(true);expect(body.to).toBe("Projects/New.md");expect(body.references.files_rewritten).toBe(1);+ // The spellings the rewrite carried out, minimal forms included.+ expect(body.references.rewritten_spellings).toEqual([+ { from: "Projects/Old.md", to: "New" },+ { from: "Projects/Old", to: "New" },+ { from: "Old", to: "New" },+ ]);+ // Freshening is off suite-wide, so the write claimed nothing and the+ // next command remains the reconciliation - and the refusal carries+ // its reason, so `not_claimed` is not mistaken for a broken spawn.+ expect(body.references.refresh).toBe("not_claimed");+ expect(body.references.refresh_reason).toBe("no_index");expect(body.references.index.state).toBe("absent");expect(body.references.index.next_command.length).toBeGreaterThan(0);expect(existsSync(join(vault, "Projects/New.md"))).toBe(true);});+test("the refusal reason reaches a terminal reader too, not only the JSON", async () => {+ note("Projects/Old.md", "x\n");+ const res = await runCli([+ "brain",+ "note-lifecycle",+ "rename",+ "Projects/Old.md",+ "Projects/New.md",+ "--vault",+ vault,+ "--apply",+ ]);+ expect(res.returncode).toBe(0);+ // The human line names why nothing was started, beside the token.+ expect(res.stdout).toContain("refresh: not_claimed (no_index)");+});+test("without --apply the verb plans and writes nothing", async () => {note("Projects/Old.md", "x\n");const res = await runCli([diff --git a/tests/cli/progress-emitter-census.test.ts b/tests/cli/progress-emitter-census.test.tsindex 0ff7b097..9b8f5644 100644--- a/tests/cli/progress-emitter-census.test.ts+++ b/tests/cli/progress-emitter-census.test.ts@@ -94,6 +94,7 @@ import { join, relative, resolve } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { PROGRESS_KIND } from "../../src/core/brain/progress.ts";+import { LANE_TASKS } from "../../src/core/brain/maintenance/lane.ts";import { OPERATION, type Operation } from "../../src/core/brain/safeguard.ts";import { writeSignal } from "../../src/core/brain/signal.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";@@ -187,6 +188,19 @@ interface EmitterSite {* failure too, so a stale reason cannot outlive the condition it names.*/readonly noAdvanceReason?: string;+ /**+ * How many terminators this entry point's stream legitimately carries,+ * when it is more than one. The default is one: a verb drives ONE+ * operation, and a second ending would make a finished run, a crashed+ * run and a hung run indistinguishable. A DISPATCHER breaks that shape+ * on purpose: the maintenance lane forwards the caller's sink to every+ * task it runs (the choice `brain-maintenance-progress.test.ts`+ * asserts - the lane never speaks in its own name), and each child+ * counter closes its own stage, so an N-task lane writes N endings and+ * the run's own ending is the LAST terminator on the stream. Declared+ * per entry point below, never inferred.+ */+ readonly terminators?: number;}const EMITTERS: Readonly<Record<string, EmitterSite>> = Object.freeze({@@ -281,6 +295,20 @@ const EMITTERS: Readonly<Record<string, EmitterSite>> = Object.freeze({operation: OPERATION.sessions,stage: "mentions",},+ // The anchor-relink lane pass (note-change truth maintenance). It is a+ // LANE task, so its only surface is `maintenance run`, which forwards the+ // sink to each task: the stream carries the pass's own walk. The signal+ // walk advances once per `sig-*.md` page in the inbox and processed+ // trees - before any parse - so any signal in the fixture produces the+ // advance, whichever arm the dream task earlier in the lane moved it to.+ "core/brain/maintenance/relink-anchors-task.ts#runRelinkAnchors": {+ entryPoint: "o2b brain maintenance run --progress",+ operation: OPERATION.relink,+ stage: "signals",+ // The lane is a dispatcher: one terminator per child task it runs,+ // with the run's own ending last (see {@link EmitterSite.terminators}).+ terminators: LANE_TASKS.length,+ },});// ─────────────────────────────────────────────────────────────────────────────@@ -301,6 +329,9 @@ let sessionHome: string;let sessionVault: string;/** A vault whose continuity ledger holds mined mentions, for the hallways fold. */let hallwaysVault: string;+/** A bootstrapped vault with one signal, for the maintenance lane's relink walk. */+let maintenanceVault: string;+let maintenanceConfig: string;/*** One run of one entry point, with `--progress` on.@@ -340,6 +371,10 @@ const ENTRY_POINTS: Readonly<Record<string, () => Promise<RunResult>>> = Object.}),"o2b brain hallways mine --progress": () =>runCli(["brain", "hallways", "mine", "--vault", hallwaysVault, "--progress"]),+ "o2b brain maintenance run --progress": () =>+ runCli(["brain", "maintenance", "run", "--vault", maintenanceVault, "--progress"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: maintenanceConfig },+ }),});beforeAll(async () => {@@ -451,6 +486,27 @@ beforeAll(async () => {hallwaysVault,]);expect(imported.returncode).toBe(0);++ // The maintenance fixture: a bootstrapped vault holding ONE signal, so+ // the relink walk's stage has a denominator and at least one `advanced`+ // record on the driven path. The signal is dated NOW because an old+ // unconsumed signal leaves the contradiction window and the dream task+ // ahead of the relink walk archives it out of both trees the walk scans.+ maintenanceVault = join(tmp, "maintenance-vault");+ mkdirSync(maintenanceVault, { recursive: true });+ maintenanceConfig = join(tmp, "maintenance-config.yaml");+ atomicWriteFileSync(maintenanceConfig, `vault: ${maintenanceVault}\n`);+ bootstrapBrain(maintenanceVault, { configPath: maintenanceConfig });+ writeSignal(maintenanceVault, {+ topic: "census-relink",+ signal: "positive",+ agent: "claude",+ principle: "Prefer the census-relink approach",+ created_at: new Date().toISOString(),+ date: new Date().toISOString().slice(0, 10),+ slug: "census-relink",+ scope: "writing",+ });});afterAll(() => {@@ -498,6 +554,16 @@ describe("progress emitter census", () => {// Sequential, not concurrent: `runCli` runs in-process and swaps// process-wide state, so two overlapping runs corrupt each other.+ // The terminator expectation is per ENTRY POINT: a dispatcher that+ // forwards the sink to every task it runs carries one terminator per+ // child counter, so the widest declared allowance for the entry point+ // is the contract its sites promise (the default stays exactly one).+ const terminatorsAllowed = new Map<string, number>();+ for (const decl of Object.values(EMITTERS)) {+ const expected = decl.terminators ?? 1;+ const known = terminatorsAllowed.get(decl.entryPoint) ?? 1;+ if (expected > known) terminatorsAllowed.set(decl.entryPoint, expected);+ }for (const [name, drive] of Object.entries(ENTRY_POINTS)) {// oxlint-disable-next-line no-await-in-loopconst run = await drive();@@ -517,9 +583,12 @@ describe("progress emitter census", () => {const terminators = records.filter((r) => r["kind"] === PROGRESS_KIND.finished || r["kind"] === PROGRESS_KIND.stopped,);- if (terminators.length !== 1) {- failures.push(`${name}: ${terminators.length} terminator(s) for one run, expected 1`);- } else if (records.at(-1) !== terminators[0]) {+ const allowed = terminatorsAllowed.get(name) ?? 1;+ if (terminators.length !== allowed) {+ failures.push(+ `${name}: ${terminators.length} terminator(s) for one run, expected ${allowed}`,+ );+ } else if (allowed === 1 && records.at(-1) !== terminators[0]) {failures.push(`${name}: records arrived after the terminator`);}}diff --git a/tests/cli/search-index-freshen.test.ts b/tests/cli/search-index-freshen.test.tsindex f9bf99b4..5819b9d9 100644--- a/tests/cli/search-index-freshen.test.ts+++ b/tests/cli/search-index-freshen.test.ts@@ -14,6 +14,8 @@ import {claimFreshen,FRESHEN_CLAIM_FILE,INDEX_FRESHEN_SURFACE,+ markFreshenPending,+ readFreshenPending,readFreshenState,} from "../../src/core/search/freshen.ts";import { acquireWriterLockSync } from "../../src/core/search/store/writer-lock.ts";@@ -135,3 +137,70 @@ test("a run that fails before it can resolve its config still records the failurexpect(state.failures).toBe(1);expect(existsSync(join(derived, FRESHEN_CLAIM_FILE))).toBe(false);});++test("a run that cannot pass leaves a queued marker for the next run", async () => {+ // The child that cannot run a pass (a config that never resolves)+ // must leave the marker exactly as it stands: a settle that ran+ // anyway would clear markers at or before the child's scan start -+ // instants no pass of this child ever scanned past - and the queued+ // write would lose its second pass. The marker names an instant+ // BEFORE the scan start on purpose: that is the instant class the+ // settle's covered branch clears, and only a pass that ran can have+ // covered it.+ markFreshenPending(derived, Date.now() - 60_000);+ const token = claimFreshen(derived, Date.now())!;+ const result = await runCli(+ [+ "search",+ "index",+ "--config",+ join(tmp, "missing.yaml"),+ "--freshen",+ token,+ "--freshen-state",+ derived,+ ],+ { env: env() },+ );+ expect(result.returncode).not.toBe(0);+ expect(readFreshenPending(derived)).not.toBeNull();+ expect(existsSync(join(derived, FRESHEN_CLAIM_FILE))).toBe(false);+});++test("a run locked out of the index leaves a queued marker for the next run", async () => {+ // INDEX_LOCKED ends the child before any pass ran, so the same rule+ // holds: nothing this child scanned can cover the marker, and the+ // release still happens. The marker names an instant before the scan+ // start - the class the settle's covered branch clears.+ markFreshenPending(derived, Date.now() - 60_000);+ const release = acquireWriterLockSync(join(derived, "brain.sqlite"));+ try {+ const token = claimFreshen(derived, Date.now())!;+ const result = await runCli(+ ["search", "index", "--freshen", token, "--freshen-state", derived],+ { env: env() },+ );+ expect(result.returncode).toBe(0);+ expect(readFreshenPending(derived)).not.toBeNull();+ expect(existsSync(join(derived, FRESHEN_CLAIM_FILE))).toBe(false);+ } finally {+ release();+ }+});++test("a completed run clears a marker its scan covered and keeps one it cannot have seen", async () => {+ // Both halves of the settle over a real child run. A marker older+ // than the run's scan start is covered by the main pass and cleared;+ // an instant AFTER the scan start is not - neither the main pass nor+ // the bounded extra pass can prove it saw that write - so the marker+ // survives the run for the next one.+ markFreshenPending(derived, Date.now() - 60_000);+ const result = await freshenRun();+ expect(result.returncode).toBe(0);+ expect(readFreshenPending(derived)).toBeNull();++ markFreshenPending(derived, Date.now() + 60_000);+ const second = await freshenRun();+ expect(second.returncode).toBe(0);+ expect(readFreshenPending(derived)).not.toBeNull();+});diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.tsindex 05861a99..4690f9ec 100644--- a/tests/core/architecture/verdict-vocabulary-census.test.ts+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts@@ -301,8 +301,11 @@ import {BASENAME_REWRITES,INDEX_EVIDENCE,INDEX_EVIDENCE_STATES,+ INDEX_REFRESH,+ INDEX_REFRESHES,isBasenameRewrite,isIndexEvidenceState,+ isIndexRefresh,isNoteLifecycleAction,NOTE_LIFECYCLE_ACTION,NOTE_LIFECYCLE_ACTIONS,@@ -1044,6 +1047,20 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([members: INDEX_EVIDENCE_STATES,guard: isIndexEvidenceState,},+ {+ // B2. Whether the write started the detached index refresh, riding+ // the report beside the index evidence above. Registered when the+ // guard was added so the vocabulary carries the same four pieces as+ // its siblings - the token a caller reads back out of a report or a+ // persisted payload has to survive the round trip through a string+ // like every other one here. Two members, and the difference between+ // them is the honesty claim: `claimed` says a run is IN FLIGHT, and+ // `not_claimed` says the evidence's next command still reconciles.+ name: "INDEX_REFRESH",+ values: INDEX_REFRESH,+ members: INDEX_REFRESHES,+ guard: isIndexRefresh,+ },{// B3. Three of its four members are refusals, and that is the unit:// the index reports dangling links as a COUNT, and a count taken@@ -1938,7 +1955,10 @@ const SCANNED = scanVocabularies(SOURCE_TREE);// 102: the storage-lifecycle wave's three - STORAGE_FORECAST_TIER (the// capacity gate's tiers), RECEIPT_LEDGER_FAMILY and RECEIPT_MODE (the// receipt-compaction surfaces' shared input vocabulary).-const VOCABULARY_POPULATION = 102;+// 103: INDEX_REFRESH (note lifecycle) gains its isIndexRefresh guard,+// completing the four-piece shape its sibling vocabularies already+// carry and so entering the scanned population.+const VOCABULARY_POPULATION = 103;const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));describe("verdict vocabulary census", () => {diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex 234fec39..5a583000 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -980,13 +980,16 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object"src/core/search/freshen.ts": {categories: [C.lockPrimitive, C.retentionDelete],- calls: ["renameSync", "unlinkSync", "writeFileSync"],+ calls: ["linkSync", "renameSync", "unlinkSync", "writeFileSync"],reason:"the freshen-on-read claim is an exclusive create (`wx`) of a token file in " +"`.open-second-brain/`, released by unlinking it; a dead run's claim is replaced by " +"an atomic rename under an exclusive takeover lock; routing it through " +"the atomic writer would lose the exclusivity that keeps concurrent readers from " +- "starting a background index run each. The run's state file goes through " ++ "starting a background index run each. The pending-write marker's settle takes the " ++ "marker by atomic rename and puts it back through an exclusive link, so a writer " ++ "that re-marked mid-settle keeps the path instead of being unlinked by the settle. " ++ "The run's state file goes through " +"`atomicWriteFileSync`. Both are this tool's own per-device state, never a note.",},@@ -1458,8 +1461,14 @@ const DIRECT_WRITE_ROWS = 83;* page-merge.ts`) rewrites the survivor page, and retargets inbound* relation edges, through `writeFrontmatterAtomic` - note-shaped* frontmatter pages, written through the shared writer by design.+ *+ * 124 -> 125: the maintenance lane's anchor-relink pass+ * (`src/core/brain/maintenance/relink-anchors-task.ts`) rewrites a+ * signal page's `entities:` line in place through the shared atomic+ * writer on the apply arm - a dry-run-by-default repair pass over+ * existing signal pages, writing no note of its own.*/-const SHARED_HELPER_ROWS = 124;+const SHARED_HELPER_ROWS = 125;// ----- Origin-channel coverage boundary (Unit C) ----------------------------@@ -1594,9 +1603,13 @@ const UNSTAMPED_DIRECT_ROWS = 82;* state; no origin stamp). 120 -> 121: the entity page-merge* (`src/core/brain/entities/page-merge.ts`) rewrites entity pages through* the shared frontmatter writer (a lifecycle merge of two pages; no origin- * stamp on the merge lane).+ * stamp on the merge lane). 121 -> 122: the maintenance lane's+ * anchor-relink pass (`src/core/brain/maintenance/relink-anchors-task.ts`)+ * rewrites a signal page's `entities:` line through the shared atomic+ * writer on the apply arm - a dry-run-by-default repair pass over+ * existing signal pages; no origin stamp on a maintenance repair.*/-const UNSTAMPED_SHARED_ROWS = 121;+const UNSTAMPED_SHARED_ROWS = 122;describe("in-vault write-site census", () => {test("every direct-fs write site carries a written exclusion", () => {diff --git a/tests/core/brain.sessions.codec.test.ts b/tests/core/brain.sessions.codec.test.tsindex 81fd9050..74eb034f 100644--- a/tests/core/brain.sessions.codec.test.ts+++ b/tests/core/brain.sessions.codec.test.ts@@ -49,6 +49,17 @@ describe("signal raw codec", () => {expect(parseSignal(path).raw).toBe(RAW);});+ test("parseSignal reads the marker back beside the expanded raw", () => {+ // `raw` alone cannot tell a byte-level rewriter that the section on+ // disk is the compressed form; the parsed flag carries that fact.+ const compressed = parseSignal(write(true));+ expect(compressed.rawCodec).toBe(true);+ expect(compressed.raw).toBe(RAW);+ const verbatim = parseSignal(write(false));+ expect(verbatim.rawCodec).toBeUndefined();+ expect(verbatim.raw).toBe(RAW);+ });+test("with rawCodec: the stored body is shorter than verbatim", () => {const compressed = readFileSync(write(true), "utf8").length;const verbatim = readFileSync(write(false), "utf8").length;diff --git a/tests/core/brain/atomic-facts.test.ts b/tests/core/brain/atomic-facts.test.tsindex 511821b4..c2b65692 100644--- a/tests/core/brain/atomic-facts.test.ts+++ b/tests/core/brain/atomic-facts.test.ts@@ -267,10 +267,115 @@ describe("lexicon-gated anchoring (recall-quality A2)", () => {const anchorables = buildAnchorables(vault, buildEntityIndex(vault), "test-agent", NOW);expect(anchorables).toHaveLength(1);expect(anchorables[0]!.id).toBe("ent-people-junk");+ // The surviving alias form, expanded once into its match variants+ // (note-change truth maintenance, F3; grid reduced per M2): the+ // canonical space join is the ONE variant the class answers to, the+ // haystack folds through the same join.expect(anchorables[0]!.forms).toEqual(["atlas prime"]);});});+/**+ * Separator-tolerant anchoring (note-change truth maintenance, F3): the+ * occurrence kernel matches separator-variant match forms with BOTH sides+ * folded - runs of space, hyphen and underscore are interchangeable, a+ * slug-prefixed form also matches at a path-segment boundary, and a+ * word-boundary rule keeps the fold from planting mid-word hits literal+ * matching did not already have.+ */+describe("anchorEntityForms - separator-tolerant matching (F3)", () => {+ test("spaced text anchors a hyphenated form", () => {+ expect(anchorEntityForms("Ada Lovelace wrote the first notes.", ["ada-lovelace"])).toEqual([+ "ada-lovelace",+ ]);+ });++ test("spaced text anchors an underscored form", () => {+ expect(anchorEntityForms("Ada Lovelace wrote the first notes.", ["ada_lovelace"])).toEqual([+ "ada_lovelace",+ ]);+ });++ test("spaced text anchors a slug-prefixed form at the path-segment boundary", () => {+ expect(+ anchorEntityForms("Ada Lovelace wrote the first notes.", ["people/ada_lovelace"]),+ ).toEqual(["people/ada_lovelace"]);+ });++ test("hyphenated text anchors a spaced form (the haystack folds too)", () => {+ expect(anchorEntityForms("The ada-lovelace memoir survived.", ["Ada Lovelace"])).toEqual([+ "ada lovelace",+ ]);+ });++ test("underscored text anchors a hyphenated form", () => {+ expect(anchorEntityForms("the ada_lovelace memoir", ["ada-lovelace"])).toEqual([+ "ada-lovelace",+ ]);+ });++ test("a mid-word occurrence never anchors, literal or folded", () => {+ expect(anchorEntityForms("Canada borders three oceans.", ["Ada"])).toEqual([]);+ expect(anchorEntityForms("canada lovelace ruled the charts.", ["ada lovelace"])).toEqual([]);+ });++ test("forms shorter than the minimum never participate, folded or not", () => {+ expect(anchorEntityForms("ada-lovelace wrote.", ["lo"])).toEqual([]);+ });++ test("a boundary-occurring short form is refused by the length gate itself", () => {+ // "lo" sits at a word boundary here, so the word-boundary rule would+ // admit it - only MIN_ANCHOR_FORM_LENGTH refuses it. (The mid-word pin+ // above cannot see the gate: the boundary guard refuses that shape+ // with or without the floor.)+ expect(anchorEntityForms("the lo fixture ran its course.", ["lo"])).toEqual([]);+ });++ test("a mixed separator run in the text anchors (the haystack folds, not just the needle)", () => {+ // No variant of the needle occurs literally in the raw text - only the+ // haystack's own expansion turns "ada -_ lovelace" into a spellings the+ // needle's variant class answers to.+ expect(anchorEntityForms("the memoir of ada -_ lovelace survived.", ["ada-lovelace"])).toEqual([+ "ada-lovelace",+ ]);+ });++ test("a standalone slug tail below the minimum never anchors", () => {+ // The tail "dc" of "ac/dc" is shorter than the floor, so the entity's+ // only emitted variant is the full form - a standalone "dc" in a text+ // never anchors the band.+ expect(anchorEntityForms("dc opened for the headliners tonight.", ["AC/DC"])).toEqual([]);+ });++ test("a full slug form still anchors at its own boundaries", () => {+ expect(anchorEntityForms("the TCP/IP runbook lives in the wiki.", ["TCP/IP"])).toEqual([+ "tcp/ip",+ ]);+ });++ test("CJK text anchors a CJK form (no-space scripts need no word boundary)", () => {+ // "田中太郎は" has a kana letter touching the name directly; a script+ // written without word spaces never reads as a mid-word hit.+ expect(anchorEntityForms("田中太郎は会議に出席した。", ["田中太郎"])).toEqual(["田中太郎"]);+ });++ test("an inflected mention anchors the base form (the boundary binds the leading side only)", () => {+ // H1 (PR 268 review): Russian and German attach endings to names with+ // no space, and the two-sided boundary rule refused every inflected+ // spelling the literal `includes` matching used to anchor. Only the+ // character before the hit must be a token edge.+ expect(anchorEntityForms("Ивана повысили до директора.", ["Иван"])).toEqual(["иван"]);+ expect(anchorEntityForms("Встреча с Иваном перенесена.", ["Иван"])).toEqual(["иван"]);+ expect(anchorEntityForms("Annas Buch liegt auf dem Tisch.", ["Anna"])).toEqual(["anna"]);+ });++ test("an attached Korean particle does not block the anchor", () => {+ // 조사 attach to a noun with no space: "김철수는" is the name plus the+ // topic particle, not a longer word.+ expect(anchorEntityForms("김철수는 회의에 출석했다.", ["김철수"])).toEqual(["김철수"]);+ });+});+/*** Recall-quality M6: the store-learned lexicon reaches the SECOND* anchoring path too. The vault-aware callers (the decomposer verb, thediff --git a/tests/core/brain/entities.canonical.test.ts b/tests/core/brain/entities.canonical.test.tsindex de330a12..78d33f4a 100644--- a/tests/core/brain/entities.canonical.test.ts+++ b/tests/core/brain/entities.canonical.test.ts@@ -3,10 +3,13 @@ import { describe, expect, test } from "bun:test";import {ENTITY_LABEL_MAX_LENGTH,InvalidEntityLabelError,+ MIN_ANCHOR_FORM_LENGTH,assertValidEntityLabel,entityIdentityKey,entityMatchForms,isValidEntityLabel,+ matchFormVariants,+ matchVariantsOccurIn,normalizeEntityName,sanitizeEntityLabel,validateEntityCategory,@@ -210,6 +213,236 @@ describe("entityMatchForms", () => {});});+// ----- Separator-variant match forms (note-change truth maintenance, F3) -----+//+// The match-form generator expands ONE already-normalized form into the+// match variants the anchoring kernels compare with: runs of space, hyphen+// or underscore are interchangeable at match time, and a slug-prefixed form+// also matches at a path-segment boundary (its last path segment alone,+// held to the same minimum form length the callers apply to the full+// form). Identity is untouched - `normalizeEntityName` keeps every+// separator, so two spellings stay two identities while matching treats+// them as one.++describe("matchFormVariants", () => {+ test("a separator-free form is its own single variant", () => {+ expect(matchFormVariants("atlas")).toEqual(["atlas"]);+ });++ test("a spaced form expands to its one canonical (space) join", () => {+ expect(matchFormVariants("ada lovelace")).toEqual(["ada lovelace"]);+ });++ test("hyphenated and underscored forms expand to the same variant class", () => {+ expect(matchFormVariants("ada-lovelace")).toEqual(matchFormVariants("ada lovelace"));+ expect(matchFormVariants("ada_lovelace")).toEqual(matchFormVariants("ada lovelace"));+ });++ test("every form expands to at most two variants: the canonical join and the tail", () => {+ // M2 (PR 268 review): the comparison the kernels run is+ // needle variants x haystack variants per entity per text, so the+ // generator folds BOTH sides to ONE canonical (space) join - tokens+ // never contain separators, and every join character counts as a+ // non-word neighbour, so one space-joined comparison answers for the+ // whole variant class. A folder-prefixed form emits the folded tail+ // beside the folded full form, and never anything else.+ expect(matchFormVariants("ada-lovelace")).toEqual(["ada lovelace"]);+ expect(matchFormVariants("ada -_ lovelace")).toEqual(["ada lovelace"]);+ expect(matchFormVariants("people/ada_lovelace")).toEqual([+ "people/ada lovelace",+ "ada lovelace",+ ]);+ // One haystack variant per text, whatever separators it carries.+ expect(matchFormVariants("the memoir of ada -_ lovelace survived")).toEqual([+ "the memoir of ada lovelace survived",+ ]);+ });++ test("a mixed separator run collapses like any single separator", () => {+ expect(matchFormVariants("ada -_ lovelace")).toEqual(matchFormVariants("ada lovelace"));+ });++ test("a slug-prefixed form also expands its last path segment", () => {+ expect(matchFormVariants("people/ada_lovelace")).toEqual([+ "people/ada lovelace",+ "ada lovelace",+ ]);+ });++ test("a slug tail below the minimum form length is never emitted", () => {+ // "AC/DC" must not mint the needle "dc": the tail is an emitted+ // variant in its own right and meets the same floor the callers+ // apply to the full form, or a standalone "dc" in a text anchors.+ const variants = matchFormVariants("ac/dc");+ expect(variants).toContain("ac/dc"); // the full form is untouched+ expect(variants).not.toContain("dc");+ for (const variant of variants) {+ expect(variant.length).toBeGreaterThanOrEqual(MIN_ANCHOR_FORM_LENGTH);+ }+ expect(matchFormVariants("tcp/ip")).toEqual(["tcp/ip"]);+ });++ test("a slug tail is minted only from a registry entity-type folder prefix", () => {+ // M1 (PR 268 review): the tail fired on ANY slash-containing name -+ // "Warner/Chappell" minted "chappell", "Sony/ATV" minted "atv" - and+ // a person named Bob Chappell stopped being protected by the merge+ // guard. The tail is the slug of an entity PAGE, so it is minted+ // only when the prefix before the slash is one of the registry's+ // entity-type folders (the categories entity ids are minted from).+ expect(matchFormVariants("warner/chappell")).toEqual(["warner/chappell"]);+ expect(matchFormVariants("sony/atv")).toEqual(["sony/atv"]);+ expect(matchFormVariants("people/ada_lovelace")).toContain("ada lovelace");+ expect(matchFormVariants("company/acme corp")).toContain("acme corp");+ });++ test("the tail gate is the slug's own parent segment, so deeper registry paths mint too", () => {+ // The gate compares the SEGMENT before the slug, not the whole+ // prefix before the slash: an alias that still carries the+ // registry's deeper path has the category folder as its immediate+ // parent and mints its tail exactly like the bare+ // `<folder>/<slug>` spelling, while a non-folder prefix anywhere+ // before the slug mints nothing.+ expect(matchFormVariants("entities/people/ada_lovelace")).toContain("ada lovelace");+ expect(matchFormVariants("Brain/entities/people/ada_lovelace")).toContain("ada lovelace");+ expect(matchFormVariants("entities/people/ada-lovelace")).toContain("ada lovelace");+ // A non-folder immediate parent keeps the whole form one variant,+ // whatever sits deeper in the path (case is the caller's normalize+ // step, so it rides through untouched here).+ expect(matchFormVariants("companies/warner/chappell")).toEqual(["companies/warner/chappell"]);+ expect(matchFormVariants("Brain/notes/tcp")).toEqual(["Brain/notes/tcp"]);+ });++ test("a slug tail at the minimum form length still expands (folder prefixes only)", () => {+ // "notes" is not one of the registry's entity-type folders, so the+ // segment gate refuses the tail long before the floor is consulted;+ // a folder-prefixed form at the floor still expands.+ expect(matchFormVariants("notes/tcp")).toEqual(["notes/tcp"]);+ expect(matchFormVariants("people/tcp")).toEqual(["people/tcp", "tcp"]);+ });++ test("edge separator runs vanish instead of planting empty tokens", () => {+ expect(matchFormVariants("-ada-")).toEqual(["ada"]);+ // A slash is path structure, not a foldable separator, so a trailing+ // slash stays part of the token; its empty tail segment adds nothing.+ expect(matchFormVariants("people/")).toEqual(["people/"]);+ });++ test("empty and separator-only input expand to nothing", () => {+ expect(matchFormVariants("")).toEqual([]);+ expect(matchFormVariants("---")).toEqual([]);+ expect(matchFormVariants(" ")).toEqual([]);+ });++ test("deterministic: same input, deeply equal output", () => {+ expect(matchFormVariants("people/ada_lovelace")).toEqual(+ matchFormVariants("people/ada_lovelace"),+ );+ });++ test("the generator unifies for matching what identity keeps apart", () => {+ // normalizeEntityName preserves separators - the two spellings stay two+ // identity keys - while the match-form class is one and the same.+ expect(normalizeEntityName("ada_lovelace")).not.toBe(normalizeEntityName("ada lovelace"));+ expect(matchFormVariants("ada_lovelace")).toEqual(matchFormVariants("ada lovelace"));+ expect(entityIdentityKey("people", "ada_lovelace")).not.toBe(+ entityIdentityKey("people", "ada lovelace"),+ );+ });+});++// ----- The word-boundary rule over match variants (F3) -----------------------+//+// Direct pins for the one comparison the anchoring kernels and their twins+// share: an occurrence must sit at a token edge, and the probe judges an+// astral neighbour whole rather than as a lone surrogate.++describe("matchVariantsOccurIn - the word-boundary rule", () => {+ test("a mid-word occurrence never matches (canada never anchors ada)", () => {+ expect(matchVariantsOccurIn(["ada"], ["canada"])).toBe(false);+ expect(matchVariantsOccurIn(["ada"], ["ada lovelace"])).toBe(true);+ });++ test("an astral-script neighbour is judged whole, so it still requires the boundary", () => {+ // U+1D41A MATHEMATICAL BOLD SMALL A is an astral letter: the boundary+ // probe must step over the surrogate pair and see a word char, never a+ // lone (always non-word) code unit.+ expect(matchVariantsOccurIn(["da"], ["\u{1D41A}da"])).toBe(false);+ expect(matchVariantsOccurIn(["\u{1D41A}da"], ["x \u{1D41A}da x"])).toBe(true);+ });++ test("a no-space-script neighbour does not block: CJK text anchors a CJK form", () => {+ // A particle or another name touches the mention directly - Han and+ // kana are written without word spaces, so adjacency there is not a+ // mid-word hit and the boundary requirement is suspended.+ expect(matchVariantsOccurIn(["田中太郎"], ["田中太郎は出張した"])).toBe(true);+ expect(matchVariantsOccurIn(["田中太郎"], ["鈴木花子と田中太郎が出席した"])).toBe(true);+ });++ test("the boundary rule still holds between spaced scripts and CJK text", () => {+ // The suspension is per neighbour script: a LATIN neighbour on the+ // leading side still blocks even in otherwise-CJK text, while the+ // trailing side is unchecked (H1) - "adable" reads as the hit plus+ // an ending, like "Ивана" or "Annas".+ expect(matchVariantsOccurIn(["ada"], ["会ada議"])).toBe(true);+ expect(matchVariantsOccurIn(["ada"], ["会adable議"])).toBe(true);+ expect(matchVariantsOccurIn(["ada"], ["xada議"])).toBe(false);+ });++ test("the other no-space scripts suspend the boundary like CJK", () => {+ // Lao, Khmer and Myanmar are written without word spaces too; their+ // adjacency is no boundary evidence, exactly like Han and kana. The+ // neighbour before each needle is a BASE letter of the same script -+ // a consonant, not a combining mark and not the string edge - so the+ // probe really sees a word character, and only the script suspension+ // can admit the hit.+ expect(matchVariantsOccurIn(["ວຽງຈັນ"], ["ເມືອງວຽງຈັນແລ້ວ"])).toBe(true);+ expect(matchVariantsOccurIn(["ក្រុងព្រៃនគរ"], ["ជិតក្រុងព្រៃនគរក្រោយ"])).toBe(true);+ expect(matchVariantsOccurIn(["ရန်ကုန်"], ["ကရန်ကုန်မြို့"])).toBe(true);+ // The suspension is per neighbour script: a spaced-script letter+ // glued to the same needle is still boundary evidence and blocks.+ expect(matchVariantsOccurIn(["ວຽງຈັນ"], ["xວຽງຈັນ"])).toBe(false);+ });++ test("an attached Korean particle does not block: the mention still anchors", () => {+ // 조사 attach to a noun with no space, so a trailing Hangul letter+ // on its own is not evidence of a mid-word hit: the pre-rule+ // literal matching anchored these, and the boundary rule applied+ // verbatim would have silenced every Korean mention.+ expect(matchVariantsOccurIn(["김철수"], ["김철수는 출석했다"])).toBe(true);+ expect(matchVariantsOccurIn(["김철수"], ["회의록: 김철수의 결재"])).toBe(true);+ expect(matchVariantsOccurIn(["김철수"], ["김철수에서 만났다"])).toBe(true);+ expect(matchVariantsOccurIn(["김철수"], ["김철수와 김영희"])).toBe(true);+ });++ test("an inflected mention anchors: the boundary rule binds the leading side only", () => {+ // H1 (PR 268 review): every language that attaches endings to a name+ // with no space lost its matches under the two-sided rule - Russian+ // "Ивана/Ивану/Иваном", the German genitive "Annas". A trailing+ // character is an ending until proven otherwise, so only the+ // character BEFORE the hit must be a token edge.+ expect(matchVariantsOccurIn(["иван"], ["иван"])).toBe(true);+ expect(matchVariantsOccurIn(["иван"], ["ивана повысили до директора"])).toBe(true);+ expect(matchVariantsOccurIn(["иван"], ["встреча с иваном перенесена"])).toBe(true);+ expect(matchVariantsOccurIn(["anna"], ["annas buch liegt hier"])).toBe(true);+ });++ test("a trailing Hangul letter no longer blocks (the pre-rule literal behavior)", () => {+ // The trailing side admits any character, so a NON-particle Hangul+ // neighbour anchors too - exactly what the pre-rule literal+ // `includes` matching did. The precision the particle probe bought on+ // the trailing side is subsumed by the leading-only rule.+ expect(matchVariantsOccurIn(["김철수"], ["김철수민"])).toBe(true);+ expect(matchVariantsOccurIn(["김철수"], ["김철수은행"])).toBe(true);+ });++ test("a leading-side Korean neighbour still blocks", () => {+ // Korean attaches no prefixes, so Hangul on the leading side remains+ // a blocked substring hit - the leading-side rules are untouched.+ expect(matchVariantsOccurIn(["철수"], ["박철수는 출석했다"])).toBe(false);+ expect(matchVariantsOccurIn(["김철수"], ["오늘김철수는 출석했다"])).toBe(false);+ });+});+// ----- Lexicon verdict growth (recall-quality wave, S1) ----------------------//// The predicate grows two case-based refusal reasons behind an optionaldiff --git a/tests/core/brain/entities/entity-read-census.test.ts b/tests/core/brain/entities/entity-read-census.test.tsindex dbcec223..320749ed 100644--- a/tests/core/brain/entities/entity-read-census.test.ts+++ b/tests/core/brain/entities/entity-read-census.test.ts@@ -266,8 +266,8 @@ describe("entity read-path census", () => {const rows = census();// Floors just under the measurement, so "everything is scoped" cannot be// reported over a file list that was never built, and so a real loss of- // input cannot pass underneath. Today: 22 rows, 10 building the index,- // 15 scoped. The previous floors (5 index readers against a measured 10)+ // input cannot pass underneath. Today: 29 rows, 15 building the index,+ // 21 scoped. The previous floors (5 index readers against a measured 10)// would have let half the population vanish and still read as healthy.expect(rows.length).toBeGreaterThan(20);expect(rows.filter((row) => row.buildsIndex).length).toBeGreaterThan(9);diff --git a/tests/core/brain/fact-extract.anchoring.test.ts b/tests/core/brain/fact-extract.anchoring.test.tsindex db87f206..31dd7d75 100644--- a/tests/core/brain/fact-extract.anchoring.test.ts+++ b/tests/core/brain/fact-extract.anchoring.test.ts@@ -153,3 +153,78 @@ describe("routeExtractedFacts anchoring with a junk-label node", () => {expect(anchored!).toContain("ent-orgs-globex");});});++/**+ * Separator-tolerant anchoring at the capture boundary (note-change truth+ * maintenance, F3): a fact's text anchors a stored form spelled with a+ * different separator run, a slug-prefixed form anchors through its last+ * path segment, and the word-boundary rule keeps a mid-word mention out of+ * the persisted `entities:` field.+ */+describe("routeExtractedFacts separator-tolerant anchoring (F3)", () => {+ test("spaced fact text anchors a hyphenated stored name", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada-Lovelace");+ const dedup = new Map<string, DedupIndexEntry>();+ const result = routeExtractedFacts(vault, {+ facts: [{ family: "quantity", text: "ada lovelace shipped 5 units", line: 1 }],+ agent: "claude-dev-agent",+ now: NOW,+ sessionRef: "session#turn-4",+ dedup,+ });+ expect(result.created).toBe(1);+ const anchored = inboxSignalBodies().find((b) => b.includes("entities:"));+ expect(anchored).toBeDefined();+ expect(anchored!).toContain("ent-people-ada-lovelace");+ });++ test("spaced fact text anchors a slug-prefixed alias form", () => {+ // The stored name cannot match the text, so only the slug-prefixed+ // alias - through its last path segment - can anchor the node.+ writeEntityNode("people", "ent-people-ada-lovelace", "Initech", ["people/ada_lovelace"]);+ const dedup = new Map<string, DedupIndexEntry>();+ const result = routeExtractedFacts(vault, {+ facts: [{ family: "quantity", text: "ada lovelace shipped 5 units", line: 1 }],+ agent: "claude-dev-agent",+ now: NOW,+ sessionRef: "session#turn-5",+ dedup,+ });+ expect(result.created).toBe(1);+ const anchored = inboxSignalBodies().find((b) => b.includes("entities:"));+ expect(anchored).toBeDefined();+ expect(anchored!).toContain("ent-people-ada-lovelace");+ });++ test("a mid-word mention never anchors into a signal", () => {+ writeEntityNode("people", "ent-people-ada", "Ada");+ const dedup = new Map<string, DedupIndexEntry>();+ const result = routeExtractedFacts(vault, {+ facts: [{ family: "quantity", text: "canada shipped 5 units", line: 1 }],+ agent: "claude-dev-agent",+ now: NOW,+ sessionRef: "session#turn-6",+ dedup,+ });+ expect(result.created).toBe(1);+ expect(inboxSignalBodies().every((b) => !b.includes("ent-people-ada"))).toBe(true);+ });++ test("CJK fact text anchors a CJK stored name into a signal", () => {+ // A kana particle touches the name directly - a script written without+ // word spaces suspends the word-boundary rule, so the mention anchors.+ writeEntityNode("people", "ent-people-tanaka-taro", "田中太郎");+ const dedup = new Map<string, DedupIndexEntry>();+ const result = routeExtractedFacts(vault, {+ facts: [{ family: "quantity", text: "田中太郎は出張を決めた", line: 1 }],+ agent: "claude-dev-agent",+ now: NOW,+ sessionRef: "session#turn-7",+ dedup,+ });+ expect(result.created).toBe(1);+ const anchored = inboxSignalBodies().find((b) => b.includes("entities:"));+ expect(anchored).toBeDefined();+ expect(anchored!).toContain("ent-people-tanaka-taro");+ });+});diff --git a/tests/core/brain/fact-extract.link-attachment.test.ts b/tests/core/brain/fact-extract.link-attachment.test.tsnew file mode 100644index 00000000..6aeaa7a8--- /dev/null+++ b/tests/core/brain/fact-extract.link-attachment.test.ts@@ -0,0 +1,228 @@+/**+ * Link-derived fact attachment (note-change truth maintenance, F4/C2):+ * a page-sourced capture resolves the source page's outbound links to+ * canonical entity ids server-side and hands them to the extraction call+ * through ONE optional parameter. The persisted `entities:` union carries+ * the text-derived anchors AND the link-derived ones, the first+ * body-order link leading when both mechanisms match, and a capture that+ * passes nothing - every session-sourced caller - is byte-identical to+ * before the parameter existed.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { writeFrontmatterAtomic } from "../../../src/core/vault.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";+import { __clearEntityIndexCache } from "../../../src/core/brain/entities/index-builder.ts";+import { routeExtractedFacts, type ExtractedFact } from "../../../src/core/brain/fact-extract.ts";+import {+ entityLinkResolver,+ pageEntityLinks,+} from "../../../src/core/brain/intake/page-entity-links.ts";+import type { DedupIndexEntry } from "../../../src/core/brain/dedup-hash.ts";++let vault: string;+let configHome: string;++const NOW = new Date("2026-10-19T12:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-link-attach-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-link-attach-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ __clearEntityIndexCache();+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ __clearEntityIndexCache();+});++function writeEntityNode(+ category: string,+ id: string,+ name: string,+ aliases: ReadonlyArray<string> = [],+): void {+ const dir = join(brainDirs(vault).entities, category);+ mkdirSync(dir, { recursive: true });+ writeFrontmatterAtomic(+ join(dir, `${id}.md`),+ {+ kind: "brain-entity",+ entity_id: id,+ category,+ name,+ ...(aliases.length > 0 ? { aliases: [...aliases] } : {}),+ status: "active",+ created_at: "2026-10-19T00:00:00Z",+ updated_at: "2026-10-19T00:00:00Z",+ tags: ["brain", "brain/entity"],+ },+ `# ${name}`,+ { overwrite: true },+ );+ __clearEntityIndexCache();+}++/** Write a source page into the vault and resolve its links the way a+ * page-sourced caller does: server-side, in first-occurrence order. The+ * `visible` predicate is the resolver's REQUIRED argument - these+ * fixtures run at the vault's own reach, and say so here rather than+ * letting a default decide. */+function resolveSourcePageLinks(rel: string, body: string): string[] {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, body, "utf8");+ return pageEntityLinks(body, entityLinkResolver(vault, { visible: () => true }));+}++function entitiesLineOfBody(body: string): string | undefined {+ return body.split(/\r?\n/).find((line) => line.startsWith("entities: "));+}++function capture(+ facts: ReadonlyArray<ExtractedFact>,+ linkDerivedEntityIds?: ReadonlyArray<string>,+) {+ const dedup = new Map<string, DedupIndexEntry>();+ return routeExtractedFacts(vault, {+ facts,+ agent: "claude-dev-agent",+ now: NOW,+ sessionRef: "session#turn-1",+ dedup,+ ambientWriteback: true,+ ambientTtlDays: 0,+ writeApprovalEnabled: false,+ durabilityDenylist: [],+ ...(linkDerivedEntityIds !== undefined ? { linkDerivedEntityIds } : {}),+ });+}++function inboxSignalBodies(): string[] {+ const dir = brainDirs(vault).inbox;+ return existsSync(dir)+ ? readdirSync(dir)+ .filter((f) => f.startsWith("sig-") && f.endsWith(".md"))+ .map((f) => readFileSync(join(dir, f), "utf8"))+ : [];+}++describe("routeExtractedFacts link-derived attachment (F4/C2)", () => {+ test("a fact from a page linking an entity without naming it gains the anchor", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ const linkDerived = resolveSourcePageLinks(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ expect(linkDerived).toEqual(["ent-people-ada-lovelace"]);++ const result = capture(+ [{ family: "quantity", text: "the review concluded with five follow-ups", line: 1 }],+ linkDerived,+ );++ expect(result.created).toBe(1);+ const bodies = inboxSignalBodies();+ expect(bodies).toHaveLength(1);+ expect(entitiesLineOfBody(bodies[0]!)).toBe("entities: ent-people-ada-lovelace");+ });++ test("the first body-order link is the primary when both mechanisms match", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ // Body order: Ada's link comes first, so Ada leads the persisted union+ // even though the fact's own text names Atlas - and Atlas, matched by+ // BOTH mechanisms, is carried once.+ const linkDerived = resolveSourcePageLinks(+ "notes/meeting.md",+ ["# Meeting", "", "- [[ent-people-ada-lovelace]] presented.", "- [[ent-project-atlas]]"].join(+ "\n",+ ),+ );+ expect(linkDerived).toEqual(["ent-people-ada-lovelace", "ent-project-atlas"]);++ const result = capture(+ [{ family: "quantity", text: "atlas prime shipped five units", line: 1 }],+ linkDerived,+ );++ expect(result.created).toBe(1);+ const body = inboxSignalBodies()[0]!;+ expect(entitiesLineOfBody(body)).toBe("entities: ent-people-ada-lovelace, ent-project-atlas");+ });++ test("session-sourced extraction passes nothing and is behavior-identical", () => {+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");++ // A fact that names an entity anchors exactly as before...+ const named = capture([+ { family: "quantity", text: "atlas prime shipped five units", line: 1 },+ ]);+ expect(named.created).toBe(1);+ expect(entitiesLineOfBody(inboxSignalBodies()[0]!)).toBe("entities: ent-project-atlas");++ // ...and a fact that names nothing persists no anchor line at all.+ const unnamed = capture([+ { family: "quantity", text: "the review concluded with five follow-ups", line: 1 },+ ]);+ expect(unnamed.created).toBe(1);+ const bodies = inboxSignalBodies();+ expect(bodies).toHaveLength(2);+ expect(bodies.filter((b) => entitiesLineOfBody(b) === undefined)).toHaveLength(1);+ expect(bodies.filter((b) => entitiesLineOfBody(b) !== undefined)).toHaveLength(1);+ });++ test("an empty link-derived list behaves exactly like passing nothing", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ const result = capture(+ [{ family: "quantity", text: "the review concluded with five follow-ups", line: 1 }],+ [],+ );+ expect(result.created).toBe(1);+ expect(inboxSignalBodies().every((b) => !b.includes("ent-people-ada-lovelace"))).toBe(true);+ });++ test("a dry run stays a rehearsal: link-derived ids forecast nothing and write nothing", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ const dedup = new Map<string, DedupIndexEntry>();+ const result = routeExtractedFacts(vault, {+ facts: [{ family: "quantity", text: "the review concluded with five follow-ups", line: 1 }],+ agent: "claude-dev-agent",+ now: NOW,+ sessionRef: "session#turn-2",+ dedup,+ dryRun: true,+ ambientWriteback: true,+ ambientTtlDays: 0,+ writeApprovalEnabled: false,+ durabilityDenylist: [],+ linkDerivedEntityIds: ["ent-people-ada-lovelace"],+ });+ expect(result).toEqual({+ created: 0,+ withheld: 1,+ deduped: 0,+ durabilityRejected: 0,+ ambientWithheld: 0,+ });+ expect(inboxSignalBodies()).toEqual([]);+ });+});diff --git a/tests/core/brain/intake/page-entity-links.test.ts b/tests/core/brain/intake/page-entity-links.test.tsnew file mode 100644index 00000000..3c5e64a0--- /dev/null+++ b/tests/core/brain/intake/page-entity-links.test.ts@@ -0,0 +1,288 @@+/**+ * Page-link to entity resolver (note-change truth maintenance, F4/C1):+ * the ordered canonical entity ids a source page links to, resolved+ * server-side through an injected accessor so the mapping stays+ * testable without a real index. Withheld entity pages are dropped+ * BEFORE returning (the link-candidates precedent: identical to+ * absent), and a page whose links resolve to nothing answers an empty+ * list, never a throw.+ */++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 { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { writeFrontmatterAtomic } from "../../../../src/core/vault.ts";+import { brainDirs } from "../../../../src/core/brain/paths.ts";+import {+ entityLinkResolver,+ pageEntityLinks,+ type EntityLinkAccessor,+} from "../../../../src/core/brain/intake/page-entity-links.ts";+import { __clearEntityIndexCache } from "../../../../src/core/brain/entities/index-builder.ts";++let vault: string;+let configHome: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-page-links-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-page-links-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ __clearEntityIndexCache();+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ __clearEntityIndexCache();+});++function writeEntityNode(+ category: string,+ id: string,+ name: string,+ aliases: ReadonlyArray<string> = [],+ status = "active",+): void {+ const dir = join(brainDirs(vault).entities, category);+ mkdirSync(dir, { recursive: true });+ writeFrontmatterAtomic(+ join(dir, `${id}.md`),+ {+ kind: "brain-entity",+ entity_id: id,+ category,+ name,+ ...(aliases.length > 0 ? { aliases: [...aliases] } : {}),+ status,+ created_at: "2026-10-19T00:00:00Z",+ updated_at: "2026-10-19T00:00:00Z",+ tags: ["brain", "brain/entity"],+ },+ `# ${name}`,+ { overwrite: true },+ );+ __clearEntityIndexCache();+}++describe("pageEntityLinks", () => {+ test("returns the linked canonical entity ids in body order, deduped across spellings", () => {+ const ids = pageEntityLinks(+ [+ "Intro prose.",+ "",+ "- [[ent-people-ada-lovelace]] wrote the note.",+ "- See [[ent-project-atlas]] and [[Ada]] again; [[ent-people-ada-lovelace|her page]].",+ ].join("\n"),+ (target) =>+ target === "ent-people-ada-lovelace" || target === "Ada"+ ? "ent-people-ada-lovelace"+ : target === "ent-project-atlas"+ ? "ent-project-atlas"+ : undefined,+ );+ expect(ids).toEqual(["ent-people-ada-lovelace", "ent-project-atlas"]);+ });++ test("answers empty when nothing resolves, and never throws on a failing accessor", () => {+ expect(pageEntityLinks("No links here at all.", () => undefined)).toEqual([]);+ expect(+ pageEntityLinks("- [[ent-people-ada-lovelace]]", () => {+ throw new Error("index exploded");+ }),+ ).toEqual([]);+ });++ test("a throwing accessor degrades to the partial list, not a failed page", () => {+ // PINNED, not incidental: the accessor is where withholding and+ // resolving live, and one target it raises on must cost the page+ // only THAT target - the links before it stay attached, the links+ // after it are indistinguishable from absent, and the page itself+ // never fails. If this test starts failing, someone turned a+ // resolver fault into a failed read.+ const ids = pageEntityLinks(+ [+ "- [[ent-people-ada-lovelace]] wrote the note.",+ "- [[ent-project-atlas]] funded it.",+ "- [[ent-orgs-acme]] reviewed it.",+ ].join("\n"),+ (target) => {+ if (target === "ent-people-ada-lovelace") return "ent-people-ada-lovelace";+ if (target === "ent-project-atlas") throw new Error("index exploded mid-page");+ return target === "ent-orgs-acme" ? "ent-orgs-acme" : undefined;+ },+ );+ expect(ids).toEqual(["ent-people-ada-lovelace", "ent-orgs-acme"]);+ });++ test("skips media and code regions the wikilink extractor skips", () => {+ const ids = pageEntityLinks(+ ["![[ent-people-ada-lovelace.png]]", "`[[ent-project-atlas]]`", "[[ent-orgs-acme]]"].join(+ "\n",+ ),+ (target) => (target === "ent-orgs-acme" ? "ent-orgs-acme" : undefined),+ );+ expect(ids).toEqual(["ent-orgs-acme"]);+ });+});++describe("entityLinkResolver", () => {+ beforeEach(() => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace", ["Ada"]);+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ });++ test("resolves the id, .md, path, slug-prefixed and alias spellings", () => {+ // These tests run at the vault's own reach, and the resolver makes+ // that decision EXPLICIT: the predicate is a required argument, so+ // "everything counts" is written here rather than defaulted to.+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("ent-people-ada-lovelace")).toBe("ent-people-ada-lovelace");+ expect(resolve("ent-people-ada-lovelace.md")).toBe("ent-people-ada-lovelace");+ expect(resolve("Brain/entities/people/ent-people-ada-lovelace.md")).toBe(+ "ent-people-ada-lovelace",+ );+ expect(resolve("people/ada-lovelace")).toBe("ent-people-ada-lovelace");+ expect(resolve("Ada")).toBe("ent-people-ada-lovelace");+ expect(resolve("ent-project-atlas")).toBe("ent-project-atlas");+ });++ test("leaves bare names, unknown targets and non-entity notes unresolved", () => {+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("Ada Lovelace")).toBeUndefined();+ expect(resolve("ent-people-nobody")).toBeUndefined();+ expect(resolve("some-regular-note")).toBeUndefined();+ });++ test("the slug fold rung never folds a bare spelling into the id's slug", () => {+ // The fold is the category/slug rung: it maps each PATH SEGMENT the+ // way the anchoring kernel's separator-tolerant spelling does. Folded+ // over a bare name it would assemble the id's own slug out of+ // "People Ada Lovelace" or "people_ada_lovelace" - bare entity NAMEs,+ // which are deliberately not a rung - and resolve spellings the+ // vault's own link resolution dangles on. Case-varying a bare id+ // stays unresolved too: ids are answered case-sensitively.+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("People Ada Lovelace")).toBeUndefined();+ expect(resolve("people_ada_lovelace")).toBeUndefined();+ expect(resolve("Ent-People-Ada-Lovelace")).toBeUndefined();+ expect(resolve("people ada lovelace")).toBeUndefined();+ // The prefixed form keeps its rung, folded or not.+ expect(resolve("People/Ada Lovelace")).toBe("ent-people-ada-lovelace");+ expect(resolve("PEOPLE/ADA-LOVELACE")).toBe("ent-people-ada-lovelace");+ });++ test("a directory prefix must be the page's own vault path, never a basename fallback", () => {+ // A link that carries a directory prefix names THAT page: the vault's+ // own link resolution dangles on Notes/ent-people-ada-lovelace, so+ // answering the entity by basename alone would attach an anchor the+ // link never supported. Only the entity page's real vault path - with+ // or without the .md suffix - resolves through a prefixed spelling.+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("Notes/ent-people-ada-lovelace")).toBeUndefined();+ expect(resolve("Notes/ent-people-ada-lovelace.md")).toBeUndefined();+ expect(resolve("Brain/entities/people/ent-people-ada-lovelace.md")).toBe(+ "ent-people-ada-lovelace",+ );+ expect(resolve("Brain/entities/people/ent-people-ada-lovelace")).toBe(+ "ent-people-ada-lovelace",+ );+ });++ test("an alias two visible entities claim stays unresolved instead of first-wins", () => {+ // The index refuses to answer a contested alias (duplicate-alias+ // conflicts, first claimant kept only for its own reads); a resolver+ // that answers first-wins turns an ambiguous link into a confident+ // wrong anchor. Ambiguous stays unresolved, for every claimant.+ writeEntityNode("people", "ent-people-ada-smith", "Ada Smith", ["Ada"]);+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("Ada")).toBeUndefined();+ // The contested spelling is gone; each entity's own spellings are not.+ expect(resolve("ent-people-ada-lovelace")).toBe("ent-people-ada-lovelace");+ expect(resolve("ent-people-ada-smith")).toBe("ent-people-ada-smith");+ });++ test("an alias claim is counted over the visible canonical population only", () => {+ // An archived page is identical to absent here, so its claim cannot+ // make a visible entity's alias ambiguous; neither can a page the+ // visible predicate refuses.+ writeEntityNode("orgs", "ent-orgs-acme", "Acme Co", ["Shared"]);+ writeEntityNode("orgs", "ent-orgs-old", "Old Co", ["Shared"], "archived");+ writeEntityNode("orgs", "ent-orgs-hidden", "Hidden Co", ["Also Shared"]);+ writeEntityNode("orgs", "ent-orgs-visible", "Visible Co", ["Also Shared"]);+ const refused = new Set(["Brain/entities/orgs/ent-orgs-hidden.md"]);+ const resolve = entityLinkResolver(vault, {+ visible: (rel) => !refused.has(rel.split("\\").join("/")),+ });+ expect(resolve("Shared")).toBe("ent-orgs-acme");+ expect(resolve("Also Shared")).toBe("ent-orgs-visible");+ });++ test("a link target is trimmed before the rungs answer it", () => {+ // WIKILINK_TARGET_RE captures the target untrimmed, so `[[id ]]` and+ // `[[id #anchor]]` hand the resolver a trailing space; the rungs must+ // answer the target the author wrote, not the whitespace around it.+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve(" ent-people-ada-lovelace ")).toBe("ent-people-ada-lovelace");+ expect(resolve("ent-people-ada-lovelace.md ")).toBe("ent-people-ada-lovelace");+ expect(resolve(" people/ada-lovelace\t")).toBe("ent-people-ada-lovelace");+ expect(resolve(" Ada ")).toBe("ent-people-ada-lovelace");+ });++ test("the slug rung folds separator runs and case like the kernel's spellings", () => {+ // The anchoring kernel matches "ada lovelace", "ada-lovelace" and+ // "ada_lovelace" as one class at a path-segment boundary, and ids are+ // minted slugified; a slug-prefixed link spelled the way authors+ // actually write them must resolve to the id those rules mint.+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("people/Ada_Lovelace")).toBe("ent-people-ada-lovelace");+ expect(resolve("People/ada lovelace")).toBe("ent-people-ada-lovelace");+ expect(resolve("people/ada--_ lovelace.md")).toBe("ent-people-ada-lovelace");+ });++ test("drops non-canonical entity pages before returning", () => {+ writeEntityNode("orgs", "ent-orgs-retired", "Retired Co", [], "archived");+ writeEntityNode("orgs", "ent-orgs-quarantined", "Quarantined Co", [], "quarantine");+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("ent-orgs-retired")).toBeUndefined();+ expect(resolve("ent-orgs-quarantined")).toBeUndefined();+ expect(resolve("orgs/retired-co")).toBeUndefined();+ });++ test("a page the visible predicate refuses is identical to absent", () => {+ const refused = new Set(["Brain/entities/people/ent-people-ada-lovelace.md"]);+ const resolve = entityLinkResolver(vault, {+ visible: (rel) => !refused.has(rel.split("\\").join("/")),+ });+ expect(resolve("ent-people-ada-lovelace")).toBeUndefined();+ expect(resolve("Ada")).toBeUndefined();+ expect(resolve("ent-project-atlas")).toBe("ent-project-atlas");+ });++ test("a malformed entity file is skipped and the rest of the index still resolves", () => {+ const broken = join(vault, "Brain", "entities", "people");+ writeFileSync(join(broken, "ent-people-broken.md"), "this is not frontmatter at all", "utf8");+ __clearEntityIndexCache();+ const resolve = entityLinkResolver(vault, { visible: () => true });+ expect(resolve("ent-people-broken")).toBeUndefined();+ expect(resolve("ent-people-ada-lovelace")).toBe("ent-people-ada-lovelace");+ });++ test("the visibility predicate is a required argument, not a defaulted one", () => {+ // A forgotten predicate must be a TYPE error at the call site, never+ // a silent decision that every canonical-scope entity - private+ // pages included - may be named in an anchor list. The bad call sits+ // in a function the runtime never invokes: the assertion is tsc's,+ // not bun's.+ const resolveWith = entityLinkResolver;+ const forgets = (): EntityLinkAccessor =>+ // @ts-expect-error - omitting `visible` refuses to compile+ resolveWith(vault);+ expect(typeof forgets).toBe("function");+ });+});diff --git a/tests/core/brain/link-graph/minimal-spelling.test.ts b/tests/core/brain/link-graph/minimal-spelling.test.tsnew file mode 100644index 00000000..74fb7299--- /dev/null+++ b/tests/core/brain/link-graph/minimal-spelling.test.ts@@ -0,0 +1,249 @@+/**+ * The minimal-spelling chooser for inbound wikilink retargets.+ *+ * When a note moves, the links that named it should come out no longer+ * than they have to be: `[[Projects/Old]]` wants to become `[[New]]`,+ * not `[[Projects/New]]`, whenever the bare basename still resolves to+ * the moved note. What "still resolves" means is not this chooser's+ * opinion to invent - it is the store's read-time resolution ladder+ * (`store/links.ts`, RESOLVED_LINK_TARGET_SQL): an exact path match+ * (with the `.md` suffix appended or not), then an unambiguous+ * nested-basename match, with a TOP-LEVEL `New.md` owning the bare+ * `New` spelling outright no matter how many nested notes also carry+ * that basename.+ *+ * So the chooser asks, shortest form first: basename, suffix-less+ * relPath, full relPath. The first spelling the ladder resolves to+ * EXACTLY the destination wins. An ambiguous spelling is not a stop -+ * it falls through to the next-longer form, because a spelling that+ * resolves to two documents resolves, by the ladder's own rule, to+ * neither, and a spelling that resolves to a DIFFERENT document is+ * precisely the wrong one never to write.+ *+ * Deliberately NOT modeled here: alias resolution. The chooser judges a+ * file population (the paths a walk produced), and aliases live in the+ * index's `doc_aliases` table, not in any walked list. A spelling that+ * only an alias could resolve is not minimal by this measure, and the+ * chooser returning a longer form for it is the honest answer.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";++import { minimalSpellingFor } from "../../../../src/core/brain/link-graph/minimal-spelling.ts";+import { indexVault } from "../../../../src/core/search/indexer.ts";+import { Store } from "../../../../src/core/search/store.ts";+import { createTempVault, makeConfig, writeMd } from "../../../helpers/search-fixtures.ts";++describe("minimalSpellingFor", () => {+ test("the unique nested basename is the minimal spelling", () => {+ const files = ["Projects/New.md", "Projects/Ref.md", "Brain/_BRAIN.md"];+ expect(minimalSpellingFor("Projects/New.md", files)).toBe("New");+ });++ test("a top-level basename is the minimal spelling for a top-level note", () => {+ const files = ["New.md", "Projects/Other.md"];+ expect(minimalSpellingFor("New.md", files)).toBe("New");+ });++ test("a top-level note with the same basename beats the nested one (ladder rung 2)", () => {+ // Bare `New` resolves, by rung 2, to the TOP-LEVEL note - so for the+ // nested destination the bare spelling is a WRONG answer, not an+ // ambiguous one, and the chooser must never return it.+ const files = ["A/New.md", "New.md"];+ expect(minimalSpellingFor("A/New.md", files)).toBe("A/New");+ });++ test("an ambiguous nested basename falls through to the suffix-less relPath", () => {+ // Two nested carriers: the ladder's basename rung resolves to+ // neither, so the next-longer form is the first honest one.+ const files = ["A/New.md", "B/New.md", "Notes/Ref.md"];+ expect(minimalSpellingFor("A/New.md", files)).toBe("A/New");+ });++ test("a basename resolving to a DIFFERENT document is never chosen", () => {+ const files = ["A/New.md", "New.md", "Deep/New.md"];+ // Bare `New` -> the top-level note (rung 2). Suffix-less `A/New` is+ // the shortest spelling that resolves to the destination.+ expect(minimalSpellingFor("A/New.md", files)).toBe("A/New");+ expect(minimalSpellingFor("Deep/New.md", files)).toBe("Deep/New");+ });++ test("the suffix-less relPath is the fallback when the basename is ambiguous", () => {+ const files = ["A/New.md", "B/New.md", "C/New.md"];+ expect(minimalSpellingFor("A/New.md", files)).toBe("A/New");+ });++ test("a case-insensitive .md spelling still tries the append rung (ladder rung 2)", () => {+ // "x.Md" ends in ".md" case-insensitively, but the ladder's append+ // rung is unconditional: a spelling resolves when a document equals it+ // OR it + ".md". The top-level "x.Md.md" therefore OWNS the "x.Md"+ // spelling (rung 2 answers it before the basename rung is reached),+ // and the nested destination must never come out as "x.Md" - the+ // ladder would resolve that link to the OTHER note.+ const files = ["x.Md.md", "B/x.Md.md"];+ expect(minimalSpellingFor("B/x.Md.md", files)).not.toBe("x.Md");+ expect(minimalSpellingFor("B/x.Md.md", files)).toBe("B/x.Md");+ });++ test("the basename rung still answers when the append form is absent", () => {+ // With no top-level "x.Md.md" in the population the append rung has+ // nothing to answer, so the unique nested carrier of the stored+ // basename "x.Md" owns the spelling - the ladder's rung 3. Trying+ // the append rung must not SUPPRESS the basename rung.+ const files = ["B/x.Md.md", "Notes/Ref.md"];+ expect(minimalSpellingFor("B/x.Md.md", files)).toBe("x.Md");+ });++ test("the exact-path rung beats the append rung when both documents exist", () => {+ // The ladder's COALESCE answers the exact path before the appended+ // one, so "x.Md" resolves to the document literally named "x.Md" -+ // which is not the destination, and the spelling falls through.+ const files = ["x.Md", "x.Md.md", "B/x.Md.md"];+ expect(minimalSpellingFor("B/x.Md.md", files)).toBe("B/x.Md");+ });++ test("a destination absent from the population yields the destination itself, never a guess", () => {+ const files = ["Notes/Ref.md"];+ expect(minimalSpellingFor("Projects/New.md", files)).toBe("Projects/New.md");+ });++ test("other notes sharing no basename never shorten the answer below the basename", () => {+ const files = ["Deep/Nested/New.md", "Deep/Nested/Old.md", "x.md"];+ expect(minimalSpellingFor("Deep/Nested/New.md", files)).toBe("New");+ });++ test("a basename carried only by the destination's own former self is judged on the post state", () => {+ // The caller derives the post-move population; the chooser only ever+ // sees files. With the old path gone and the new one present, the+ // basename of the NEW name is what decides.+ const files = ["Projects/New.md", "Projects/Ref.md"];+ expect(minimalSpellingFor("Projects/New.md", files)).toBe("New");+ });++ test("an uppercase .MD stem is not stripped: the bare lowercase form is never the answer", () => {+ // The store's `documentBasename` strips a trailing `.md` CASE-+ // SENSITIVELY, so `Projects/Old.MD` keeps the stored basename+ // `Old.MD` and the bare spelling `Old` dangles. The chooser's+ // basename rung must strip under the same rule, or it would hand+ // back exactly the spelling the ladder cannot resolve.+ const files = ["Projects/Old.MD", "Projects/Ref.md"];+ expect(minimalSpellingFor("Projects/Old.MD", files)).not.toBe("Old");+ expect(minimalSpellingFor("Projects/Old.MD", files)).toBe("Old.MD");+ });++ test("empty basename and multi-segment destinations stay well-formed", () => {+ expect(minimalSpellingFor("Solo.md", ["Solo.md"])).toBe("Solo");+ expect(minimalSpellingFor("a/b/c/Deep.md", ["a/b/c/Deep.md", "a/b/c/Other.md"])).toBe("Deep");+ });+});++/**+ * Chooser and ladder agreement, pinned against a real index.+ *+ * The chooser re-derives the store's resolution rules in pure form, and+ * a re-derivation drifts unless something compares the two on the same+ * vault. Each fixture below builds a temp vault whose shape is one of+ * the chooser's unit populations, asks the chooser for the minimal+ * spelling of a destination, writes a referencing note that uses the+ * chosen spelling (and, where the shape has one, a second note using+ * the bare basename), indexes the vault, and then asks the store's OWN+ * ladder - `resolvedDocLinkPairs`, the same RESOLVED_LINK_TARGET_SQL+ * the census and the dangling list follow - which document that link+ * resolves to. Agreement means: the chosen spelling lands on the+ * destination document, every time, on every population shape.+ */+describe("agreement with the store resolution ladder", () => {+ let vault: string;+ let dbPath: string;+ let cleanup: () => void;++ beforeEach(() => {+ const created = createTempVault("minimal-spelling-ladder");+ vault = created.vault;+ dbPath = created.dbPath;+ cleanup = created.cleanup;+ });+ afterEach(() => cleanup());++ /** Index `vault` and return the resolved target path of every link. */+ async function resolvedLinkTargets(): Promise<Array<{ source: string; target: string }>> {+ const config = makeConfig({ vault, dbPath });+ await indexVault(config, { force: true });+ const store = await Store.open(config, { mode: "read" });+ try {+ const idToPath = new Map<number, string>();+ for (const [path, summary] of store.listDocuments()) idToPath.set(summary.id, path);+ return store.resolvedDocLinkPairs().flatMap((pair) => {+ const source = idToPath.get(pair.source);+ const target = idToPath.get(pair.target);+ return source !== undefined && target !== undefined ? [{ source, target }] : [];+ });+ } finally {+ await store.close();+ }+ }++ /**+ * Write the population, ask the chooser for the minimal spelling of+ * `destination`, write a ref note citing that spelling, and return the+ * chosen spelling so the assertions can name what they pinned.+ */+ function refCitingChooserSpelling(+ population: ReadonlyArray<string>,+ destination: string,+ ): string {+ const spelling = minimalSpellingFor(+ destination,+ population.filter((rel) => rel !== "Notes/Ref.md"),+ );+ writeMd(vault, "Notes/Ref.md", `see [[${spelling}]] here\n`);+ for (const rel of population) if (rel !== "Notes/Ref.md") writeMd(vault, rel, "body\n");+ return spelling;+ }++ test("a unique nested basename resolves through the ladder to the destination", async () => {+ const destination = "Projects/New.md";+ const spelling = refCitingChooserSpelling(+ ["Projects/New.md", "Projects/Ref.md", "Notes/Ref.md"],+ destination,+ );+ expect(spelling).toBe("New");+ const pairs = await resolvedLinkTargets();+ expect(pairs).toContainEqual({ source: "Notes/Ref.md", target: destination });+ });++ test("a top-level destination's bare spelling resolves through the exact rung", async () => {+ const destination = "New.md";+ const spelling = refCitingChooserSpelling(+ ["New.md", "Projects/Other.md", "Notes/Ref.md"],+ destination,+ );+ expect(spelling).toBe("New");+ const pairs = await resolvedLinkTargets();+ expect(pairs).toContainEqual({ source: "Notes/Ref.md", target: destination });+ });++ test("under a top-level basename carrier the suffix-less spelling resolves to the nested destination", async () => {+ const destination = "A/New.md";+ const spelling = refCitingChooserSpelling(["A/New.md", "New.md", "Notes/Ref.md"], destination);+ expect(spelling).toBe("A/New");+ const pairs = await resolvedLinkTargets();+ expect(pairs).toContainEqual({ source: "Notes/Ref.md", target: destination });+ });++ test("with two nested carriers the suffix-less spelling resolves and the bare one resolves to neither", async () => {+ const destination = "A/New.md";+ const spelling = refCitingChooserSpelling(+ ["A/New.md", "B/New.md", "Notes/Ref.md"],+ destination,+ );+ expect(spelling).toBe("A/New");+ writeMd(vault, "Bare/Ref.md", "bare [[New]] here\n");+ const pairs = await resolvedLinkTargets();+ // The chooser's spelling lands on the destination...+ expect(pairs).toContainEqual({ source: "Notes/Ref.md", target: destination });+ // ...and the bare spelling the chooser refused is unresolved, which+ // is exactly why it was refused.+ expect(pairs.find((pair) => pair.source === "Bare/Ref.md")).toBeUndefined();+ });+});diff --git a/tests/core/brain/maintenance/relink-anchors.test.ts b/tests/core/brain/maintenance/relink-anchors.test.tsnew file mode 100644index 00000000..0a1e5085--- /dev/null+++ b/tests/core/brain/maintenance/relink-anchors.test.ts@@ -0,0 +1,1220 @@+/**+ * The relink maintenance lane task (note-change truth maintenance,+ * F4/C3): recompute the entity anchors of page-sourced signals with the+ * shipped rules - text anchors through the shared occurrence kernel,+ * link-derived anchors through the page-link resolver - additively only+ * (an existing anchor is never removed), dry-run report by default with+ * an apply flag, at the maintenance lane's local reach, and never+ * calling a model.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { writeFrontmatterAtomic } from "../../../../src/core/vault.ts";+import { brainDirs } from "../../../../src/core/brain/paths.ts";+import type { ProgressEvent } from "../../../../src/core/brain/progress.ts";+import { writeSignal, parseSignal } from "../../../../src/core/brain/signal.ts";+import { parseFrontmatter } from "../../../../src/core/vault.ts";+import { LANE_TASK, LANE_TASKS, isLaneTask } from "../../../../src/core/brain/maintenance/lane.ts";+import { buildLaneTasks } from "../../../../src/core/brain/maintenance/lane-tasks.ts";+import { isOperation } from "../../../../src/core/brain/safeguard.ts";+import { resolveSearchConfig } from "../../../../src/core/search/index.ts";+import {+ decideRawRewrite,+ runRelinkAnchors,+} from "../../../../src/core/brain/maintenance/relink-anchors-task.ts";++const NOW = new Date("2026-10-19T04:00:00Z");++let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-relink-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-relink-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function writeEntityNode(+ category: string,+ id: string,+ name: string,+ aliases: ReadonlyArray<string> = [],+ status = "active",+ visibility?: "private",+): void {+ const dir = join(brainDirs(vault).entities, category);+ mkdirSync(dir, { recursive: true });+ writeFrontmatterAtomic(+ join(dir, `${id}.md`),+ {+ kind: "brain-entity",+ entity_id: id,+ category,+ name,+ ...(aliases.length > 0 ? { aliases: [...aliases] } : {}),+ status,+ ...(visibility !== undefined ? { visibility } : {}),+ created_at: "2026-10-19T00:00:00Z",+ updated_at: "2026-10-19T00:00:00Z",+ tags: ["brain", "brain/entity"],+ },+ `# ${name}`,+ { overwrite: true },+ );+}++function writeSourcePage(rel: string, body: string): void {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, body, "utf8");+}++/** A source page reserved against remote reads (`visibility: private`). */+function writePrivateSourcePage(rel: string, body: string): void {+ const abs = join(vault, rel);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFrontmatterAtomic(abs, { visibility: "private" }, body, { overwrite: true });+}++/** Restamp a stored signal page `visibility: private` (local-only readers). */+function markSignalPrivate(file: string): void {+ const path = join(brainDirs(vault).inbox, file);+ const [meta, body] = parseFrontmatter(path);+ writeFrontmatterAtomic(path, { ...meta, visibility: "private" }, body, { overwrite: true });+}++function writePageSourcedSignal(input: {+ readonly sourceRef?: string;+ readonly sourceRefs?: ReadonlyArray<string>;+ readonly principle: string;+ readonly storedEntityIds: ReadonlyArray<string>;+ readonly topic?: string;+ /**+ * The signal's source_type stamp. Defaults to `extracted` - the pass's+ * in-scope stamp; `"live"` omits the field entirely, which is how a+ * `brain_feedback` signal is stored (live is the implicit default).+ */+ readonly sourceType?: "extracted" | "inline" | "live";+ /** Write the page with no `## Raw` section at all (v0.10.1 shape). */+ readonly noRawSection?: boolean;+ /** Store the raw body codec-compressed (the `_raw_codec` marker). */+ readonly rawCodec?: boolean;+ /** Verbatim raw body overriding the stored-ids / placeholder default. */+ readonly rawBody?: string;+}): void {+ const sourceRefs = input.sourceRefs ?? [input.sourceRef ?? ""];+ const sourceType = input.sourceType ?? "extracted";+ writeSignal(vault, {+ topic: input.topic ?? "fact-quantity",+ signal: "positive",+ agent: "tester",+ principle: input.principle,+ created_at: "2026-10-19T01:00:00Z",+ date: "2026-10-19",+ slug: input.topic ?? "fact-quantity",+ source: sourceRefs.map((ref) => `[[${ref}]]`),+ ...(sourceType === "live" ? {} : { source_type: sourceType }),+ dedup_hash: `hash-${input.principle.length}-${sourceRefs.join(".").replace(/\W/g, "")}`,+ ...(input.noRawSection+ ? {}+ : input.rawBody !== undefined+ ? { raw: input.rawBody }+ : input.storedEntityIds.length > 0+ ? { raw: `entities: ${input.storedEntityIds.join(", ")}` }+ : { raw: "_(not provided)_" }),+ ...(input.rawCodec ? { rawCodec: true } : {}),+ });+}++/**+ * Every byte under `Brain/log/`, as one deterministic string: the+ * dry-run-writes-nothing pins compare whole snapshots, not single files,+ * so a skip event landing in any shard fails the comparison.+ */+function logSnapshot(): string {+ const root = brainDirs(vault).log;+ if (!existsSync(root)) return "<absent>";+ const out: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ )) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) walk(path);+ else out.push(`${path}\n${readFileSync(path, "utf8")}`);+ }+ };+ walk(root);+ return out.join("\n");+}++function inboxFiles(): ReadonlyArray<string> {+ const dir = brainDirs(vault).inbox;+ return existsSync(dir)+ ? readdirSync(dir)+ .filter((f) => f.startsWith("sig-") && f.endsWith(".md"))+ .toSorted()+ : [];+}++function entitiesLineOf(file: string): string | undefined {+ const body = readFileSync(join(brainDirs(vault).inbox, file), "utf8");+ return body.split(/\r?\n/).find((line) => line.startsWith("entities: "));+}++describe("runRelinkAnchors", () => {+ test("dry run by default: reports the addable anchors and writes nothing", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ });+ const before = inboxFiles().map((f) => readFileSync(join(brainDirs(vault).inbox, f), "utf8"));++ const report = runRelinkAnchors(vault, { now: NOW });++ expect(report.apply).toBe(false);+ expect(report.signalsScanned).toBe(1);+ expect(report.signalsPageSourced).toBe(1);+ expect(report.signalsChanged).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(report.perSource).toEqual([{ source: "notes/meeting.md", signals: 1, anchorsAdded: 1 }]);+ const after = inboxFiles().map((f) => readFileSync(join(brainDirs(vault).inbox, f), "utf8"));+ expect(after).toEqual(before);+ });++ test("apply unions text-derived and link-derived anchors additively, and is idempotent", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ });+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.apply).toBe(true);+ expect(report.signalsChanged).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(entitiesLineOf(file)).toBe("entities: ent-project-atlas, ent-people-ada-lovelace");++ const second = runRelinkAnchors(vault, { now: NOW, apply: true });+ expect(second.anchorsAdded).toBe(0);+ expect(second.signalsChanged).toBe(0);+ expect(entitiesLineOf(file)).toBe("entities: ent-project-atlas, ent-people-ada-lovelace");+ });++ test("an existing anchor is never removed, even when the recompute no longer matches it", () => {+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeEntityNode("orgs", "ent-orgs-retired", "Retired Co", [], "archived");+ writeSourcePage("notes/meeting.md", "# Meeting\n\nNothing linked here.\n");+ writePageSourcedSignal({+ // The principle names nothing the recompute can anchor - the archived+ // node is out of canonical scope and the source page links nothing -+ // so the recompute produces no anchor at all.+ sourceRef: "notes/meeting.md",+ principle: "the depot confirmed receipt the same day",+ storedEntityIds: ["ent-orgs-retired"],+ });+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.anchorsAdded).toBe(0);+ expect(report.signalsChanged).toBe(0);+ expect(entitiesLineOf(file)).toBe("entities: ent-orgs-retired");+ });++ test("a signal whose source names no vault page is out of scope and untouched", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writePageSourcedSignal({+ sourceRef: "session:abc123#turn-4",+ principle: "Ada Lovelace designed the engine",+ storedEntityIds: [],+ });+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsScanned).toBe(1);+ expect(report.signalsPageSourced).toBe(0);+ expect(report.signalsChanged).toBe(0);+ const body = readFileSync(join(brainDirs(vault).inbox, file), "utf8");+ expect(body).not.toContain("ent-people-ada-lovelace");+ });++ test("a page-sourced signal gains anchors from a source page it links without naming", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/notes.md",+ "# Notes\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/notes",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(entitiesLineOf(file)).toBe("entities: ent-people-ada-lovelace");+ });++ test("per-source counts aggregate the signals that share one source page", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ ["# Meeting", "", "- [[ent-people-ada-lovelace]]", "- [[ent-project-atlas]]"].join("\n"),+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ });+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the depot confirmed receipt the same day",+ storedEntityIds: [],+ topic: "fact-url",+ });++ const report = runRelinkAnchors(vault, { now: NOW });++ // The first signal already stores Atlas and gains Ada from the page;+ // the second names nothing and gains both links. Three anchors across+ // the two signals, aggregated under their one shared source.+ expect(report.perSource).toEqual([{ source: "notes/meeting.md", signals: 2, anchorsAdded: 3 }]);+ expect(report.anchorsAdded).toBe(3);+ });++ test("a signal without a Raw section reports no addition it could not make", () => {+ // No `## Raw` section means the anchor has no home on the page: the+ // rewrite refuses it, so reporting the addition - in either arm -+ // would be a count for a write that never happens.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ noRawSection: true,+ });+ const file = inboxFiles()[0]!;+ const before = readFileSync(join(brainDirs(vault).inbox, file), "utf8");++ const dry = runRelinkAnchors(vault, { now: NOW });+ expect(dry.signalsPageSourced).toBe(1);+ expect(dry.signalsChanged).toBe(0);+ expect(dry.anchorsAdded).toBe(0);++ const applied = runRelinkAnchors(vault, { now: NOW, apply: true });+ expect(applied.signalsChanged).toBe(0);+ expect(applied.anchorsAdded).toBe(0);+ expect(readFileSync(join(brainDirs(vault).inbox, file), "utf8")).toBe(before);+ });++ test("a codec-compressed signal is out of the rewrite's reach and counted by neither arm", () => {+ // The compressed section collapses whitespace runs, so a blank-line+ // run merges the `entities:` line into the line above it: a+ // byte-level rewrite would find no line to replace, append a second+ // one, and the next parse - which reads the FIRST entities line of+ // the EXPANDED section - would never see it. The signal is out of+ // the pass's reach, like a page without a Raw section - and the+ // raw-shape gate does not claim it: the codec gate runs first, so+ // the skip is the byte form's, counted by neither arm.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ // Four newlines collapse into one run marker, merging the entities+ // line into the preceding line on disk; Atlas is stored, Ada is the+ // addition the pass must NOT claim it can make.+ rawBody: "progress notes\n\n\n\nentities: ent-project-atlas",+ rawCodec: true,+ });+ const file = join(brainDirs(vault).inbox, inboxFiles()[0]!);+ const before = readFileSync(file, "utf8");+ expect(before).toContain("_raw_codec");++ const dry = runRelinkAnchors(vault, { now: NOW });+ expect(dry.signalsPageSourced).toBe(1);+ expect(dry.signalsSkippedRawShape).toBe(0);+ expect(dry.signalsChanged).toBe(0);+ expect(dry.anchorsAdded).toBe(0);++ const applied = runRelinkAnchors(vault, { now: NOW, apply: true });+ expect(applied.signalsChanged).toBe(0);+ expect(applied.anchorsAdded).toBe(0);+ expect(readFileSync(file, "utf8")).toBe(before);+ // The stored record still parses, expanded, with the marker read back.+ const parsed = parseSignal(file);+ expect(parsed.rawCodec).toBe(true);+ expect(parsed.raw).toBe("progress notes\n\n\n\nentities: ent-project-atlas");+ });++ test("an extractor-shaped raw stored codec-compressed is still held out by the codec flag", () => {+ // The shape gate subsumes the old codec skip only for PROSE sections;+ // it must not wave through the one signal whose expanded raw IS the+ // extractor's line: on disk the section is the compressed form, and+ // a byte-level rewrite there would append a line the next parse+ // never reads. The flag keeps that signal out, counted by neither+ // arm, exactly as before.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ rawBody: "entities: ent-project-atlas",+ rawCodec: true,+ });+ const file = join(brainDirs(vault).inbox, inboxFiles()[0]!);+ const before = readFileSync(file, "utf8");++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.signalsSkippedRawShape).toBe(0);+ expect(report.signalsChanged).toBe(0);+ expect(report.anchorsAdded).toBe(0);+ expect(readFileSync(file, "utf8")).toBe(before);+ });++ test("two consecutive dry runs report identical numbers", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ });+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the depot confirmed receipt the same day",+ storedEntityIds: [],+ topic: "fact-url",+ });+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "no raw section on this one",+ storedEntityIds: [],+ topic: "fact-topic",+ noRawSection: true,+ });++ const first = runRelinkAnchors(vault, { now: NOW });+ const second = runRelinkAnchors(vault, { now: NOW });+ expect(second).toEqual(first);+ });++ test("a dry run and an apply run over the same vault report the same numbers", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ });++ const dry = runRelinkAnchors(vault, { now: NOW });+ const applied = runRelinkAnchors(vault, { now: NOW, apply: true });+ expect(applied.signalsScanned).toBe(dry.signalsScanned);+ expect(applied.signalsPageSourced).toBe(dry.signalsPageSourced);+ expect(applied.signalsChanged).toBe(dry.signalsChanged);+ expect(applied.anchorsAdded).toBe(dry.anchorsAdded);+ expect(applied.perSource).toEqual(dry.perSource);+ });++ test("a placeholder Raw section still gains the text-derived anchors", () => {+ // The "(not provided)" placeholder is the section the rewrite can+ // fill; a signal whose stored raw reads as absent must not lose the+ // text match - only the WRITE waits on the rewrite's support.+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage("notes/meeting.md", "# Meeting\n\nNo entity links here.\n");+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: [],+ });+ const file = inboxFiles()[0]!;++ const dry = runRelinkAnchors(vault, { now: NOW });+ expect(dry.anchorsAdded).toBe(1);++ const applied = runRelinkAnchors(vault, { now: NOW, apply: true });+ expect(applied.anchorsAdded).toBe(1);+ expect(entitiesLineOf(file)).toBe("entities: ent-project-atlas");+ });++ test("two pointers to one page count that page once", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRefs: ["notes/meeting.md", "notes/meeting"],+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });++ const report = runRelinkAnchors(vault, { now: NOW });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.perSource).toEqual([{ source: "notes/meeting.md", signals: 1, anchorsAdded: 1 }]);+ });++ test("a directory shadowing the page name does not swallow the page", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ // A DIRECTORY at the exact ref path: an existence probe answers true+ // for it, and reading it fails - which must cost the pass its .md+ // sibling, never the page itself.+ mkdirSync(join(vault, "notes", "meeting"), { recursive: true });+ writeFileSync(join(vault, "notes", "meeting", "inner.txt"), "x", "utf8");+ writePageSourcedSignal({+ sourceRef: "notes/meeting",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });++ const applied = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(applied.signalsPageSourced).toBe(1);+ expect(applied.anchorsAdded).toBe(1);+ });++ test("a dry run leaves the Brain log byte-identical; the apply arm stamps the skip audit", () => {+ // The shared anchorable build logs an entity-anchor-skip for a+ // canonical entity whose NAME fails the quality gate. That log event+ // is a write: the preview must compute the same anchors without+ // stamping it, and the apply arm - the write path - stamps it exactly+ // as the capture path does.+ writeEntityNode("orgs", "ent-orgs-junk", "***", ["junk"]);+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });++ const before = logSnapshot();+ const dry = runRelinkAnchors(vault, { now: NOW });+ expect(logSnapshot()).toBe(before);+ expect(dry.anchorsAdded).toBe(1);++ const applied = runRelinkAnchors(vault, { now: NOW, apply: true });+ expect(applied.anchorsAdded).toBe(dry.anchorsAdded);+ // The write path stamps the audit the preview withheld.+ expect(logSnapshot()).not.toBe(before);+ expect(logSnapshot()).toContain("entity-anchor-skip");+ });++ test("the signal walk is one stage over both trees, started once", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: [],+ topic: "fact-url",+ });+ // One signal archived into the processed tree, so the walk has work+ // in both directories it scans.+ const processedDir = brainDirs(vault).processed;+ mkdirSync(processedDir, { recursive: true });+ const moved = inboxFiles()[0]!;+ renameSync(join(brainDirs(vault).inbox, moved), join(processedDir, moved));++ const events: ProgressEvent[] = [];+ runRelinkAnchors(vault, { now: NOW, onProgress: (event) => events.push(event) });++ const starts = events.filter((event) => event.kind === "started");+ expect(starts).toHaveLength(1);+ expect(starts[0]!.stage).toBe("signals");+ expect(starts[0]!.total).toBe(2);+ expect(events.filter((event) => event.kind === "advanced")).toHaveLength(2);+ expect(events.filter((event) => event.kind === "finished")).toHaveLength(1);+ });++ test("a vault path with a trailing separator still resolves and counts its pages", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });++ const report = runRelinkAnchors(`${vault}/`, { now: NOW });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(report.perSource).toEqual([{ source: "notes/meeting.md", signals: 1, anchorsAdded: 1 }]);+ });++ test("an unreadable signal file is counted, never fatal", () => {+ const dir = brainDirs(vault).inbox;+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "sig-2026-10-19-broken.md"), "totally not a signal page", "utf8");++ const report = runRelinkAnchors(vault, { now: NOW });++ expect(report.signalsScanned).toBe(1);+ expect(report.signalsUnreadable).toBe(1);+ expect(report.signalsPageSourced).toBe(0);+ });+});++describe("the resolution binds at the reach the signal itself is readable at", () => {+ test("a remotely readable signal never gains a private entity page's id", () => {+ // The signal page carries no visibility reservation, so every+ // remote-reach reader can list it. Its resolution therefore binds at+ // remote reach: the public link attaches, and the private page's id+ // adds nothing - writing it would disclose the record to every+ // reader that can list the signal, and the pass never removes an+ // anchor, so the leak would be permanent.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("people", "ent-people-secret-person", "Secret Person", [], "active", "private");+ writeSourcePage(+ "notes/meeting.md",+ ["# Meeting", "", "- [[ent-people-ada-lovelace]]", "- [[ent-people-secret-person]]"].join(+ "\n",+ ),+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(entitiesLineOf(file)).toBe("entities: ent-people-ada-lovelace");+ const body = readFileSync(join(brainDirs(vault).inbox, file), "utf8");+ expect(body).not.toContain("ent-people-secret-person");+ });++ test("the same fixture with a local-only signal still gains the private anchor", () => {+ // A signal page reserved against remote reads stays a local-reach+ // fact: the lane is a local repair pass, and it heals what only a+ // local reader sees. Nothing about the signal leaves the host, so+ // the private id costs no disclosure here.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("people", "ent-people-secret-person", "Secret Person", [], "active", "private");+ writeSourcePage(+ "notes/meeting.md",+ ["# Meeting", "", "- [[ent-people-ada-lovelace]]", "- [[ent-people-secret-person]]"].join(+ "\n",+ ),+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ markSignalPrivate(inboxFiles()[0]!);+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.anchorsAdded).toBe(2);+ expect(entitiesLineOf(file)).toBe(+ "entities: ent-people-ada-lovelace, ent-people-secret-person",+ );+ });++ test("a remotely readable signal anchors nothing from a principle naming a private entity", () => {+ // The TEXT half binds at the same per-signal reach as the link half.+ // The anchorable list is built at the lane's reach, so a principle+ // naming a PRIVATE entity matched that entity and pushed its id into+ // a signal every remote-reach reader can list - the same leak the+ // link half's reach fix closed, entering through the text arm. The+ // private name anchors nothing; a public name on the same signal+ // class still anchors; a local-only signal keeps healing the+ // private name.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("people", "ent-people-secret-person", "Secret Person", [], "active", "private");+ writeSourcePage("notes/meeting.md", "# Meeting\n\nNo entity links here.\n");+ // Remotely readable, names the private entity only: nothing anchors.+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Secret Person joined the review",+ storedEntityIds: [],+ });+ // Remotely readable, names the public entity: still anchors.+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Ada Lovelace joined the review",+ storedEntityIds: [],+ topic: "fact-public",+ });+ // Local-only, names the private entity: the lane still heals it.+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Secret Person joined the review",+ storedEntityIds: [],+ topic: "fact-private",+ });+ markSignalPrivate(inboxFiles()[0]!);+ // Sorted by name: `fact-private` (local-only, heals the private+ // name), `fact-public` (remote, anchors the public name),+ // `fact-quantity` (remote, names the private entity).+ const [healedFile, publicFile, remoteSecretFile] = inboxFiles();++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(3);+ expect(report.anchorsAdded).toBe(2);+ expect(report.signalsChanged).toBe(2);+ expect(entitiesLineOf(healedFile!)).toBe("entities: ent-people-secret-person");+ expect(entitiesLineOf(publicFile!)).toBe("entities: ent-people-ada-lovelace");+ expect(entitiesLineOf(remoteSecretFile!)).toBeUndefined();+ const body = readFileSync(join(brainDirs(vault).inbox, remoteSecretFile!), "utf8");+ expect(body).not.toContain("ent-people-secret-person");+ });++ test("a remotely readable signal whose source page is private is out of scope", () => {+ // The source filter binds at the same per-signal reach as the+ // resolver: a signal any remote reader can list gains nothing from a+ // page that reader cannot open - reading the page's links at the+ // lane's reach while writing the ids into a remotely readable page+ // would launder the page's contents past its own reservation.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writePrivateSourcePage("notes/secret.md", "# Secret\n\n- [[ent-people-ada-lovelace]]\n");+ writePageSourcedSignal({+ sourceRef: "notes/secret.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ const file = inboxFiles()[0]!;+ const before = readFileSync(join(brainDirs(vault).inbox, file), "utf8");++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(0);+ expect(report.anchorsAdded).toBe(0);+ expect(readFileSync(join(brainDirs(vault).inbox, file), "utf8")).toBe(before);+ });++ test("a local-only signal still reads its private source page at the lane's reach", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writePrivateSourcePage("notes/secret.md", "# Secret\n\n- [[ent-people-ada-lovelace]]\n");+ writePageSourcedSignal({+ sourceRef: "notes/secret.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ markSignalPrivate(inboxFiles()[0]!);+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(entitiesLineOf(file)).toBe("entities: ent-people-ada-lovelace");+ });+});++describe("the pass reads only server-stamped sources", () => {+ test("a feedback-sourced or inline-sourced signal pointing at a page gains nothing", () => {+ // A `brain_feedback` caller supplied its own `source:` pointer (and a+ // `live` signal carries no source_type at all - absence IS the live+ // stamp); an inline marker is author-written the same way. A+ // caller-chosen page must not choose which entity ids attach:+ // server-derived facts outrank caller-supplied claims, so both are+ // out of the pass's scope entirely - the pointer is never even read.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ sourceType: "live",+ });+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Ada Lovelace joined the review",+ storedEntityIds: [],+ topic: "fact-inline",+ sourceType: "inline",+ });+ const before = inboxFiles().map((f) => readFileSync(join(brainDirs(vault).inbox, f), "utf8"));++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsScanned).toBe(2);+ expect(report.signalsPageSourced).toBe(0);+ expect(report.anchorsAdded).toBe(0);+ const after = inboxFiles().map((f) => readFileSync(join(brainDirs(vault).inbox, f), "utf8"));+ expect(after).toEqual(before);+ });++ test("an extracted-sourced signal pointing at the same page still does", () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ sourceType: "extracted",+ });+ const file = inboxFiles()[0]!;++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.anchorsAdded).toBe(1);+ expect(entitiesLineOf(file)).toBe("entities: ent-people-ada-lovelace");+ });+});++describe("the rewrite touches only the extractor's own raw shape", () => {+ test("a quote line starting with entities: is never overwritten", () => {+ // An extracted stamp on a hand-joined page: the Raw section is a+ // verbatim quote whose first line happens to start with `entities:`.+ // The old line-level rewrite read that line as the anchor line,+ // counted its free text as stored anchors, and overwrote the quote's+ // own words. The shape check refuses: the raw is not the extractor's+ // single `entities:` line, so the signal is skipped and counted.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ rawBody: "entities: ent-project-atlas\nAda Lovelace joined the review.",+ });+ const file = join(brainDirs(vault).inbox, inboxFiles()[0]!);+ const before = readFileSync(file, "utf8");++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsPageSourced).toBe(1);+ expect(report.signalsSkippedRawShape).toBe(1);+ expect(report.signalsChanged).toBe(0);+ expect(report.anchorsAdded).toBe(0);+ expect(readFileSync(file, "utf8")).toBe(before);+ });++ test("a quote with a heading never gets a mid-quote splice", () => {+ // The raw-section rewrite used to stop at the first `## ` line while+ // the parser read to EOF, so an entities line spliced into a quote+ // containing a heading landed mid-quote. The shape check refuses the+ // page before any line is touched.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ rawBody: "Ada said:\n\n## Verbatim\n\nthe review concluded with five follow-ups.",+ });+ const file = join(brainDirs(vault).inbox, inboxFiles()[0]!);+ const before = readFileSync(file, "utf8");++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsSkippedRawShape).toBe(1);+ expect(report.signalsChanged).toBe(0);+ expect(report.anchorsAdded).toBe(0);+ expect(readFileSync(file, "utf8")).toBe(before);+ });++ test("an extracted signal with malformed raw is skipped with a count", () => {+ // One line, but not the extractor's: nothing about it is an anchor+ // line, and splicing one in after it would edit a record the pass+ // has no business editing. Skipped, counted, never written.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ rawBody: "just a note line",+ });+ const file = join(brainDirs(vault).inbox, inboxFiles()[0]!);+ const before = readFileSync(file, "utf8");++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsSkippedRawShape).toBe(1);+ expect(report.signalsChanged).toBe(0);+ expect(report.anchorsAdded).toBe(0);+ expect(readFileSync(file, "utf8")).toBe(before);+ });++ test("the shape check is exact: the extractor's own line is still rewritten", () => {+ // The positive twin: the exact shape `routeExtractedFacts` writes -+ // one `entities: <ids>` line, nothing else - is the one shape the+ // rewrite still serves, so the pass keeps healing narrow extractor+ // anchor lists.+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeEntityNode("project", "ent-project-atlas", "Atlas Prime");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "Atlas Prime shipped five units to the depot",+ storedEntityIds: ["ent-project-atlas"],+ });+ const file = join(brainDirs(vault).inbox, inboxFiles()[0]!);++ const report = runRelinkAnchors(vault, { now: NOW, apply: true });++ expect(report.signalsSkippedRawShape).toBe(0);+ expect(report.signalsChanged).toBe(1);+ expect(entitiesLineOf(inboxFiles()[0]!)).toBe(+ "entities: ent-project-atlas, ent-people-ada-lovelace",+ );+ });+});++describe("the apply arm re-gates the bytes it actually rewrites", () => {+ // The parse's bytes can go stale before the write: a page edited+ // between the pass's parseSignal and the apply read would otherwise+ // have the rewrite run on bytes no gate checked - the quote overwrite+ // the shape gate exists to prevent, back through the second read.+ // `decideRawRewrite` is the drift re-check: the SAME hold-out, judged+ // on the rewrite's own bytes, with the stored half rebuilt from them.++ test("a Raw turned quote between parse and read is refused, not overwritten", () => {+ // The parse saw the extractor's one-line raw; by the time the apply+ // arm reads the page, the section is a verbatim quote whose own line+ // starts with `entities:` - the exact bytes the old flow happily+ // rewrote. The byte gate answers unsafe-shape.+ const before = [+ "---",+ "kind: brain-signal",+ "---",+ "## Raw",+ "entities: ent-project-atlas",+ "Ada Lovelace joined the review.",+ "",+ ].join("\n");+ expect(decideRawRewrite(before, ["ent-people-ada-lovelace"])).toEqual({+ action: "unsafe-shape",+ });+ });++ test("a heading after the entities line between parse and read is refused, not spliced into", () => {+ // The parse saw the extractor's one-line raw; the apply read finds a+ // heading after the `entities:` line. The parser reads `## Raw` to+ // EOF, so the parse-time shape gate would reject these bytes as a+ // multi-line section - the byte gate must too, though only the span+ // up to the heading still looks like the extractor's one line.+ const before = [+ "---",+ "kind: brain-signal",+ "---",+ "## Raw",+ "entities: ent-project-atlas",+ "## Notes",+ "Ada Lovelace joined the review.",+ "",+ ].join("\n");+ expect(decideRawRewrite(before, ["ent-people-ada-lovelace"])).toEqual({+ action: "unsafe-shape",+ });+ });++ test("a Raw turned codec between parse and read is refused, even when the compressed form spells the extractor's line", () => {+ // Same window, opposite edit: the frontmatter now carries the+ // `_raw_codec` marker beside a real section, so the bytes on disk+ // are the reversible compressed form. The collapse that hid the+ // section's real content can leave ONE line that starts with+ // `entities: ` and parses to an id - the shape gate alone would+ // accept it and rewrite the compressed bytes - so the marker itself+ // is what refuses here, with the parse-time codec gate's own+ // uncounted answer.+ const before = [+ "---",+ "kind: brain-signal",+ "_raw_codec: 1",+ "---",+ "## Raw",+ "entities: ent-project-atlas",+ "",+ ].join("\n");+ expect(decideRawRewrite(before, ["ent-people-ada-lovelace"])).toEqual({+ action: "codec",+ });+ });++ test("a codec marker over an absent or placeholder section is not a codec page", () => {+ // The parse gate fires for a marker AND a real section only+ // (`rawCodec` is storedCodec: marker + rawSection), so the mirror+ // falls through for these and the old flow's answers stand: a+ // placeholder is still fillable, a missing section still has no+ // home - neither is counted as anything.+ const placeholder = "---\nkind: brain-signal\n_raw_codec: 1\n---\n## Raw\n_(not provided)_\n";+ expect(decideRawRewrite(placeholder, ["ent-c"])).toEqual({+ action: "rewrite",+ next: "---\nkind: brain-signal\n_raw_codec: 1\n---\n## Raw\nentities: ent-c\n",+ appended: ["ent-c"],+ });+ expect(+ decideRawRewrite("---\nkind: brain-signal\n_raw_codec: 1\n---\n\nbody\n", ["ent-c"]),+ ).toEqual({ action: "no-home" });+ });++ test("an edit that widened the stored list keeps its ids", () => {+ // The parse read `entities: a`; the apply read sees `entities: a, b`+ // - a concurrent edit stored `b`. The rebuilt line keeps it: the+ // pass is additive, and a line built from the parse's stale `stored`+ // would have dropped it. `appended` names what the rewrite adds.+ const before = "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a, ent-b\n";+ expect(decideRawRewrite(before, ["ent-c"])).toEqual({+ action: "rewrite",+ next: "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a, ent-b, ent-c\n",+ appended: ["ent-c"],+ });+ });++ test("an edit that already stored every computed id makes the rewrite a no-op", () => {+ // The parse computed `ent-b` as an addition; a concurrent edit stored+ // it before the apply read. The truthful answer is nothing to add -+ // no rewrite, nothing counted - where the old flow would have+ // counted a write of byte-identical contents.+ const before = "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a, ent-b\n";+ expect(decideRawRewrite(before, ["ent-b"])).toEqual({ action: "no-home" });+ });++ test("an edit that withdrew the stored list is not resurrected", () => {+ // The parse read `entities: a`; the apply read sees the placeholder+ // - the anchor list was withdrawn after the parse. The rebuilt line+ // carries only the pass's own additions.+ const before = "---\nkind: brain-signal\n---\n## Raw\n_(not provided)_\n";+ expect(decideRawRewrite(before, ["ent-c"])).toEqual({+ action: "rewrite",+ next: "---\nkind: brain-signal\n---\n## Raw\nentities: ent-c\n",+ appended: ["ent-c"],+ });+ });++ test("an id the bytes already store is never duplicated", () => {+ const before = "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a\n";+ expect(decideRawRewrite(before, ["ent-a", "ent-b"])).toEqual({+ action: "rewrite",+ next: "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a, ent-b\n",+ appended: ["ent-b"],+ });+ });++ test("bytes with no Raw section have no home, as before", () => {+ expect(decideRawRewrite("---\nkind: brain-signal\n---\n\nsome body\n", ["ent-a"])).toEqual({+ action: "no-home",+ });+ });++ test("the unchanged page rewrites exactly as the parse-level flow did", () => {+ // The common case: the bytes match the parse, so the decision is the+ // old rewrite, stored ids first and the additions appended.+ const before = "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a\n";+ expect(decideRawRewrite(before, ["ent-b"])).toEqual({+ action: "rewrite",+ next: "---\nkind: brain-signal\n---\n## Raw\nentities: ent-a, ent-b\n",+ appended: ["ent-b"],+ });+ });+});++describe("the relink lane task registration", () => {+ test("relink is the fifth lane task, and an operation with a budget", () => {+ expect(LANE_TASKS).toHaveLength(5);+ expect(LANE_TASKS).toContain(LANE_TASK.relink);+ expect(isLaneTask("relink")).toBe(true);+ expect(isOperation(LANE_TASK.relink)).toBe(true);+ });++ test("buildLaneTasks registers the relink task beside the four built-ins, dry-run by default", async () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ const before = inboxFiles().map((f) => readFileSync(join(brainDirs(vault).inbox, f), "utf8"));+ const set = buildLaneTasks({+ vault,+ configPath,+ searchConfig: resolveSearchConfig({ vault, configPath }),+ now: NOW,+ forceCost: false,+ safeguardFor: (operation) => ({+ checkpoint: () => {},+ timeoutMs: null,+ operation,+ }),+ });+ expect(set.taskNames).toEqual([...LANE_TASKS]);+ const relink = set.tasks.find((task) => task.name === LANE_TASK.relink);+ expect(relink).toBeDefined();+ // A lane pass never returns a spend receipt: it spends no model budget.+ expect(await relink!.run()).toBeUndefined();+ const after = inboxFiles().map((f) => readFileSync(join(brainDirs(vault).inbox, f), "utf8"));+ expect(after).toEqual(before);+ // The preview is not discarded: the set surfaces the report the run+ // produced, so both front doors can carry what the pass would add.+ const report = set.relinkReport();+ expect(report?.apply).toBe(false);+ expect(report?.signalsPageSourced).toBe(1);+ expect(report?.anchorsAdded).toBe(1);+ expect(report?.perSource).toEqual([+ { source: "notes/meeting.md", signals: 1, anchorsAdded: 1 },+ ]);+ });++ test("relinkApply hands the task the apply arm, and the surfaced report says what changed", async () => {+ writeEntityNode("people", "ent-people-ada-lovelace", "Ada Lovelace");+ writeSourcePage(+ "notes/meeting.md",+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ );+ writePageSourcedSignal({+ sourceRef: "notes/meeting.md",+ principle: "the review concluded with five follow-ups",+ storedEntityIds: [],+ });+ const file = inboxFiles()[0]!;+ const set = buildLaneTasks({+ vault,+ configPath,+ searchConfig: resolveSearchConfig({ vault, configPath }),+ now: NOW,+ forceCost: false,+ relinkApply: true,+ safeguardFor: (operation) => ({+ checkpoint: () => {},+ timeoutMs: null,+ operation,+ }),+ });+ const relink = set.tasks.find((task) => task.name === LANE_TASK.relink);+ expect(await relink!.run()).toBeUndefined();+ expect(entitiesLineOf(file)).toBe("entities: ent-people-ada-lovelace");+ const report = set.relinkReport();+ expect(report?.apply).toBe(true);+ expect(report?.signalsChanged).toBe(1);+ expect(report?.anchorsAdded).toBe(1);+ });++ test("the surfaced report is undefined before the relink task has run", () => {+ const set = buildLaneTasks({+ vault,+ configPath,+ searchConfig: resolveSearchConfig({ vault, configPath }),+ now: NOW,+ forceCost: false,+ safeguardFor: (operation) => ({+ checkpoint: () => {},+ timeoutMs: null,+ operation,+ }),+ });+ expect(set.relinkReport()).toBeUndefined();+ });+});diff --git a/tests/core/brain/notes/note-lifecycle-defects.test.ts b/tests/core/brain/notes/note-lifecycle-defects.test.tsindex 32385f12..3f678456 100644--- a/tests/core/brain/notes/note-lifecycle-defects.test.ts+++ b/tests/core/brain/notes/note-lifecycle-defects.test.ts@@ -35,9 +35,41 @@* refused as `destination_occupied`.* 14. a vault-wide in-place rewrite of hand-authored notes reported* `nothing_at_risk`.+ * 15. a bare-name repair derived its reported `to` spelling from a+ * third-party note without asking whether the caller may read that+ * note, so a restricted caller's report named a page withheld from+ * it.+ * 16. the repair rules joined the destination-collapsing rules in one+ * ordered reduce, so a repair rule whose `from` was the+ * destination's own bare basename rewrote the spellings the main+ * pass had JUST written - repointing the renamed note's inbound+ * links onto an unrelated note.+ * 17. the counting probe matched only the moved note's own spellings,+ * so the files the repair pass writes were absent from the plan's+ * `inbound_files` and from `--expect`'s number.+ * 18. the forced post-write refresh spawned no matter how young the+ * index stamp was, so writes arriving in a steady stream chained+ * one detached indexer run after another forever.+ * 19. a refused refresh claim recorded nothing on the diagnostic when+ * the freshen machinery answered with a skip token instead of+ * throwing, and one transient failure read as broken forever+ * because a successful claim never cleared the slot.+ * 20. the reason a refused refresh gave lived only in a process-global+ * that no production surface rendered - and in a multi-vault server+ * that global could answer one vault's reason for another. The+ * reason now travels on the report that refused, as+ * `references.refresh_reason`, read from that call's own decision.+ * 21. the renamed note's own bare `[[Old]]` links were withheld from+ * the rewrite whenever the DESTINATION basename was contested -+ * sound when the target was the bare basename, but the rewrite now+ * aims at the minimal spelling, which is unambiguous by+ * construction. The withholding broke links that resolved before+ * the move. The bare pair is now emitted whenever `[[Old]]`+ * uniquely resolved to the source before it, and is withheld only+ * for a nested source the bare spelling never uniquely named.*/-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";import {chmodSync,existsSync,@@ -48,13 +80,14 @@ import {rmSync,writeFileSync,} from "node:fs";+import { dirname, join } from "node:path";import { tmpdir } from "node:os";-import { join } from "node:path";import { bootstrapBrain } from "../../../../src/core/brain/init.ts";import {BASENAME_REWRITE,INDEX_EVIDENCE,+ INDEX_REFRESH,NOTE_LIFECYCLE_ACTION,noteLifecycle,NoteLifecycleError,@@ -62,6 +95,7 @@ import {import { RECOVERABILITY_STATE } from "../../../../src/core/brain/gates/recoverability.ts";import { CountGuardError } from "../../../../src/core/brain/count-guard.ts";import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { writeFreshenState } from "../../../../src/core/search/freshen.ts";import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";let vault: string;@@ -77,6 +111,7 @@ beforeEach(() => {});afterEach(() => {+ mock.restore();rmSync(vault, { recursive: true, force: true });rmSync(configHome, { recursive: true, force: true });});@@ -170,7 +205,7 @@ describe("a rewrite that cannot be written (3)", () => {// And the vault is in exactly the state the result describes.expect(existsSync(join(vault, "Projects/New.md"))).toBe(true);- expect(read("Aaa/Ref.md")).toContain("[[Projects/New]]");+ expect(read("Aaa/Ref.md")).toContain("[[New]]");expect(read("Docs/Ref.md")).toContain("[[Projects/Old]]");},);@@ -189,7 +224,7 @@ describe("a rewrite that cannot be written (3)", () => {});describe("the bare-basename guard (5)", () => {- test("withholds when another note already carries the DESTINATION basename", async () => {+ test("repairs the third-party bare spelling the rename turns from unique to ambiguous, and rewrites the moved note's own", async () => {note("A/Old.md", "x\n");note("B/New.md", "a different note that already owns the name\n");note("Notes/Ref.md", "bare [[Old]] and bare [[New]]\n");@@ -201,12 +236,83 @@ describe("the bare-basename guard (5)", () => {apply: true,});- expect(res.references.basename).toBe(BASENAME_REWRITE.ambiguous);+ // `[[New]]` named exactly one note (B/New.md) before the rename and+ // two nested carriers after it: the repair re-points it to the+ // shortest spelling of its pre-rename target that still resolves.+ // `[[Old]]` named the moved note - the only carrier there was - so+ // it is rewritten TOO, aimed at the minimal spelling of the+ // destination, which is unambiguous by construction: with B/New.md+ // standing, that spelling is `A/New`, and the link resolves to the+ // same note it named before the move (21).+ expect(res.references.basename).toBe(BASENAME_REWRITE.applied);const ref = read("Notes/Ref.md");- // Rewriting would have produced two `[[New]]` links, and by- // `store/links.ts`'s ladder a basename with two carriers resolves to- // neither. Leaving `[[Old]]` alone leaves one working link working.- expect(ref).toBe("bare [[Old]] and bare [[New]]\n");+ expect(ref).toBe("bare [[A/New]] and bare [[B/New]]\n");+ expect(res.references.rewrittenSpellings).toContainEqual({ from: "Old", to: "A/New" });+ expect(res.references.rewrittenSpellings).toContainEqual({ from: "New", to: "B/New" });+ });++ test("the review's scenario: a contested destination basename no longer strands the moved note's own bare links", async () => {+ // A/Old.md, B/Foo.md, and X.md holding `[[Old]] [[Foo]]`. Renaming+ // A/Old.md to A/Foo.md used to leave `[[Old]]` dangling: the old+ // rule withheld the bare rewrite because `Foo` was contested, even+ // though the rewrite target is the minimal spelling `A/Foo`, which+ // is unambiguous by construction. `[[Old]]` named exactly one note+ // before the move; after it, both of X's links resolve.+ note("A/Old.md", "x\n");+ note("B/Foo.md", "a different note that already owns the name\n");+ note("X.md", "[[Old]] [[Foo]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/Foo.md",+ apply: true,+ });++ expect(read("X.md")).toBe("[[A/Foo]] [[B/Foo]]\n");+ // Both rewrites are on the report: the third-party repair first,+ // then the moved note's own bare spelling onto the minimal form.+ expect(res.references.rewrittenSpellings).toContainEqual({ from: "Foo", to: "B/Foo" });+ expect(res.references.rewrittenSpellings).toContainEqual({ from: "Old", to: "A/Foo" });+ });++ test("an already-ambiguous bare spelling stays untouched, and a dangling one is not adopted", async () => {+ note("A/Old.md", "x\n");+ note("C/Old.md", "a second carrier of the old name\n");+ note("Notes/Ref.md", "bare [[Old]] and bare [[New]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/New.md",+ apply: true,+ });++ // `[[Old]]` named one of TWO notes before the move - unprovable+ // which, so nothing may rewrite it. `[[New]]` had no carrier before+ // the move; that it resolves NOW is luck, and adopting a link that+ // never resolved here would be a guess dressed as a repair.+ expect(res.references.basename).toBe(BASENAME_REWRITE.ambiguous);+ expect(read("Notes/Ref.md")).toBe("bare [[Old]] and bare [[New]]\n");+ });++ test("a single TOP-LEVEL carrier keeps owning the bare spelling, so no repair fires", async () => {+ note("A/Old.md", "x\n");+ note("New.md", "the top-level owner of the name\n");+ note("Notes/Ref.md", "bare [[New]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/New.md",+ apply: true,+ });++ // The ladder's exact-path rung hands `New` to the top-level note+ // before any carrier counting starts, whatever the nested count+ // becomes - the resolution did not change, so the link must not.+ expect(read("Notes/Ref.md")).toBe("bare [[New]]\n");+ expect(res.references.rewrittenSpellings.some((pair) => pair.from === "New")).toBe(false);});test("still applies when neither basename is contested", async () => {@@ -223,6 +329,192 @@ describe("the bare-basename guard (5)", () => {});});+describe("the refresh claim beside the index evidence (7)", () => {+ test("a claimed refresh does not pretend the index has already caught up", async () => {+ note("Projects/Old.md", "x\n");+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } =+ await import("../../../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+ // Freshen ON, the stamp far older than any interval: this write+ // claims the detached refresh.+ const saved = process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = "60";+ let res;+ try {+ res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ refreshSpawn: () => {},+ });+ } finally {+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = saved ?? "0";+ }+ expect(res.references.refresh).toBe(INDEX_REFRESH.claimed);+ // The claim says a run is IN FLIGHT, nothing more: the evidence+ // still reports the pre-refresh stamp and the stale state, and the+ // next command stays on the report.+ expect(res.references.index.state).toBe(INDEX_EVIDENCE.stale);+ expect(res.references.index.lastIndexedAt).toBe("2026-08-15T00:00:00.000Z");+ expect(res.references.index.nextCommand.length).toBeGreaterThan(0);+ });+});++describe("the refresh claim decision on the injected clock", () => {+ test("a backoff ahead of input.now is honoured even though the wall clock has passed it", async () => {+ note("Projects/Old.md", "x\n");+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } =+ await import("../../../../src/core/search/store.ts");+ const config = resolveSearchConfig({ vault });+ const store = await Store.open(config, { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+ // A failed run left a backoff that ended in 2021: long behind the+ // wall clock this suite runs at, and still ahead of the instant the+ // caller injects below. The claim decision has to be made on THAT+ // instant - a deterministic run may not have its behaviour moved by+ // whichever wall clock happens to execute it.+ writeFreshenState(dirname(config.dbPath), {+ failures: 1,+ backoffUntil: "2021-01-01T00:00:00.000Z",+ lastOutcome: "failed",+ lastRunAt: "2020-12-01T00:00:00.000Z",+ lastDurationMs: 5,+ lastError: "injected failure",+ lastChanged: null,+ });+ const saved = process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = "60";+ let res;+ try {+ res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ now: new Date("2020-06-01T00:00:00.000Z"),+ refreshSpawn: () => {},+ });+ } finally {+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = saved ?? "0";+ }+ // Under the injected instant the failure backoff is still active, so+ // the forced refresh refuses: force skips the freshness interval+ // gate only, and the backoff stands. Deciding on the wall clock+ // instead would spawn right past a refusal the caller's own timeline+ // says is active.+ expect(res.references.refresh).toBe(INDEX_REFRESH.notClaimed);+ });+});++describe("a refresh claim whose machinery raises", () => {+ // This runner's mock registration outlives mock.restore() across test+ // FILES, so the teardown re-registers the REAL module object instead:+ // whatever leaks past this file is freshen.ts itself, byte for byte.+ const FRESHEN_MODULE = "../../../../src/core/search/freshen.ts";+ let realFreshen: Record<string, unknown> | null = null;++ afterEach(() => {+ if (realFreshen !== null) mock.module(FRESHEN_MODULE, () => realFreshen);+ mock.restore();+ realFreshen = null;+ });++ test("still answers not_claimed, and the report names the failure (20)", async () => {+ // Force the freshen machinery to raise when the claim invokes it -+ // the shape of a permanently broken freshen path, as opposed to one+ // deliberately configured off. The token stays `not_claimed` either+ // way (the public vocabulary does not grow for this), but the old+ // bare catch swallowed the distinction entirely: a broken spawn was+ // indistinguishable from a disabled one. The reason now lands on the+ // result itself, read from THIS call's decision - never from a+ // process-global another vault could have written.+ realFreshen = { ...(await import(FRESHEN_MODULE)) };+ mock.module(FRESHEN_MODULE, () => ({+ maybeFreshenIndex: () => {+ throw new Error("freshen machinery exploded");+ },+ }));+ note("Projects/Old.md", "x\n");+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } =+ await import("../../../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ refreshSpawn: () => {},+ });++ expect(res.references.refresh).toBe(INDEX_REFRESH.notClaimed);+ expect(res.applied).toBe(true);+ expect(res.references.refreshReason).toBe("freshen machinery exploded");+ });++ test("a refusal that answers instead of throwing names its skip token, and a later success clears it (19)", async () => {+ // The freshen machinery refuses INSIDE itself - a spawn that failed+ // there answers with a skip token and does not throw - so the bare+ // catch above never ran for it: the diagnostic stayed empty and a+ // broken freshen path was indistinguishable from a silent one.+ realFreshen = { ...(await import(FRESHEN_MODULE)) };+ mock.module(FRESHEN_MODULE, () => ({+ maybeFreshenIndex: () => "spawn_failed",+ }));+ note("Projects/Old.md", "x\n");+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } =+ await import("../../../../src/core/search/store.ts");+ const stampIndex = async (): Promise<void> => {+ const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+ };+ await stampIndex();++ const refused = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ refreshSpawn: () => {},+ });++ expect(refused.references.refresh).toBe(INDEX_REFRESH.notClaimed);+ // The skip token IS the reason: it lands on the report verbatim.+ expect(refused.references.refreshReason).toBe("spawn_failed");++ // And a claim that succeeds carries no reason, so one transient+ // refusal is not misread later as a permanently broken freshen path.+ mock.module(FRESHEN_MODULE, () => realFreshen!);+ const saved = process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = "60";+ try {+ await stampIndex();+ const claimed = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/New.md",+ to: "Projects/Newer.md",+ apply: true,+ refreshSpawn: () => {},+ });+ expect(claimed.references.refresh).toBe(INDEX_REFRESH.claimed);+ expect(claimed.references.refreshReason).toBeNull();+ } finally {+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = saved ?? "0";+ }+ });+});+describe("index evidence on a plan-only run (7)", () => {test("an existing index is reported unchanged, not stale", async () => {note("Projects/Old.md", "x\n");@@ -254,6 +546,174 @@ describe("index evidence on a plan-only run (7)", () => {});});+describe("a repair derived from a page the caller may not read (15)", () => {+ test("is applied for the readers who can see it, but names no pair in the report", async () => {+ note("A/Old.md", "x\n");+ note("B/New.md", "a different note that already owns the name\n");+ note("Notes/Ref.md", "bare [[Old]] and bare [[New]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/New.md",+ apply: true,+ readable: (rel) => rel !== "B/New.md",+ });++ // The REPAIR pair was derived from the carrier of the contested+ // basename. That carrier is withheld here, so the report answers as+ // a vault without the page would: no `to` naming it.+ expect(res.references.rewrittenSpellings).not.toContainEqual({ from: "New", to: "B/New" });+ // The moved note's OWN bare rewrite is different: its pair derives+ // from the paths the caller itself supplied, so it is applied AND+ // reported (21) - and the file on disk carries both rewrites.+ expect(res.references.rewrittenSpellings).toContainEqual({ from: "Old", to: "A/New" });+ // The repair itself still ran - the readers who CAN see the carrier+ // are not left with a spelling that resolves to neither note.+ expect(read("Notes/Ref.md")).toBe("bare [[A/New]] and bare [[B/New]]\n");+ });++ test("a caller who may read the carrier keeps the pair", async () => {+ note("A/Old.md", "x\n");+ note("B/New.md", "a different note that already owns the name\n");+ note("Notes/Ref.md", "bare [[Old]] and bare [[New]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/New.md",+ apply: true,+ readable: () => true,+ });++ expect(res.references.rewrittenSpellings).toContainEqual({ from: "New", to: "B/New" });+ });+});++describe("a destination-collapsing pass that chained into the repair rules (16)", () => {+ test("a repair rule never rewrites a link the main pass just produced", async () => {+ note("Projects/Widget.md", "x\n");+ note("Docs/Old.md", "the sole carrier of the contested bare name\n");+ note("Notes/Ref.md", "[[Projects/Widget]] and [[Old]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.move,+ path: "Projects/Widget.md",+ to: "Old.md",+ apply: true,+ });++ // The first link names the moved note, now at Old.md; the second+ // names the note that always lived at Docs/Old.md. Chained rules+ // collapsed both onto Docs/Old - every inbound reference to the+ // renamed note repointed at a note it never named.+ expect(read("Notes/Ref.md")).toBe("[[Old]] and [[Docs/Old]]\n");+ expect(res.references.filesRewritten).toBe(1);+ });+});++describe("the plan's blast radius covers the repair pass (17)", () => {+ test("a file mentioning only the contested basename is listed on the plan", async () => {+ note("A/Old.md", "x\n");+ note("B/New.md", "a different note that already owns the name\n");+ note("Notes/Ref.md", "pathed [[A/Old]]\n");+ note("Notes/Casualty.md", "See [[New]].\n");++ const planned = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/New.md",+ });++ expect(planned.applied).toBe(false);+ expect(planned.references.inboundFiles).toContain("Notes/Casualty.md");+ expect(planned.references.inboundFiles).toContain("Notes/Ref.md");+ expect(existsSync(join(vault, "Notes/Casualty.md"))).toBe(true);++ // And the apply does exactly what the plan listed: both files are+ // rewritten, so the plan's number is the number `--expect` guards.+ const applied = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "A/Old.md",+ to: "A/New.md",+ apply: true,+ expect: 2,+ });+ expect(applied.references.filesRewritten).toBe(2);+ expect(read("Notes/Casualty.md")).toBe("See [[B/New]].\n");+ });+});++describe("the forced refresh against the write's own instant (18)", () => {+ test("an index stamped after the write began still claims this write's run", async () => {+ note("Projects/Old.md", "x\n");+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } =+ await import("../../../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+ // Freshen ON, and the write's own clock is BEFORE the stamp. The+ // stamp still claims nothing about this write: it marks when a run+ // FINISHED, and a run that finished after the write began may have+ // scanned before the write landed - so a stamp cannot prove the+ // index has seen the write, and a floor that skipped on one would+ // silently leave this write unindexed until the next interval or+ // the next write. The claim therefore spawns.+ const saved = process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = "60";+ const spawned: string[][] = [];+ try {+ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ now: new Date("2026-08-01T00:00:00.000Z"),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });+ expect(res.references.refresh).toBe(INDEX_REFRESH.claimed);+ } finally {+ // Restore whatever the environment ACTUALLY held, including its+ // absence - writing "0" back when the variable was unset leaks a+ // freshen setting onto every follower test file in the process.+ if (saved === undefined) delete process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ else process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = saved;+ }+ expect(spawned).toHaveLength(1);+ });++ test("a write that began after the last stamp still claims its refresh", async () => {+ note("Projects/Old.md", "x\n");+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } =+ await import("../../../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+ // The ordinary post-write shape: the stamp predates the write, so+ // the index has not seen the write and the claim must spawn.+ const saved = process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = "60";+ const spawned: string[][] = [];+ try {+ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ now: new Date("2026-09-01T00:00:00.000Z"),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });+ expect(res.references.refresh).toBe(INDEX_REFRESH.claimed);+ } finally {+ if (saved === undefined) delete process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"];+ else process.env["OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S"] = saved;+ }+ expect(spawned).toHaveLength(1);+ });+});+describe("the append-only observation log (8)", () => {test("is reported as an inbound reference and never rewritten", async () => {note("Projects/Old.md", "x\n");@@ -272,7 +732,7 @@ describe("the append-only observation log (8)", () => {// ...and the record does not change.expect(read("Brain/log/2026-08-15.md")).toBe("- agent said [[Projects/Old]] at 10:00\n");expect(res.references.filesRewritten).toBe(1);- expect(read("Notes/Ref.md")).toContain("[[Projects/New]]");+ expect(read("Notes/Ref.md")).toContain("[[New]]");});});@@ -299,7 +759,7 @@ describe("the count guard and the note's own self-reference (10)", () => {expect: 1,});expect(res.references.filesRewritten).toBe(1);- expect(read("Projects/New.md")).toContain("[[Projects/New]]");+ expect(read("Projects/New.md")).toContain("[[New]]");});test("a delete still excludes its own file, which strands nothing", async () => {@@ -393,7 +853,7 @@ describe("the recoverability verdict of a relocation (14)", () => {});// The file was overwritten and nothing regenerates a user's prose.- expect(read("Notes/Handwritten.md")).toContain("[[Projects/New]]");+ expect(read("Notes/Handwritten.md")).toContain("[[New]]");expect(res.recoverability.state).toBe(RECOVERABILITY_STATE.unproven);expect(res.recoverability.blockers).toContain("no_recovery_point");expect(res.recoverability.blockers).toContain("outside_brain_root");diff --git a/tests/core/brain/notes/note-lifecycle.test.ts b/tests/core/brain/notes/note-lifecycle.test.tsindex fcd56fe6..1c4c8228 100644--- a/tests/core/brain/notes/note-lifecycle.test.ts+++ b/tests/core/brain/notes/note-lifecycle.test.ts@@ -27,12 +27,15 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";import { bootstrapBrain } from "../../../../src/core/brain/init.ts";import {BASENAME_REWRITE,INDEX_EVIDENCE,+ INDEX_REFRESH,+ INDEX_REFRESHES,+ isIndexRefresh,isNoteLifecycleAction,NOTE_ARCHIVE_ROOT,NOTE_LIFECYCLE_ACTION,@@ -43,6 +46,11 @@ import {import { RECOVERABILITY_STATE } from "../../../../src/core/brain/gates/recoverability.ts";import { CountGuardError } from "../../../../src/core/brain/count-guard.ts";import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import {+ FRESHEN_PENDING_FILE,+ readFreshenPending,+ settleFreshenPending,+} from "../../../../src/core/search/freshen.ts";let vault: string;let configHome: string;@@ -84,8 +92,21 @@ describe("the action vocabulary", () => {});});+describe("the index-refresh vocabulary", () => {+ // The guard ships beside its siblings' (isIndexEvidenceState,+ // isBasenameRewrite): a token a caller reads back out of a report or a+ // persisted payload has to survive the round trip through a string.+ test("every declared refresh token is a member and the guard refuses everything else", () => {+ expect([...INDEX_REFRESHES].toSorted()).toEqual(Object.values(INDEX_REFRESH).toSorted());+ for (const token of INDEX_REFRESHES) expect(isIndexRefresh(token)).toBe(true);+ for (const outsider of [null, 42, {}, "", "Claimed", "not-claimed", undefined]) {+ expect(isIndexRefresh(outsider)).toBe(false);+ }+ });+});+describe("rename", () => {- test("moves the bytes and rewrites path-spelled inbound wikilinks", async () => {+ test("moves the bytes and rewrites path-spelled inbound wikilinks to the minimal spelling", async () => {note("Projects/Old.md", "---\ntitle: Old\n---\n\nbody\n");note("Projects/Ref.md",@@ -106,11 +127,44 @@ describe("rename", () => {expect(read("Projects/New.md")).toContain("body");const ref = read("Projects/Ref.md");- expect(ref).toContain("[[Projects/New]]");- expect(ref).toContain("[[Projects/New.md]]");- expect(ref).toContain("[[Projects/New|x]]");+ // Minimal spellings, not form preservation: the new basename is+ // unique after the move, so every old form collapses onto `[[New]]`+ // instead of each link keeping its original length.+ expect(ref).toBe("see [[New]] and [[New]] and [[New|x]]\n");expect(ref).not.toContain("Old");expect(res.references?.filesRewritten).toBe(1);+ expect(res.references?.rewrittenSpellings).toEqual([+ { from: "Projects/Old.md", to: "New" },+ { from: "Projects/Old", to: "New" },+ { from: "Old", to: "New" },+ ]);+ });++ test("rewrites path-spelled links to the suffix-less form when the destination basename is contested", async () => {+ note("Projects/Old.md", "x\n");+ note("Elsewhere/New.md", "another note that will still own the name\n");+ note("Projects/Ref.md", "pathed [[Projects/Old]] and suffixed [[Projects/Old.md]]\n");++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ apply: true,+ });++ // Bare `New` would have two carriers after the move and resolve, by+ // the ladder's own rule, to neither - so the shortest HONEST+ // spelling is the suffix-less path. The destination basename being+ // contested does NOT withhold the moved note's own bare `[[Old]]`+ // rewrite: it named exactly one note before the move, and its+ // rewrite target is the minimal spelling `Projects/New`, which is+ // unambiguous by construction.+ expect(res.references?.basename).toBe(BASENAME_REWRITE.applied);+ expect(read("Projects/Ref.md")).toBe("pathed [[Projects/New]] and suffixed [[Projects/New]]\n");+ expect(res.references?.rewrittenSpellings).toContainEqual({+ from: "Old",+ to: "Projects/New",+ });});test("rewrites references that live inside Brain/, not only outside it", async () => {@@ -128,7 +182,7 @@ describe("rename", () => {apply: true,});- expect(read("Brain/reports/weekly.md")).toContain("[[Projects/New]]");+ expect(read("Brain/reports/weekly.md")).toContain("[[New]]");expect(res.references?.filesRewritten).toBe(1);});@@ -161,10 +215,10 @@ describe("rename", () => {expect(res.references?.basename).toBe(BASENAME_REWRITE.ambiguous);const ref = read("Projects/Ref.md");- // The unambiguous path spelling still moves; the bare one is left- // exactly as it was, because it may name the other note.- expect(ref).toContain("[[Projects/New]]");- expect(ref).toContain("[[Old]]");+ // The path spelling collapses onto the (uncontested) new basename;+ // the bare `[[Old]]` is left exactly as it was, because it may name+ // the other note.+ expect(ref).toBe("bare [[Old]] and pathed [[New]]\n");});test("refuses a destination in another directory - that is a move", async () => {@@ -241,6 +295,13 @@ describe("rename", () => {expect(res.applied).toBe(false);expect(res.references?.inboundFiles).toEqual(["Projects/Ref.md"]);expect(res.references?.filesRewritten).toBe(0);+ // The plan is reported in the spellings it would write, minimal+ // forms included, so a dry run previews exactly the apply.+ expect(res.references?.rewrittenSpellings).toEqual([+ { from: "Projects/Old.md", to: "New" },+ { from: "Projects/Old", to: "New" },+ { from: "Old", to: "New" },+ ]);expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);expect(read("Projects/Ref.md")).toContain("[[Projects/Old]]");});@@ -274,6 +335,316 @@ describe("the freshness of the evidence a rename acted on", () => {});});+/** Stamp a vault's index without running a full index pass. */+async function stampIndex(at: string): Promise<void> {+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const { LAST_INDEXED_AT_STATE_KEY, Store } = await import("../../../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });+ store.setState(LAST_INDEXED_AT_STATE_KEY, at);+ await store.close();+}++/** The rename input every refresh test moves the same note with. */+function renameInput(apply: boolean) {+ return {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/Old.md",+ to: "Projects/New.md",+ ...(apply ? { apply: true } : {}),+ } as const;+}++/**+ * The detached refresh an applied write claims (F2).+ *+ * The tests run with the suite-wide freshen-off default and turn the+ * interval on only inside the specific tests that need it, so no real+ * indexer is ever left behind; the spawn is always intercepted by the+ * `refreshSpawn` seam. The "force was passed" evidence is indirect but+ * binding: the index stamp in these fixtures is SECONDS old, so an+ * unforced call would answer `fresh` and spawn nothing.+ */+describe("the detached refresh an applied write claims", () => {+ const FRESHEN_INTERVAL_ENV = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";+ let savedInterval: string | undefined;+ let intervalWasSaved = false;++ beforeEach(() => {+ savedInterval = undefined;+ intervalWasSaved = false;+ });+ afterEach(() => {+ if (!intervalWasSaved) return;+ // Restore whatever the environment ACTUALLY held, including its+ // absence. Writing back a hardcoded "60" here once leaked a freshen+ // interval onto every follower test file sharing the process.+ if (savedInterval === undefined) delete process.env[FRESHEN_INTERVAL_ENV];+ else process.env[FRESHEN_INTERVAL_ENV] = savedInterval;+ intervalWasSaved = false;+ });++ /** Capture the interval the environment holds right now, once. */+ function saveInterval(): void {+ if (intervalWasSaved) return;+ savedInterval = process.env[FRESHEN_INTERVAL_ENV];+ intervalWasSaved = true;+ }++ function withFreshenOn(): void {+ saveInterval();+ process.env[FRESHEN_INTERVAL_ENV] = "60";+ }++ test("an applied rename claims one detached refresh, and the child is the freshen run", async () => {+ withFreshenOn();+ // A stamp younger than the interval: only the force path spawns here.+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ const spawned: string[][] = [];++ const res = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });++ expect(res.references?.refresh).toBe(INDEX_REFRESH.claimed);+ // A claim that started names no refusal, so the reason is null+ // rather than a bare absent key a reader would have to guess about.+ expect(res.references?.refreshReason).toBeNull();+ expect(spawned).toHaveLength(1);+ const argv = spawned[0]!.join(" ");+ expect(argv).toContain("search index");+ expect(argv).toContain("--freshen");+ expect(argv).toContain("--freshen-state");+ // The evidence read stays synchronous: the report still describes+ // the index as it stood at the end of the call.+ expect(res.references?.index.state).toBe(INDEX_EVIDENCE.stale);+ });++ test("the claim resolves through the config file the caller passed, not the environment alone", async () => {+ // The interval is 0 by CONFIG FILE here - the suite-wide env default+ // is scrubbed - so the claim reads `off` only if it resolves the+ // search config through the caller's refreshConfigPath. Resolved+ // without it, the default interval stands and the rename claims a+ // run the operator's config refused.+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ atomicWriteFileSync(configPath, `vault: ${vault}\nsearch_freshen_interval_s: 0\n`);+ const key = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";+ const saved = process.env[key];+ delete process.env[key];+ try {+ const res = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshConfigPath: configPath,+ });+ expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ expect(res.references?.refreshReason).toBe("off");+ } finally {+ if (saved === undefined) delete process.env[key];+ else process.env[key] = saved;+ }+ });++ test("claim exclusivity prevents doubles: a second applied write spawns nothing", async () => {+ withFreshenOn();+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ const first: string[][] = [];+ const second: string[][] = [];++ const one = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: (argv: string[]) => first.push(argv),+ });+ const two = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/New.md",+ to: "Projects/Newer.md",+ apply: true,+ refreshSpawn: (argv: string[]) => second.push(argv),+ });++ expect(one.references?.refresh).toBe(INDEX_REFRESH.claimed);+ // The intercepted spawn never runs a child, so the first claim is+ // still held - and the second write must not spawn past it. Its+ // refusal names the reason instead of leaving `not_claimed` to be+ // read as a deliberate config-off.+ expect(two.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ expect(two.references?.refreshReason).toBe("claimed");+ expect(second).toHaveLength(0);+ });++ test("a freshen interval of 0 disables the post-write spawn - config off means off", async () => {+ saveInterval();+ process.env[FRESHEN_INTERVAL_ENV] = "0";+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ const spawned: string[][] = [];++ const res = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });++ expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ // `not_claimed` alone cannot distinguish a broken freshen path from+ // a deliberate off; the reason can.+ expect(res.references?.refreshReason).toBe("off");+ expect(spawned).toHaveLength(0);+ });++ test("a plan-only run claims nothing", async () => {+ withFreshenOn();+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ const spawned: string[][] = [];++ const res = await noteLifecycle(vault, {+ ...renameInput(false),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });++ expect(res.applied).toBe(false);+ expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ // No write, no attempt: a plan-only run refused nothing, so there is+ // no reason to name - null, not a borrowed skip token.+ expect(res.references?.refreshReason).toBeNull();+ expect(spawned).toHaveLength(0);+ });++ test("an unindexed vault claims nothing - there is nothing to refresh", async () => {+ withFreshenOn();+ note("Projects/Old.md", "x\n");+ const spawned: string[][] = [];++ const res = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });++ expect(res.references?.index.state).toBe(INDEX_EVIDENCE.absent);+ expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ // Nothing to refresh is itself a stated reason: the machinery's own+ // no-index token, not a bare unexplained refusal.+ expect(res.references?.refreshReason).toBe("no_index");+ expect(spawned).toHaveLength(0);+ });++ test("a write landing while a run is in flight is queued: two rapid renames produce a second pass", async () => {+ withFreshenOn();+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ const first: string[][] = [];+ const second: string[][] = [];++ // The first rename claims the run; the intercepted spawn never runs+ // a child, so the claim stays held - the shape of a refresh still in+ // flight.+ await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: (argv: string[]) => first.push(argv),+ });+ // The run's scan has (conceptually) started; the second rename lands+ // DURING it.+ const scanStart = Date.now();+ const two = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.rename,+ path: "Projects/New.md",+ to: "Projects/Newer.md",+ apply: true,+ refreshSpawn: (argv: string[]) => second.push(argv),+ });++ expect(two.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ expect(second).toHaveLength(0);+ // ...but the write is no longer dropped. A durable marker beside the+ // freshen state says a write is pending since that instant.+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const stateDir = dirname(resolveSearchConfig({ vault }).dbPath);+ const marker = readFreshenPending(stateDir);+ expect(marker).not.toBeNull();+ expect(marker!.since).toBeGreaterThanOrEqual(scanStart);+ expect(existsSync(join(stateDir, FRESHEN_PENDING_FILE))).toBe(true);++ // The child's settle, before releasing the claim: the marker is+ // newer than the scan start, so ONE bounded extra pass runs and the+ // pass that covered it clears the marker. No loop, no leak.+ let passes = 0;+ const ran = await settleFreshenPending(stateDir, scanStart, async () => {+ passes++;+ });+ expect(ran).toBe(true);+ expect(passes).toBe(1);+ expect(readFreshenPending(stateDir)).toBeNull();+ });++ test("an interval of 0 never spawns and never marks - config off means off", async () => {+ saveInterval();+ process.env[FRESHEN_INTERVAL_ENV] = "0";+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "x\n");+ // A held claim, so anything that tried to refresh would answer+ // `claimed` - only config-off stands between this write and it.+ const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");+ const stateDir = dirname(resolveSearchConfig({ vault }).dbPath);+ const { claimFreshen } = await import("../../../../src/core/search/freshen.ts");+ expect(claimFreshen(stateDir, Date.now())).toBeString();+ const spawned: string[][] = [];++ const res = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });++ expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ expect(res.references?.refreshReason).toBe("off");+ expect(spawned).toHaveLength(0);+ // Off is off: no run is queued either, because an operator who+ // disabled freshening asked for exactly that.+ expect(readFreshenPending(stateDir)).toBeNull();+ expect(existsSync(join(stateDir, FRESHEN_PENDING_FILE))).toBe(false);+ });++ test("a spawn failure never fails the write", async () => {+ withFreshenOn();+ await stampIndex(new Date().toISOString());+ note("Projects/Old.md", "body\n");+ note("Projects/Ref.md", "see [[Projects/Old]]\n");++ const res = await noteLifecycle(vault, {+ ...renameInput(true),+ refreshSpawn: () => {+ throw new Error("no fork");+ },+ });++ expect(res.applied).toBe(true);+ expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);+ expect(read("Projects/New.md")).toContain("body");+ expect(read("Projects/Ref.md")).toContain("[[New]]");+ });++ test("an applied delete claims the same refresh", async () => {+ withFreshenOn();+ await stampIndex(new Date().toISOString());+ note("Projects/Gone.md", "x\n");+ const spawned: string[][] = [];++ const res = await noteLifecycle(vault, {+ action: NOTE_LIFECYCLE_ACTION.delete,+ path: "Projects/Gone.md",+ apply: true,+ confirm: true,+ refreshSpawn: (argv: string[]) => spawned.push(argv),+ });++ expect(res.applied).toBe(true);+ expect(res.references?.refresh).toBe(INDEX_REFRESH.claimed);+ expect(spawned).toHaveLength(1);+ });+});+describe("move", () => {test("relocates across directories and rewrites the path spelling", async () => {note("Inbox/Note.md", "---\ntitle: Note\n---\n\nbody\n");@@ -289,7 +660,9 @@ describe("move", () => {expect(res.applied).toBe(true);expect(read("Projects/Note.md")).toContain("body");expect(existsSync(join(vault, "Inbox/Note.md"))).toBe(false);- expect(read("Inbox/Ref.md")).toContain("[[Projects/Note]]");+ // The basename stays unique through the move, so the rewritten link+ // comes out at its minimal spelling.+ expect(read("Inbox/Ref.md")).toContain("[[Note]]");// The basename did not change, so there was no bare spelling to fix.expect(res.references?.basename).toBe(BASENAME_REWRITE.notNeeded);});diff --git a/tests/core/brain/truth/contamination.test.ts b/tests/core/brain/truth/contamination.test.tsindex 678a1305..4e9032f7 100644--- a/tests/core/brain/truth/contamination.test.ts+++ b/tests/core/brain/truth/contamination.test.ts@@ -73,6 +73,75 @@ describe("checkEntityContamination (pure)", () => {});expect(result.clean).toBe(true);});++ // Separator-tolerant twins (note-change truth maintenance, F3): the+ // check shares the anchoring kernels' match-form rule, so its inclusion+ // test folds separator runs on both sides, matches a slug-prefixed form+ // at the path-segment boundary, and never sees a mid-word mention.++ test("separator-folded mentions clear the entity across spellings", () => {+ const result = checkEntityContamination({+ conclusion: "Ada-Lovelace approved the rollout",+ sources: ["ada lovelace signed off this morning"],+ entities: [person("ent-people-ada-lovelace", "Ada-Lovelace")],+ });+ expect(result.clean).toBe(true);+ expect(result.violations).toHaveLength(0);+ });++ test("a slug-prefixed alias clears the entity through its last path segment", () => {+ // The slug-prefixed alias is the entity's ONLY matchable form (the+ // name matches nothing), the conclusion carries the slug form, and the+ // source mentions only the bare tail - so the tail expansion is the+ // ONE route that can clear the citation, and this test fails if the+ // last-segment expansion is ever dropped.+ const result = checkEntityContamination({+ conclusion: "see people/ada_lovelace for the rollout decision",+ sources: ["ada lovelace signed off this morning"],+ entities: [person("ent-people-ada-lovelace", "***", ["people/ada_lovelace"])],+ });+ expect(result.clean).toBe(true);+ expect(result.violations).toHaveLength(0);+ });++ test("a mid-word mention is not a mention (canada never anchors ada)", () => {+ const result = checkEntityContamination({+ conclusion: "Canada approved the rollout",+ sources: ["Nothing relevant"],+ entities: [person("ent-people-ada", "Ada")],+ });+ expect(result.clean).toBe(true);+ expect(result.violations).toHaveLength(0);+ });++ test("an inflected mention in the conclusion is a violation when no source cites it", () => {+ // H1 (PR 268 review), missed violation: Russian attaches case+ // endings with no space, so the two-sided boundary rule silenced the+ // conclusion's "Иваном" and a conclusion asserting an uncited+ // entity's presence read as clean. The leading-only rule anchors it.+ const result = checkEntityContamination({+ conclusion: "Встреча с Иваном перенесена на четверг",+ sources: ["Протокол встречи: повестка без участников"],+ entities: [person("ent-people-ivan", "Иван")],+ });+ expect(result.clean).toBe(false);+ expect(result.violations).toHaveLength(1);+ expect(result.violations[0]!.entityId).toBe("ent-people-ivan");+ });++ test("an inflected mention in a source clears the cited entity", () => {+ // H1 (PR 268 review), false alarm: the conclusion names "Иван" while+ // the cited source says "Ивану" - the two-sided rule refused the+ // source hit and flagged a properly cited conclusion. The+ // leading-only rule restores the citation.+ const result = checkEntityContamination({+ conclusion: "Иван утвердил бюджет",+ sources: ["Ивану показали проект бюджета на утреннем созвоне"],+ entities: [person("ent-people-ivan", "Иван")],+ });+ expect(result.clean).toBe(true);+ expect(result.violations).toHaveLength(0);+ });});describe("deepSynthesis wiring", () => {diff --git a/tests/core/brain/truth/merge-guard.test.ts b/tests/core/brain/truth/merge-guard.test.tsindex 6b86b153..aac8bff9 100644--- a/tests/core/brain/truth/merge-guard.test.ts+++ b/tests/core/brain/truth/merge-guard.test.ts@@ -114,6 +114,106 @@ describe("guardEntityMerge (pure)", () => {expect(verdict.allowed).toBe(true);});+ // Separator-tolerant twins (note-change truth maintenance, F3): the+ // guard shares the anchoring kernels' match-form rule, so its inclusion+ // test folds separator runs on both sides, matches a slug-prefixed form+ // at the path-segment boundary, and never anchors a mid-word mention.++ test("separator-folded mentions anchor across hyphen and underscore spellings", () => {+ const ada = person("ent-people-ada-lovelace", "Ada-Lovelace", ["ada_lovelace"]);+ const verdict = guardEntityMerge({+ keepText: "Ada Lovelace decided to ship on Friday",+ dropText: "Bob Hale decided to ship on Friday",+ entities: [ada, bob],+ });+ expect(verdict.allowed).toBe(false);+ expect(verdict.keepAnchors).toEqual(["ent-people-ada-lovelace"]);+ expect(verdict.dropAnchors).toEqual(["ent-people-bob-hale"]);+ });++ test("a slug-prefixed alias matches through its last path segment", () => {+ // The "***" name matches nothing, so only the slug-prefixed alias -+ // via its "ada lovelace" tail - can anchor the first entity.+ const weird = person("ent-people-ada-lovelace", "***", ["people/ada_lovelace"]);+ const verdict = guardEntityMerge({+ keepText: "Ada Lovelace decided to ship on Friday",+ dropText: "Bob Hale decided to ship on Friday",+ entities: [weird, bob],+ });+ expect(verdict.allowed).toBe(false);+ expect(verdict.keepAnchors).toEqual(["ent-people-ada-lovelace"]);+ });++ test("a mid-word mention never anchors (canada never anchors ada)", () => {+ const ada = person("ent-people-ada", "Ada");+ const verdict = guardEntityMerge({+ keepText: "Canada approved the rollout",+ dropText: "Bob Hale approved the rollout",+ entities: [ada, bob],+ });+ expect(verdict.keepAnchors).toEqual([]);+ expect(verdict.allowed).toBe(true);+ });++ test("CJK names fire the protected-name path (no-space scripts anchor)", () => {+ // Kana particles touch the names directly - a script written without+ // word spaces suspends the boundary rule, so both sides anchor and a+ // disjoint CJK pair blocks the merge exactly like a Latin one.+ const tanaka = person("ent-people-tanaka-taro", "田中太郎");+ const suzuki = person("ent-people-suzuki-hanako", "鈴木花子");+ const verdict = guardEntityMerge({+ keepText: "田中太郎は出張を決めた",+ dropText: "鈴木花子は出張を決めた",+ entities: [tanaka, suzuki],+ });+ expect(verdict.keepAnchors).toEqual(["ent-people-tanaka-taro"]);+ expect(verdict.dropAnchors).toEqual(["ent-people-suzuki-hanako"]);+ expect(verdict.allowed).toBe(false);+ });++ test("inflected Russian names fire the protected-name path (leading-only boundary)", () => {+ // H1 (PR 268 review): Russian attaches case endings to names with no+ // space - "Ивана", "Петра" - and the two-sided boundary rule silenced+ // both sides, letting claims about different people collapse. The+ // leading-only rule keeps the veto: each side anchors its own person+ // through the inflected spelling and the sets are disjoint.+ const ivan = person("ent-people-ivan", "Иван");+ const petr = person("ent-people-petr", "Петр");+ const verdict = guardEntityMerge({+ keepText: "Ивана повысили до директора",+ dropText: "Петра повысили до директора",+ entities: [ivan, petr],+ });+ expect(verdict.keepAnchors).toEqual(["ent-people-ivan"]);+ expect(verdict.dropAnchors).toEqual(["ent-people-petr"]);+ expect(verdict.allowed).toBe(false);+ });++ test("a slash-bearing company name no longer anchors through its bare tail", () => {+ // M1 (PR 268 review): the slug tail fired on ANY slash-containing+ // name, so keep "Bob Chappell left the firm" also anchored the+ // Warner/Chappell organization through the tail "chappell", the+ // anchor sets overlapped, and the merge was allowed. The tail is+ // minted only from a registry entity-type folder prefix, so the+ // person and the organization stay disjoint and the veto holds.+ const bob = person("ent-people-bob-chappell", "Bob Chappell");+ const warner: GuardEntityLike = {+ id: "ent-company-warner-chappell",+ category: "company",+ name: "Warner/Chappell",+ aliases: [],+ status: "active",+ };+ const verdict = guardEntityMerge({+ keepText: "Bob Chappell left the firm",+ dropText: "Warner/Chappell left the firm",+ entities: [bob, warner],+ });+ expect(verdict.keepAnchors).toEqual(["ent-people-bob-chappell"]);+ expect(verdict.dropAnchors).toEqual(["ent-company-warner-chappell"]);+ expect(verdict.allowed).toBe(false);+ });+test("default guarded categories cover people and orgs", () => {expect(GUARDED_ENTITY_CATEGORIES).toContain("people");expect(GUARDED_ENTITY_CATEGORIES).toContain("org");diff --git a/tests/core/brain/truth/stated-claims.test.ts b/tests/core/brain/truth/stated-claims.test.tsindex d4067f7f..722a5b55 100644--- a/tests/core/brain/truth/stated-claims.test.ts+++ b/tests/core/brain/truth/stated-claims.test.ts@@ -59,6 +59,13 @@ const ALICE: AtomicEntityLike = {status: "active",};+const ATLAS_PRIME: AtomicEntityLike = {+ id: "ent-atlas-prime",+ name: "Atlas Prime",+ aliases: [],+ status: "active",+};+describe("anchorEntityForms", () => {test("returns the quality-gated normalized forms that occur in the text", () => {expect(anchorEntityForms("Alice Mason joined Google.", ["Alice Mason", "Google"])).toEqual([@@ -247,6 +254,59 @@ describe("appendStatedClaims", () => {expect(outcome.committed[0]!.event.entity).toBe("alice mason");});+ test("a claim whose text spells the entity with different separators still anchors", () => {+ const outcome = withDeviceId("", () =>+ appendStatedClaims(+ vault,+ {+ ...PAYLOAD,+ text: "atlas-prime joined Google in June after leaving Meta.",+ claims: [claim({ subject: "Atlas Prime", object: "Google" })],+ },+ { entities: [ATLAS_PRIME] },+ ),+ );+ // The text hyphenates the name the claim states spaced: separator+ // runs are interchangeable at match time, so the folded verdict+ // resolves one token sequence either way and the claim commits+ // under the canonical spelling.+ expect(outcome.ungrounded).toEqual([]);+ expect(outcome.committed).toHaveLength(1);+ expect(outcome.committed[0]!.event.entity).toBe("atlas prime");+ });++ test("a mid-word occurrence never anchors: Canada does not anchor Ada", () => {+ const outcome = withDeviceId("", () =>+ appendStatedClaims(vault, {+ ...PAYLOAD,+ text: "The Canada rollout touched Google in June.",+ claims: [claim({ subject: "Ada", object: "Google" })],+ }),+ );+ // "Canada" contains "ada" as a substring, but every occurrence must+ // sit at a word boundary, so the mid-word hit never anchors the+ // subject while the object still does.+ expect(outcome.committed).toEqual([]);+ expect(outcome.ungrounded[0]!.reasons).toEqual(["subject_unanchored"]);+ });++ test("an inflected subject anchors: the boundary rule binds the leading side only", () => {+ // H1 (PR 268 review): Russian attaches case endings with no space, so+ // "Ивана" is the accusative of "Иван" - the two-sided rule refused+ // the hit and reported the claim subject_unanchored. Only the+ // character before the hit must be a token edge.+ const outcome = withDeviceId("", () =>+ appendStatedClaims(vault, {+ ...PAYLOAD,+ text: "Ивана повысили до директора, а Google одобрил бюджет.",+ claims: [claim({ subject: "Иван", object: "Google" })],+ }),+ );+ expect(outcome.ungrounded).toEqual([]);+ expect(outcome.committed).toHaveLength(1);+ expect(outcome.committed[0]!.event.entity).toBe("иван");+ });+test("a claim with an empty subject reports missing_subject", () => {const outcome = withDeviceId("", () =>appendStatedClaims(vault, { ...PAYLOAD, claims: [claim({ subject: " " })] }),diff --git a/tests/core/search/freshen.test.ts b/tests/core/search/freshen.test.tsindex d825e80e..62775f0b 100644--- a/tests/core/search/freshen.test.ts+++ b/tests/core/search/freshen.test.ts@@ -14,19 +14,26 @@ import { join } from "node:path";import {claimFreshen,+ clearFreshenPending,decideFreshen,FRESHEN_CLAIM_FILE,+ FRESHEN_PENDING_FILE,FRESHEN_SKIP,freshenCommand,freshenSpawnOptions,+ markFreshenPending,maybeFreshenIndex,nextBackoffMs,+ readFreshenPending,readFreshenState,releaseFreshen,+ settleFreshenPending,+ takeFreshenPending,writeFreshenState,} from "../../../src/core/search/freshen.ts";import { acquireWriterLockSync } from "../../../src/core/search/store/writer-lock.ts";import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import type { FreshenPending } from "../../../src/core/search/freshen.ts";import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";const NOW = Date.parse("2026-10-07T12:00:00.000Z");@@ -311,6 +318,108 @@ describe("maybeFreshenIndex", () => {expect(decision).toBe(FRESHEN_SKIP.spawnFailed);expect(existsSync(join(vault, ".open-second-brain", FRESHEN_CLAIM_FILE))).toBe(false);});++ test("force spawns despite a fresh index - a write that just happened is due by definition", () => {+ expect(+ maybeFreshenIndex(config, { lastIndexedAt: ago(5), nowMs: NOW, spawn, force: true }),+ ).toBe("spawned");+ expect(calls).toHaveLength(1);+ // The child argv is the same run the interval path starts: same+ // command, same claim protocol.+ expect(calls[0]!.join(" ")).toContain(`search index --vault ${vault}`);+ });++ // There is deliberately no freshness floor against the write's own+ // instant: the stamp marks when a run FINISHED, and a run that finished+ // after the write began may have scanned before the write landed - a+ // stamp cannot prove the index has seen the write, so a floor built on+ // one would silently leave the write unindexed until the next interval+ // or the next write. The test above is the pin: the youngest stamp+ // that is not "never stamped" still spawns. A run already in flight is+ // the collapse that remains, and the claim exclusivity test below+ // holds it.++ test("force with the interval at 0 still refuses - config off means off", () => {+ const offConfig = {+ ...config,+ freshen: { intervalSeconds: 0, embeddings: false, configPath: "/cfg/config.yaml" },+ } as unknown as ResolvedSearchConfig;+ expect(+ maybeFreshenIndex(offConfig, { lastIndexedAt: ago(300), nowMs: NOW, spawn, force: true }),+ ).toBe(FRESHEN_SKIP.off);+ expect(calls).toHaveLength(0);+ });++ test("force with no freshen settings at all still refuses", () => {+ const { freshen: _drop, ...rest } = config as unknown as Record<string, unknown>;+ expect(+ maybeFreshenIndex(rest as unknown as ResolvedSearchConfig, {+ lastIndexedAt: ago(300),+ nowMs: NOW,+ spawn,+ force: true,+ }),+ ).toBe(FRESHEN_SKIP.off);+ expect(calls).toHaveLength(0);+ });++ test("an index never stamped stays self-heal's even under force", () => {+ expect(maybeFreshenIndex(config, { lastIndexedAt: null, nowMs: NOW, spawn, force: true })).toBe(+ FRESHEN_SKIP.noIndex,+ );+ expect(calls).toHaveLength(0);+ });++ test("claim exclusivity holds under force: the second claimant spawns nothing", () => {+ expect(+ maybeFreshenIndex(config, { lastIndexedAt: ago(300), nowMs: NOW, spawn, force: true }),+ ).toBe("spawned");+ expect(+ maybeFreshenIndex(config, { lastIndexedAt: ago(300), nowMs: NOW, spawn, force: true }),+ ).toBe(FRESHEN_SKIP.claimed);+ expect(calls).toHaveLength(1);+ });++ test("an active backoff from a failed run still refuses under force", () => {+ writeFreshenState(join(vault, ".open-second-brain"), {+ failures: 1,+ backoffUntil: new Date(NOW + 30_000).toISOString(),+ lastOutcome: "failed",+ lastRunAt: ago(10),+ lastDurationMs: 100,+ lastError: "boom",+ lastChanged: null,+ });+ expect(+ maybeFreshenIndex(config, { lastIndexedAt: ago(300), nowMs: NOW, spawn, force: true }),+ ).toBe(FRESHEN_SKIP.backoff);+ expect(calls).toHaveLength(0);+ });++ test("an indexer already holding the writer lock is left alone under force", () => {+ const release = acquireWriterLockSync(config.dbPath);+ try {+ expect(+ maybeFreshenIndex(config, { lastIndexedAt: ago(300), nowMs: NOW, spawn, force: true }),+ ).toBe(FRESHEN_SKIP.writerLock);+ expect(calls).toHaveLength(0);+ } finally {+ release();+ }+ });++ test("a read-only open never freshens a vault it does not own, force included", () => {+ expect(+ maybeFreshenIndex(config, {+ lastIndexedAt: ago(300),+ nowMs: NOW,+ spawn,+ force: true,+ readOnly: true,+ }),+ ).toBe(FRESHEN_SKIP.readOnly);+ expect(calls).toHaveLength(0);+ });});describe("claim races", () => {@@ -361,6 +470,218 @@ describe("claim races", () => {});});+describe("the pending-refresh marker a refused forced claim leaves", () => {+ // A write that lands while another run holds the claim used to be+ // answered `not_claimed` and forgotten: the in-flight run may already+ // have walked past the changed files, and its fresh stamp then+ // suppressed freshen-on-read for a whole interval. The marker is the+ // queue: the forced caller writes "pending since <instant>" beside the+ // freshen state, and the child - before releasing the claim - runs ONE+ // more incremental pass when the marker is newer than its scan start.+ let dir: string;+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "osb-freshen-pending-"));+ });+ afterEach(() => rmSync(dir, { recursive: true, force: true }));++ test("marks, reads and clears beside the freshen state", () => {+ expect(readFreshenPending(dir)).toBeNull();+ markFreshenPending(dir, NOW);+ // Same directory the claim and the state live in - the child is+ // handed exactly this directory as `--freshen-state`.+ const raw = JSON.parse(readFileSync(join(dir, FRESHEN_PENDING_FILE), "utf8")) as {+ since: number;+ };+ expect(raw.since).toBe(NOW);+ expect(readFreshenPending(dir)).toEqual({ since: NOW });+ clearFreshenPending(dir);+ expect(readFreshenPending(dir)).toBeNull();+ // Clearing an absent marker is nothing to fail a write over.+ expect(() => clearFreshenPending(dir)).not.toThrow();+ });++ test("a take puts the marker back on restore, and drops it on drop", () => {+ markFreshenPending(dir, NOW);+ const taken = takeFreshenPending(dir)!;+ expect(taken.pending).toEqual({ since: NOW });+ // While taken, the path is empty: a concurrent reader sees no marker.+ expect(readFreshenPending(dir)).toBeNull();+ taken.restore();+ expect(readFreshenPending(dir)).toEqual({ since: NOW });++ const again = takeFreshenPending(dir)!;+ again.drop();+ expect(readFreshenPending(dir)).toBeNull();+ });++ test("a writer that re-marks while the settle holds a take keeps the path", () => {+ // The race the take exists to close: the old read-then-clear settle+ // could unlink a marker a writer had JUST written newer, losing the+ // newest write its instant stood for. The restore answers the+ // occupied path atomically - the newer marker stays, the taken one+ // is superseded, never merged.+ markFreshenPending(dir, NOW);+ const taken = takeFreshenPending(dir)!;+ markFreshenPending(dir, NOW + 60_000);+ taken.restore();+ expect(readFreshenPending(dir)).toEqual({ since: NOW + 60_000 });++ // And a drop of a stale take never touches a newer marker either.+ const stale = takeFreshenPending(dir)!;+ expect(stale.pending).toEqual({ since: NOW + 60_000 });+ markFreshenPending(dir, NOW + 120_000);+ stale.drop();+ expect(readFreshenPending(dir)).toEqual({ since: NOW + 120_000 });+ });++ test("a take of an absent marker is null, and a torn marker survives a settle untouched", async () => {+ expect(takeFreshenPending(dir)).toBeNull();+ // A torn marker is not a readable instant: the settle neither runs+ // a pass on it nor destroys the file - the next real mark overwrites+ // it, and the next run judges the readable one.+ writeFileSync(join(dir, FRESHEN_PENDING_FILE), "{ not json", "utf8");+ let passes = 0;+ const ran = await settleFreshenPending(dir, NOW, async () => {+ passes++;+ });+ expect(ran).toBe(false);+ expect(passes).toBe(0);+ expect(existsSync(join(dir, FRESHEN_PENDING_FILE))).toBe(true);+ });++ test("a marker newer than the scan start runs ONE more pass, and the pass that covers it clears it", async () => {+ // Instants are pinned to the real clock here because the settle+ // compares the extra pass against its own scan start, which is+ // real: `Date.now()` in this suite ran ahead of any fixed fixture,+ // and a clock behind the fixture would flip the verdict.+ const markedAt = Date.now() - 1_000;+ markFreshenPending(dir, markedAt);+ // The in-flight run started scanning BEFORE the write landed: its+ // stamp cannot prove it saw the write, so the child owes one pass.+ const scanStart = markedAt - 5_000;+ let passes = 0;+ const ran = await settleFreshenPending(dir, scanStart, async () => {+ passes++;+ });+ expect(ran).toBe(true);+ expect(passes).toBe(1);+ // The extra pass started after the marker's instant, so it covered+ // the pending write - and the marker goes with it. A marker that+ // outlived its own coverage would push every later run into an+ // extra pass forever.+ expect(readFreshenPending(dir)).toBeNull();+ });++ test("a marker the main pass already covered is cleared without a second pass", async () => {+ markFreshenPending(dir, NOW - 60_000);+ const scanStart = NOW; // the run started after the pending write+ let passes = 0;+ const ran = await settleFreshenPending(dir, scanStart, async () => {+ passes++;+ });+ expect(ran).toBe(false);+ expect(passes).toBe(0);+ expect(readFreshenPending(dir)).toBeNull();+ });++ test("the bound holds: a marker landing during the extra pass survives it, and no second pass runs", async () => {+ // Instants are pinned to the real clock here because the settle+ // compares markers against its own scan starts, which are real:+ // `Date.now()` in this suite ran ahead of any fixed fixture.+ markFreshenPending(dir, Date.now() - 1_000);+ const scanStart = Date.now() - 5_000;+ let passes = 0;+ let passStart = 0;+ const ran = await settleFreshenPending(dir, scanStart, async () => {+ passes++;+ passStart = Date.now();+ // Another write lands while the extra pass is in flight: the+ // forced caller re-marks with the newer instant. One extra pass+ // is the bound - this write waits for the next run, which covers+ // it and clears the marker then.+ markFreshenPending(dir, passStart + 60_000);+ });+ expect(ran).toBe(true);+ expect(passes).toBe(1);+ // Newer than the extra pass's own scan start: NOT covered by it.+ expect(readFreshenPending(dir)).toEqual({ since: passStart + 60_000 });+ // The NEXT run's child, with its own later scan start, covers it.+ let nextPasses = 0;+ await settleFreshenPending(dir, passStart + 120_000, async () => {+ nextPasses++;+ });+ expect(nextPasses).toBe(0);+ expect(readFreshenPending(dir)).toBeNull();+ });++ test("a child that cannot run a pass (config unresolvable) leaves the marker for the next run", async () => {+ markFreshenPending(dir, NOW);+ const ran = await settleFreshenPending(dir, NOW - 5_000, null);+ expect(ran).toBe(false);+ // Still queued - dropping it here would be the silent loss the+ // marker exists to prevent.+ expect(readFreshenPending(dir)).toEqual({ since: NOW });+ });++ test("no marker, no pass", async () => {+ let passes = 0;+ const ran = await settleFreshenPending(dir, NOW - 5_000, async () => {+ passes++;+ });+ expect(ran).toBe(false);+ expect(passes).toBe(0);+ });++ test("a hard kill during the extra pass leaves the marker standing on its path", async () => {+ // The take-first settle moved the marker into its hold file BEFORE+ // the extra pass ran, so a child killed mid-pass stranded the marker+ // where nothing reads it again: the write stood unqueued and+ // unmarked. The settle now reads without taking and takes only once+ // the pass has finished, so at every instant up to and including the+ // kill the marker is exactly where the next run reads it.+ const markedAt = Date.now() - 1_000;+ markFreshenPending(dir, markedAt);+ const scanStart = markedAt - 5_000;+ let observedDuringPass: FreshenPending | null | undefined;+ const killDuringPass = new Promise<void>((resolve) => {+ void settleFreshenPending(dir, scanStart, async () => {+ // The kill lands here in a real child: the pass never returns,+ // and nothing the settle does after it ever runs.+ observedDuringPass = readFreshenPending(dir);+ resolve();+ await new Promise<void>(() => {});+ }).catch(() => {});+ });+ await killDuringPass;+ // Mid-pass, the marker is still on its own path - not hidden in the+ // settle's hold file, where the kill would leave it for good.+ expect(observedDuringPass).toEqual({ since: markedAt });+ expect(readFreshenPending(dir)).toEqual({ since: markedAt });+ });++ test("a failed extra pass leaves the marker queued for the next run", async () => {+ // A pass that threw covered nothing, so the marker goes back on its+ // path - it must not stay stranded in the settle's hold file, where+ // nothing would read it again. This is the pin the CLI child's+ // "an uncovered marker survives for the next run" rests on.+ const markedAt = Date.now() - 1_000;+ markFreshenPending(dir, markedAt);+ const scanStart = markedAt - 5_000;+ let passes = 0;+ try {+ await settleFreshenPending(dir, scanStart, async () => {+ passes++;+ throw new Error("indexer exploded");+ });+ throw new Error("the settle should have propagated the pass failure");+ } catch (e) {+ expect((e as Error).message).toBe("indexer exploded");+ }+ expect(passes).toBe(1);+ expect(readFreshenPending(dir)).toEqual({ since: markedAt });+ });+});+test("the spawned run is told where its state lives", () => {const vault = mkdtempSync(join(tmpdir(), "osb-freshen-statedir-"));try {diff --git a/tests/helpers/linear-time.ts b/tests/helpers/linear-time.tsindex d1d45d20..5219fc9a 100644--- a/tests/helpers/linear-time.ts+++ b/tests/helpers/linear-time.ts@@ -2,7 +2,8 @@* Ceiling for the regression guards that prove a pass over a large input* stays linear. A quadratic pass over 256 KiB takes tens of seconds (the old* quote normaliser: 50 s, the old fence mask: 20 s); linear code takes well- * under 0.5 s even on a loaded runner, so the ceiling is generous on purpose- * and still discriminates by an order of magnitude.+ * under 0.5 s on a quiet runner and has been observed up to about 4 s on a+ * loaded CI runner, so the ceiling keeps an order of magnitude over the quiet+ * case while still sitting far below any quadratic time.*/-export const LINEAR_CEILING_MS = 2000;+export const LINEAR_CEILING_MS = 5000;diff --git a/tests/mcp/brain-create-note.test.ts b/tests/mcp/brain-create-note.test.tsindex 0a2239cb..a241fd25 100644--- a/tests/mcp/brain-create-note.test.ts+++ b/tests/mcp/brain-create-note.test.ts@@ -6,7 +6,7 @@* context. Refusals map to INVALID_PARAMS and write nothing.*/-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";import { appendFileSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";@@ -54,6 +54,163 @@ afterEach(() => {const tool = NOTES_TOOLS.find((t) => t.name === "brain_create_note")!;const handler = tool.handler;+/** Stamp the vault's index with an old instant: the claim's stale gate must pass. */+async function stampIndexStale(): Promise<void> {+ const { LAST_INDEXED_AT_STATE_KEY, Store } = await import("../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault, configPath: ctx.configPath! }), {+ mode: "write",+ });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+}++function withIntervalEnv(value: string): () => void {+ const key = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";+ const saved = process.env[key];+ process.env[key] = value;+ return () => {+ if (saved === undefined) delete process.env[key];+ else process.env[key] = saved;+ };+}++/**+ * The post-write index refresh a created note claims.+ *+ * The card names created notes among the writes that must resolve+ * without a reindex, so an applied create claims the SAME detached,+ * claim-guarded refresh a lifecycle write claims - fire-and-forget, with+ * the claim marker and its refusal reason on the receipt under the same+ * vocabulary (`index_refresh`, `index_refresh_reason`). The seam is the+ * freshen module itself, mocked here so the assertion sees the forced+ * call without ever spawning a real indexer; the suite-wide freshen-off+ * default keeps every OTHER test in this file inert.+ */+describe("brain_create_note - the post-write refresh claim", () => {+ // This runner's mock registration outlives mock.restore() across test+ // FILES, so the teardown re-registers the REAL module object instead:+ // whatever leaks past this file is freshen.ts itself, byte for byte.+ const FRESHEN_MODULE = "../../src/core/search/freshen.ts";+ let realFreshen: Record<string, unknown> | null = null;+ let forcedCalls: Array<{ vault: string; opts: Record<string, unknown> }> = [];++ afterEach(() => {+ if (realFreshen !== null) mock.module(FRESHEN_MODULE, () => realFreshen);+ mock.restore();+ realFreshen = null;+ forcedCalls = [];+ });++ /** Intercept the freshen machinery at the deferred-import seam. */+ async function mockFreshenSpawned(): Promise<void> {+ realFreshen = { ...(await import(FRESHEN_MODULE)) };+ forcedCalls = [];+ mock.module(FRESHEN_MODULE, () => ({+ ...realFreshen,+ maybeFreshenIndex: (config: { vault: string }, opts: Record<string, unknown>) => {+ forcedCalls.push({ vault: config.vault, opts });+ return "spawned" as const;+ },+ }));+ }++ test("an applied create claims one forced refresh: the seam sees force, and the receipt says claimed", async () => {+ // An index exists and is stale: the claim's stale gate passes and the+ // forced machinery is what the seam intercepts.+ await stampIndexStale();+ await mockFreshenSpawned();+ const restore = withIntervalEnv("60");+ try {+ const res = (await handler(ctx, {+ path: "Notes/Refreshed.md",+ frontmatter: { title: "R" },+ content: "a created note that claims its refresh",+ })) as Record<string, unknown>;++ expect(res["created"]).toBe(true);+ // The same claim marker vocabulary the lifecycle tool renders, on+ // the create receipt: a run is IN FLIGHT, never landed.+ expect(res["index_refresh"]).toBe("claimed");+ expect(res["index_refresh_reason"]).toBeNull();+ // The seam assertion: one forced call for THIS vault - force past+ // the freshness gate, because the create is due by definition.+ expect(forcedCalls).toHaveLength(1);+ expect(forcedCalls[0]!.vault).toBe(vault);+ expect(forcedCalls[0]!.opts["force"]).toBe(true);+ } finally {+ restore();+ }+ });++ test("config off does not claim: the receipt says not_claimed and names off", async () => {+ // An index exists (so the stale gate passes and the machinery is+ // what refuses), and no mock: with the interval at 0 the REAL+ // machinery answers before any spawn could be considered, so nothing+ // can leak out of this test either.+ await stampIndexStale();+ const restore = withIntervalEnv("0");+ try {+ const res = (await handler(ctx, {+ path: "Notes/Unrefreshed.md",+ content: "an operator who disabled freshening asked for exactly that",+ })) as Record<string, unknown>;++ expect(res["created"]).toBe(true);+ expect(res["index_refresh"]).toBe("not_claimed");+ expect(res["index_refresh_reason"]).toBe("off");+ } finally {+ restore();+ }+ });++ test("the claim resolves through the server's own config file, not the environment alone", async () => {+ // The freshen-off decision arrives by CONFIG FILE here - the env+ // var the suite defaults to 0 is scrubbed, because the environment+ // wins over the config file and would answer `off` whether or not+ // the claim resolved the server's configPath. The claim reads the+ // config file only because it resolves the search config through+ // it, the file every other search-resolving call in the tool reads.+ // Resolved without it, the default interval stands and the create+ // claims a run the operator's config refused.+ await stampIndexStale();+ atomicWriteFileSync(+ join(configHome, "config.yaml"),+ `vault: ${vault}\nagent_name: claude\nsearch_freshen_interval_s: 0\n`,+ );+ const key = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";+ const saved = process.env[key];+ delete process.env[key];+ try {+ const res = (await handler(ctx, {+ path: "Notes/ConfigOff.md",+ content: "the config file's off is the claim's off",+ })) as Record<string, unknown>;++ expect(res["created"]).toBe(true);+ expect(res["index_refresh"]).toBe("not_claimed");+ expect(res["index_refresh_reason"]).toBe("off");+ } finally {+ if (saved === undefined) delete process.env[key];+ else process.env[key] = saved;+ }+ });++ test("a skipped create wrote nothing, so it carries no refresh marker at all", async () => {+ await handler(ctx, { path: "Notes/There.md", content: "first\n" });+ const res = (await handler(ctx, {+ path: "Notes/There.md",+ content: "second\n",+ if_exists: "skip",+ })) as Record<string, unknown>;++ expect(res["created"]).toBe(false);+ // Byte-identical-when-absent: a receipt for a write that did not+ // happen says nothing about a refresh it did not claim.+ expect("index_refresh" in res).toBe(false);+ expect("index_refresh_reason" in res).toBe(false);+ });+});+describe("brain_create_note", () => {test("is registered with a write-shaped name and schema", () => {expect(tool).toBeDefined();@@ -264,7 +421,17 @@ describe("brain_create_note - the lint attached to the receipt", () => {frontmatter: { title: "Clean" },content: "plain prose, no links",});- expect(Object.keys(res)).toEqual(["created", "outcome", "path", "write_id"]);+ // A landed create carries the refresh-claim marker beside the audit+ // half (freshening is off suite-wide, so it reads not_claimed with+ // its reason).+ expect(Object.keys(res)).toEqual([+ "created",+ "outcome",+ "path",+ "write_id",+ "index_refresh",+ "index_refresh_reason",+ ]);expect(res).toMatchObject({ created: true, outcome: "created", path: "Notes/Clean.md" });// `write_id` joined the receipt with the note-write record// (who-wrote-what, Task A); its value is derived from the instant of@@ -359,7 +526,16 @@ describe("brain_create_note - widened near-duplicate hint", () => {frontmatter: { title: "L" },content: BODY,})) as Record<string, unknown>;- expect(Object.keys(res)).toEqual(["created", "outcome", "path", "write_id"]);+ // "Unchanged" now includes the refresh-claim marker a landed create+ // carries (the lint widening is what this test keeps unchanged).+ expect(Object.keys(res)).toEqual([+ "created",+ "outcome",+ "path",+ "write_id",+ "index_refresh",+ "index_refresh_reason",+ ]);});test("with the key on and no index, the receipt says widening did not run", async () => {diff --git a/tests/mcp/brain-governance.test.ts b/tests/mcp/brain-governance.test.tsindex c5c8d8e2..edacc2c1 100644--- a/tests/mcp/brain-governance.test.ts+++ b/tests/mcp/brain-governance.test.ts@@ -254,7 +254,7 @@ test("brain_maintenance run executes the lane; status reads the journal", asyncexpect(ran["verdict"]).toBe("run");const tasks = ran["tasks"] as Array<{ name: string; ok: boolean }>;// Same lane contract as the CLI verb (link-recall-intelligence).- expect(tasks.map((t) => t.name)).toEqual(["dream", "reindex", "bridges", "clusters"]);+ expect(tasks.map((t) => t.name)).toEqual(["dream", "reindex", "bridges", "clusters", "relink"]);expect(tasks.every((t) => t.ok)).toBe(true);const status = await call(server, "brain_maintenance", { operation: "status" });diff --git a/tests/mcp/brain-update-append-note.test.ts b/tests/mcp/brain-update-append-note.test.tsindex 29be408f..482f9da1 100644--- a/tests/mcp/brain-update-append-note.test.ts+++ b/tests/mcp/brain-update-append-note.test.ts@@ -14,10 +14,10 @@* read as a clear request rather than as an absent argument.*/-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { mkdtempSync } from "node:fs";-import { join } from "node:path";+import { dirname, join } from "node:path";import { tmpdir } from "node:os";import { bootstrapBrain } from "../../src/core/brain/init.ts";@@ -27,6 +27,7 @@ import { WriteBatchError } from "../../src/core/brain/write-batch.ts";import { PAGE_LINT_KEY } from "../../src/core/brain/page-lint.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../../src/mcp/protocol.ts";import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";+import { resolveSearchConfig } from "../../src/core/search/index.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";/**@@ -76,6 +77,205 @@ function seedNote(rel: string, body: string, frontmatter = ""): void {const updateTool = NOTES_TOOLS.find((t) => t.name === "brain_update_note")!;const appendTool = NOTES_TOOLS.find((t) => t.name === "brain_append_note")!;+// The freshen seam both claim describes below intercept. Module scope so+// the update and the append tests share ONE registration and ONE+// teardown - two private copies of a mock that must be un-registered is+// exactly how a leaked mock starts.+const FRESHEN_MODULE = "../../src/core/search/freshen.ts";+let realFreshen: Record<string, unknown> | null = null;+let forcedCalls: Array<{ vault: string; opts: Record<string, unknown> }> = [];++/** Intercept the freshen machinery at the deferred-import seam. */+async function mockFreshenSpawned(): Promise<void> {+ realFreshen = { ...(await import(FRESHEN_MODULE)) };+ forcedCalls = [];+ mock.module(FRESHEN_MODULE, () => ({+ ...realFreshen,+ maybeFreshenIndex: (config: { vault: string }, opts: Record<string, unknown>) => {+ forcedCalls.push({ vault: config.vault, opts });+ return "spawned" as const;+ },+ }));+}++afterEach(() => {+ // This runner's mock registration outlives mock.restore() across test+ // FILES, so the teardown re-registers the REAL module object instead:+ // whatever leaks past this file is freshen.ts itself, byte for byte.+ if (realFreshen !== null) mock.module(FRESHEN_MODULE, () => realFreshen);+ mock.restore();+ realFreshen = null;+ forcedCalls = [];+});++/** Stamp the vault's index with an old instant: the claim's stale gate must pass. */+async function stampIndexStale(): Promise<void> {+ const { LAST_INDEXED_AT_STATE_KEY, Store } = await import("../../src/core/search/store.ts");+ const store = await Store.open(resolveSearchConfig({ vault, configPath: ctx.configPath! }), {+ mode: "write",+ });+ store.setState(LAST_INDEXED_AT_STATE_KEY, "2026-08-15T00:00:00.000Z");+ await store.close();+}++function withIntervalEnv(value: string): () => void {+ const key = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";+ const saved = process.env[key];+ process.env[key] = value;+ return () => {+ if (saved === undefined) delete process.env[key];+ else process.env[key] = saved;+ };+}++/**+ * The post-write index refresh a content edit claims.+ *+ * The release notes promise that a content edit claims a refresh, so an+ * applied update claims the SAME detached, claim-guarded refresh a+ * lifecycle write claims - fire-and-forget, with the claim marker and+ * its refusal reason on the receipt under the same vocabulary+ * (`index_refresh`, `index_refresh_reason`). The seam is the freshen+ * module itself, mocked here so the assertion sees the forced call+ * without ever spawning a real indexer; the suite-wide freshen-off+ * default keeps every OTHER test in this file inert.+ */+describe("brain_update_note - the post-write refresh claim", () => {+ test("a content edit claims one forced refresh: the seam sees force, and the receipt says claimed", async () => {+ seedNote("Notes/Doc.md", "old body", "title: Doc");+ // An index exists and is stale: the claim's stale gate passes and+ // the forced machinery is what the seam intercepts.+ await stampIndexStale();+ await mockFreshenSpawned();+ const restore = withIntervalEnv("60");+ try {+ const res = (await updateTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "new body",+ })) as Record<string, unknown>;++ expect(res["updated"]).toBe(true);+ // The same claim marker vocabulary the lifecycle tool renders, on+ // the update receipt: a run is IN FLIGHT, never landed.+ expect(res["index_refresh"]).toBe("claimed");+ expect(res["index_refresh_reason"]).toBeNull();+ // The seam assertion: one forced call for THIS vault - force past+ // the freshness gate, because the edit is due by definition.+ expect(forcedCalls).toHaveLength(1);+ expect(forcedCalls[0]!.vault).toBe(vault);+ expect(forcedCalls[0]!.opts["force"]).toBe(true);+ } finally {+ restore();+ }+ });++ test("config off does not claim: the receipt says not_claimed and names off", async () => {+ seedNote("Notes/Doc.md", "old body", "title: Doc");+ // An index exists (so the stale gate passes and the machinery is+ // what refuses), and no mock: with the interval at 0 the REAL+ // machinery answers before any spawn could be considered, so nothing+ // can leak out of this test either.+ await stampIndexStale();+ const restore = withIntervalEnv("0");+ try {+ const res = (await updateTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "new body",+ })) as Record<string, unknown>;++ expect(res["updated"]).toBe(true);+ expect(res["index_refresh"]).toBe("not_claimed");+ expect(res["index_refresh_reason"]).toBe("off");+ } finally {+ restore();+ }+ });++ test("a writer-locked index still queues the write: the receipt names writer_lock and the marker stands", async () => {+ seedNote("Notes/Doc.md", "old body", "title: Doc");+ // An index exists and is stale, the interval is on, and the REAL+ // machinery runs - no seam. The index writer lock is HELD: the shape+ // of a detached refresh mid-pass, which holds it for the bulk of its+ // run, where the lock probe answers before the claim is ever+ // consulted. A write that took the lock's answer home unmarked would+ // be dropped for a whole interval by the run's fresh stamp - the+ // exact mid-refresh drop the pending marker exists to prevent.+ await stampIndexStale();+ const { acquireWriterLockSync } = await import("../../src/core/search/store/writer-lock.ts");+ const { FRESHEN_PENDING_FILE, readFreshenPending } = await import(FRESHEN_MODULE);+ const dbPath = resolveSearchConfig({ vault, configPath: ctx.configPath! }).dbPath;+ const release = acquireWriterLockSync(dbPath);+ const scanStart = Date.now();+ const restore = withIntervalEnv("60");+ try {+ const res = (await updateTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "new body",+ })) as Record<string, unknown>;++ expect(res["updated"]).toBe(true);+ expect(res["index_refresh"]).toBe("not_claimed");+ expect(res["index_refresh_reason"]).toBe("writer_lock");+ // The queue: a durable marker beside the freshen state says a+ // write is pending since an instant after this test's own scan+ // start, so the in-flight child's settle runs the one bounded+ // extra pass that covers it before it releases the claim.+ const stateDir = dirname(dbPath);+ const marker = readFreshenPending(stateDir);+ expect(marker).not.toBeNull();+ expect(marker!.since).toBeGreaterThanOrEqual(scanStart);+ expect(existsSync(join(stateDir, FRESHEN_PENDING_FILE))).toBe(true);+ } finally {+ release();+ restore();+ }+ });++ test("the claim resolves through the server's own config file, not the environment alone", async () => {+ seedNote("Notes/Doc.md", "old body", "title: Doc");+ // The freshen-off decision arrives by CONFIG FILE here - the env+ // var the suite defaults to 0 is scrubbed - and the claim reads it+ // only because it resolves the search config through the server's+ // configPath. Resolved without it, the default interval stands and+ // the edit claims a run the operator's config refused.+ await stampIndexStale();+ atomicWriteFileSync(+ join(configHome, "config.yaml"),+ `vault: ${vault}\nagent_name: claude\nsearch_freshen_interval_s: 0\n`,+ );+ const key = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";+ const saved = process.env[key];+ delete process.env[key];+ try {+ const res = (await updateTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "new body",+ })) as Record<string, unknown>;++ expect(res["updated"]).toBe(true);+ expect(res["index_refresh"]).toBe("not_claimed");+ expect(res["index_refresh_reason"]).toBe("off");+ } finally {+ if (saved === undefined) delete process.env[key];+ else process.env[key] = saved;+ }+ });++ test("a byte-identical re-apply wrote nothing, so it carries no refresh marker at all", async () => {+ seedNote("Notes/Doc.md", "same body", "title: Doc");+ const res = (await updateTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "same body",+ })) as Record<string, unknown>;++ expect(res["updated"]).toBe(false);+ // Byte-identical-when-absent: a receipt for a write that did not+ // happen says nothing about a refresh it did not claim.+ expect("index_refresh" in res).toBe(false);+ expect("index_refresh_reason" in res).toBe(false);+ });+});+describe("brain_update_note", () => {test("is registered and requires a path", () => {expect(updateTool).toBeDefined();@@ -204,6 +404,69 @@ describe("brain_update_note", () => {});});+describe("brain_append_note - the post-write refresh claim", () => {+ test("an applied append claims one forced refresh: the seam sees force, and the receipt says claimed", async () => {+ // An append writes body bytes, so it is a content edit: the release+ // notes' "a content edit claims" covers it, and an append that left+ // the index stale for an interval would be the gap the claim exists+ // to close.+ seedNote("Notes/Doc.md", "first", "title: Doc");+ await stampIndexStale();+ await mockFreshenSpawned();+ const restore = withIntervalEnv("60");+ try {+ const res = (await appendTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "second",+ })) as Record<string, unknown>;++ expect(res["appended"]).toBe(true);+ expect(res["index_refresh"]).toBe("claimed");+ expect(res["index_refresh_reason"]).toBeNull();+ expect(forcedCalls).toHaveLength(1);+ expect(forcedCalls[0]!.vault).toBe(vault);+ expect(forcedCalls[0]!.opts["force"]).toBe(true);+ } finally {+ restore();+ }+ });++ test("config off does not claim: the receipt says not_claimed and names off", async () => {+ seedNote("Notes/Doc.md", "first", "title: Doc");+ await stampIndexStale();+ const restore = withIntervalEnv("0");+ try {+ const res = (await appendTool.handler(ctx, {+ path: "Notes/Doc.md",+ content: "second",+ })) as Record<string, unknown>;++ expect(res["appended"]).toBe(true);+ expect(res["index_refresh"]).toBe("not_claimed");+ expect(res["index_refresh_reason"]).toBe("off");+ } finally {+ restore();+ }+ });++ test("a refused append wrote nothing, so it claims nothing", async () => {+ // The typed refusal is thrown before any claim is attempted. The+ // mock is installed and freshening is ON (with a stamped stale+ // index, so a claim that DID run would reach the seam) - the+ // assertion has something to catch: a claim hoisted above the write+ // would light the seam up on its way to the refusal.+ await stampIndexStale();+ await mockFreshenSpawned();+ const restore = withIntervalEnv("60");+ try {+ await rejectedMcpError(appendTool.handler(ctx, { path: "Notes/Ghost.md", content: "x" }));+ expect(forcedCalls).toHaveLength(0);+ } finally {+ restore();+ }+ });+});+describe("brain_append_note", () => {test("is registered and requires path and content", () => {expect(appendTool).toBeDefined();@@ -296,8 +559,16 @@ describe("the lint attached to the update / append receipts", () => {// The shape is pinned in full so a field cannot arrive unannounced.// `write_id` joined it with the note-write record (who-wrote-what,// Task A) and is the one key whose VALUE cannot be a literal: it is- // derived from the instant of the write.- expect(Object.keys(res)).toEqual(["updated", "path", "write_id"]);+ // derived from the instant of the write. The refresh-claim marker+ // joined it when content edits started claiming a refresh (freshening+ // is off suite-wide, so it reads not_claimed with its reason).+ expect(Object.keys(res)).toEqual([+ "updated",+ "path",+ "write_id",+ "index_refresh",+ "index_refresh_reason",+ ]);expect(res).toMatchObject({ updated: true, path: "Notes/Clean.md" });expect(res["write_id"]).toMatch(NOTE_WRITE_ID_RE);// An id present means no audit reason is owed, and the lint has@@ -309,7 +580,18 @@ describe("the lint attached to the update / append receipts", () => {test("a clean append carries the flag, the path and the write id, in that order", async () => {seedNote("Notes/CleanA.md", "first", "title: CleanA");const res = await call(appendTool, { path: "Notes/CleanA.md", content: "second" });- expect(Object.keys(res)).toEqual(["appended", "path", "write_id"]);+ // The shape is pinned in full so a field cannot arrive unannounced.+ // The refresh-claim marker joined the update receipt when content+ // edits started claiming a refresh, and the append - a content edit+ // of its own - claims under the same vocabulary (freshening is off+ // suite-wide, so it reads not_claimed with its reason).+ expect(Object.keys(res)).toEqual([+ "appended",+ "path",+ "write_id",+ "index_refresh",+ "index_refresh_reason",+ ]);expect(res).toMatchObject({ appended: true, path: "Notes/CleanA.md" });expect(res["write_id"]).toMatch(NOTE_WRITE_ID_RE);expect("audit_reason" in res).toBe(false);diff --git a/tests/mcp/brain-write-batch.test.ts b/tests/mcp/brain-write-batch.test.tsindex 19df6451..cd52f0ad 100644--- a/tests/mcp/brain-write-batch.test.ts+++ b/tests/mcp/brain-write-batch.test.ts@@ -481,7 +481,16 @@ describe("brain_write_batch - the absolute-path advisory on the receipt", () =>path: "Notes/App.md",content: "clean addition",})) as Record<string, unknown>;- expect(Object.keys(res)).toEqual(["appended", "path", "write_id"]);+ // The refresh-claim marker rides the append receipt under the same+ // vocabulary the update receipt carries (freshening is off+ // suite-wide, so it reads not_claimed with its reason); no advisory.+ expect(Object.keys(res)).toEqual([+ "appended",+ "path",+ "write_id",+ "index_refresh",+ "index_refresh_reason",+ ]);expect("path_advisory" in res).toBe(false);});});diff --git a/tests/mcp/maintenance-parity-census.test.ts b/tests/mcp/maintenance-parity-census.test.tsindex b1f57cef..a249255e 100644--- a/tests/mcp/maintenance-parity-census.test.ts+++ b/tests/mcp/maintenance-parity-census.test.ts@@ -47,7 +47,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -64,7 +64,19 @@ import {CUSTOM_TASKS_OFF_NOTICE,} from "../../src/core/brain/maintenance/custom-tasks.ts";import { isOperation } from "../../src/core/brain/safeguard.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { writeFrontmatterAtomic } from "../../src/core/vault.ts";import { ADMIN_TOOLS } from "../../src/mcp/brain/admin-tools.ts";+// Measured caps on the tool's text: the registry keeps every description+// short. Imported rather than restated so the two ratchets cannot drift -+// the retry_tasks description enumerates the known lane tasks, so a lane+// task's registration grows the measured length and the cap moves with the+// population rather than shortening the text that names what an operator+// may retry.+import {+ PROPERTY_DESCRIPTION_MAX as RETRY_PROPERTY_DESCRIPTION_MAX,+ TOOL_DESCRIPTION_MAX,+} from "../../src/mcp/registry-guard.ts";import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";@@ -554,10 +566,6 @@ describe("an unknown retry name is refused by name on both surfaces", () => {});});-/** Measured caps on the tool's text: the registry keeps every description short. */-const TOOL_DESCRIPTION_MAX = 300;-const RETRY_PROPERTY_DESCRIPTION_MAX = 160;-describe("the tool's text stays inside its budget", () => {test("description and retry_tasks property are measured, and name no configured task", () => {const tool = ADMIN_TOOLS.find((t) => t.name === TOOL_NAME)!;@@ -700,3 +708,180 @@ describe("declared custom tasks are retried and refused the same way on both surexpect((JSON.parse(cli.stdout) as { notice?: string }).notice).toBe(CUSTOM_TASKS_OFF_NOTICE);});});++describe("the relink arm is opt-in on the tool too", () => {+ let tmp: string;+ let vault: string;+ let configPath: string;++ beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-maint-relink-"));+ vault = join(tmp, "vault");+ mkdirSync(vault, { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ const init = await runCli(["brain", "init", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(init.returncode).toBe(0);+ });++ afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ });++ async function callTool(args: Record<string, unknown>) {+ const server = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION },+ });+ return (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name: TOOL_NAME, arguments: args },+ })) as {+ error?: { code: number; message: string };+ result?: { structuredContent?: Record<string, unknown>; content?: Array<{ text: string }> };+ };+ }++ function toolPayload(res: Awaited<ReturnType<typeof callTool>>): Record<string, unknown> {+ if (res.result?.structuredContent) return res.result.structuredContent;+ return JSON.parse(res.result?.content?.[0]?.text ?? "{}") as Record<string, unknown>;+ }++ /** One entity, one page linking it, one page-sourced signal naming nothing. */+ function writeRelinkFixture(): string {+ const entitiesDir = join(vault, "Brain", "entities", "people");+ mkdirSync(entitiesDir, { recursive: true });+ const now = new Date().toISOString();+ writeFrontmatterAtomic(+ join(entitiesDir, "ent-people-ada-lovelace.md"),+ {+ kind: "brain-entity",+ entity_id: "ent-people-ada-lovelace",+ category: "people",+ name: "Ada Lovelace",+ status: "active",+ created_at: now,+ updated_at: now,+ tags: ["brain", "brain/entity"],+ },+ "# Ada Lovelace",+ { overwrite: true },+ );+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(+ join(vault, "notes", "meeting.md"),+ "# Meeting\n\n- [[ent-people-ada-lovelace]] joined the review.\n",+ "utf8",+ );+ writeSignal(vault, {+ topic: "relink-surface",+ signal: "positive",+ agent: "tester",+ principle: "the review concluded with five follow-ups",+ created_at: now,+ date: now.slice(0, 10),+ slug: "relink-surface",+ scope: "writing",+ source: ["[[notes/meeting.md]]"],+ // The pass's in-scope stamp: relink reads only server-derived+ // sources, so the fixture signal is extraction-written.+ source_type: "extracted",+ dedup_hash: `relink-surface-${now}`,+ // The placeholder Raw section: the shape a signal stored without a+ // verbatim quote carries, and the line the relink rewrite can fill.+ raw: "_(not provided)_",+ });+ const inbox = join(vault, "Brain", "inbox");+ const name = readdirSync(inbox).find((f) => f.startsWith("sig-") && f.endsWith(".md"));+ if (name === undefined) throw new Error("fixture signal was not written");+ return join(inbox, name);+ }++ test("relink_apply rewrites the stored lines and the result carries the report", async () => {+ const signalPath = writeRelinkFixture();+ const res = await callTool({ operation: "run", relink_apply: true });+ expect(res.error).toBeUndefined();+ const payload = toolPayload(res);+ const relink = payload["relink"] as {+ apply: boolean;+ signalsChanged: number;+ anchorsAdded: number;+ };+ expect(relink.apply).toBe(true);+ expect(relink.signalsChanged).toBe(1);+ expect(relink.anchorsAdded).toBe(1);+ expect(readFileSync(signalPath, "utf8")).toContain("entities: ent-people-ada-lovelace");+ });++ test("without it the tool's relink task previews and the report says so", async () => {+ const signalPath = writeRelinkFixture();+ const before = readFileSync(signalPath, "utf8");+ const res = await callTool({ operation: "run" });+ expect(res.error).toBeUndefined();+ const payload = toolPayload(res);+ const relink = payload["relink"] as { apply: boolean; anchorsAdded: number };+ expect(relink.apply).toBe(false);+ expect(relink.anchorsAdded).toBe(1);+ expect(readFileSync(signalPath, "utf8")).toBe(before);+ });++ test('relink_apply as the string "true" applies, not previews', async () => {+ // Clients commonly round-trip a boolean as a string. The literal+ // `=== true` read turned that spelling into a PREVIEW that still+ // reported `verdict: ok` - the caller believed it had applied and+ // read a clean run over changes that were never written.+ const signalPath = writeRelinkFixture();+ const res = await callTool({ operation: "run", relink_apply: "true" });+ expect(res.error).toBeUndefined();+ const relink = toolPayload(res)["relink"] as {+ apply: boolean;+ signalsChanged: number;+ };+ expect(relink.apply).toBe(true);+ expect(relink.signalsChanged).toBe(1);+ expect(readFileSync(signalPath, "utf8")).toContain("entities: ent-people-ada-lovelace");+ });++ test('a relink_apply value that is neither boolean nor "true"/"false" is refused, not previewed', async () => {+ // The refusal, not the silent preview, is the contract for everything+ // else: "yes" and 1 must come back INVALID_PARAMS naming the argument+ // - a caller that misread the schema stops and corrects instead of+ // reading an ok verdict over a run that applied nothing.+ writeRelinkFixture();+ const yes = await callTool({ operation: "run", relink_apply: "yes" });+ expect(yes.error?.code).toBe(INVALID_PARAMS);+ expect(yes.error?.message).toContain("relink_apply");+ const one = await callTool({ operation: "run", relink_apply: 1 });+ expect(one.error?.code).toBe(INVALID_PARAMS);+ expect(one.error?.message).toContain("relink_apply");+ });++ test("force_cost rides the same boolean rule relink_apply does", async () => {+ // The literal `=== true` read left the exact bug the relink_apply+ // coercion fixed alive one argument over. What is pinned here is the+ // coercion contract on THIS argument: the string spelling is ADMITTED+ // (not refused - the admission contract the relink_apply string test+ // pins through the same helper), and every non-boolean junk value is+ // refused by name, where the old read silently demoted it to the+ // default. That the admitted true then overrides the embedding cost+ // gate is the spend gate's own pin (the embedding-spend-preview+ // suite drives forceCost through the gate directly).+ writeRelinkFixture();+ const stringTrue = await callTool({ operation: "run", force_cost: "true" });+ expect(stringTrue.error).toBeUndefined();++ const yes = await callTool({ operation: "run", force_cost: "yes" });+ expect(yes.error?.code).toBe(INVALID_PARAMS);+ expect(yes.error?.message).toContain("force_cost");+ const one = await callTool({ operation: "run", force_cost: 1 });+ expect(one.error?.code).toBe(INVALID_PARAMS);+ expect(one.error?.message).toContain("force_cost");+ });+});diff --git a/tests/mcp/note-lifecycle-references-reach.test.ts b/tests/mcp/note-lifecycle-references-reach.test.tsindex f12d7111..830c7732 100644--- a/tests/mcp/note-lifecycle-references-reach.test.ts+++ b/tests/mcp/note-lifecycle-references-reach.test.ts@@ -39,8 +39,14 @@ interface Fixture {/*** A visible note linked from a visible page and, in one of the two vaults,* from a private page. With no `reach`, the server mints none: remote.+ * `visibleCarrier`, when given, is an extra VISIBLE page shared by both+ * vaults - the sole carrier of a basename a repair-arm move can contest.*/-function fixture(withSecret: boolean, reach?: typeof TRANSPORT_REACH.local): Fixture {+function fixture(+ withSecret: boolean,+ reach?: typeof TRANSPORT_REACH.local,+ visibleCarrier?: string,+): Fixture {const base = mkdtempSync(join(tmpdir(), "o2b-lifecycle-refs-reach-"));bases.push(base);const vault = join(base, "vault");@@ -51,6 +57,10 @@ function fixture(withSecret: boolean, reach?: typeof TRANSPORT_REACH.local): FixwriteFileSync(join(vault, TARGET), "# Target\n");writeFileSync(join(vault, "Notes/open.md"), "# Open\nSee [[Notes/target]].\n");if (withSecret) writeFileSync(join(vault, PRIVATE_PATH), SECRET_BODY);+ if (visibleCarrier !== undefined) {+ mkdirSync(dirname(join(vault, visibleCarrier)), { recursive: true });+ writeFileSync(join(vault, visibleCarrier), "# Draft\nA visible note.\n");+ }const server = new MCPServer({ vault, configPath }, reach !== undefined ? { reach } : undefined);return { vault, server };}@@ -98,7 +108,9 @@ describe("a linking page the caller cannot read is left out of the report", () =const hidden = fixture(true);await answer(hidden, { action: "move", path: TARGET, to: "Other/target.md", apply: true });const secret = readFileSync(join(hidden.vault, PRIVATE_PATH), "utf8");- expect(secret).toContain("[[Other/target]]");+ // The basename stays unique through the move, so the rewritten link+ // lands at its minimal spelling.+ expect(secret).toContain("[[target]]");expect(secret).not.toContain("[[Notes/target]]");});});@@ -134,3 +146,43 @@ describe("a hidden page at the destination is a known one-bit limitation", () =>});}});++describe("the bare-name repair arm at reach", () => {+ // The repair target spelling is derived from the third-party note that+ // carries the basename the move contests. A carrier the caller may not+ // read must contribute no pair: the remote answer names it no more than+ // a vault without that page would.+ test("a withheld sole carrier of the contested basename is never named", async () => {+ const hidden = fixture(true);+ for (const args of [+ { action: "move", path: TARGET, to: "Other/secret.md" },+ { action: "move", path: TARGET, to: "Other/secret.md", apply: true },+ ]) {+ const out = await answer(hidden, args);+ // The repair's reported `to` is the carrier's suffix-less spelling,+ // so the assertion runs at that precision too.+ expect(out).not.toContain("Notes/secret");+ expect(out).not.toContain(`${PRIVATE_PATH}`);+ }+ });++ test("at local reach the repair names the carrier - the control", async () => {+ const out = await answer(fixture(true, TRANSPORT_REACH.local), {+ action: "move",+ path: TARGET,+ to: "Other/secret.md",+ });+ expect(out).toContain("Notes/secret");+ });++ test("with a visible carrier the answers are byte-identical with and without the withheld page", async () => {+ // A VISIBLE note is the sole carrier of the contested basename, so+ // the repair fires and is reported in both vaults. The unrelated+ // withheld page in one of them must not change a byte of the answer -+ // the same contract the calls above pin, now covering the repair arm.+ const hidden = fixture(true, undefined, "Notes/draft.md");+ const absent = fixture(false, undefined, "Notes/draft.md");+ const args = { action: "move", path: TARGET, to: "Other/draft.md" };+ expect(await answer(hidden, args)).toBe(await answer(absent, args));+ });+});diff --git a/tests/mcp/note-lifecycle.test.ts b/tests/mcp/note-lifecycle.test.tsindex 97e89f95..921921ea 100644--- a/tests/mcp/note-lifecycle.test.ts+++ b/tests/mcp/note-lifecycle.test.ts@@ -21,7 +21,7 @@ import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";-import { INDEX_EVIDENCE } from "../../src/core/brain/notes/lifecycle.ts";+import { INDEX_EVIDENCE, INDEX_REFRESH } from "../../src/core/brain/notes/lifecycle.ts";import { LIFECYCLE_FILE_TOOLS } from "../../src/mcp/brain/lifecycle-file-tools.ts";import { MCPError } from "../../src/mcp/protocol.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";@@ -84,10 +84,22 @@ describe("dispatch", () => {const references = res["references"] as Record<string, unknown>;expect(references["files_rewritten"]).toBe(1);expect(references["inbound_files"]).toEqual(["Projects/Ref.md"]);+ // The spellings the rewrite carried out, minimal forms included.+ expect(references["rewritten_spellings"]).toEqual([+ { from: "Projects/Old.md", to: "New" },+ { from: "Projects/Old", to: "New" },+ { from: "Old", to: "New" },+ ]);+ // Freshening is off suite-wide, so the write claimed nothing - and+ // the refusal says why on the same response, so a caller reading+ // `not_claimed` is not left to distinguish a deliberate off from a+ // broken freshen path.+ expect(references["refresh"]).toBe(INDEX_REFRESH.notClaimed);+ expect(references["refresh_reason"]).toBe("no_index");const index = references["index"] as Record<string, unknown>;expect(index["state"]).toBe(INDEX_EVIDENCE.absent);expect(typeof index["next_command"]).toBe("string");- expect(readFileSync(join(vault, "Projects/Ref.md"), "utf8")).toContain("[[Projects/New]]");+ expect(readFileSync(join(vault, "Projects/Ref.md"), "utf8")).toContain("[[New]]");});test("dry run is the default: nothing moves without an explicit apply", async () => {diff --git a/uv.lock b/uv.lockindex b674ea66..f60d5e7a 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.88.0"+version = "1.89.0"source = { editable = "." }