Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
110 KB
Raw Blame
/**
 * Unit B — every in-vault write site, measured rather than described.
 *
 * The write binding this release ships covers ONE class of destination:
 * the vault-relative path a caller names. That is a real boundary and it
 * is also a small fraction of what puts bytes into a vault. Shipping it
 * while describing the surface as "enforced" would be theatre: dozens of
 * modules reach `node:fs` directly and pass no shared writer at all —
 * including, before this unit, one that wrote a complete vault note with
 * hand-rolled frontmatter and one inside a CLI verb.
 *
 * How many there are is not written down in this docblock, because a
 * number in prose is the thing that goes stale. {@link
 * DIRECT_WRITE_EXCLUSIONS} below IS the count, and it is exact by
 * construction: it walks the tree, finds every direct-`fs` write into
 * the vault, and requires each to carry a written exclusion naming the
 * category it falls in and the reason it does not route through a shared
 * writer. A new direct writer fails here and is named in the failure.
 *
 * ## The population, defined structurally
 *
 * A module is IN POPULATION when it can address the vault. Four clauses,
 * and the last three exist because the first two are a list of places:
 * it lives under one of {@link VAULT_WRITE_ROOTS}, or it is one of
 * {@link VAULT_WRITER_FILES}, or it imports the vault-location
 * vocabulary ({@link VAULT_VOCABULARY_IMPORT_RE}), or it NAMES a vault
 * location itself - a `join(` rooted on a vault argument
 * ({@link VAULT_ROOT_JOIN_RE}), or the derived-store directory as a bare
 * literal ({@link DERIVED_STORE_LITERAL_RE}).
 *
 * The import clause used to carry that argument alone, and the claim
 * above it - that it "stops a new in-vault writer escaping by living
 * somewhere new" - was measured false on this branch. `src/core/state/
 * migrate.ts` is 960 lines that copy, remove and prune every state
 * surface under `<vault>/.open-second-brain/` and `<vault>/Brain/`, and
 * it was outside the population on all three counts: not under a write
 * root, not a named writer file, and it reaches its paths through
 * `./surfaces.ts` rather than through `paths.ts`. `src/core/doctor.ts`,
 * which opens and removes a probe file in the vault ROOT, and
 * `src/core/install/manifest.ts`, which writes `<vault>/.open-second-
 * brain/install.lock.json`, escaped the same way. A rule that names only
 * one spelling of "vault path" is a rule about that spelling.
 *
 * Modules that write only outside the vault - the install adapters, the
 * machine-config exporter - are still out by the rule rather than by
 * twenty hand-written "not a vault" entries, because none of them roots
 * a `join(` on a vault or names the store directory.
 *
 * ## What counts as a WRITE
 *
 * A CONTENT write: a call that puts file bytes on disk, or removes,
 * moves, or re-permissions a file. `mkdirSync` is deliberately NOT in
 * the set. A directory holds no content, every atomic writer creates its
 * own parent, and counting it would make this census a list of every
 * module that writes anything — which is what the vault-guard census
 * (`tests/core/brain/vault-guard-census.test.ts`) already is. The two
 * censuses answer different questions: that one asks whether a
 * write-capable MODULE asserts vault identity, this one asks whether a
 * write SITE goes through a shared writer.
 *
 * Only identifiers actually bound from `node:fs` or `node:fs/promises`
 * count, so a local helper that happens to be called `writeFileSync` is
 * not miscounted, and a module that reaches `fs` through the shared
 * writers shows up in the shared class instead. "Bound" covers every
 * form the language offers - several statements in one file, a renamed
 * binding, a namespace import, either quote style - because the detector
 * previously read only a file's FIRST `node:fs` statement and the live
 * vault append in `src/core/brain/git/store.ts` sat on the second one.
 * Runtime writers that need no import (`Bun.write`) are matched on the
 * receiver instead.
 *
 * What it still does not see, stated rather than implied: a write issued
 * through a `node:fs/promises` FileHandle method, or through a binding
 * re-exported by an intermediate module. Both would be new shapes in
 * this tree, and the shape table in "the census can fail" is where a new
 * one gets added the day it appears.
 *
 * ## Why the exclusions are categorised
 *
 * Fifty free-text reasons are a wall nobody reads. Every entry carries a
 * category from a closed vocabulary, so the shape of the gap is legible
 * at a glance — how much of it is append-only ledgers, how much is
 * lifecycle moves that author no content, how much is retention pruning
 * — and the free text says only what the category cannot.
 */

import { describe, expect, test } from "bun:test";
import { readdirSync, readFileSync } from "node:fs";
import { join, relative } from "node:path";

import { type LexedSource, lexSource } from "../../helpers/source-lexer.ts";

const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
const SRC_ROOT = join(REPO_ROOT, "src");

/** Trees whose modules address the vault by construction. */
const VAULT_WRITE_ROOTS: ReadonlyArray<string> = Object.freeze([
  "src/core/brain/",
  "src/core/search/",
  "src/cli/brain/",
  "src/mcp/",
]);

/** Vault writers that live outside those trees, named individually. */
const VAULT_WRITER_FILES: ReadonlyArray<string> = Object.freeze([
  "src/core/vault.ts",
  "src/core/fs-atomic.ts",
]);

/**
 * The vault-location vocabulary. Importing it is addressing the vault.
 *
 * Three modules, because three modules spell a vault location:
 * `paths.ts` composes them, `path-constants.ts` DECLARES the names they
 * are composed from, and `state/surfaces.ts` enumerates the durable ones
 * as derivations a caller can invoke. `migrate.ts` reaches every state
 * surface through the third and named neither of the first two.
 *
 * The basename has to be the WHOLE last segment. `\bpaths\.ts` was too
 * loose: `-` is a word boundary, so `./hardcoded-paths.ts`,
 * `../claude-memory-paths.ts` and `../session-paths.ts` all matched.
 * Measured against this branch, the segment separator drops EIGHT
 * modules that no other clause enrols - seven install adapters reaching
 * `../session-paths.ts` (`generic.ts`, `codex.ts`, `pi.ts`, `grok.ts`,
 * `aider.ts`, `_json-mcp.ts`, `copilot-cli.ts`), every one of which
 * writes, plus `src/core/hygiene/scan-repo.ts` on
 * `./hardcoded-paths.ts`, which does not. Seven writers leaving a
 * write-site census sounds like a loss and is not: they write into the
 * runtimes' own config directories, never into a vault, and the
 * docblock above says so as the rule that keeps them out. Admitting
 * them would mean seven hand-written "not a vault" exclusions arguing
 * against the rule beside them.
 *
 * Over-inclusion is the safe direction for a gate in general; here it
 * defeats the gate's own stated boundary, so the segment separator is
 * required.
 */
const VAULT_VOCABULARY_IMPORT_RE =
  /^[ \t]*import\b[^;]*?\bfrom\s*"\.(?:[^"]*\/)?(?:paths|path-constants|surfaces)\.ts"/m;

/**
 * A path built from a vault root by hand, which is what `doctor.ts` does
 * and no import can reveal. Matched on the CODE view, so the receiver has
 * to be a real identifier rather than a name inside a quoted example.
 */
const VAULT_ROOT_JOIN_RE = /\bjoin\s*\(\s*(?:vault|vaultPath|vaultRoot|vaultDir)\b/;

/**
 * The derived-store directory spelled as a bare literal, which is how
 * `install/manifest.ts` names `<vault>/.open-second-brain/`. Read off the
 * comment-stripped view, which keeps string CONTENTS: on the code view a
 * literal's body is blanked and nothing would ever match.
 */
const DERIVED_STORE_LITERAL_RE = /"\.open-second-brain"|'\.open-second-brain'/;

/**
 * Calls that put file bytes on disk, or remove, move, or re-permission a
 * file. See the docblock for why `mkdirSync` is not among them.
 */
const CONTENT_WRITE_CALLS: ReadonlyArray<string> = Object.freeze([
  // `node:fs`
  "writeFileSync",
  "appendFileSync",
  "writeSync",
  "renameSync",
  "rmSync",
  "unlinkSync",
  "rmdirSync",
  "cpSync",
  "copyFileSync",
  "createWriteStream",
  "truncateSync",
  "ftruncateSync",
  "symlinkSync",
  "linkSync",
  "utimesSync",
  "chmodSync",
  // `node:fs/promises` twins of the same operations. Nothing in `src/`
  // imports them today; they are here so the FIRST one is reported rather
  // than admitted. The import gate below is what keeps a local helper
  // named `rm` or `link` from being miscounted as one of these.
  "writeFile",
  "appendFile",
  "rename",
  "rm",
  "unlink",
  "rmdir",
  "cp",
  "copyFile",
  "truncate",
  "symlink",
  "link",
  "utimes",
  "chmod",
]);

const CONTENT_WRITE_SET: ReadonlySet<string> = new Set(CONTENT_WRITE_CALLS);

/**
 * Writers reachable with no import at all, so no import gate can see them.
 * Named in full (`Bun.write`) because the receiver is what identifies them.
 */
const GLOBAL_WRITE_CALLS: ReadonlyArray<string> = Object.freeze(["Bun.write"]);

/** The shared writers a site may route through instead. */
const SHARED_WRITE_CALLS: ReadonlyArray<string> = Object.freeze([
  "atomicWriteFileSync",
  "atomicWriteText",
  "atomicCreateFileSyncExclusive",
  "writeFrontmatterAtomic",
  "writeFrontmatter",
  // The Brain log's append writer (`src/core/brain/log-append-io.ts`):
  // one append per event to a JSONL shard or its markdown twin.
  "appendSeparated",
]);

/** A dotted call name as a pattern that tolerates spacing around the dot. */
function callPattern(name: string): string {
  return name.split(".").join(String.raw`\s*\.\s*`);
}

/** Longest name first, so a prefix cannot shadow the longer name after it. */
function alternation(names: ReadonlyArray<string>): string {
  return [...names]
    .toSorted((a, b) => b.length - a.length)
    .map(callPattern)
    .join("|");
}

function callRe(names: ReadonlyArray<string>): RegExp {
  return new RegExp(String.raw`\b(${alternation(names)})\s*\(`, "g");
}

/** Member calls on a namespace import, e.g. `fs.writeFileSync(...)`. */
function namespaceCallRe(namespace: string): RegExp {
  return new RegExp(String.raw`\b${namespace}\s*\.\s*(${CONTENT_WRITE_ALTERNATION})\s*\(`, "g");
}

/** The matched call text, with the spacing the source happened to use removed. */
function normalizeCallName(matched: string): string {
  return matched.replace(/\s+/g, "");
}

const CONTENT_WRITE_ALTERNATION = alternation(CONTENT_WRITE_CALLS);
const GLOBAL_WRITE_RE = callRe(GLOBAL_WRITE_CALLS);
const SHARED_WRITE_RE = callRe(SHARED_WRITE_CALLS);

/**
 * Every `node:fs` / `node:fs/promises` import statement, in both binding
 * forms and both quote styles.
 *
 * GLOBAL on purpose. It used to be non-global and read with `.exec()`, so
 * only a module's FIRST `node:fs` statement counted - and the live vault
 * append in `src/core/brain/git/store.ts`, whose `appendFileSync` arrives
 * on the second statement, was invisible to a census that reported a clean
 * sweep. `import type { … }` does not match, because a type cannot be
 * called.
 */
const FS_IMPORT_RE =
  /import\s*(?:\*\s*as\s+([A-Za-z_$][\w$]*)|\{([^}]*)\})\s*from\s*["']node:fs(?:\/promises)?["']/g;

/**
 * Why a direct-`fs` write site does not go through a shared writer.
 * Closed on purpose: a new shape of gap should have to be named, not
 * absorbed into free text.
 */
const WRITE_CATEGORY = Object.freeze({
  /** This module IS a shared writer; the raw call is its implementation. */
  sharedWriterItself: "shared-writer-itself",
  /** Append to a line-oriented ledger. A rewrite would not be an append. */
  appendOnlyLedger: "append-only-ledger",
  /** Move an existing artifact between lifecycle locations; authors no content. */
  lifecycleMove: "lifecycle-move",
  /** Delete an artifact under a retention, reset, or cleanup policy. */
  retentionDelete: "retention-delete",
  /** Machine-readable artifact (JSON, JSONL, sqlite, archive) - never a note. */
  machineArtifact: "machine-artifact",
  /** A lock, marker, or other concurrency primitive. */
  lockPrimitive: "lock-primitive",
  /** Bulk copy of a whole subtree, in or out. */
  archiveTransfer: "archive-transfer",
  /** Permission or metadata change on an existing file; writes no bytes. */
  metadataOnly: "metadata-only",
  /** A file written only to find out whether the location accepts writes, then removed. */
  writeProbe: "write-probe",
  /** Bytes written into a disposable directory shaped like a vault, never an operator's. */
  fixtureMaterialisation: "fixture-materialisation",
} as const);

type WriteCategory = (typeof WRITE_CATEGORY)[keyof typeof WRITE_CATEGORY];

/**
 * The bar an exclusion reason has to clear, matching the one
 * `state-surface-census` already applies to its own exclusion map. An
 * argument for why a write site cannot route through the shared writer
 * does not fit in eighty characters; a label does.
 */
const MIN_REASON_LENGTH = 80;

/** Words that mean "nobody has decided yet", which is not a reason. */
const LAZY_REASON_RE = /\bTODO\b|\bfor now\b|\blater\b/i;

interface WriteExclusion {
  /** Every category this file's direct calls fall in. Never empty. */
  readonly categories: ReadonlyArray<WriteCategory>;
  /** The `node:fs` calls this file makes directly, sorted. */
  readonly calls: ReadonlyArray<string>;
  /** What the categories alone do not say. Never empty. */
  readonly reason: string;
}

const C = WRITE_CATEGORY;

/**
 * Every in-vault write site that reaches `node:fs` directly, with the
 * argument for why it is not behind a shared writer.
 *
 * This is the record the write binding cannot cover. Two entries were
 * removed by this unit rather than written: `core/brain/handoff.ts` now
 * emits its frontmatter through `writeFrontmatterAtomic` instead of
 * hand-rolling the block, and `cli/brain/verbs/links.ts` rewrites notes
 * through `atomicWriteFileSync` instead of truncating them in place.
 */
const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object.freeze({
  // --- The record-lane page store (task 2.10 WP6) ----------------------
  "src/core/store/lane-pages.ts": {
    categories: [C.lifecycleMove, C.retentionDelete],
    calls: ["renameSync", "rmSync"],
    reason:
      "on an unswitched machine the lane page store moves a record-lane page into its archive " +
      "folder and removes a page its lane module retired, exactly as the lane modules did before; " +
      "pages themselves are written through the shared atomic writers, and a store-only machine " +
      "writes lane-entry records instead.",
  },
  // --- The brain store migration (task 2.3) -----------------------------
  "src/core/store-migration/exporters.ts": {
    categories: [C.appendOnlyLedger, C.retentionDelete, C.machineArtifact],
    calls: ["appendFileSync", "rmSync", "writeFileSync"],
    reason:
      "the rollback's legacy exporters write store records back into the legacy layout on purpose: " +
      "signal and record-lane pages, preference pages rewritten from their fold, pinned context, and " +
      "one appended row per log event in this device's own day shard; a page whose fold removed it " +
      "is deleted. They run only under the migration gate during a rollback.",
  },
  "src/core/store-migration/removal.ts": {
    categories: [C.archiveTransfer, C.lifecycleMove],
    calls: ["cpSync", "renameSync", "rmSync"],
    reason:
      "removing the legacy tree moves Brain/ and the derived store folder out of the vault into a " +
      "dated device-local archive by rename, or by copy, verify and remove across filesystems; " +
      "nothing is deleted without a verified archive copy. Its journal naming the archive is a " +
      "device-local file, removed once the removal is recorded.",
  },
  "src/core/store-migration/transition-watermark.ts": {
    categories: [C.machineArtifact],
    calls: ["writeFileSync"],
    reason:
      "the automatic transition import keeps its hourly throttle stamp and its per-file watermark " +
      "of the legacy tree (recorded by the migration and the transition imports at their final " +
      "pass) as two small JSON files in the device-local migration folder; it reads the vault and " +
      "writes nothing into it.",
  },
  "src/core/store-migration/rollback.ts": {
    categories: [C.archiveTransfer, C.appendOnlyLedger, C.machineArtifact],
    calls: ["appendFileSync", "cpSync", "rmSync", "writeFileSync"],
    reason:
      "the rollback replaces Brain/ with the migration snapshot's extracted tree (the snapshot " +
      "folders kept) and keeps its restore state and its per-record replay journal in the " +
      "device-local migration folder.",
  },
  "src/core/store-migration/backup.ts": {
    categories: [C.archiveTransfer, C.machineArtifact, C.retentionDelete],
    calls: ["copyFileSync", "rmSync", "writeFileSync"],
    reason:
      "the migration backup copies the snapshot archive and every backup-class surface OUT of the " +
      "vault into the device-local migration folder, writes its manifest and the unparseable-item " +
      "archive there, and removes the scratch folder of its test restore; it reads the vault and " +
      "never writes into it.",
  },
  "src/core/store-migration/local-state.ts": {
    categories: [C.archiveTransfer, C.machineArtifact],
    calls: ["copyFileSync"],
    reason:
      "the migration copies device-local and backup-class surfaces OUT of the vault into the " +
      "device-local migration folder, and copies accepted skills from the legacy Brain/skills " +
      "tree to the vault's own skills/ folder (files agents read, never store records), each " +
      "copy verified by hash and never over a different file already there.",
  },
  // --- The shared writers themselves ------------------------------------
  "src/core/brain/log-append-io.ts": {
    categories: [C.sharedWriterItself, C.appendOnlyLedger],
    calls: ["ftruncateSync", "truncateSync", "writeSync"],
    reason:
      "this module IS the append writer the Brain log routes through: one write per event on a " +
      "descriptor opened with the append flag, a truncate to drop trailing whitespace an editor " +
      "left, so the shard ends byte-identical to the rewrite it replaced, and a truncate back to " +
      "the old size when a write fails part way.",
  },
  "src/core/fs-atomic.ts": {
    categories: [C.sharedWriterItself],
    calls: ["linkSync", "renameSync", "unlinkSync", "writeSync"],
    reason:
      "this module IS the atomic-write pipeline every other site routes through; " +
      "the raw calls are its implementation of temp-file plus link(2)/rename(2).",
  },
  "src/core/vault.ts": {
    categories: [C.sharedWriterItself],
    calls: ["writeFileSync"],
    reason:
      "`writeFrontmatter`, the deliberately non-atomic sibling of " +
      "`writeFrontmatterAtomic`, used where a torn file on crash is acceptable " +
      "because the target is regenerated on the next run.",
  },

  // --- Append-only ledgers ----------------------------------------------
  "src/core/brain/capture/telegram-capture.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one JSON line per capture-routing decision, appended to the decision log. Every shared " +
      "writer in the set rewrites a whole file, so routing an append through one would have to " +
      "read the log back first - and this log is the only record that a rejected capture arrived " +
      "at all, which is precisely what a read-modify-rewrite race loses.",
  },
  "src/core/brain/continuity/store.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["writeFileSync"],
    reason:
      "`writeFileSync(..., { flag: 'a' })` under the shard lock - an O_APPEND write, " +
      "not a rewrite. Continuity appends are deliberately unfsynced and fail-open so " +
      "telemetry can never fail the operation it observes.",
  },
  "src/core/brain/decisions/receipts.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one receipt JSON line per decision, appended to a per-device shard so two machines syncing " +
      "one vault never write the same file. The append is the commit point: the timeline emission " +
      "after it is fail-soft precisely because the receipt is already durable, and a whole-file " +
      "rewrite would put that ordering the other way round.",
  },
  "src/core/brain/diagnostics.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "the WAL-gap fixer appends the missing terminal phase line to a dream workrun " +
      "log. Additive by contract: the forensic content before the gap is preserved.",
  },
  "src/core/brain/dream-workrun.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "the write-ahead phase log itself. Rewriting it would destroy the very record " +
      "that lets an interrupted run be detected.",
  },
  "src/core/brain/git/store.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one JSON line per ingested commit or tag appended to the per-repo " +
      "`commits.jsonl`, behind `assertVaultIdentityForWrite` and after the dedup pass " +
      "that drops shas already on disk. The `state.json` watermark beside it already " +
      "goes through `atomicWriteFileSync`, because a watermark is a rewrite and a " +
      "record is an append. This entry exists because the detector was fixed: the " +
      "import arrives on the module's SECOND `node:fs` statement, and a non-global " +
      "regex read only the first.",
  },
  "src/core/brain/health/edit-history.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "deduplicated edit-history lines appended to the per-page history log, in one call per " +
      "batch. The dedup runs against what is already on disk, so the file is read before every " +
      "append - and rewriting it from that read is exactly the operation that would drop a line " +
      "another process appended in between.",
  },
  "src/core/brain/idempotency-ledger.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["writeFileSync"],
    reason:
      "`writeFileSync(..., { flag: 'a' })` inside the shard lock: one record line per " +
      "remembered key, appended.",
  },
  "src/core/brain/lineage/ledger.ts": {
    categories: [C.appendOnlyLedger, C.lockPrimitive],
    calls: ["appendFileSync"],
    reason:
      "appends one record line; the COMPACTION arm beside it already uses " +
      "`atomicWriteFileSync`, because rewriting is a different operation from " +
      "appending. The trim lock it proves stale by its own mtime is broken through " +
      "`removeStaleLockSync` in `sync-lockfile.ts`, with exactly one retry.",
  },
  "src/core/brain/freeze.ts": {
    categories: [C.lockPrimitive, C.retentionDelete],
    calls: ["unlinkSync"],
    reason:
      "the freeze marker is a concurrency primitive over the whole vault rather than a " +
      "note: its entire content is its existence, `unfreeze` is the one command that " +
      "removes it, and the `unfreeze` log event records who did so and what the marker " +
      "said. There is nothing for a shared note writer to write.",
  },
  "src/core/brain/maintenance/journal.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync", "renameSync", "writeFileSync"],
    reason:
      "O_APPEND per line so gate-refusal writers - which run BEFORE the lease is " +
      "held - interleave instead of racing a read-modify-rewrite. The tmp-plus-rename " +
      "sweep is the one safe rewrite point and runs only while the lease is held.",
  },
  "src/core/brain/metrics.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one JSON line per surface metrics record, appended to that surface's own JSONL. These are " +
      "observations of runs that already finished and nothing regenerates them, so the file only " +
      "ever grows; a shared writer would turn every measurement into a full rewrite of the " +
      "history it is being added to.",
  },
  "src/core/brain/pref-audit.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one rendered line per preference mutation, appended to that preference's audit. It is the " +
      "provenance behind a rule the agents follow and cannot be reconstructed from the preference " +
      "file it describes, so losing an interleaved line to a rewrite would lose the only copy of " +
      "a promotion, an edit or a retirement.",
  },
  "src/core/brain/query-demand.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one JSON line per query-demand record, appended under the log lock, with the byte-cap " +
      "compaction running inside that same lock immediately afterwards. The append and the " +
      "compaction are deliberately different operations, and the second already goes through " +
      "`atomicWriteFileSync` - a rewrite is a rewrite and an append is not.",
  },
  "src/core/brain/recurrence.ts": {
    categories: [C.appendOnlyLedger],
    calls: ["appendFileSync"],
    reason:
      "one JSON line per recurrence event, appended behind `assertVaultIdentityForWrite` and an " +
      "`ensureInsideVault` on the directory. The support counts a proposal is judged on ARE the " +
      "accumulated lines, so the file is only ever extended; nothing in it is ever revised, and a " +
      "rewrite would be a way to lose evidence rather than a way to save it.",
  },

  // --- Lifecycle moves: an existing artifact changes location ------------
  "src/core/brain/capture/capture-note.ts": {
    categories: [C.lifecycleMove],
    calls: ["renameSync", "rmSync"],
    reason:
      "archives a staged capture into `processed/`. The `rmSync` is the source half of " +
      "the cross-device copy-then-remove fallback taken when `rename(2)` cannot span " +
      "filesystems.",
  },
  "src/core/brain/dream-apply.ts": {
    categories: [C.lifecycleMove],
    calls: ["renameSync"],
    reason:
      "moves every consumed signal out of `inbox/` into its processed location. A rename authors " +
      "no content - the signal file's bytes are the same bytes at a new name - and it is " +
      "deliberately best-effort per signal, because a source already moved by an earlier run is " +
      "benign on a rerun while a real I/O failure is still surfaced.",
  },
  "src/core/brain/intentions.ts": {
    categories: [C.lifecycleMove],
    calls: ["renameSync", "rmSync"],
    reason:
      "archives an active intention into `history/` under a collision-suffixed name, " +
      "with the same cross-device copy-then-remove fallback.",
  },
  "src/core/brain/pending/pending-lanes.ts": {
    categories: [C.lifecycleMove],
    calls: ["unlinkSync"],
    reason:
      "the multi-lane queue's two exits, generalized from the A3 applier: apply " +
      "exclusive-creates the decoded publish target and refuses an occupied name " +
      "BEFORE the unlink, so the record exists twice at that instant and never zero " +
      "times; reject lands the retire-shaped render through `writeFrontmatterAtomic` " +
      "refusing an occupied retired name before the staged copy goes. Its write half " +
      "is the shared writer class (`atomicWriteFileSync`, `atomicCreateFileSyncExclusive`); " +
      "the unlink is the only direct call.",
  },
  "src/core/brain/permissions/ledger.ts": {
    categories: [C.appendOnlyLedger, C.lockPrimitive],
    calls: ["writeFileSync"],
    reason:
      "`writeFileSync(..., { flag: 'a' })` inside the per-shard `proper-lockfile`: one " +
      "decision-ledger row per gate verdict, appended to the device's month shard. " +
      "Append-only on the idempotency-ledger model - nothing is ever rewritten, so " +
      "the shared writer class has no rewrite to route.",
  },
  "src/core/brain/preference.ts": {
    categories: [C.lifecycleMove],
    calls: ["unlinkSync"],
    reason:
      "removes the source only after `writeFrontmatterAtomic` landed the retired copy " +
      "AND its presence on disk was re-confirmed - the retire is a move whose write " +
      "half already goes through the shared writer.",
  },
  "src/core/brain/notes/lifecycle.ts": {
    categories: [C.lifecycleMove, C.retentionDelete],
    calls: ["copyFileSync", "linkSync", "renameSync", "unlinkSync"],
    reason:
      "the note-file rename / move / archive is a relocation whose write half is " +
      "`linkSync` - a second NAME for the source inode, re-confirmed on disk before the " +
      "source name is dropped, which is the signal retire's ordering with the bytes " +
      "never leaving the filesystem. It relinks rather than re-rendering, so a note's " +
      "own prose AND its exact bytes survive whatever their encoding; reading it as " +
      "UTF-8 and writing the string back replaced every unpaired byte with U+FFFD. " +
      "`copyFileSync` with `COPYFILE_EXCL` is the `EXDEV` arm, for a vault with a mount " +
      "point inside it, and has the same two properties that matter: byte-exact and " +
      "refuse-if-present. `renameSync` completes the case-only rename, where the " +
      "destination NAMES the source entry: the inode gets a third, private name, the " +
      "source name goes, and the rename attaches the staged name to the destination - " +
      "so the bytes are reachable under some name at every instant. The second " +
      "`unlinkSync` is the delete, which runs inside `withDestructiveSnapshot` and " +
      "reports a verdict saying the archive it took does not cover a note living " +
      "outside `Brain/`.",
  },
  "src/core/brain/notes/folder-lifecycle.ts": {
    categories: [C.lifecycleMove],
    calls: ["rmdirSync", "unlinkSync"],
    reason:
      "the folder move's per-file relocation rides the file surface's own shared " +
      "helpers, so the module's direct calls are the emptied-directories prune and " +
      "one fault cleanup: `rmdirSync` removes each directory the moves emptied, " +
      "deepest first, and refuses a non-empty directory, so a folder whose subtree " +
      "still holds a failed file keeps it; the one `unlinkSync` drops a destination " +
      "name a mid-set fault linked after the source name's drop had already failed, " +
      "with the source name still holding that inode. No byte is ever reached, and " +
      "the report names where every file stands.",
  },
  "src/core/brain/recompile.ts": {
    categories: [C.lifecycleMove],
    calls: ["copyFileSync", "renameSync", "rmSync", "writeFileSync"],
    reason:
      "moves an orphaned generated page into the cleanup directory under a name proven free by " +
      "the suffix loop immediately above the call, so the move can never overwrite a page already " +
      "parked there. The bytes are the page's own and are unchanged by the move; there is no " +
      "content for a writer to render and nothing to make atomic beyond `rename(2)` itself. " +
      "Across volumes (the device-local snapshots folder of a switched machine) the move is a " +
      "copy, then the source's removal; a page a store-only machine holds as a lane record is " +
      "written out with an exclusive create (`wx`) under the same free name.",
  },
  "src/core/brain/skill-accept-journal.ts": {
    categories: [C.machineArtifact, C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "the skill accept journal and its prior-content copy are device-local repair markers " +
      "(machine state: the vault's Brain/ on an unswitched machine, the device-local state once " +
      "switched), written as plain files so they never become synced lane records; clearing one " +
      "is the end of the transaction it recorded.",
  },
  "src/core/brain/signal-retire.ts": {
    categories: [C.lifecycleMove],
    calls: ["unlinkSync"],
    reason:
      "the signal twin of the preference retire: shared-writer write first, existence " +
      "re-confirmed, then the source unlinked.",
  },
  "src/core/search/store/lifecycle.ts": {
    categories: [C.lifecycleMove, C.retentionDelete],
    calls: ["renameSync", "unlinkSync"],
    reason:
      "restores the parked `.old` (else the `.bak`) sqlite index over a missing database " +
      "after a crashed reindex, re-checked under the lock, and deletes a `.old` a completed " +
      "swap left beside the live index. A database file has no text-writer form.",
  },

  // --- Retention, reset and cleanup deletes ------------------------------
  "src/core/brain/exact-state.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "clears one aspect's exact-state file behind `assertVaultIdentityForWrite`, after the " +
      "aspect name has been validated and the file confirmed to exist. The absence IS the cleared " +
      "state on this lane - there is no empty-file representation to write instead - so no shared " +
      "writer has a form for this operation.",
  },
  "src/core/brain/git/ingest.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "clears the git ingest `state.json` on a rescan that found no head, so the next " +
      "run starts as an initial walk rather than inheriting a stale marker.",
  },
  "src/core/brain/checkpoint-store.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "clears one checkpoint - an ingest plan's or a session import's - behind " +
      "`assertVaultIdentityForWrite`, reporting false rather than throwing when there was nothing " +
      "to clear. Absence is the terminal state for a resume point: a lane with no checkpoint " +
      "starts from the beginning, which is the same thing a checkpoint rewritten to empty would " +
      "have to mean.",
  },
  "src/core/brain/lineage/identity.ts": {
    categories: [C.retentionDelete],
    calls: ["unlinkSync"],
    reason:
      "clears a worktree identity marker, and prunes the oldest markers past the cap. " +
      "A marker's whole content is its existence.",
  },
  "src/core/brain/notes/revert.ts": {
    categories: [C.retentionDelete],
    calls: ["unlinkSync"],
    reason:
      "removes a note the selected writes created, when undoing them means the note should " +
      "not exist at all. There is nothing for a shared writer to author on the way out, and " +
      "the restore half of the same module writes the recorded before-image through " +
      "`atomicWriteFileSync`. The unlink runs inside `withDestructiveSnapshot`, so the " +
      "destructive-site census holds it rather than an exclusion of its own, and the bytes it " +
      "removes are kept as a before-image first, which is what makes the delete revertible.",
  },
  "src/core/brain/payload-inventory.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "removes payload files under `Brain/.payloads/` that nothing in the vault references " +
      "(`o2b brain payload gc --apply`). A removal has no shared-writer form; the rmSync runs " +
      "inside `withDestructiveSnapshot`, which the destructive-site census holds, and the " +
      "plan is re-measured inside that recovery point so a newly referenced payload survives.",
  },
  "src/core/brain/anticipatory-prune.ts": {
    categories: [C.retentionDelete],
    calls: ["unlinkSync"],
    reason:
      "prunes anticipatory cache entries by file age and a count cap. Every entry is a derived " +
      "context pack rebuilt on the next refresh, so there is nothing for a shared writer to " +
      "author on the way out, and the prune marker goes through `atomicWriteFileSync`.",
  },
  "src/core/brain/notes/write-record.ts": {
    categories: [C.retentionDelete],
    calls: ["unlinkSync"],
    reason:
      "prunes note-write before-images past a retention window read from each file's own mtime, " +
      "and keeps any image whose age cannot be measured. The store is content-addressed, so a " +
      "file's NAME is the digest of its bytes: there is nothing for a shared writer to author on " +
      "the way out, and the write half of the same module already goes through " +
      "`atomicWriteFileSync`.",
  },
  "src/core/brain/source-cleanup.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason: "deletes pages belonging to a removed source, each re-checked by `ensureInsideVault`.",
  },
  "src/core/brain/portability/knowledge-pack.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "`knowledge-pack uninstall --confirm` removes the entries one pack stamped, each " +
      "re-checked by `ensureInsideVault`, inside the destructive-snapshot gate.",
  },
  "src/core/brain/watchdog.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "under `--remediate --apply` only: removes a non-directory occupying a path the " +
      "tree requires to be a directory, immediately before creating it.",
  },
  "src/core/search/tuning-store.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "deletes the persisted tuning state, which returns search to the shipped defaults until the " +
      "next tuning run. Absence is the reset state by design: the reader re-validates whatever it " +
      "finds against the parameter grid, so writing a neutral document instead would be a claim " +
      "that a tuning run had happened and chosen it.",
  },
  "src/mcp/artifact-store.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "prunes preview-artifact directories past their TTL. Directory removal has no " +
      "shared-writer form.",
  },

  // --- Machine-readable artifacts: JSON, sqlite, archives ----------------
  "src/cli/brain/verbs/export.ts": {
    categories: [C.machineArtifact],
    calls: ["renameSync", "unlinkSync", "writeSync"],
    reason:
      "`o2b brain export --format transcripts-jsonl` spools the corpus record by " +
      "record to a temp sibling of the operator-named `--out` and renames it into " +
      "place, so peak memory is one conversation rather than the whole corpus and a " +
      "guard refusal still leaves nothing written. `atomicWriteFileSync` cannot serve " +
      "it: that helper takes the complete contents as a string, which is precisely " +
      "the materialisation being avoided. The `unlinkSync` removes the spool on a " +
      "refusal and after a stdout run. Never a vault note - the source is the " +
      "runtimes' own session directories and the target is a path the operator named.",
  },
  "src/cli/brain/verbs/continuity.ts": {
    categories: [C.machineArtifact],
    calls: ["writeFileSync"],
    reason:
      "`o2b brain continuity export` writes JSONL/JSON export files into an " +
      "operator-named output directory, not vault notes.",
  },
  "src/cli/main.ts": {
    categories: [C.machineArtifact],
    calls: ["writeFileSync"],
    reason:
      "`o2b config export --output` writes a redacted machine-config snapshot to an " +
      "operator-named path. In population only because the module imports the vault " +
      "path vocabulary elsewhere; this write never targets the vault.",
  },
  "src/core/brain/portability/pointer.ts": {
    categories: [C.machineArtifact],
    calls: ["rmSync"],
    reason:
      "the project-side pointer NAMING a vault lives outside that vault " +
      "(`assertNotInsideVault`); removing it is not an in-vault write at all.",
  },
  "src/core/brain/secrets/crypto.ts": {
    categories: [C.machineArtifact],
    calls: ["chmodSync", "writeFileSync", "writeSync"],
    reason:
      "writes key bytes into a descriptor opened `wx` at mode 0600. The exclusivity " +
      "and the mode are the point, and no shared writer takes a mode. The two additions " +
      "serve the same custody boundary: `chmodSync` re-applies the owner-only modes on " +
      "load (the POSIX mirror of the Windows ACL re-application, for a keyfile that " +
      "arrived with a copied or restored vault), and `writeFileSync` plants the " +
      "`.gitignore` that keeps the keyfile and the ciphertext out of a vault commit " +
      "(a Syncthing peer reads only its own .stignore) - both machine-artifact writes inside the same state dir, " +
      "best-effort and warned when they fail.",
  },
  "src/core/brain/secrets/store.ts": {
    categories: [C.machineArtifact],
    calls: ["chmodSync", "renameSync", "rmSync", "writeFileSync"],
    reason:
      "hand-rolled tmp-plus-rename because it must write at mode 0600, which " +
      "`atomicWriteFileSync` cannot express. Routing it through the shared writer " +
      "would leave the secrets file world-readable for the length of the swap. " +
      "`chmodSync` re-applies that 0600 on load to a store that arrived with a copied " +
      "or restored vault, the same custody repair the keyfile beside it gets. " +
      "`rmSync` drops this process's own staging folder of the vault-secrets " +
      "adoption (`<secrets dir>.adopt-<pid>`, in the device-local state), which is " +
      "copied whole and renamed into place so the secrets folder appears complete or not at all.",
  },
  "src/core/brain/secrets/token-store.ts": {
    categories: [C.machineArtifact],
    calls: ["renameSync", "writeFileSync"],
    reason:
      "hand-rolled tmp-plus-rename for the same reason its sibling store uses one: " +
      "the mcp-tokens.json swap must land at mode 0600 at CREATION, which " +
      "`atomicWriteFileSync` cannot express, and routing it through the shared " +
      "writer would leave the hash-at-rest store world-readable for the length of " +
      "the swap. The write also drops the module's own mtime-cache entry - the " +
      "invalidation that lets a CLI-side rotation reach a running server on its " +
      "next resolve - which no shared writer knows to do.",
  },
  "src/core/brain/secrets/envelope.ts": {
    categories: [C.machineArtifact],
    calls: ["chmodSync", "renameSync", "unlinkSync", "writeSync"],
    reason:
      "restores the raw keyfile bytes when the written envelope fails its read-back " +
      "unwrap: a partial-write-safe `writeSync` loop into a tmp file renamed over " +
      "the only copy of the key at 0600 - custody bytes the shared writer must not " +
      "own (the envelope write itself now routes through the shared atomic writer). " +
      "The unlink clears the tmp when the rename is refused; `chmodSync` " +
      "re-asserts the 0600 on the envelope the keyfile it replaced carried.",
  },
  "src/core/brain/truth/store.ts": {
    categories: [C.appendOnlyLedger, C.machineArtifact, C.retentionDelete],
    calls: ["appendFileSync", "rmSync", "writeFileSync"],
    reason:
      "appends one claim event per line, rewrites the DERIVED state JSON in full, and " +
      "compacts shards by rewriting or removing them.",
  },
  "src/core/search/activation/store.ts": {
    categories: [C.machineArtifact, C.retentionDelete],
    calls: ["rmSync", "writeFileSync"],
    reason:
      "one content-addressed JSON file per access event, the derived activation state " +
      "beside it, and a retention sweep over the events.",
  },
  "src/core/search/embeddings/registry.ts": {
    categories: [C.machineArtifact],
    calls: ["writeFileSync"],
    reason: "rewrites the embedding-provider registry JSON in full, name-sorted for determinism.",
  },
  "src/core/search/feedback.ts": {
    categories: [C.machineArtifact, C.retentionDelete],
    calls: ["rmSync", "writeFileSync"],
    reason:
      "one content-addressed JSON file per recall-feedback event, the derived learned " +
      "weights beside it, and the reset that removes them.",
  },
  "src/core/search/indexer.ts": {
    categories: [C.machineArtifact, C.lifecycleMove],
    calls: ["renameSync", "unlinkSync"],
    reason:
      "swaps a freshly built sqlite index into place under the index lock, keeping the " +
      "previous file as `.bak`. A database is not text and has no shared-writer form.",
  },
  "src/core/search/link-ratchet.ts": {
    categories: [C.archiveTransfer],
    calls: ["cpSync", "rmSync"],
    reason:
      "copies the subject vault into a `mkdtemp` workdir to measure it, then removes " +
      "the workdir. Nothing is written into the vault at all.",
  },
  "src/core/search/reinforce.ts": {
    categories: [C.machineArtifact, C.retentionDelete],
    calls: ["rmSync", "writeFileSync"],
    reason:
      "one content-addressed JSON file per reinforcement event, plus the sweep that " +
      "clears the directory.",
  },
  "src/core/search/rerank/registry.ts": {
    categories: [C.machineArtifact],
    calls: ["writeFileSync"],
    reason: "rewrites the rerank-provider registry JSON in full, name-sorted for determinism.",
  },
  "src/core/search/session-focus.ts": {
    categories: [C.retentionDelete],
    calls: ["rmSync"],
    reason:
      "the call that clears the per-session focus JSON (the write itself goes through the shared " +
      "atomic text writer). Each entry expires on its own and is rewritten whole by the next `focus` call, so a " +
      "torn file costs one session's standing query and is replaced rather than repaired; the " +
      "clear removes the file because an empty focus and no focus are the same state.",
  },
  "src/core/search/tuning.ts": {
    categories: [C.machineArtifact],
    calls: ["writeFileSync"],
    reason:
      "persists the tuning result JSON, keyed by a hash of the dataset it came from, so a result " +
      "is only ever read back against the same inputs that produced it. A partial file fails that " +
      "key check and is treated as no result at all, which is the same outcome as never having " +
      "run the tuning pass - the cost of a torn write is one re-run.",
  },

  // --- Bulk subtree transfer ---------------------------------------------
  "src/core/brain/init.ts": {
    categories: [C.archiveTransfer],
    calls: ["cpSync", "renameSync"],
    reason:
      "one recursive copy per bootstrap subdirectory into a destination the pre-check " +
      "already proved empty. This is also the path that CREATES the tree, so it can " +
      "not be gated on anything the tree is about to contain. The rename re-dates the " +
      "starter bundle's own log filenames immediately after that copy, inside the same " +
      "proven-empty destination.",
  },
  "src/core/brain/snapshot.ts": {
    categories: [C.archiveTransfer, C.retentionDelete],
    calls: [
      "cpSync",
      "linkSync",
      "renameSync",
      "rmSync",
      "unlinkSync",
      "writeFileSync",
      "writeSync",
    ],
    reason:
      "writes the compressed archive BYTES into `.snapshots/`, prunes archives past " +
      "the retention count, and restores by recursive copy. A torn archive fails on " +
      "restore exactly as any interrupted snapshot does; no Markdown parser reads it. " +
      "The derived-store restore adds the rename pair: it stages the decompressed " +
      "database beside its destination and swaps it in under the search writer lock, " +
      "which IS the atomic write for a SQLite file - the same discipline `reindexVault` " +
      "uses, and the reason a partial decompression can never be observed as the live " +
      "store. The unlink removes a partial store archive whose snapshot was refused. " +
      "The gzip fallback writes the archive one compressed member at a time (`writeSync` " +
      "on a descriptor opened `wx`) so a Brain tree of any size never sits in memory. " +
      "Both compressors write a partial name, and the archive is published under its " +
      "final name by an exclusive hard link (`linkSync`, or a checked rename where the " +
      "filesystem has no links), so a killed compression never leaves a torn archive.",
  },
  "src/core/maintenance/self-heal-upgrade-state.ts": {
    categories: [C.lockPrimitive, C.retentionDelete],
    calls: ["unlinkSync", "writeFileSync"],
    reason:
      "the automatic-upgrade worker lock is an exclusive create (`wx`) of a token file in " +
      "`.open-second-brain/`, released by unlinking it; routing it through the atomic " +
      "writer would lose the exclusivity that makes it a lock. The failed-upgrade marker is " +
      "written through `atomicWriteFileSync` and unlinked once nothing is pending, which is " +
      "this tool's own per-device state, never a note.",
  },

  "src/core/search/freshen.ts": {
    categories: [C.lockPrimitive, C.retentionDelete],
    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 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.",
  },

  "src/core/state/machine-state.ts": {
    categories: [C.archiveTransfer, C.machineArtifact],
    calls: ["cpSync", "writeFileSync"],
    reason:
      "Resolves where this machine's state lives, and on a store-only machine writes only " +
      "device-local state outside the vault: the one-time restore of the migration backup " +
      "(`cpSync` of each backed-up file that has no live copy) and the marker that records it. " +
      "Its one join onto the vault reads the `.open-second-brain/` an older release kept in a " +
      "bare vault, copied once into the device-local root by `state-moves.ts`; the vault is " +
      "never written. Neither is a note, so the shared note writer has nothing to stamp.",
  },

  "src/core/state/migrate.ts": {
    categories: [C.archiveTransfer, C.lifecycleMove, C.retentionDelete],
    calls: ["copyFileSync", "rmSync", "rmdirSync"],
    reason:
      "`o2b state migrate` moves the whole declared state tree to another filesystem, which is " +
      "the one operation here that a shared writer would make WORSE rather than safer. Each file " +
      "is copied byte-for-byte and re-digested at the destination against the digest the plan " +
      "bound, so a torn copy is caught by the hash and unwound; `atomicWriteFileSync` takes a " +
      "complete string, which for a multi-gigabyte SQLite index is the materialisation being " +
      "avoided, and it would re-encode bytes this pass must not touch. The `rmSync` removes each " +
      "source only after every copy landed AND verified, and removes the destination copies again " +
      "on the unwind - the same file list, in reverse. `rmdirSync` prunes only directories " +
      "`pruneIfEmpty` proved empty, so nothing that arrived beside the migration is ever removed. " +
      "The manifest that binds all of it DOES go through `atomicWriteFileSync`, because that one " +
      "is a rewrite of a small document and is the record a rollback reads.",
  },

  // --- Concurrency primitives --------------------------------------------
  "src/core/brain/sync-lockfile.ts": {
    categories: [C.lockPrimitive],
    calls: ["unlinkSync", "writeSync"],
    reason:
      "the lock itself. Its semantics come from the exclusive create; the body it " +
      "writes is a diagnostic pid/timestamp stamp whose failure is deliberately " +
      "non-fatal, and the unlink is the release (only of a lock file its holder still " +
      "owns) or the removal of an abandoned lock by the one contender whose exclusive " +
      "takeover claim on that file won.",
  },

  "src/core/search/store/writer-lock.ts": {
    categories: [C.lockPrimitive],
    calls: ["rmdirSync", "utimesSync"],
    reason:
      "the search index writer lock itself, an empty `<dbPath>.lock` directory. Its " +
      "semantics come from the exclusive `mkdir`; `utimesSync` is the heartbeat that " +
      "stamps the directory's mtime, and `rmdirSync` is the release (only of a lock whose " +
      "mtime and inode are still this holder's) or the removal of a lock past its stale " +
      "window by the contender about to re-create it. No file bytes are written.",
  },

  // --- Metadata only -----------------------------------------------------
  "src/core/brain/health/remediation.ts": {
    categories: [C.metadataOnly],
    calls: ["chmodSync"],
    reason:
      "narrows non-owner permission bits on an existing file or directory. No bytes " +
      "are written, so there is nothing for a writer to make atomic.",
  },
  "src/core/brain/payload-registry.ts": {
    categories: [C.metadataOnly],
    calls: ["utimesSync"],
    reason:
      "touches a content-addressed payload that a new row is about to reference again, so the " +
      "gc's grace period restarts for it. No bytes are written; the payload itself is written " +
      "through `atomicWriteFileSync` in the same `put()`.",
  },

  // --- Write probes: bytes written to learn whether writing works --------
  "src/core/doctor.ts": {
    categories: [C.writeProbe],
    calls: ["rmSync", "writeSync"],
    reason:
      "`checkVaultWriteable` opens `<vault>/.open-second-brain-doctor-test` and removes it again, " +
      "and `checkConfigWriteable` does the same to the config path, creating it only if it was " +
      "absent. The QUESTION is whether the open and the write succeed, so routing them through a " +
      "helper that reports success or throws would answer a different question - and the answer " +
      "the doctor gives is the raw errno, which is what the fix line it prints is derived from. " +
      "Zero bytes are written and the probe never outlives the check.",
  },

  // --- Fixture materialisation: a vault-shaped disposable directory ------
  "src/core/doctor-selftest.ts": {
    categories: [C.fixtureMaterialisation, C.retentionDelete],
    calls: ["rmSync", "writeFileSync"],
    reason:
      "drives the doctor self-test against a THROWAWAY store: the writes seed and journal a " +
      "scratch vault the harness creates under the system temp dir, and the rmSync removes that " +
      "same tree when the run ends, on success and on failure alike. Nothing is written beside " +
      "the operator's vault, so there is no durability guarantee for an atomic writer to add.",
  },
  "src/core/bench/fixture.ts": {
    categories: [C.fixtureMaterialisation],
    calls: ["writeFileSync"],
    reason:
      "materialises a repo-local benchmark fixture into the caller-supplied disposable directory, " +
      "whose note paths were checked against traversal and absolute forms at parse time. It is in " +
      "population because it joins `Brain/` onto a directory it calls a vault, which is exactly " +
      "the shape the widened rule is meant to catch; what it writes is fixture text into a tree " +
      "the bench harness creates and deletes, never an operator's vault, so there is no " +
      "durability guarantee for an atomic writer to add.",
  },

  // --- Mixed: an accept protocol that moves, appends and rolls back ------
  "src/core/brain/skill-proposals.ts": {
    categories: [C.appendOnlyLedger, C.retentionDelete],
    calls: ["appendFileSync", "rmdirSync"],
    reason:
      "appends one JSON line per verifier rejection on an unswitched machine (a store-only " +
      "machine writes the ledger row instead); and, when a journalled `mature_page` accept is " +
      "rolled back, removes the now-empty skill directory with `rmdirSync`, which refuses a " +
      "non-empty directory, so the empty shell goes and a directory holding anything else " +
      "stays. The page moves and removals go through the lane page store.",
  },
});

interface CensusFile {
  readonly path: string;
  readonly text: string;
}

interface CensusRow {
  readonly path: string;
  /** Direct `node:fs` content-write calls this file makes, sorted, deduped. */
  readonly directCalls: ReadonlyArray<string>;
  /** How many shared-writer calls it makes. */
  readonly sharedCalls: number;
}

/** Every `.ts` file under `src/`, as path + text. */
function readSourceTree(): CensusFile[] {
  const files: CensusFile[] = [];
  const walk = (dir: string): void => {
    for (const entry of readdirSync(dir, { withFileTypes: true })) {
      const abs = join(dir, entry.name);
      if (entry.isDirectory()) walk(abs);
      else if (entry.name.endsWith(".ts")) {
        files.push({
          path: relative(REPO_ROOT, abs).split("\\").join("/"),
          text: readFileSync(abs, "utf8"),
        });
      }
    }
  };
  walk(SRC_ROOT);
  files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
  return files;
}

/**
 * Whether this module can address the vault - see the docblock.
 *
 * Both views, and which clause reads which is not interchangeable. The
 * import specifier and the store-directory literal ARE strings, so they
 * are read off `withoutComments`; the other view blanks a literal's body
 * and no module would ever be found to import `paths.ts` again. The
 * `join(vault` clause is read off `code`, because a name inside a quoted
 * example builds no path.
 */
function addressesVault(path: string, views: LexedSource): boolean {
  if (VAULT_WRITE_ROOTS.some((root) => path.startsWith(root))) return true;
  if (VAULT_WRITER_FILES.includes(path)) return true;
  if (VAULT_VOCABULARY_IMPORT_RE.test(views.withoutComments)) return true;
  if (DERIVED_STORE_LITERAL_RE.test(views.withoutComments)) return true;
  return VAULT_ROOT_JOIN_RE.test(views.code);
}

interface FsImports {
  /**
   * Local binding -> the `node:fs` name it was imported under. The two
   * differ under `import { writeFileSync as put }`, and matching on the
   * LOCAL name is what makes the renamed form countable at all.
   */
  readonly bindings: ReadonlyMap<string, string>;
  /** Local names of namespace imports, e.g. `fs` in `import * as fs`. */
  readonly namespaces: ReadonlySet<string>;
}

/**
 * `renameWithRetry` from `src/core/fs-atomic.ts` is `renameSync` retried
 * through transient Windows sharing violations: the same lifecycle move,
 * so it is counted under the `node:fs` name it wraps. `unlinkWithRetry`
 * is `unlinkSync` under the same retry.
 */
const FS_WRAPPER_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*["'][^"']*\/fs-atomic(?:\.ts)?["']/g;
const FS_WRAPPER_ALIASES: ReadonlyMap<string, string> = new Map([
  ["renameWithRetry", "renameSync"],
  ["unlinkWithRetry", "unlinkSync"],
]);

/** What this module actually imported from `node:fs` / `node:fs/promises`. */
function fsImports(text: string): FsImports {
  const bindings = new Map<string, string>();
  const namespaces = new Set<string>();
  for (const match of text.matchAll(FS_IMPORT_RE)) {
    const namespace = match[1];
    if (namespace !== undefined) {
      namespaces.add(namespace);
      continue;
    }
    for (const raw of match[2]!.split(",")) {
      const [imported, local] = raw
        .trim()
        .split(/\s+as\s+/)
        .map((part) => part.trim());
      if (imported === undefined || imported.length === 0) continue;
      bindings.set(local !== undefined && local.length > 0 ? local : imported, imported);
    }
  }
  for (const match of text.matchAll(FS_WRAPPER_IMPORT_RE)) {
    for (const raw of match[1]!.split(",")) {
      const [imported, local] = raw
        .trim()
        .split(/\s+as\s+/)
        .map((part) => part.trim());
      const alias = imported === undefined ? undefined : FS_WRAPPER_ALIASES.get(imported);
      if (alias === undefined) continue;
      bindings.set(local !== undefined && local.length > 0 ? local : imported!, alias);
    }
  }
  return { bindings, namespaces };
}

/** The `node:fs` write calls this module makes directly, by their fs name. */
function directWriteCalls(text: string, imported: FsImports): Set<string> {
  const direct = new Set<string>();
  const locals = [...imported.bindings.keys()];
  if (locals.length > 0) {
    for (const match of text.matchAll(callRe(locals))) {
      const name = imported.bindings.get(normalizeCallName(match[1]!));
      if (name !== undefined && CONTENT_WRITE_SET.has(name)) direct.add(name);
    }
  }
  for (const namespace of imported.namespaces) {
    for (const match of text.matchAll(namespaceCallRe(namespace))) {
      direct.add(normalizeCallName(match[1]!));
    }
  }
  for (const match of text.matchAll(GLOBAL_WRITE_RE)) {
    direct.add(normalizeCallName(match[1]!));
  }
  return direct;
}

/**
 * One lex per module, kept, because the fixtures below re-run the whole
 * tree once per intruder shape and lexing is the expensive step. Keyed by
 * path and re-checked against the text, so a synthetic module reusing a
 * real path cannot read a stale view.
 */
const LEXED = new Map<string, { readonly text: string; readonly views: LexedSource }>();

function lexedViews(file: CensusFile): LexedSource {
  const cached = LEXED.get(file.path);
  if (cached !== undefined && cached.text === file.text) return cached.views;
  const views = lexSource(file.text);
  LEXED.set(file.path, { text: file.text, views });
  return views;
}

/**
 * Classify one file into its direct and shared write sites.
 *
 * The two views are not interchangeable and the census dies quietly if
 * they are swapped: imports are read off {@link LexedSource.withoutComments}
 * because a specifier is a string, and calls off
 * {@link LexedSource.code} because a `writeFileSync(` inside a quoted
 * example is not a call. Routing the import read through `code` was
 * measured to drop this census from 64 direct rows to zero with an EMPTY
 * failure list - a clean sweep over nothing, which is the reading this
 * file exists to remove. `the specifier view is the one imports are read
 * from` below pins that.
 */
function classify(file: CensusFile): CensusRow | null {
  const views = lexedViews(file);
  if (!addressesVault(file.path, views)) return null;
  const direct = directWriteCalls(views.code, fsImports(views.withoutComments));
  const shared = [...views.code.matchAll(SHARED_WRITE_RE)].length;
  if (direct.size === 0 && shared === 0) return null;
  return { path: file.path, directCalls: [...direct].toSorted(), sharedCalls: shared };
}

function census(files: ReadonlyArray<CensusFile>): CensusRow[] {
  const rows: CensusRow[] = [];
  for (const file of files) {
    const row = classify(file);
    if (row !== null) rows.push(row);
  }
  return rows;
}

const SOURCE_TREE = readSourceTree();
const ROWS = census(SOURCE_TREE);
const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);

/**
 * Measured modules calling a filesystem write directly. An equality.
 *
 * 65 -> 68, and every one of the three is a module the old population
 * rule could not see rather than a write site that appeared: the widened
 * rule enrolled `src/core/state/migrate.ts` (the state-tree move),
 * `src/core/doctor.ts` (the vault and config write probes) and
 * `src/core/bench/fixture.ts` (fixture materialisation into a
 * vault-shaped disposable directory). Each is now carrying a written
 * exclusion above.
 *
 * 68 -> 69: `src/core/brain/notes/write-record.ts` prunes before-images
 * past their retention window; its write half routes through
 * `atomicWriteFileSync`, so only the unlink is a direct call.
 *
 * 70 -> 71: `src/core/brain/notes/revert.ts` unlinks the note a reverted
 * create brought into existence; its restore half writes the recorded
 * before-image through `atomicWriteFileSync`.
 *
 * 71 -> 72: `src/core/brain/portability/knowledge-pack.ts` removes the
 * entries one pack stamped (`knowledge-pack uninstall --confirm`); its
 * install half writes through the OKF import and the preference txn.
 *
 * 72 -> 73: `src/core/brain/payload-inventory.ts` removes unreferenced
 * payload files for `o2b brain payload gc --apply`, inside the
 * destructive gate.
 *
 * 73 -> 74: `src/core/brain/payload-registry.ts` touches a payload that
 * is about to be referenced again (`utimesSync`), restarting the gc grace
 * period; metadata only.
 *
 * 74 -> 75: `src/core/maintenance/self-heal-upgrade-state.ts` claims and
 * releases the automatic-upgrade worker lock (an exclusive create) and
 * removes the failed-upgrade marker once nothing is pending.
 * 75 -> 76: the doctor self-test seeds and journals a throwaway store in
 * temp storage and removes the tree when the run ends.
 * 76 -> 77: `src/core/search/freshen.ts` claims and releases the
 * freshen-on-read claim (an exclusive create) in `.open-second-brain/`.
 *
 * 77 -> 78: `src/core/brain/secrets/envelope.ts` replaces the raw keyfile
 * with the passphrase-wrapped envelope (tmp-plus-rename at 0600), the
 * custody-boundary twin of the store and keyfile rows beside it.
 *
 * 78 -> 79: `src/core/brain/secrets/token-store.ts` writes the per-agent
 * MCP token store (tmp-plus-rename at 0600), the third custody row.
 *
 * 79 -> 80: the note-lane owner-frontmatter guard (write-side-trust Task 13)
 * gives `src/core/brain/notes/create-note.ts` a direct-fs write site for the
 * decision-ledger warn row.
 *
 * 80 -> 81: the intake's stage disposition
 * (`src/core/brain/intake/extract-intake.ts`) moves each created entity
 * page into the review queue - stage, then unlink the canonical copy. A
 * lifecycle move authors no content; the unlink is the site's only
 * direct call.
 *
 * 81 -> 82: the source archive (`src/core/brain/provenance/
 * source-archive.ts`) discards an entry whose last citing page a
 * confirmed delete-by-source removed - an evidence-store prune whose
 * only direct call is the rmSync; its write half routes through the
 * shared atomic writer.
 *
 * 82 -> 83: the entity page-merge (`src/core/brain/entities/page-merge.ts`)
 * archives the dropped entity page inside `withDestructiveSnapshot` - a
 * retention delete whose every rewrite in the same block routes through
 * the shared frontmatter writer.
 *
 * 83 -> 84: the pledge family's remove archives its page
 * (`src/core/brain/pledges.ts`) - the obligations move one family over,
 * `renameWithRetry` read as its renameSync shape plus the fallback rmSync;
 * every byte it writes routes through the shared writers.
 *
 * 84 -> 85: the pledge intake's mid-batch rollback
 * (`src/core/brain/pledge-intake.ts`) - one rmSync that resets the vault to
 * the pre-intake state, its re-anchor rewrite still on the shared writer.
 *
 * 86 -> 87: the anticipatory cache prune
 * (`src/core/brain/anticipatory-prune.ts`) - a retention delete by age and
 * count whose marker write routes through the shared atomic writer.
 *
 * 87 -> 88: the Brain log's append writer
 * (`src/core/brain/log-append-io.ts`) - the log appender stopped
 * rewriting each day shard through the atomic writer and appends one
 * event per write instead; the raw calls are that writer's implementation.
 *
 * 88 -> 89: the brain store migration backup
 * (`src/core/store-migration/backup.ts`) - it copies the snapshot and the
 * backup-class surfaces out of the vault into device-local state.
 *
 * 89 -> 93: the transition, removal and rollback of the store migration
 * (`src/core/store-migration/{auto-transition,exporters,removal,rollback}.ts`).
 *
 * 93 -> 94: the lane page store (`src/core/store/lane-pages.ts`) moves and
 * removes record-lane pages on an unswitched machine.
 * 94 -> 90: the record-lane modules (dead-ends, obligations, pledges,
 * pledge-intake) write through the lane page store (task 2.10 WP6).
 * 90 -> 89: write sessions too.
 * 89 -> 88: gap tasks too.
 * 88 -> 86: entities (registry, label hygiene, page merge) and derived artifacts write through the lane page store (task 2.10 WP6).
 * 86 -> 84: procedural memory, skill proposals, the accept journal and extract-intake write through the lane page store (task 2.10 WP6).
 * 84 -> 81: attention flows, clusters, co-occurrence, hallways, dream bundles and architect notes write through the lane page store (task 2.10 WP6).
 * 81 -> 79: foresight, cluster and bridge verbs, bridge proposals and the source, report and distillation pages write through the lane page store (task 2.10 WP6).
 * 79 -> 78: source archives, the review-queue lanes, source cleanup and OKF import write through the lane page store (task 2.10 WP6).
 * 78 -> 79: the migration places accepted skills from Brain/skills in the vault's skills/ folder as files (task 2.10).
 * 79 -> 80: the skill accept journal writes its repair markers as machine-state files, not lane records.
 * 80 -> 81: machine-state reads a bare vault's own `.open-second-brain/` to seed the device-local state (device-local writes only).
 * 81 -> 82: the search index writer lock is taken, refreshed and released by its own module instead of `proper-lockfile`, to check ownership.
 */
const DIRECT_WRITE_ROWS = 82;

/**
 * Measured modules reaching a write through a shared helper. An equality.
 *
 * 95 -> 97, from the same widening and nothing else:
 * `src/core/install/manifest.ts` writes `<vault>/.open-second-brain/
 * install.lock.json` through `atomicWriteFileSync` and was out of
 * population entirely, and `src/core/state/migrate.ts` writes the
 * migration manifest through the same helper. The shared class is the
 * half of this census that needs no exclusion, so a module arriving here
 * is the outcome the record wants.
 *
 * 97 -> 98: `src/core/brain/expiration-set.ts`, the post-creation
 * expiration mutation, rewrites a signal's or preference's frontmatter
 * through `writeFrontmatterAtomic` - a new module in the shared class,
 * which is where a new writer belongs.
 *
 * 98 -> 99: `src/core/brain/design-note.ts` commits its note through
 * `writeFrontmatterAtomic`, exclusively, so it needs no exclusion either -
 * it arrives in the class the record wants modules to arrive in.
 *
 * 99 -> 100: `src/core/brain/dead-letter.ts` writes one record per failed
 * multi-artifact commit through `atomicWriteFileSync`, and removes
 * nothing - deleting the only evidence of a partial write is exactly what
 * that module declines to do - so it too arrives with no exclusion owed.
 *
 * 100 -> 101: `src/core/brain/notes/write-record.ts` writes each note
 * before-image through `atomicWriteFileSync`. It is in BOTH classes, not
 * only this one - the retention prune it also owns unlinks directly - so
 * it is the rare module that arrives in the shared class and still owes
 * a written exclusion for the other half.
 *
 * 102 -> 103: `src/core/brain/notes/revert.ts` restores a before-image
 * through `atomicWriteFileSync` and, like the record module beside it,
 * sits in both classes - the delete arm unlinks directly and carries its
 * own written exclusion.
 *
 * Attribution note: `src/core/brain/payload-registry.ts` holds one of
 * these sites (the `atomicWriteFileSync` in `put()`, which externalizes an
 * oversized payload into `Brain/.payloads/`). `src/core/brain/packs/pack.ts`
 * holds none - it only builds a preview. A test-audit pass once deleted
 * both and blamed the 103 -> 102 move on pack.ts; the move was the
 * registry's, and restoring both put the count back at 103.
 *
 * 103 -> 104: `src/core/brain/portability/knowledge-pack.ts` records each
 * staged page's install fingerprint through `atomicWriteFileSync`. Its
 * uninstall removal keeps its direct-class exclusion.
 *
 * 104 -> 105: `src/core/maintenance/self-heal-upgrade-state.ts` writes the
 * failed-upgrade marker through `atomicWriteFileSync`; its lock and marker
 * removal are direct and carry their own exclusion.
 *
 * 105 -> 106: `src/core/brain/dedup-index-cache.ts` persists the
 * machine-local dedup index cache through `atomicWriteFileSync`, outside
 * the vault (issue #195).
 *
 * 106 -> 107: `src/core/brain/link-graph/orphan-repair.ts` detaches a
 * signal's `session_ref` through `writeFrontmatterAtomic`.
 * 107 -> 108: `src/core/brain/link-graph/repair-lane.ts` stages hub
 * candidates through the shared atomic JSONL writer.
 * 108 -> 109: `src/core/search/session-focus.ts` writes the focus through
 * `atomicWriteText` (mode 0600, a leaf link is replaced, not followed).
 *
 * 109 -> 110: `src/core/search/freshen.ts` writes the freshen-on-read state
 * file through `atomicWriteFileSync`.
 *
 * 110 -> 111: `src/core/brain/lifecycle/correction.ts` retires the corrected
 * record through `writeFrontmatterAtomic`.
 *
 * 111 -> 112: `src/cli/brain/verbs/secret.ts` writes the exported
 * credential bundle to the operator-named `--out` through
 * `atomicWriteFileSync` (an egress destination, not a vault note).
 *
 * 112 -> 113: `src/cli/bootstrap/receipt.ts` writes the bootstrap receipt
 * through `atomicWriteFileSync` (custody state, not a vault note).
 *
 * 113 -> 114: the decision ledger appends its month/device JSONL shard
 * through the shared atomic writer (write-side-trust Task 2).
 *
 * 114 -> 115: `src/core/brain/secrets/envelope.ts` writes the unwrapped
 * envelope through `atomicWriteText` at 0600 (the unwrap round-trip gained a
 * second-process path), moving it into BOTH classes - the raw-keyfile
 * restore beside it stays direct and keeps its exclusion.
 *
 * 115 -> 117, from the recall-quality wave and nothing else: the shared
 * derived-artifact IO helper (`src/core/brain/derived-artifact.ts`) writes
 * its schema-stamped artifacts through `atomicWriteFileSync`, and the
 * hallways pass (`src/core/brain/link-graph/hallways.ts`) writes
 * `Brain/link-graph/hallways.json` and its dismissal keys through the
 * same helper class.
 *
 * 117 -> 119, from the answer-trust wave and nothing else: the source
 * archive (`src/core/brain/provenance/source-archive.ts`) persists its
 * redacted entries through `atomicWriteFileSync`, and `src/core/config.ts`
 * joins the population through its new `path-constants.ts` import (the
 * quote_check resolvers) carrying the config write it already made
 * through the same shared writer.
 *
 * 119 -> 120, from the storage-lifecycle wave and nothing else: the
 * receipt fold engine (`src/core/brain/receipts/compact.ts`) rewrites
 * each folded receipt-ledger shard through `atomicWriteFileSync` with
 * the `expectBefore` compare-and-swap, under the shard's own lock - a
 * machine JSONL rewrite that carries no note content, so it arrives in
 * the shared class needing no exclusion.
 *
 * 120 -> 121, from the session-mining-economy wave and nothing else: the
 * session mining ledger (`src/core/brain/session-mining-ledger.ts`)
 * writes its tombstone JSON through `atomicWriteFileSync` under the
 * ledger file's own lock - derived-store machine state, not a note, so
 * it arrives in the shared class needing no exclusion.
 *
 * 121 -> 122, from the v1.86.1 review fixes and nothing else: the pending
 * mining surveys (`src/core/brain/session-mining-surveys.ts`) write their
 * JSON through `atomicWriteFileSync` under the file's own lock - derived-
 * store machine state, not a note, needing no exclusion.
 *
 * 122 -> 123, from the guarded-host-writes wave and nothing else: the
 * protect consent gate (`src/core/brain/protect.ts`) persists the applied
 * settings through `atomicWriteFileSync` - machine state written only
 * after an explicit consent receipt, not a note, needing no exclusion.
 *
 * 123 -> 124: the entity page-merge (`src/core/brain/entities/
 * 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.
 *
 * 125 -> 126: the cross-topic rule promotion (`src/core/brain/
 * dream-plan-cross-topic.ts`) writes its `Brain/cross-topic-rules.json`
 * daily-budget ledger through the shared atomic writer when a promotion
 * fires - machine state beside the rollup ledger, written only on the
 * changed path, needing no exclusion.
 *
 * 126 -> 128: the dated-commitments wave's two page writers -
 * `src/core/brain/pledge-intake.ts` and `src/core/brain/pledges.ts` -
 * commit `Brain/pledges/` pages through the shared atomic writer
 * (note-shaped pages by design; pledges.ts also carries the archive move
 * the direct-fs record excused, needing no exclusion for its write half).
 *
 * 128 -> 130, from the write-honesty wave and nothing else: the
 * content-class stamp's line insert
 * (`src/core/brain/provenance/content-class.ts`, commit dca029dd) rewrites
 * a just-written page through `atomicWriteFileSync` so the stamp cannot
 * lose the rest of the document, and the privacy-marker restamp verb
 * (`src/core/brain/privacy-marker-restamp.ts`, commit 571081ff) rewrites a
 * page's `visibility:` line through the same helper on its apply arm - a
 * dry-run-by-default repair pass over existing pages, writing no page of
 * its own.
 *
 * 130 -> 132, from the host-memory readback wave and nothing else: the
 * continuity promote verb (`src/core/brain/continuity/promote-host-memory.ts`)
 * lands its rendered preference pages through the shared atomic writer,
 * and its manifest sidecar (`src/core/brain/host-memory-promotions.ts`)
 * commits `Brain/.imports/host-memory-promotions.json` through the same
 * helper - both under the apply arm only, the dry run writes nothing.
 *
 * 132 -> 133, from the trust-and-responsiveness-hardening wave: the
 * gitignore guard (`src/core/brain/gitignore-guard.ts`) commits the seeded
 * vault `.gitignore` through the shared atomic writer - git configuration at
 * the vault root, created or merged at brain init, never a page under
 * `Brain/`.
 *
 * 133 -> 135, from the delivery-trust wave: the attestation kernel's record
 * writer (`src/core/brain/attestation/record.ts`) lands one attestation JSON
 * through the shared atomic writer and the signing kernel
 * (`src/core/brain/attestation/signing.ts`) writes the keypair halves the
 * same way - both committed through the shared writer, so both join the
 * shared-helper population.
 *
 * 135 -> 136, from the operator-approved lesson promotion lane
 * (t_1e952e43) and nothing else: the approvals ledger writer
 * (`src/core/brain/lessons-promotion.ts`) commits
 * `.open-second-brain/lessons-approvals.json` through the shared atomic
 * writer under the file's own lock - derived-store machine state, not a
 * note, so it joins the shared class needing no exclusion. The lane's
 * rules-file writes ride the shared rules-block writer
 * (`src/core/install/rules-block.ts`), which carries its own row.
 *
 * 136 -> 137, from the agent-presence wave (t_ba41a78a) and nothing
 * else: the instruction-block installer
 * (`src/core/install/instruction-block.ts`) commits the vault-root
 * agent-instruction file through the shared rules-block writer and the
 * `instruction-block.lock.json` ownership record through the shared
 * atomic writer - every byte it writes rides a shared helper, so it
 * joins the shared class needing no exclusion.
 *
 * 137 -> 138: the anticipatory cache prune
 * (`src/core/brain/anticipatory-prune.ts`) commits its rate-limit marker
 * through the shared atomic writer - cache machine state, not a note.
 *
 * 138 -> 139: the Brain log's append writer
 * (`src/core/brain/log-append-io.ts`) declares `appendSeparated`, which
 * this census now names as a shared writer, so the module reads as a
 * shared row the way `fs-atomic.ts` does for its own writers.
 *
 * 139 -> 140: the store-aware index location
 * (`src/core/search/brain-store/location.ts`) records the store root it
 * last read in device-local state, through the shared atomic writer, so
 * an unknown probe keeps only an index of the same root.
 *
 * 140 -> 141: the store-only predicate (`src/core/store/store-only.ts`)
 * names the vault's `Brain/` root to tell a fresh install from a legacy
 * one, and keeps its sticky switch marker in device-local state through
 * the shared atomic writer; it writes nothing in the vault.
 *
 * 141 -> 142: the vault adapter's `.base` stamping
 * (`src/core/vault-adapter/bases.ts`) moved out of `brain/init.ts`, which
 * keeps its own rows for `_brain.yaml` and `_BRAIN.md`.
 *
 * 142 -> 141: the two memory importers (`import-claude-memory.ts`,
 * `continuity/promote-host-memory.ts`) no longer write preference pages
 * themselves; both hand the text to the one preference page write path
 * (`src/core/brain/preference-page-write.ts`), which writes the page
 * through the shared atomic writer on an unswitched machine and the
 * store records only once switched (task 2.10). Two rows leave, one
 * arrives.
 *
 * 141 -> 142: the lane page store (`src/core/store/lane-pages.ts`, task
 * 2.10 WP6) writes a record-lane page through the shared writers on an
 * unswitched machine and the store records once switched.
 * 142 -> 135: the record-lane modules (dead-ends, handoff, obligations,
 * pledges, pledge-intake, theses, tensions) write through the lane page
 * store (task 2.10 WP6), so their shared-writer rows leave.
 * 135 -> 133: report snapshots and write sessions too.
 * 133 -> 128: decisions, open decisions, design notes, gap tasks and triggers too.
 * 128 -> 127: commit-mined decision candidates too.
 * 127 -> 123: entities (registry, label hygiene, page merge) and derived artifacts write through the lane page store (task 2.10 WP6).
 * 123 -> 118: procedural memory, skill proposals, the accept journal and extract-intake write through the lane page store (task 2.10 WP6).
 * 118 -> 114: attention flows, clusters, co-occurrence, hallways, dream bundles and architect notes write through the lane page store (task 2.10 WP6).
 * 114 -> 110: foresight, cluster and bridge verbs, bridge proposals and the source, report and distillation pages write through the lane page store (task 2.10 WP6).
 * 110 -> 109: source archives, the review-queue lanes, source cleanup and OKF import write through the lane page store (task 2.10 WP6).
 *
 * 109 -> 110: the shared brain settings writer
 * (`src/core/brain/policy/settings-write.ts`) edits `_brain.yaml` on an
 * unswitched machine; once switched it writes settings records.
 *
 * 110 -> 112: the skill accept journal and skill proposals write their
 * machine-state files (journal, prior-content copy, watermark) as files
 * with the shared atomic writer, not as lane records.
 * 112 -> 113: the legacy-tree removal journals its archive
 * (`removal.json`, device-local migration folder) before the first move,
 * so an interrupted removal finishes into the same archive.
 * 113 -> 114: the procedural graph, hints and usage counters are machine
 * state written with the shared atomic writer, not lane records, so a
 * usage tick appends no store record (task 3.10).
 * 114 -> 115: the lane-id repair writes its device-local "repaired" marker
 * with the shared atomic writer, once per store (task 3.9).
 */
const SHARED_HELPER_ROWS = 115;

// ----- Origin-channel coverage boundary (Unit C) ----------------------------

/**
 * The origin-channel stamp reaches four writers, and this census is where
 * the OTHER ones are counted rather than described.
 *
 * Unit C derives a channel (`mcp-tool` / `cli` / `import`) at the process
 * entry point and stamps it on four record families. The population is
 * bounded on purpose - a stamp is only worth having on records that
 * already carry structured metadata - so the honest statement of what
 * ships is "four writers carry it and N measured write sites do not",
 * and N has to come from the same walk that produces every other number
 * in this file. A prose claim of uniformity would be the exact
 * dishonesty the wave removes.
 *
 * Against the write-binding taxonomy (`src/core/write-binding/index.ts`)
 * the four are one CALLER-NAMED envelope (the note target resolver), one
 * SLUG-DERIVED writer (signals), and two FULLY-DERIVED writers (the log
 * pair and the continuity ledger). The rest of the fully-derived class -
 * dream workruns, decision receipts, capture decisions, every telemetry
 * ledger - is inside the uncovered counts below and stays there.
 */
const ORIGIN_CHANNEL_STAMPED: ReadonlyArray<string> = Object.freeze([
  "src/core/brain/continuity/store.ts",
  "src/core/brain/ingest/ingest.ts",
  "src/core/brain/log.ts",
  "src/core/brain/notes/create-note.ts",
  "src/core/brain/signal.ts",
  // The shared mutation seam: every MCP note update and append stamps the
  // writing process's channel there, so an agent-authored body can never
  // ride an inherited operator stamp.
  "src/core/brain/write-batch.ts",
]);

/** Import specifier of the resolver, in either quote style. */
const ORIGIN_CHANNEL_IMPORT_RE = /from\s*["'][^"']*\/origin-channel\.ts["']/;

/**
 * The record-writer read. Keyed on the READ and not on the import,
 * because the entry points that CLAIM the channel import the same module
 * and write no record - counting them would inflate the covered class
 * with modules that stamp nothing.
 */
const ORIGIN_CHANNEL_READ_RE = /\boriginChannelStamp\s*\(/;

function stampsOriginChannel(file: CensusFile): boolean {
  const views = lexedViews(file);
  return (
    ORIGIN_CHANNEL_IMPORT_RE.test(views.withoutComments) && ORIGIN_CHANNEL_READ_RE.test(views.code)
  );
}

const STAMPED_PATHS: ReadonlySet<string> = new Set(
  SOURCE_TREE.filter(stampsOriginChannel).map((file) => file.path),
);

/**
 * Direct-`fs` write sites the stamp does not reach - MEASURED off the
 * sweep, not derived from {@link DIRECT_WRITE_ROWS}.
 *
 * It used to be written as `DIRECT_WRITE_ROWS - 1` and asserted against
 * `DIRECT_ROWS.length - stampedDirect.length`, which is the same
 * arithmetic on both sides of an `expect`: the assertion restated pins
 * the file had already made and could not fail on its own. The number
 * below is what the sweep actually reports, so the assertion measures
 * the swept tree; the one excused site that IS stamped is the continuity
 * ledger, which appends its own record shape and carries the channel on
 * the record rather than in frontmatter.
 *
 * 70 -> 71: the knowledge-pack uninstall's removal (a delete stamps nothing).
 * 71 -> 72: the payload gc's removal (a delete stamps nothing).
 * 72 -> 73: the payload registry's touch (metadata only).
 * 73 -> 74: the automatic-upgrade lock and marker removal (state, not notes).
 * 74 -> 75: the doctor self-test's throwaway-store writes (temp storage).
 * 75 -> 76: the freshen-on-read claim and its release (state, not notes).
 * 76 -> 77: the secrets keyfile envelope swap (custody bytes, not notes).
 * 77 -> 78: the per-agent MCP token store's custody swap (hash-at-rest
 *   state, not notes).
 * 78 -> 79: the decision ledger's lock-scoped append
 *   (`src/core/brain/permissions/ledger.ts`): one row per gate verdict,
 *   written with `writeFileSync` flag 'a' inside the per-shard lock -
 *   append-only on the idempotency-ledger model, so there is no rewrite
 *   for the shared writer to route. (Both write-side-trust steps moved
 *   the count 77 -> 79; only the custody swap was written down here.)
 * 79 -> 80: the intake's stage-disposition page move (a lifecycle move
 * whose only direct call is the unlink; it stamps no channel).
 * 80 -> 81: the source archive's entry discard (answer trust) - a
 * content-addressed evidence prune whose last citing page the same
 * confirmed delete-by-source removed; no origin stamp on archive cleanup.
 * 81 -> 82: the entity page-merge's archive removal
 * (`src/core/brain/entities/page-merge.ts`) - a delete stamps nothing.
 * 82 -> 83: the pledge family's archive move
 * (`src/core/brain/pledges.ts`) - a lifecycle move stamps no channel,
 * the obligations entry one family over.
 * 83 -> 84: the pledge intake's mid-batch rollback
 * (`src/core/brain/pledge-intake.ts`) - a reset to the pre-intake state
 * stamps no channel either.
 * 85 -> 86: the anticipatory cache prune
 * (`src/core/brain/anticipatory-prune.ts`) - a retention delete of derived
 * cache entries stamps nothing.
 * 86 -> 87: the Brain log's append writer
 * (`src/core/brain/log-append-io.ts`) - the stamp is applied by its caller,
 * `log.ts`, which still reads as a stamped shared-helper row.
 * 87 -> 88: the brain store migration backup
 * (`src/core/store-migration/backup.ts`) - copies of machine state carry
 * no origin channel.
 * 88 -> 92: the transition, removal and rollback of the store migration -
 * device-local state, and legacy exports that replay records as written.
 * 92 -> 93: the lane page store's archive moves and removals stamp no channel.
 * 93 -> 89: the record-lane modules (dead-ends, obligations, pledges,
 * pledge-intake) write through the lane page store (task 2.10 WP6).
 * 89 -> 88: write sessions too.
 * 88 -> 87: gap tasks too.
 * 87 -> 85: entities (registry, label hygiene, page merge) and derived artifacts write through the lane page store (task 2.10 WP6).
 * 85 -> 83: procedural memory, skill proposals, the accept journal and extract-intake write through the lane page store (task 2.10 WP6).
 * 83 -> 80: attention flows, clusters, co-occurrence, hallways, dream bundles and architect notes write through the lane page store (task 2.10 WP6).
 * 80 -> 78: foresight, cluster and bridge verbs, bridge proposals and the source, report and distillation pages write through the lane page store (task 2.10 WP6).
 * 78 -> 77: source archives, the review-queue lanes, source cleanup and OKF import write through the lane page store (task 2.10 WP6).
 * 77 -> 78: the migration places accepted skills from Brain/skills in the vault's skills/ folder as files (task 2.10).
 * 78 -> 79: the skill accept journal's repair markers are machine-state files.
 * 79 -> 80: machine-state reads a bare vault's own `.open-second-brain/` to seed the device-local state (device-local writes only).
 * 80 -> 81: the search index writer lock's own module (lock directory metadata only, no stamped bytes).
 */
const UNSTAMPED_DIRECT_ROWS = 81;

/**
 * Shared-helper write sites the stamp does not reach, measured the same
 * way. The three stamped writers that route through the shared helpers -
 * the log pair through `atomicWriteFileSync`, signals and notes through
 * `writeFrontmatterAtomic` - are the ones missing from this count.
 * The payload registry's `put()` is one of the unstamped sites counted, and
 * so is the knowledge-pack install fingerprint (100 -> 101), and the
 * failed-upgrade marker `self-heal-upgrade-state.ts` writes (101 -> 102),
 * and the dedup index cache, a derived file outside the vault (102 -> 103),
 * and the orphan-repair detach (103 -> 104). 104 -> 105: the repair lane
 * stages hub candidates through the shared atomic JSONL writer. 105 -> 106:
 * the session focus writes through the shared atomic text writer. 106 -> 107:
 * the freshen-on-read state file writes through the shared atomic writer.
 * 107 -> 108: the correction sweep retires its target's frontmatter through
 * the shared atomic frontmatter writer. 108 -> 109: the credential-bundle
 * export writes the operator-named `--out` through the shared atomic writer
 * (an egress destination, and no origin stamp on exports). 109 -> 110: the
 * bootstrap receipt writes `<vault>/.open-second-brain/bootstrap.lock.json`
 * through the shared atomic writer (custody state, not notes). 110 -> 111:
 * the decision ledger appends its month/device JSONL shard through the shared
 * atomic writer (write-side-trust Task 2). 111 -> 112: the envelope swap
 * writes its custody bytes through the shared atomic writer (custody state,
 * not notes). 112 -> 114: the recall-quality wave's derived artifacts - the
 * shared derived-artifact helper and the hallways artifact with its
 * dismissal keys - write machine JSON through the shared atomic writer
 * (derived state, not notes; no origin stamp on either). 114 -> 116: the
 * answer-trust wave - the source archive persists its redacted entries
 * through the shared atomic writer (evidence bytes; no origin stamp on an
 * archive put), and the config writer joins the population through its new
 * path-constants import carrying the config write it already made (module
 * state, not notes). 116 -> 117: the receipt fold engine
 * (`src/core/brain/receipts/compact.ts`) rewrites its named shards through
 * the shared atomic writer (machine JSONL ledger rows, not notes; no
 * origin stamp on a fold rewrite). 117 -> 118: the session mining ledger
 * (`src/core/brain/session-mining-ledger.ts`) writes its tombstone JSON
 * through the shared atomic writer (derived-store machine state, not
 * notes; no origin stamp on machine state). 118 -> 119: the pending mining
 * surveys (`src/core/brain/session-mining-surveys.ts`) write their JSON
 * the same way (derived-store machine state; no origin stamp). 119 -> 120:
 * the protect consent gate (`src/core/brain/protect.ts`) persists the
 * applied settings through the shared atomic writer (consent-gated machine
 * 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). 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.
 * 122 -> 123: the cross-topic rule promotion (`src/core/brain/
 * dream-plan-cross-topic.ts`) writes its `Brain/cross-topic-rules.json`
 * daily-budget ledger through the shared atomic writer when a promotion
 * fires (machine state beside the rollup ledger; no origin stamp).
 * 123 -> 125: the dated-commitments wave's two page writers -
 * `src/core/brain/pledge-intake.ts` and `src/core/brain/pledges.ts` both
 * commit pledge pages through the shared atomic writer (vault note pages,
 * and no origin stamp on the pledge lane).
 * 125 -> 127, from the write-honesty wave and nothing else: the
 * content-class stamp's line insert
 * (`src/core/brain/provenance/content-class.ts`, commit dca029dd) and the
 * privacy-marker restamp verb
 * (`src/core/brain/privacy-marker-restamp.ts`, commit 571081ff) both
 * rewrite existing pages through the shared atomic writer, and neither
 * stamps an origin channel - one writes a class the writer derives, the
 * other a visibility token the page's own informal marker declares.
 * 126 -> 128 is the same wave as the shared-helper pin above: the
 * continuity promote verb and its promotion manifest both commit through
 * the shared atomic writer, and a ledger readback stamps no origin
 * channel - the pages it lands are vault pages, not channel records.
 * 128 -> 129 is the gitignore guard (trust-and-responsiveness-hardening):
 * the `.gitignore` it seeds is git configuration at the vault root,
 * carrying no origin channel - no record family of Unit C names it.
 *
 * 129 -> 131 is the delivery-trust wave's attestation kernel: the record
 * writer and the signing kernel commit through the shared atomic writer,
 * and neither stamps an origin channel - an attestation is evidence about
 * the store, not a stored record family.
 * 131 -> 130 is the same wave's mutation channel stamp: the shared
 * write-batch seam moved from the unstamped to the stamped shared class
 * when note mutations began stamping the writing process's channel.
 * 130 -> 131, from the operator-approved lesson promotion lane
 * (t_1e952e43) and nothing else: the approvals ledger writer
 * (`src/core/brain/lessons-promotion.ts`) commits the
 * `lessons-approvals.json` state table through the shared atomic writer -
 * machine state in the derived store, carrying no origin channel.
 * 131 -> 132, from the agent-presence wave (t_ba41a78a) and nothing
 * else: the instruction-block installer
 * (`src/core/install/instruction-block.ts`) commits the vault-root
 * agent-instruction file through the shared rules-block writer and the
 * `instruction-block.lock.json` ownership record through the shared
 * atomic writer - both under the apply arm only, the plan and the dry
 * run write nothing, and neither write stamps an origin channel.
 * 132 -> 133: the anticipatory cache prune's rate-limit marker
 * (`src/core/brain/anticipatory-prune.ts`), written through the shared
 * atomic writer, carries no origin channel.
 * 133 -> 134: the Brain log's append writer
 * (`src/core/brain/log-append-io.ts`) is a shared row by its own
 * declaration and stamps nothing; `log.ts`, its caller, stamps.
 * 134 -> 135: the store-aware index location's remembered store root
 * (`src/core/search/brain-store/location.ts`) is device-local machine
 * state, not a note, and carries no origin channel.
 * 135 -> 136: the store-only predicate's switch marker
 * (`src/core/store/store-only.ts`) is device-local machine state, not a
 * note, and carries no origin channel.
 * 136 -> 137: the vault adapter's `.base` files
 * (`src/core/vault-adapter/bases.ts`) are view definitions copied from the
 * bundled templates, not notes, and carry no origin channel.
 *
 * 137 -> 136: the memory importers' page writes moved into the one
 * preference page write path (`src/core/brain/preference-page-write.ts`,
 * task 2.10); a preference page is not a note and carries no origin
 * channel, so two unstamped rows leave and one arrives.
 * 136 -> 137: the lane page store (`src/core/store/lane-pages.ts`) writes
 * record-lane pages, not notes; it carries no origin channel.
 * 137 -> 130: the record-lane modules (dead-ends, handoff, obligations,
 * pledges, pledge-intake, theses, tensions) write through the lane page
 * store (task 2.10 WP6).
 * 130 -> 128: report snapshots and write sessions too.
 * 128 -> 123: decisions, open decisions, design notes, gap tasks and triggers too.
 * 123 -> 122: commit-mined decision candidates too.
 * 122 -> 118: entities (registry, label hygiene, page merge) and derived artifacts write through the lane page store (task 2.10 WP6).
 * 118 -> 113: procedural memory, skill proposals, the accept journal and extract-intake write through the lane page store (task 2.10 WP6).
 * 113 -> 109: attention flows, clusters, co-occurrence, hallways, dream bundles and architect notes write through the lane page store (task 2.10 WP6).
 * 109 -> 106: foresight, cluster and bridge verbs, bridge proposals and the source, report and distillation pages write through the lane page store (task 2.10 WP6).
 * 106 -> 105: source archives, the review-queue lanes, source cleanup and OKF import write through the lane page store (task 2.10 WP6).
 *
 * 105 -> 106: the shared brain settings writer edits `_brain.yaml` on an
 * unswitched machine; a settings file is not a note and carries no origin
 * channel.
 *
 * 106 -> 108: the skill accept journal's and skill proposals' machine-state
 * files carry no origin channel.
 * 108 -> 109: the legacy-tree removal's device-local journal, machine
 * state and no note.
 * 109 -> 110: the procedural graph, hints and usage counters, machine
 * state and no note (task 3.10).
 * 110 -> 111: the lane-id repair's device-local marker, machine state and
 * no note (task 3.9).
 */
const UNSTAMPED_SHARED_ROWS = 111;

describe("in-vault write-site census", () => {
  test("every direct-fs write site carries a written exclusion", () => {
    const unlisted = DIRECT_ROWS.filter((row) => !(row.path in DIRECT_WRITE_EXCLUSIONS)).map(
      (row) => `${row.path} [${row.directCalls.join(",")}]`,
    );
    // Named, not counted: the failure has to say which file.
    expect(unlisted).toEqual([]);
  });

  test("no exclusion outlives the site it excuses", () => {
    const present = new Set(DIRECT_ROWS.map((row) => row.path));
    const stale = Object.keys(DIRECT_WRITE_EXCLUSIONS).filter((path) => !present.has(path));
    expect(stale).toEqual([]);
  });

  test("each exclusion still names exactly the calls its site makes", () => {
    // A new KIND of direct write inside an already-excused file is a new
    // decision, not one the existing argument already covered.
    const drifted: string[] = [];
    for (const row of DIRECT_ROWS) {
      const entry = DIRECT_WRITE_EXCLUSIONS[row.path];
      if (entry === undefined) continue;
      if (entry.calls.join(",") !== row.directCalls.join(",")) {
        drifted.push(
          `${row.path}: declared [${entry.calls.join(",")}] found [${row.directCalls.join(",")}]`,
        );
      }
    }
    expect(drifted).toEqual([]);
  });

  test("every exclusion carries a reason that is an argument, not a label", () => {
    // `length > 0` was the whole bar here, which "x" cleared. The sibling
    // censuses - `state-surface-census` and `forward-pointer-rail` - both
    // require a real minimum and reject the words that mean "not yet",
    // and there is no reading on which THIS record deserves a lower one:
    // it is the list of write sites the shared binding cannot cover, and
    // a one-word entry in it is an unexamined site wearing an exclusion.
    const thin: string[] = [];
    const lazy: string[] = [];
    const uncategorised: string[] = [];
    for (const [path, entry] of Object.entries(DIRECT_WRITE_EXCLUSIONS)) {
      if (entry.reason.trim().length < MIN_REASON_LENGTH) {
        thin.push(`${path} (${entry.reason.trim().length})`);
      }
      if (LAZY_REASON_RE.test(entry.reason)) lazy.push(path);
      if (entry.categories.length === 0) uncategorised.push(path);
    }
    expect(thin.toSorted().join("\n")).toBe("");
    expect(lazy.toSorted().join("\n")).toBe("");
    expect(uncategorised.toSorted().join("\n")).toBe("");
  });

  test("the two writers this unit routed through a shared helper are gone from the record", () => {
    // Both wrote vault content by hand: one a complete note with
    // hand-rolled frontmatter, one a truncating rewrite of notes the
    // operator edits concurrently. Their absence here is the assertion.
    const direct = new Set(DIRECT_ROWS.map((row) => row.path));
    expect(direct.has("src/core/brain/handoff.ts")).toBe(false);
    expect(direct.has("src/cli/brain/verbs/links.ts")).toBe(false);
  });
});

describe("origin-channel coverage boundary", () => {
  test("exactly the four declared writers stamp the channel", () => {
    // Named, not counted, in both directions: a new stamper and a writer
    // that stopped stamping are different findings and read differently.
    expect([...STAMPED_PATHS].toSorted()).toEqual([...ORIGIN_CHANNEL_STAMPED]);
  });

  test("the direct-fs exclusion record is uncovered but for the continuity ledger", () => {
    const stampedDirect = DIRECT_ROWS.filter((row) => STAMPED_PATHS.has(row.path)).map(
      (row) => row.path,
    );
    expect(stampedDirect.toSorted()).toEqual(["src/core/brain/continuity/store.ts"]);
    // The measured remainder, counted off the sweep rather than
    // subtracted from a pin. This is the honest sizing of the unit: the
    // stamp lands on four writers, and this many swept direct-`fs`
    // sites - append-only ledgers, lifecycle moves, retention deletes,
    // machine artifacts - put bytes in the vault without one.
    const unstampedDirect = DIRECT_ROWS.filter((row) => !STAMPED_PATHS.has(row.path));
    expect(unstampedDirect.length).toBe(UNSTAMPED_DIRECT_ROWS);
  });

  test("the shared-helper class is uncovered but for the log, signal and note writers", () => {
    const sharedRows = ROWS.filter((row) => row.sharedCalls > 0);
    const stampedShared = sharedRows
      .filter((row) => STAMPED_PATHS.has(row.path))
      .map((row) => row.path);
    // The ingest summary page still stamps the channel, but it writes
    // through the lane page store now (task 2.10 WP6), so its row left the
    // shared-helper class; the stamp is held by `ORIGIN_CHANNEL_STAMPED`.
    expect(stampedShared.toSorted()).toEqual([
      "src/core/brain/log.ts",
      "src/core/brain/notes/create-note.ts",
      "src/core/brain/signal.ts",
      "src/core/brain/write-batch.ts",
    ]);
    const unstampedShared = sharedRows.filter((row) => !STAMPED_PATHS.has(row.path));
    expect(unstampedShared.length).toBe(UNSTAMPED_SHARED_ROWS);
  });

  test("a new stamper anywhere in the tree is reported, not absorbed", () => {
    // The detector's own failure mode: a module that reads the stamp and
    // is not in the declared four has widened the covered class, and the
    // boundary numbers above are stale the moment it lands.
    const intruder: CensusFile = {
      path: "src/core/brain/synthetic-stamper.ts",
      text:
        'import { originChannelStamp } from "../origin-channel.ts";\n' +
        "export const channel = originChannelStamp();\n",
    };
    expect(stampsOriginChannel(intruder)).toBe(true);
    expect(STAMPED_PATHS.has(intruder.path)).toBe(false);
  });

  test("claiming the channel is not stamping it", () => {
    // The entry points import the same module to CLAIM the channel and
    // write no record. Keying the detector on the import alone would put
    // them in the covered class and overstate the coverage by three.
    expect(
      stampsOriginChannel({
        path: "src/cli/synthetic-entry-point.ts",
        text:
          'import { ORIGIN_CHANNEL, setOriginChannel } from "../core/origin-channel.ts";\n' +
          "setOriginChannel(ORIGIN_CHANNEL.cli);\n",
      }),
    ).toBe(false);
  });
});

describe("the census can fail", () => {
  /** Run the real census over the real tree plus one synthetic module. */
  function unlistedWith(intruder: CensusFile): string[] {
    return census([...SOURCE_TREE, intruder])
      .filter((row) => row.directCalls.length > 0)
      .filter((row) => !(row.path in DIRECT_WRITE_EXCLUSIONS))
      .map((row) => row.path);
  }

  /**
   * Every source shape a direct write can arrive in. Each must be reported
   * on its own: the detector used to see only the first `node:fs` import
   * statement of a file, in the one binding form and the one quote style,
   * so the shapes below were unreachable by construction and the suite
   * still passed. A shape that stops being detected shows up here as a
   * named failure rather than as a silently smaller census.
   */
  const INTRUDER_SHAPES: ReadonlyArray<readonly [string, string]> = Object.freeze([
    [
      "a plain named import",
      'import { writeFileSync } from "node:fs";\nwriteFileSync("x", "y");\n',
    ],
    [
      "a second `node:fs` import statement",
      'import { readFileSync } from "node:fs";\nimport { appendFileSync } from "node:fs";\nappendFileSync("x", "y");\n',
    ],
    ["a renamed binding", 'import { writeFileSync as put } from "node:fs";\nput("x", "y");\n'],
    ["a namespace import", 'import * as fs from "node:fs";\nfs.writeFileSync("x", "y");\n'],
    [
      "the promise API",
      'import { writeFile } from "node:fs/promises";\nawait writeFile("x", "y");\n',
    ],
    [
      "a single-quoted specifier",
      "import { writeFileSync } from 'node:fs';\nwriteFileSync('x', 'y');\n",
    ],
    ["a runtime built-in needing no import", 'await Bun.write("x", "y");\n'],
  ]);

  for (const [shape, source] of INTRUDER_SHAPES) {
    test(`a new direct writer using ${shape} is reported unlisted`, () => {
      const path = "src/core/brain/synthetic-intruder.ts";
      expect(unlistedWith({ path, text: source })).toEqual([path]);
    });
  }

  test("a type-only fs import is not a write site", () => {
    // The complement of the import gate: naming a type cannot write bytes,
    // and counting it would put every module that annotates a `Dirent` in
    // the record.
    expect(
      classify({
        path: "src/core/brain/synthetic-types-only.ts",
        text: 'import type { WriteFileOptions } from "node:fs";\nexport type T = WriteFileOptions;\n',
      }),
    ).toBeNull();
  });

  test("the live second-statement import stays visible", () => {
    // The concrete defect this detector fix closes, pinned by name: the
    // vault append in the git record store arrives through the module's
    // SECOND `node:fs` statement. A regression to a single-statement read
    // makes this row vanish and the sweep read as clean.
    const row = DIRECT_ROWS.find((candidate) => candidate.path === "src/core/brain/git/store.ts");
    expect(row?.directCalls).toEqual(["appendFileSync"]);
  });

  test("a writer outside every vault root is out of population, not silently listed", () => {
    // The complement of the rule above: over-reach would drag the
    // install adapters in and make the record meaningless.
    const outsider: CensusFile = {
      path: "src/core/install/adapters/synthetic.ts",
      text: 'import { writeFileSync } from "node:fs";\nwriteFileSync("x", "y");\n',
    };
    expect(classify(outsider)).toBeNull();
  });

  test("a writer in a brand-new directory that joins onto a vault is in population", () => {
    // The hole the widened rule closes, driven as a shape rather than as
    // the three real modules that fell through it: living somewhere no
    // list mentions, and importing no path vocabulary, used to be enough.
    const path = "src/core/somewhere-new/synthetic-vault-writer.ts";
    const text =
      'import { writeFileSync } from "node:fs";\n' +
      'import { join } from "node:path";\n' +
      "export function stamp(vault: string): void {\n" +
      '  writeFileSync(join(vault, "marker"), "x");\n' +
      "}\n";
    expect(unlistedWith({ path, text })).toEqual([path]);
  });

  test("a writer naming the derived store as a bare literal is in population too", () => {
    // The second half of the widening: `install/manifest.ts` never says
    // `join(vault` and never imports the vocabulary - it spells the
    // directory name itself.
    const path = "src/core/somewhere-new/synthetic-store-writer.ts";
    const text =
      'import { writeFileSync } from "node:fs";\n' +
      'import { join } from "node:path";\n' +
      "export function stamp(root: string): void {\n" +
      '  writeFileSync(join(root, ".open-second-brain", "marker.json"), "{}");\n' +
      "}\n";
    expect(unlistedWith({ path, text })).toEqual([path]);
  });

  test("the derived-store name in prose alone does not enrol a module", () => {
    // The complement, and the reason the literal clause reads the
    // comment-stripped view: a docblock that mentions the directory
    // builds no path into it.
    expect(
      classify({
        path: "src/core/somewhere-new/synthetic-prose.ts",
        text:
          "/** Never writes to .open-second-brain, and says so here. */\n" +
          'import { writeFileSync } from "node:fs";\n' +
          'writeFileSync("x", "y");\n',
      }),
    ).toBeNull();
  });

  test("the detectors still match the shapes they measure", () => {
    // A regex that stopped matching would report a clean sweep over an
    // empty set. Pin the measurement, not only its verdict - and pin it
    // as an EQUALITY. These were floors of 58 and 88 against a measured
    // 64 and 94, and one of the two comments explaining the gap already
    // named a stale figure (63), which is what a floor does to the
    // number under it: nobody is keeping it. A floor also cannot fail on
    // the drift it exists to catch until six sites have already gone
    // dark.
    //
    // A moved number is a finding, not a re-measurement chore: state in
    // the same commit what added or removed a write site.
    expect(DIRECT_ROWS.length).toBe(DIRECT_WRITE_ROWS);
    expect(ROWS.filter((row) => row.sharedCalls > 0).length).toBe(SHARED_HELPER_ROWS);
  });
});