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
fix: MCP startup off the upgrade path, fair ingest locks, inline plugin MCP manifest, inbox archive (v1.61.0) (#217)
Serg Eroshe83979b9d5f51
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex e307f449..e2aa09f1 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.60.0",+ "version": "1.61.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"@@ -8,5 +8,16 @@"license": "MIT","homepage": "https://github.com/itechmeat/open-second-brain","repository": "https://github.com/itechmeat/open-second-brain",- "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]+ "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"],+ "mcpServers": {+ "open-second-brain": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp"]+ },+ "open-second-brain-writer": {+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ "args": ["mcp", "--scope", "writer"],+ "alwaysLoad": true+ }+ }}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 59d83a58..db6d7a3d 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.60.0",+ "version": "1.61.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/.mcp.json b/.mcp.jsondeleted file mode 100644index c952dcea..00000000--- a/.mcp.json+++ /dev/null@@ -1,13 +0,0 @@-{- "mcpServers": {- "open-second-brain": {- "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",- "args": ["mcp"]- },- "open-second-brain-writer": {- "command": "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",- "args": ["mcp", "--scope", "writer"],- "alwaysLoad": true- }- }-}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5cdfec5d..9c0f453c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,33 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.61.0] - 2026-09-28++MCP server start-up off the Brain upgrade path, fair ingest locks, the Claude Code MCP manifest inside `plugin.json`, and an inbox archive (issues #216, #198, #196, #195).++### Fixed++- **The full MCP server answers `initialize` without waiting for a Brain upgrade (#216).** After a plugin update, `ensureVaultCurrent` planned and applied a pending `_brain.yaml` / `_BRAIN.md` upgrade, snapshot included, synchronously inside `o2b mcp` and the `SessionStart` hook, before the server read its first request; on a large vault that took 7 to 35 s and could miss the host's 30 s connect timeout. The upgrade now runs in a detached `o2b brain upgrade --self-heal` worker behind a per-vault lock (`.open-second-brain/self-heal-upgrade.lock`, handed to the worker and held until it exits). Measured on a vault with a 315 MB `Brain/` tar: a full `initialize` took 823 to 1037 ms and hit ENOBUFS on every start before, and 223 to 259 ms once the worker had applied the upgrade.+- **Brain snapshots stream through files instead of a 256 MB buffer (#216).** tar writes a staging file that the compressor reads, the in-process gzip fallback compresses in bounded chunks (a multi-member gzip file every reader accepts), and the zstd restore path decompresses to a staging file, so a `Brain/` tree of any size no longer fails with `ENOBUFS`.+- **A snapshot archive appears under its final name only once it is complete.** Both compressors write a partial file in `.snapshots/`, and the archive is published by an exclusive hard link (a checked rename where the filesystem has no hard links); the manifest is written after it. A process killed during compression, or a failed compressor, no longer leaves a truncated `<run_id>.tar.zst` without a manifest that listing, retention and rollback would treat as a recovery point. The partial file of a killed snapshot is never listed, and retention removes it once it is a day old.+- **One vault directory keeps one `vault_name` spelling (#216).** On a case-insensitive filesystem two spellings of the same vault path rendered two different `_BRAIN.md` files, so each runtime saw the other's manual as a pending upgrade. A `vault_name` that differs only by case and names the same directory (same device and inode) is kept.+- **Contended ingest locks are handed over to their waiters (#198).** A writer that released a sync lock and came straight back for it could win every draw while a waiter slept, so a healthy four-process ingest race was refused on the Windows runner. Waiters now mark the held lock, a holder that releases a marked lock steps back before re-acquiring, and a long-waiting waiter polls more often; the exclusive create still grants the lock and an expired budget is still a named `ELOCKED`. At the Windows runner's pace (emulated on Linux) the race's longest wait fell from 5017 ms with 4 refusals to 753 ms with none, and the race tests no longer retry refused writes.+- **Starting Claude Code in a checkout of this repository no longer shows two failed MCP servers (#196).** The plugin's servers are declared inline in `.claude-plugin/plugin.json` (`mcpServers`, same commands and arguments, `alwaysLoad` on the writer server), and the repository-root `.mcp.json`, which Claude Code also loaded as a project config with an empty `CLAUDE_PLUGIN_ROOT`, is removed.+- **Session capture stays well under the hook timeout on a large inbox on a slow mount (#195).** The signal dedup index is revalidated against a machine-local cache (per directory: listing digest, count and mtime; per file: size and mtime; git's racy-clean window), so a sync tool that replaces a file under the same name is still re-read, and its async callers stat and read in parallel. With 4000 signals on WSL `/mnt/c` the index took 16 s before, 1.9 s cold and 0.17 s warm now; an inline session capture fell from 17 s to 2.9 s.+- **The session-capture process ceiling reaches the dedup walk (#195).** The hook hands the walk a cooperative deadline equal to its ceiling, checked between files, so a synchronous walk stops before the host timeout instead of running past it.++### Added++- **Inbox archive (#195).** Every dream pass moves inbox signals older than `dream.contradiction_window_days` that it did not consume into `Brain/inbox/archived/`, byte for byte (`archived_signals` in the summary and the `dream` log event, previewed by `--dry-run`, idempotent, never deleted). Such a signal can no longer count toward a candidate, so promotion outcomes inside the window are unchanged. Archived signals stay readable by query, backlinks, sources, expiration, forget, the claim graph and the doctor record checks, a preference evidenced by one keeps its sign, and the dedup index covers them so a re-imported session does not re-create one. The archive clock never runs ahead of the wall clock, so `--now` in the future archives nothing that is still inside the window today, a name already taken in `archived/` is reported instead of re-planned, and a staged bundle does not count newly archivable signals as drift. `dream.archive_stale_signals: false` keeps the previous behaviour.+- **`o2b brain doctor` reports `inbox-archivable` (#195)** while inbox signals older than the window wait for a dream pass, with the inbox size, the archivable count (exactly what the next pass archives) and `o2b brain dream` as the next step.+- **Failed automatic upgrades are visible and back off (#216).** A failed attempt is recorded per device in `.open-second-brain/self-heal-upgrade.json` and on the `self_heal_upgrade` metrics surface; `o2b doctor` gains a `self_heal_upgrade` check, `o2b brain status` a `self-heal-upgrade-failed` problem, and `o2b brain upgrade --dry-run` / `--check` print the last failure (JSON `self_heal_failure`). The next automatic attempt waits one hour, doubling per consecutive failure up to 24 hours; `o2b brain upgrade --apply --yes` ignores the cooldown and clears the record.+- **Environment variables** `OPEN_SECOND_BRAIN_LOCK_WAIT_MS` (the ingest lock wait, default 5000 ms; the interactive wait is unchanged), `OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR` (where the dedup index cache lives) and `OPEN_SECOND_BRAIN_DEDUP_CACHE=0` (turns the cache off), listed together in `docs/cli-reference.md`. The dedup index cache is listed in the data-ownership statement.++### Changed++- **A refused ingest write says what to do next (#198):** how long it waited, then retry the ingest, run the parallel ingests one at a time, or raise `OPEN_SECOND_BRAIN_LOCK_WAIT_MS`.+- **Docs:** `docs/how-it-works.md`, `docs/architecture.md`, `docs/observability.md`, `docs/updating.md`, `docs/metrics.md`, `docs/mcp.md`, `docs/cli-reference.md` and `README.md` describe the start-up worker, streaming and atomic snapshots, the inbox archive, the dedup index cache and the inline MCP manifest; the state-surface counts in `docs/cli-reference.md` are current (45 surfaces, 17 memory-bearing).+## [1.60.0] - 2026-09-27Optional decision-model support, second part: every remaining use, more routes, threshold profiles and a setup skill (issue #213, Parts 3 to 10).@@ -7783,6 +7810,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.61.0]: https://github.com/itechmeat/open-second-brain/compare/v1.60.0...v1.61.0[1.60.0]: https://github.com/itechmeat/open-second-brain/compare/v1.59.0...v1.60.0[1.59.0]: https://github.com/itechmeat/open-second-brain/compare/v1.58.2...v1.59.0[1.58.2]: https://github.com/itechmeat/open-second-brain/compare/v1.58.1...v1.58.2diff --git a/README.md b/README.mdindex 42199916..dd7e14a8 100644--- a/README.md+++ b/README.md@@ -104,7 +104,7 @@ Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`mem| Runtime | Install || ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |-| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |+| Claude Code | Marketplace plugin (bundled MCP servers + hooks) - [`install/claudecode.md`](install/claudecode.md) || OpenAI Codex | `codex plugin marketplace add ...` then `o2b install --target codex --apply` (MCP servers via `codex mcp add`, or a `config.toml` merge without the binary) - [`install/codex.md`](install/codex.md) || OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) || opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](install/opencode.md) |diff --git a/docs/architecture.md b/docs/architecture.mdindex 3ee66f58..9de5bfa5 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -244,6 +244,7 @@ Brain/active.md # derived digest, auto-regeneratedinbox/ # raw taste signals, sig-<date>-<slug>.mdprocessed/ # signals already folded into a preference+ archived/ # unconsumed signals older than dream.contradiction_window_dayspreferences/ # active rules: pref-<slug>.md, status unconfirmed | confirmedretired/ # ret-<slug>.md with retired_reasonlog/ # YYYY-MM-DD.md, append-only event log (dream / apply-evidence / etc.)@@ -266,7 +267,7 @@ Three architectural invariants:- **Filesystem-first.** No database, no daemon. Every artifact is plain Markdown with YAML frontmatter; backup is `cp -r` or `tar`.- **Deterministic core.** The `dream` algorithm is a pure function of inputs (signals, preferences, log, configuration, current time). No LLM calls inside the core. Semantic merging, if needed, is delegated to external agents via the same CLI / MCP surface. External judgment (the bench judge, the hygiene conflict resolver) goes through one sanctioned fail-open boundary: the operator-configured command bridge (`src/core/reliability/command-bridge.ts`).-- **Pre-run snapshot + atomic per-file writes.** Each `dream` run takes a `.snapshots/<run_id>.tar.zst` before any state change; per-file writes go through `fs-atomic` (temp + rename). Combined with retention of the most-recent N snapshots, this gives reversible, audit-friendly mutation.+- **Pre-run snapshot + atomic per-file writes.** Each `dream` run takes a `.snapshots/<run_id>.tar.zst` before any state change (streamed through a staging file, and published under its final name only once complete); per-file writes go through `fs-atomic` (temp + rename). Combined with retention of the most-recent N snapshots, this gives reversible, audit-friendly mutation.The layered diagram from the top of this document still holds β `Brain/` sits at the same level as the vault files in the bottom layer:diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex a378b44f..87914202 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -114,6 +114,25 @@ passed, so a caller reads the same three-way answer the exit code carries;`ok` is read off that exit code, and being two-valued it means only "notestablished as healthy" when false.+### The automatic Brain upgrade check++`o2b doctor` reports `self_heal_upgrade`. After a plugin update the+full-scope `o2b mcp` server and the `SessionStart` hook bring a stale+`_brain.yaml` / `_BRAIN.md` current in a detached worker+(`o2b brain upgrade --self-heal`, not an operator flag). A failed attempt+is recorded per device in `.open-second-brain/self-heal-upgrade.json`, and+the check then fails with the error, the time of the last attempt, the+number of consecutive failures and the time from which the next automatic+attempt is due; its fix is `o2b brain upgrade --dry-run`. The same record+appears in `o2b brain status` as the `self-heal-upgrade-failed` problem+and at the end of `o2b brain upgrade --dry-run` / `--check` output (JSON:+`self_heal_failure`).++The next automatic attempt waits a cooldown of one hour, doubling with+each consecutive failure up to 24 hours, instead of repeating the same+failing upgrade on every start. `o2b brain upgrade --apply --yes` ignores+the cooldown and clears the record once nothing is pending.+### The codegraph partner check`o2b doctor` consults the optional [codegraph](https://github.com/colbymchenry/codegraph)@@ -354,7 +373,7 @@ o2b brain unprotect (CLI-only) Remove the Open-Second-Brain-managed deo2b brain snapshot log (CLI-only) Newest-first listing of every recovery point: run id, created_at, typed reason, size, manifest presence, derived-store coverage; --reason filters (unregistered value exits 2), --limit caps, --jsono2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, or snapshot vs live Brain/o2b brain rollback (CLI-only) Restore Brain/ from a snapshot (--dry-run previews; drift abort vs --force-rollback); --list, the prompt and --json name the snapshot reason ('unknown' when the sidecar records none)-o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes+o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes; --dry-run and --check also print the last failed automatic upgradeo2b brain export Read-only dump of active preferences, or (since v1.50.0) a session-transcript dataset: --format json|llms-txt|transcripts-jsonl [--out <path>] [--force]; the transcript form takes --transcripts <file|dir> and reads no vault at all (see "The transcript corpus" below). Since v1.49.0 the preference bytes pass the shared egress redactor (stderr carries a notice when anything was removed), and a `pref-*.md` the parser cannot read is REFUSED, not skipped: exit 1 naming every unreadable file in one run rather than exit 0 over a shorter list. `o2b brain doctor` reports the same fileso2b brain bank-export (CLI-only) One-file backup bundle: preferences, the page graph, page contracts, the sources dashboard. Redacted on the way out; refuses with exit 1 on an unreadable `pref-*.md` (since v1.49.0)o2b brain bank-import (CLI-only) Restore a bank bundle (--mode skip|overwrite|merge) [--trusted-restore]. Preference rows restore UNTRUSTED by default: every row lands `unconfirmed`, unpinned, at low confidence, on a fresh trial window dated from the restore - including a row the bundle already marked unconfirmed - and the run names each row it reset; `--trusted-restore` keeps the carried status, confidence, pin and window verbatim, for a backup you vouch for. A malformed preference already in the DESTINATION does not abort the import: the rows restore and the run prints `topic-key check incomplete: <path>` for each rule the topic-collision scan could not read, because that list is then a partial answer (since v1.49.0)@@ -644,6 +663,20 @@ under `--json`; `line` is 0 for a warning about no single pattern line,which covers both a `--src-subpath` warning and an ignore file that couldnot be read.+Parallel ingest workers share the content manifest, the plan checkpoint,+the session ledger and the git record store, and each write to one of them+waits for a file lock. The wait is 5 000 ms by default; set+`OPEN_SECOND_BRAIN_LOCK_WAIT_MS` (a whole number of milliseconds, `0` means+one attempt) to give a slow host (antivirus scanning, network or synced+folders) a longer one. A value that is not a whole number is an error, not+the default. The variable does not change the one-second wait of+interactive commands such as the architect run. Waiters take turns: a+writer that releases a lock someone is waiting on hands it over before it+takes it again. A write that still cannot get the lock is refused with+`ELOCKED` and `lock busy: <lock file>`, writes nothing, and says what to do+next: retry the ingest, run the parallel ingests one at a time, or raise+the wait.+### Trusted recall and memory write surface (since v1.35.0)```text@@ -1146,6 +1179,7 @@ o2b brain dream [run] [--dry-run] | stage | validate <run-id> | apo2b brain dream retriage R re-run the deterministic salience gate (`dream.salience_threshold`) against staged bundle R and report the delta: which facts would newly enter or leave the rollup ladder's fold set, each named with its current and its staged score. Read-only - the bundle is never rewritten, so re-stage to adopt the new partition. An unknown bundle, or one staged before the gate shipped, exits 2 naming the reason. Mirrors MCP `brain_dream` `action: "retriage"`o2b brain dream --step S run ONE independently-runnable step instead of the full pass: `scan` (pure read) or `heal-enrich` (asking for it is the opt-in, so the config gate is not consulted). Any other token - including a dream reporting phase - exits 2 with the specific reason that step cannot run alone and the runnable set. Returns a partial result marked `partial: true`, never a run summary. Mirrors MCP `brain_dream` `step`o2b brain dream --gate N=V override one phase gate for THIS RUN ONLY (`--gate heal_enrich=true|false`); repeatable, never written back to `Brain/_brain.yaml`, so a targeted pass needs no config edit and no revert. An unknown gate or a non-boolean value exits 2 naming the known gates. Mirrors MCP `brain_dream` `gates: {heal_enrich: bool}`+o2b brain dream (archive) every run also moves inbox signals older than `dream.contradiction_window_days` that it did not consume into `Brain/inbox/archived/` (never deleted; `archived_signals` in the summary and the log event, previewed by `--dry-run`, count in MCP `archived_signals_count`). `dream.archive_stale_signals: false` turns it off; `o2b brain doctor` reports `inbox-archivable` while a pass is dueo2b brain doctor gains the removed-tool-reference warning: vault notes, root instruction files, and installed skills naming a tool removed in 1.0.0 are flagged with the replacemento2b brain doctor opt-in `entity-alias-candidate` lint (off by default): with `entity_semantic_dedup_enabled: true` surfaces lexical entity-name variants ("Google LLC" vs "Google Inc") as PROPOSAL-ONLY alias-merge candidates via a deterministic jaccard layer (`entity_semantic_dedup_lexical_threshold`, default 0.8); never auto-merges or rewrites the identity key. The embedding-cosine layer (`entity_semantic_dedup_threshold`, default 0.92, reuses the configured embedding provider) is exposed as a library reader for apply planso2b brain daily | weekly | monthly | morning-brief | timeline@@ -1181,6 +1215,22 @@ Which emitters those verbs actually have is not taken on trust. `tests/cli/progrFor the two verbs that do hold a handle, a second interrupt is not intercepted and falls through to the default handler, so a wedged run is always killable by pressing the key twice. And an interrupt that arrives while such a verb is in a region with no checkpoint - opening a store, writing a report - is not swallowed: the verb prints `interrupted: SIGINT arrived while β¦ stopping now` and ends with the signal's code rather than returning 0. A run the operator stopped never exits 0.+## Lock and cache overrides (since v1.61.0)++Three environment variables tune how long a writer waits for a shared lock+and where the machine-local dedup cache lives. None of them has a+`_brain.yaml` key: they describe the host, not the vault.++| Variable | Default | Effect |+| --- | --- | --- |+| `OPEN_SECOND_BRAIN_LOCK_WAIT_MS` | `5000` | How long a write to shared ingest state (content manifest, plan checkpoint, session ledger, git record store) waits for its lock before it is refused with `ELOCKED`. A whole number of milliseconds; `0` means one attempt; anything else is an error. The one-second interactive wait is not affected. See [Source pipeline integrity](#source-pipeline-integrity-and-operator-tooling-since-v1340). |+| `OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR` | the user cache directory, `open-second-brain/dedup-index/` | Where the signal dedup index cache is kept, one `<vault-digest>.json` per vault, outside the vault. |+| `OPEN_SECOND_BRAIN_DEDUP_CACHE` | on | `0` turns the dedup index cache off; every capture then walks the inbox, `processed/` and `archived/` in full. |++The automatic Brain upgrade worker takes no override: its lock is+`.open-second-brain/self-heal-upgrade.lock` in the vault, so a hook, the MCP+server and the worker agree on it whatever their temp directories are.+## Vault scopeSingle scope policy for every vault walker: `vault.ignore_paths` excludes, and the optional `vault.include_paths` allowlist narrows. A path is in scope when it is not excluded AND, if an allowlist is declared, under one of its roots. Absent, the allowlist changes nothing; an empty one is refused at parse time, because a list admitting no path is an off switch on indexing rather than a boundary. A dead include root is an error-severity `vault-include-missing-path` doctor finding β unlike a dead exclusion, it can leave the index empty.@@ -1255,7 +1305,7 @@ hand-written copies.### The catalogue and the two tiers-**40 declared surfaces**, printed whole. A row says what this build CAN keep+**45 declared surfaces**, printed whole. A row says what this build CAN keepat that location, never that this machine has it; presence is the measuredhalf. They are grouped by what losing one costs, which is the first thing amigration needs:@@ -1269,7 +1319,7 @@ The tier is a RECOVERY story, not a location: `Brain/.state/anticipatory/`sits inside the Markdown tree and is `derived` because deleting it costs onerecomputation, and the search index sits outside it and is `derived` for thesame reason. Whether a surface can hold memory CONTENT is a separate axis,-reported per row and counted in the summary line - 15 of the 40 can.+reported per row and counted in the summary line - 17 of the 45 can.Only two overrides move anything: `OPEN_SECOND_BRAIN_SEARCH_DB` /`search_db_path` relocate the search store and everything that follows it,diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 173e75a8..309cc0fa 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -36,7 +36,8 @@ caller names and can move a note to a second top-level directory,β βββ active.md # derived: confirmed + quarantine + recently retiredβ βββ inbox/ # raw taste signalsβ β βββ sig-<date>-<slug>.md-β β βββ processed/ # signals already folded into rules+β β βββ processed/ # signals already folded into rules+β β βββ archived/ # unconsumed signals past the contradiction windowβ βββ preferences/ # active rulesβ β βββ pref-<slug>.md # status: unconfirmed | confirmed | quarantineβ βββ retired/ # archived rules@@ -277,6 +278,7 @@ flowchart TDA12 --> A14A13 --> A14A14[Move consumed signals to processed/]+ A14 --> A15[Archive unconsumed signals older than the window to archived/]endApply --> LogEvent["Append dream event to log/today.md"]@@ -291,6 +293,29 @@ Key rules baked into the pipeline:created only when `candidate_threshold` (default 3) **same-sign**signals on one topic appear within `contradiction_window_days`.Mixed signals cancel and the rule does not form.+- **Inbox archive.** A signal outside `contradiction_window_days` counts+ toward nothing, and never will again, so a signal the run did not+ consume and that is older than the window moves byte for byte to+ `Brain/inbox/archived/` (`archived_signals` in the summary and the log+ event; `--dry-run` previews it). A stale file stays in the inbox only+ when it is tombstoned, does not parse as a signal (including an+ unparseable `created_at`), or its name is already taken in `archived/`+ (a warning names it); a past `expiration_date` does not archive a+ signal still inside the window, because the pass still counts it. The+ rule runs against the earlier of `--now` and the real time, so a pass+ with a future `--now` archives nothing still inside the window today. A+ staged bundle does not treat newly archivable signals as drift.+ Archived signals stay readable: the pass reads them as history (a+ preference evidenced by one keeps its sign), and query, backlinks,+ sources, expiration, forget, the claim graph and the doctor record+ checks include them.+ They also stay in the capture dedup index, so re-importing an old+ session does not re-create them. `dream.archive_stale_signals: false`+ keeps them in the inbox; raising `contradiction_window_days` later does+ not bring archived signals back, move them by hand if that is wanted.+ `o2b brain doctor` reports `inbox-archivable` while a pass is due,+ counting the signals the pass selects for the archive (a `--dry-run`+ archives the same set less any signal it consumes instead).- **Intent review is audit data.** Each run computes `intent_reviews`before mutation so operators can see topics that are ready, weak, orconflicted. The review is exposed by `dream`, `brain_review_candidates`,@@ -542,7 +567,7 @@ are mirrored in MCP; destructive operations are CLI-only by design.| Toggle pin | `o2b brain pin / unpin` | β (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` || Protect Brain/ | `o2b brain protect / unprotect` | β (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` || Restore snapshot | `o2b brain rollback` | β (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |-| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. |+| Upgrade managed files | `o2b brain upgrade` | β (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. After a plugin update the MCP server and the `SessionStart` hook run the same upgrade in a detached worker, off the start-up path, and back off after a failure (see `docs/updating.md`). || Export active prefs | `o2b brain export --format json\|llms-txt` | β (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. || Export a transcript corpus | `o2b brain export --format transcripts-jsonl --transcripts <file\|dir>` | β (CLI-only) | since v1.50.0: one JSON object per line, one per CONVERSATION, built from recorded session logs. Reads no vault. Messages carry role, text and the NAMES of the tools a turn called, never the tool inputs. `--runtime` filters by adapter; `--since`/`--until` select whole conversations by their start. Guarded record by record; a secret-shaped identifier refuses the whole export and writes nothing. Full contract in [`cli-reference.md`](cli-reference.md). || Force-directed explorer | `o2b brain explorer [--port \| --export]` | β (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |@@ -596,6 +621,15 @@ tool output documented as never backed up (archiving and hashing itmade unrelated cache churn trip the drift gate). Retention defaults toten newest archives.+The archive is streamed: tar writes a staging file and the compressor+reads it, so the size of `Brain/` sets no memory ceiling. The compressor+writes a partial file in `.snapshots/`, and the archive appears under its+final `<run_id>.tar.zst` name only once it is complete, published by an+exclusive hard link that refuses a name already taken; the manifest is+written after that. A snapshot interrupted during compression therefore+leaves no recovery point behind, only a `<run_id>.tar.zst.partial-*` file+that nothing lists; retention removes it once it is a day old.+From v0.10.6 every snapshot ships with a SHA-256 sidecar manifest(`Brain/.snapshots/<run_id>.manifest.json`) listing every regularfile the snapshot **covers** β the same tree, minus the two excluded@@ -900,7 +934,7 @@ differs:```mermaidgraph LRHermes -- "mcp_servers.yaml" --> Stdio["o2b mcp (stdio)"]- ClaudeCode["Claude Code"] -- "bundled .mcp.json" --> Stdio+ ClaudeCode["Claude Code"] -- "plugin.json mcpServers" --> StdioCodex -- "codex mcp add" --> StdioGrokBuild["Grok Build"] -- "config.toml [mcp_servers]" --> StdioOpenClaw -- "native JS plugin" --> InProc["in-process tools"]@@ -913,7 +947,8 @@ graph LR`brain-memory` skill enabled in the active profile (via`hermes-skills-sync enable <profile> brain-memory`) so the LLMrecognises preference triggers in conversation.-- **Claude Code** picks up the bundled `.mcp.json` and the+- **Claude Code** picks up the `mcpServers` declared in the bundled+ `.claude-plugin/plugin.json` and theplugin-shipped `brain-memory/SKILL.md` automatically.- **Codex** registers the MCP server with `codex mcp add`; the sameskill bundle is loaded automatically.diff --git a/docs/mcp.md b/docs/mcp.mdindex 07aabdb0..7434b802 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -1031,7 +1031,7 @@ server to your Codex MCP config the same way as Hermes.## Writer split (Claude Code 2.1.121+)-The plugin's `.mcp.json` ships **two** MCP-server entries:+The plugin manifest `.claude-plugin/plugin.json` declares **two** MCP-server entries inline under `mcpServers` (there is deliberately no `.mcp.json` at the repository root: Claude Code would also load it as a project config for sessions started in a checkout, where `${CLAUDE_PLUGIN_ROOT}` is unset and both servers fail to spawn):- `open-second-brain` - the full surface, whose advertised tool count is stated once under "Tool Highlights" above (including the consolidated `brain_brief`, `brain_analytics`, and `schema_inspect`, plus `brain_health`, `brain_mcp_landscape`, `brain_agent_query`, `brain_agent_diff`, `brain_recall_gate`, `brain_pinned_context`, `brain_memory_bridge`, `brain_pre_compress_pack`, `brain_audit`, `brain_sources`, and `brain_switch_vault`) and 18 hidden deprecated aliases listed under "Consolidated views and deprecated aliases" above; subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.- `open-second-brain-writer` - a minimal always-loaded surface of five tools: `brain_feedback`, `brain_apply_evidence`, `brain_note`, `brain_pinned_context` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md` plus pinned context, v0.16.0). The agent records taste signals, evidence events, milestone notes, and current-task pinned facts - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.diff --git a/docs/metrics.md b/docs/metrics.mdindex f8abd695..d4795913 100644--- a/docs/metrics.md+++ b/docs/metrics.md@@ -80,6 +80,7 @@ writes, and a metric record is a summary, not a report.| `dream_stage` | `o2b brain dream stage` / `apply`, MCP `brain_dream` (since 1.0.0) | `action` (`stage`/`apply`), `run_id`, `proposals`, `sources`, `changed`; apply adds `new_unconfirmed`, `confirmed`, `retired` counts || `prompt_prefix` | decision-panel commit (opt-in `promptPrefixMetric`), context-pack consume (opt-in `promptPrefix`) | `kind` (`write_session`/`context_pack`), `prefix_hash` (sha-256 of the stable preamble), `prefix_chars`, `call_count`, `stable_count` || `vault_vitals` | `o2b brain vitals` | `preferences_scanned`, `domain_diversity`, `connectivity_index`, `orphan_count`, `gap_pressure` |+| `self_heal_upgrade` | `o2b brain upgrade --self-heal` (the detached worker `ensureVaultCurrent` starts) | `outcome` (`applied` / `failed`), `duration_ms`, `files` (rewritten, or pending on `failed`), `error` (on `failed`). An attempt that finds nothing pending writes no row || `self_heal_reindex` | `ensureVaultCurrent` (parent) and `o2b search reindex --self-heal <run-id>` (child) | parent row: `decision` (`spawned` / `skipped_writer_lock`), `run_id` (on `spawned`). Child row: `outcome` (`completed` / `failed`), `run_id`, `duration_ms`, `error` (on `failed`) |Payload fields marked "(lane runs)" appear only on maintenance-lanediff --git a/docs/observability.md b/docs/observability.mdindex 3f0dbf43..f49e7601 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -13,7 +13,10 @@ Open Second Brain records what it did - learning events, recall decisions, serve| Session lineage ledger | `Brain/.state/session-lineage[.<device-id>].jsonl` (+ `session-lineage-gaps[.<device-id>].jsonl`) | `recordLineageObservation()` in `src/core/brain/lineage/ledger.ts` | one JSON record per line, sequence-numbered and hash-chained per file || Session lifecycle audit | `Brain/log/session-lifecycle/` | `captureSessionLifecycleEvent()` in `src/core/brain/session-lifecycle.ts` | JSONL audit rows || Bench runs | `<runs-dir>/<run-id>/` (default `.open-second-brain/bench-runs/`, gitignored) | `runMemoryBench()` in `src/core/bench/phases.ts` | `checkpoint.json`, per-question results, `report.json` |+| Failed automatic upgrade | `.open-second-brain/self-heal-upgrade.json` (per device, not synced with `Brain/`) | `recordSelfHealUpgradeFailure()` in `src/core/maintenance/self-heal-upgrade-state.ts` | one JSON object: `failed_at`, `error`, `consecutive_failures`, `pending`, `retry_after`; read by `o2b doctor` (`self_heal_upgrade`), `o2b brain status` and `o2b brain upgrade --dry-run` || Metrics | `Brain/metrics/<surface>[.<device-id>].jsonl` | `appendMetric()` in `src/core/brain/metrics.ts` | one run-level JSON record per line (see `docs/metrics.md`) |+| Signal archive | `Brain/inbox/archived/sig-*.md` | the dream pass (`archiveStaleSignals()` in `src/core/brain/dream-apply.ts`, policy in `src/core/brain/signal-archive.ts`) | the inbox signal file, moved byte for byte; the moving run's `dream` log event lists every id under `archived_signals` |+| Dedup index cache | `$OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR`, else the user cache dir `open-second-brain/dedup-index/<vault-digest>.json` (outside the vault; `OPEN_SECOND_BRAIN_DEDUP_CACHE=0` disables) | `writeDedupIndexCache()` in `src/core/brain/dedup-index-cache.ts` | one JSON file per vault: per directory its listing digest, count and mtime, per signal file its size, mtime, id and `dedup_hash`; derived, safe to delete |### The per-device shard rule@@ -35,7 +38,7 @@ The `prompt_prefix` metric surface measures STRUCTURAL prompt-prefix stability (| Kind | Fires when ||---|---|-| `dream`, `promote`, `retire`, `noted-redundant`, `signal-suppressed`, `skip-corrupted-frontmatter`, `reconcile` | the deterministic learning pass runs |+| `dream`, `promote`, `retire`, `noted-redundant`, `signal-suppressed`, `skip-corrupted-frontmatter`, `reconcile` | the deterministic learning pass runs. The `dream` event lists signals moved to `inbox/processed/` under `moved_to_processed` and signals moved to `inbox/archived/` (older than `dream.contradiction_window_days`, never consumed) under `archived_signals` || `feedback`, `apply-evidence`, `force-confirmed`, `reject` | a taste signal or evidence event is recorded || `pin`, `unpin`, `rollback`, `merge`, `upgrade` | operator-facing vault maintenance || `freeze`, `unfreeze` | an operator stopped or reopened the content lane for every device that syncs the vault (`o2b brain freeze` / `o2b brain unfreeze`). One event per real transition only - a second freeze, or an unfreeze on an open vault, writes nothing. `freeze` carries the `reason` and the `device_id` it was set from; `unfreeze` carries the `frozen_at`, `by` and `reason` read off the marker before it was removed, which is the only place they survive the file |diff --git a/docs/updating.md b/docs/updating.mdindex e5380bdc..82059381 100644--- a/docs/updating.md+++ b/docs/updating.md@@ -324,7 +324,14 @@ hook), `ensureVaultCurrent` brings an already-initialised vault current,hands-off:- a stale `_brain.yaml` / `_BRAIN.md` is migrated (snapshot-backed, additive;- user content untouched);+ user content untouched) by a detached worker, so the server answers its+ first request and the hook returns without waiting for the planning, the+ pre-apply snapshot or the rewrite. One worker runs per vault per machine:+ the caller claims a lock file before the spawn and the worker releases it.+ A failed attempt is recorded (`o2b doctor` check `self_heal_upgrade`,+ `o2b brain status`, `o2b brain upgrade --dry-run`) and the next automatic+ attempt waits a cooldown (one hour, doubling per consecutive failure, at+ most 24 hours) instead of running again on every start;- a stale-schema or missing search index is rebuilt in the **background** (adetached reindex), so startup never blocks; and as a safety net the searchread path self-heals a stale/missing index on first query;@@ -355,7 +362,10 @@ written into the vault would let one device mark the work done and make anotherskip its own per-device step (the search index is per-device). State checks arecheap reads on every start; only a real migration does work, and the approachalso handles interrupted migrations and downgrades. Any per-device version note-lives outside the vault and is for logging only, never for gating.+lives outside the vault and is for logging only, never for gating. The one+per-device record that does gate, the failed-upgrade marker under+`.open-second-brain/`, only ever delays a retry after a failure; it never marks+an upgrade done.The manual `o2b search reindex` / `o2b brain upgrade` commands still exist forexplicit use; auto-migration just reuses their logic.diff --git a/hooks/lib/process-ceiling.ts b/hooks/lib/process-ceiling.tsindex f1a71f16..126ee157 100644--- a/hooks/lib/process-ceiling.ts+++ b/hooks/lib/process-ceiling.ts@@ -20,6 +20,15 @@* the host's own per-hook timeout is the OUTER bound and this ceiling sits* inside it: the host can kill a wedged process this timer cannot reach.*+ * Long synchronous work that the hook itself runs - the signal dedup walk+ * reads every signal file with blocking I/O - is the one case the timer+ * cannot reach AND the hook can do something about. {@link ceilingSafeguard}+ * hands such work the same deadline as a cooperative `Safeguard`: the walk+ * checks it between files and throws `SafeguardTimeoutError` at the first+ * boundary past the ceiling, so the hook unwinds, audits and exits before+ * the host kills it. Under budget the checkpoints cost a clock read each and+ * change nothing.+ ** ## Which deadline is authoritative** The host's is. It is enforced from outside the process, it survives a@@ -38,6 +47,8 @@* instead of silently disarming the watchdog again.*/+import { createSafeguard, type Safeguard } from "../../src/core/brain/safeguard.ts";+/*** The per-hook timeout every entry in `hooks/hooks.json` declares, in* seconds. Mirrored here because JSON cannot import a constant; the test@@ -74,6 +85,18 @@ export function resolveHookCeilingMs(return Math.floor(value);}+/** Operation name the cooperative ceiling reports on a timeout. */+export const HOOK_CEILING_OPERATION = "hook";++/**+ * A cooperative deadline equal to the ceiling, for synchronous work inside+ * the hook (see the module docblock). Created at the same moment as+ * {@link armProcessCeiling} so both measure from the same start.+ */+export function ceilingSafeguard(ceilingMs: number, now: () => number = Date.now): Safeguard {+ return createSafeguard({ operation: HOOK_CEILING_OPERATION, timeoutMs: ceilingMs, now });+}+export interface ProcessCeilingOptions {/** Hard deadline in milliseconds. */readonly ceilingMs: number;diff --git a/hooks/session-capture.ts b/hooks/session-capture.tsindex 92ab4449..6f410782 100644--- a/hooks/session-capture.ts+++ b/hooks/session-capture.ts@@ -10,9 +10,12 @@* capture may need the signal dedup index (see* `lifecycleEventNeedsDedup`) is handed to a detached worker and the* hook returns at once; every other event is captured inline. The- * dedup walk reads every `sig-*.md` and on a slow mount (WSL 9p) takes- * longer than the host's 10 s timeout - synchronously, so the- * in-process ceiling below could never cut it short.+ * dedup walk reads every `sig-*.md`, which on a slow mount (WSL 9p)+ * could take longer than the host's 10 s timeout. When it does run+ * inline (hand-off disabled or failed) it runs under a cooperative+ * deadline equal to the ceiling (`ceilingSafeguard`), checked between+ * files, so it stops and the hook exits cleanly before the host kills+ * it.* - WORKER (`--deferred <spool>`): reads the spooled payload, deletes the* spool, and captures with no host deadline. Workers for one vault run* one at a time, so two deferred events cannot both miss each other's@@ -34,7 +37,12 @@ import {lifecycleEventNeedsDedup,} from "../src/core/brain/session-lifecycle.ts";import { hookAuditDir } from "../src/core/brain/paths.ts";-import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";+import { SafeguardTimeoutError, type Safeguard } from "../src/core/brain/safeguard.ts";+import {+ armProcessCeiling,+ ceilingSafeguard,+ resolveHookCeilingMs,+} from "./lib/process-ceiling.ts";import { appendAuditRecord } from "../src/core/reliability/audit.ts";import { normalizeHookPayload, readHookInput } from "./lib/stdin.ts";@@ -129,12 +137,24 @@ async function acquireWorkerLock(vault: string): Promise<(() => void) | null> {}}-async function capture(vault: string, payload: unknown): Promise<void> {+async function capture(vault: string, payload: unknown, safeguard: Safeguard): Promise<void> {// Normalize grok's camelCase payload to the internal snake_case shape so the// lifecycle capture reads the same fields it does for Claude Code and Codex.- await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {- agent: resolveAgentName(),- });+ try {+ await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {+ agent: resolveAgentName(),+ safeguard,+ });+ } catch (err) {+ // The cooperative deadline tripped inside synchronous work (the dedup+ // walk): the same verdict the ceiling timer records, reached from the+ // inside. Nothing was written past the checkpoint.+ if (err instanceof SafeguardTimeoutError) {+ audit(vault, "hook_ceiling_exceeded", { cooperative: true });+ return;+ }+ throw err;+ }}async function runWorker(spool: string): Promise<void> {@@ -156,9 +176,10 @@ async function runWorker(spool: string): Promise<void> {ceilingMs: WORKER_CEILING_MS,onExpire: () => audit(vault, "hook_ceiling_exceeded", { mode: "deferred" }),});+ const safeguard = ceilingSafeguard(WORKER_CEILING_MS);const release = await acquireWorkerLock(vault);try {- await capture(vault, payload);+ await capture(vault, payload, safeguard);} finally {release?.();disarm();@@ -170,10 +191,12 @@ async function runHook(): Promise<void> {// continuity append) self-terminates at the ceiling instead of orphaning// the hook process or blocking the host agent.let auditVault: string | null = null;+ const ceilingMs = resolveHookCeilingMs();const disarm = armProcessCeiling({- ceilingMs: resolveHookCeilingMs(),+ ceilingMs,onExpire: () => audit(auditVault, "hook_ceiling_exceeded", {}),});+ const safeguard = ceilingSafeguard(ceilingMs);try {const vault = resolveVault();if (vault === null) return;@@ -186,7 +209,7 @@ async function runHook(): Promise<void> {}const normalized = normalizeHookPayload(payload);if (deferEnabled() && lifecycleEventNeedsDedup(normalized) && handOff(normalized)) return;- await capture(vault, normalized);+ await capture(vault, normalized, safeguard);} finally {disarm();}diff --git a/install/claudecode.md b/install/claudecode.mdindex cee02a30..39383713 100644--- a/install/claudecode.md+++ b/install/claudecode.md@@ -1,8 +1,9 @@# Claude CodeClaude Code installs OSB through its marketplace subsystem. The-bundled `.mcp.json` auto-registers the MCP server so there is no-explicit `claude mcp add` step.+`mcpServers` block in the bundled `.claude-plugin/plugin.json`+auto-registers both MCP servers, so there is no explicit+`claude mcp add` step.## 1. Install the plugin@@ -31,7 +32,7 @@ o2b brain init --vault /path/to/vault`o2b init` persists `vault`, `agent_name`, and `timezone` into`~/.config/open-second-brain/config.yaml`. The auto-registered-`.mcp.json` calls `o2b mcp` with no flags; the server reads the+servers call `o2b mcp` with no vault flags; the server reads thepersisted config at spawn time.## 4. Verifydiff --git a/install/windows.md b/install/windows.mdindex 128211aa..79c02621 100644--- a/install/windows.md+++ b/install/windows.md@@ -65,8 +65,8 @@ carries the host.`bun run <plugin>\src\cli\main.ts mcp`, without a console window, and readsthe config from `%LOCALAPPDATA%\open-second-brain\config.yaml`.- **Claude Code** (`claude.exe`) - install the plugin as in- [`claudecode.md`](claudecode.md). Claude Code starts the `.mcp.json`- command through `cmd.exe /d /s /c`, which resolves the extensionless+ [`claudecode.md`](claudecode.md). Claude Code starts the plugin's MCP+ server command through `cmd.exe /d /s /c`, which resolves the extensionless`scripts/o2b` to its `scripts\o2b.cmd` sibling via PATHEXT - noWindows-specific plugin config is needed. The lifecycle hooks are POSIXshell commands and run under Git Bash, which Claude Code finds throughdiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 4f06a571..d4969e22 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.60.0",+ "version": "1.61.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 171e3892..721237f6 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.60.0",+ "version": "1.61.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 0bddbead..4cede0bc 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.60.0"+version: "1.61.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex f8507f14..a81cf5ab 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.60.0",+ "version": "1.61.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/codex/README.md b/plugins/codex/README.mdindex 39f80e69..bb61f4df 100644--- a/plugins/codex/README.md+++ b/plugins/codex/README.md@@ -104,7 +104,7 @@ Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`mem| Runtime | Install || ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |-| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/claudecode.md) |+| Claude Code | Marketplace plugin (bundled MCP servers + hooks) - [`install/claudecode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/claudecode.md) || OpenAI Codex | `codex plugin marketplace add ...` then `o2b install --target codex --apply` (MCP servers via `codex mcp add`, or a `config.toml` merge without the binary) - [`install/codex.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/codex.md) || OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/openclaw.md) || opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/opencode.md) |diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 0bddbead..4cede0bc 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.60.0"+version: "1.61.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex aca95397..e6e7a89b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.60.0"+version = "1.61.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.tsindex 40593d0f..4e8cd15f 100644--- a/src/cli/brain/verbs/dream.ts+++ b/src/cli/brain/verbs/dream.ts@@ -575,5 +575,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {if (summary.contradictions.length > 0) ok(`contradictions: ${summary.contradictions.join(", ")}`);if (summary.moved_to_processed.length > 0)ok(`moved_to_processed: ${summary.moved_to_processed.length}`);+ const archived = summary.archived_signals?.length ?? 0;+ if (archived > 0) ok(`archived_signals: ${archived}`);return 0;}diff --git a/src/cli/brain/verbs/extract-signals.ts b/src/cli/brain/verbs/extract-signals.tsindex 6f07681f..d08eae44 100644--- a/src/cli/brain/verbs/extract-signals.ts+++ b/src/cli/brain/verbs/extract-signals.ts@@ -13,6 +13,7 @@*/import { readFileSync } from "node:fs";+import { loadDedupIndex } from "../../../core/brain/dedup-hash.ts";import {commitExtractedSignals,@@ -137,6 +138,9 @@ export async function cmdBrainExtractSignals(argv: string[]): Promise<number> {const res = commitExtractedSignals(vault, sessionRef, payload, {agent: resolveBrainAgent(flags, config),now,+ // Loaded with parallel I/O here, where the caller can await it; the+ // commit's own fallback is the synchronous walk.+ dedup: await loadDedupIndex(vault),});recordExtractPrefilterCommit(vault, decisionModel, res, now);if (asJson) {diff --git a/src/cli/brain/verbs/init.ts b/src/cli/brain/verbs/init.tsindex 22f783b9..0ebaf437 100644--- a/src/cli/brain/verbs/init.ts+++ b/src/cli/brain/verbs/init.ts@@ -102,5 +102,12 @@ export async function cmdBrainInit(argv: string[]): Promise<number> {*/function brainHasNothingRecorded(vault: string): boolean {const { counts } = computeBrainStatus(vault);- return counts.inbox + counts.inbox_processed + counts.preferences + counts.retired === 0;+ return (+ counts.inbox ++ counts.inbox_processed ++ counts.inbox_archived ++ counts.preferences ++ counts.retired ===+ 0+ );}diff --git a/src/cli/brain/verbs/sources.ts b/src/cli/brain/verbs/sources.tsindex 5b04aaa2..41238563 100644--- a/src/cli/brain/verbs/sources.ts+++ b/src/cli/brain/verbs/sources.ts@@ -27,10 +27,14 @@ export async function cmdBrainSources(argv: string[]): Promise<number> {process.stdout.write("no signals\n");return 0;}- const lines = [`sources (${report.total_active} active, ${report.total_processed} processed)`];+ const lines = [+ `sources (${report.total_active} active, ${report.total_processed} processed, ` ++ `${report.total_archived} archived)`,+ ];for (const s of report.sources) {lines.push(- ` ${s.agent} [${s.source_type}] active=${s.active} processed=${s.processed} topics=${s.distinct_topics}`,+ ` ${s.agent} [${s.source_type}] active=${s.active} processed=${s.processed} ` ++ `archived=${s.archived} topics=${s.distinct_topics}`,);}process.stdout.write(lines.join("\n") + "\n");diff --git a/src/cli/brain/verbs/upgrade.ts b/src/cli/brain/verbs/upgrade.tsindex f6f695db..4a92b57d 100644--- a/src/cli/brain/verbs/upgrade.ts+++ b/src/cli/brain/verbs/upgrade.ts@@ -15,6 +15,41 @@ import {readSingleLine,renderUpgradePlanJson,} from "../helpers.ts";+import { info } from "../../output.ts";+import { runSelfHealUpgrade } from "../../../core/maintenance/self-heal-upgrade.ts";+import {+ clearSelfHealUpgradeFailure,+ describeSelfHealUpgradeFailure,+ readSelfHealUpgradeFailure,+ recordSelfHealUpgradeFailure,+ type SelfHealUpgradeFailure,+} from "../../../core/maintenance/self-heal-upgrade-state.ts";++/** JSON shape of a recorded automatic-upgrade failure. */+function failureJson(failure: SelfHealUpgradeFailure): Record<string, unknown> {+ return {+ failed_at: failure.failedAt,+ error: failure.error,+ consecutive_failures: failure.consecutiveFailures,+ pending: failure.pending,+ retry_after: failure.retryAfter,+ };+}++/** Print the plan, plus the last automatic-upgrade failure when one is recorded. */+function printPlan(plan: UpgradePlan, failure: SelfHealUpgradeFailure | null, json: boolean): void {+ if (json) {+ okJson({+ ...renderUpgradePlanJson(plan),+ self_heal_failure: failure === null ? null : failureJson(failure),+ });+ return;+ }+ printUpgradePlanText(plan);+ if (failure !== null) {+ info(`last automatic upgrade: ${describeSelfHealUpgradeFailure(failure)}`);+ }+}export async function cmdBrainUpgrade(argv: string[]): Promise<number> {const { flags } = parse(argv, {@@ -24,9 +59,19 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {yes: { type: "boolean" },check: { type: "boolean" },json: { type: "boolean" },+ // The detached worker `ensureVaultCurrent` starts, with the lock claim+ // it was handed. Not an operator flag: the worker's outcome is+ // recorded, never printed (its streams are ignored).+ "self-heal": { type: "string" },});const { vault } = brainVerbContext(flags);+ const selfHealToken = flags["self-heal"] as string | undefined;+ if (selfHealToken !== undefined) {+ runSelfHealUpgrade(vault, { lockToken: selfHealToken });+ return 0;+ }+if (flags["dry-run"] && flags["apply"])return fail("brain upgrade: --dry-run and --apply are mutually exclusive");if (flags["check"] && flags["apply"])@@ -39,21 +84,15 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {return fail(`upgrade plan failed: ${(exc as Error).message ?? exc}`);}+ const failure = readSelfHealUpgradeFailure(vault);+if (flags["check"]) {- if (flags["json"]) {- okJson(renderUpgradePlanJson(plan));- } else {- printUpgradePlanText(plan);- }+ printPlan(plan, failure, Boolean(flags["json"]));return plan.pending > 0 || plan.errors > 0 ? 2 : 0;}if (!flags["apply"]) {- if (flags["json"]) {- okJson(renderUpgradePlanJson(plan));- } else {- printUpgradePlanText(plan);- }+ printPlan(plan, failure, Boolean(flags["json"]));return 0;}@@ -62,6 +101,8 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {`upgrade aborted: ${plan.errors} file(s) failed to plan; run with --dry-run to inspect the error.`,);if (plan.pending === 0) {+ // Nothing left for the automatic upgrade to retry either.+ clearSelfHealUpgradeFailure(vault);if (flags["json"]) {okJson({ run_id: "", snapshot_path: "", files_updated: [] });} else {@@ -90,9 +131,22 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {}let result;+ const now = new Date();try {- result = applyUpgrade(vault, { now: new Date() });+ result = applyUpgrade(vault, { now });} catch (exc) {+ // Recorded as the automatic path records it, so `o2b doctor` shows+ // the latest failure and the automatic retry waits its cooldown.+ try {+ recordSelfHealUpgradeFailure(+ vault,+ (exc as Error).message ?? String(exc),+ plan.files.filter((f) => f.status === "update").map((f) => f.path),+ now,+ );+ } catch {+ // The error below is what the operator acts on.+ }if (exc instanceof BrainUpgradeError) {process.stderr.write(`error: ${exc.message}\n`);return 1;@@ -100,6 +154,7 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {return fail(`upgrade failed: ${describeErrorChain(exc)}`);}+ clearSelfHealUpgradeFailure(vault);if (flags["json"]) {okJson({run_id: result.run_id,diff --git a/src/cli/main.ts b/src/cli/main.tsindex cd4d889c..d4dfee50 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -24,6 +24,7 @@ import { EGRESS_OUTCOME, redactForEgress } from "../core/egress/guard.ts";import { listSecretReferences } from "../core/secret-ref.ts";import { BRAIN_INDEX_REL } from "../core/brain/paths.ts";import { ensureVaultCurrent } from "../core/maintenance/ensure-current.ts";+import { checkSelfHealUpgrade } from "../core/maintenance/self-heal-upgrade-state.ts";import { doctor } from "../core/doctor.ts";import { checkHermesResolverParity } from "../core/doctor-hermes-parity.ts";import { runReadinessProbes, type ReadinessReport } from "../core/doctor-readiness.ts";@@ -357,6 +358,8 @@ async function cmdDoctor(argv: string[]): Promise<number> {// meaningless there, and this verb is the surface that owns the question.const parity = checkHermesResolverParity({ config, repoRoot });if (parity) results.push(parity);+ // Also outside `doctor()`, which is bundled into the OpenClaw artifact.+ results.push(checkSelfHealUpgrade(vault));} catch (exc) {process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);return DOCTOR_EXIT.failed;diff --git a/src/core/brain/agent-source/vault-provider.ts b/src/core/brain/agent-source/vault-provider.tsindex ad652d5d..444d33f0 100644--- a/src/core/brain/agent-source/vault-provider.ts+++ b/src/core/brain/agent-source/vault-provider.ts@@ -29,7 +29,7 @@ export const vaultAgentSourceProvider: AgentSourceProvider = Object.freeze({function collectVaultContributions(vault: string): ReadonlyArray<AgentSourceContribution> {const dirs = brainDirs(vault);- const signals = collectSignals(dirs.inbox, dirs.processed);+ const signals = collectSignals(dirs.inbox, dirs.processed, dirs.archived);const signalAgentById = new Map(signals.map((signal) => [signal.id, signal.agent]));const contributions: AgentSourceContribution[] = [];diff --git a/src/core/brain/artifact-ref-view.ts b/src/core/brain/artifact-ref-view.tsindex ad20f071..94ed555d 100644--- a/src/core/brain/artifact-ref-view.ts+++ b/src/core/brain/artifact-ref-view.ts@@ -154,6 +154,7 @@ function artifactPath(vault: string, id: string): string | null {dirs.retired,dirs.inbox,dirs.processed,+ dirs.archived,dirs.pending,join(vault, BRAIN_SOURCES_REL),dirs.entities,diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.tsindex 0ec0be82..9cba8d85 100644--- a/src/core/brain/backlinks.ts+++ b/src/core/brain/backlinks.ts@@ -213,6 +213,7 @@ export function buildBacklinkIndex(vault: string, ownerScope?: string | null): BcollectPreferences(dirs.retired, "retired", push, fail);collectSignals(dirs.inbox, push, fail);collectSignals(dirs.processed, push, fail);+ collectSignals(dirs.archived, push, fail);collectLog(vault, dirs.log, push, fail);// Freeze each entry's array so downstream callers can't mutate thediff --git a/src/core/brain/checkpoint-store.ts b/src/core/brain/checkpoint-store.tsindex 377df282..e3563953 100644--- a/src/core/brain/checkpoint-store.ts+++ b/src/core/brain/checkpoint-store.ts@@ -30,7 +30,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";import { DERIVED_STORE_DIR } from "./path-constants.ts";-import { acquireLockSyncWithRetry, type LockHandle } from "./sync-lockfile.ts";+import { acquireLockSyncWithRetry, ingestLockRemedy, type LockHandle } from "./sync-lockfile.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";/**@@ -142,7 +142,9 @@ export function removeCheckpointFile(vault: string, path: string): boolean {* done work silently turned back into pending work on the next resume.*/export function withCheckpointLock<T>(path: string, fn: () => T): T {- const handle: LockHandle = acquireLockSyncWithRetry(path);+ const handle: LockHandle = acquireLockSyncWithRetry(path, undefined, {+ remedy: ingestLockRemedy,+ });try {return fn();} finally {diff --git a/src/core/brain/claim-graph.ts b/src/core/brain/claim-graph.tsindex 941af74b..b8cb9ec9 100644--- a/src/core/brain/claim-graph.ts+++ b/src/core/brain/claim-graph.ts@@ -49,7 +49,14 @@ export const CLAIM_GRAPH_MAX_NODES = 5000;export const CLAIM_GRAPH_VERSION = 1;/** Brain memory subdirectories the projection scans (relative to `Brain/`). */-const SCANNED_SUBDIRS = ["preferences", "retired", "inbox", "inbox/processed", "theses"] as const;+const SCANNED_SUBDIRS = [+ "preferences",+ "retired",+ "inbox",+ "inbox/processed",+ "inbox/archived",+ "theses",+] as const;// ----- Errors ---------------------------------------------------------------diff --git a/src/core/brain/config-template.ts b/src/core/brain/config-template.tsindex 8ca88316..82d28dfb 100644--- a/src/core/brain/config-template.ts+++ b/src/core/brain/config-template.ts@@ -188,6 +188,13 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.f"Opt-in heal-phase enrichment. Left off, the heal phase is a","checkpoint-only no-op.",]),+ example("archive_stale_signals", false, [+ "Unset by default, which archives: inbox signals older than",+ "contradiction_window_days that no preference consumed can never",+ "count toward a candidate again, so dream moves them to",+ "Brain/inbox/archived/ (never deleted). Set false to keep them in",+ "the inbox.",+ ]),example("salience_threshold", 0.2, ["Unset by default, which leaves the salience gate open: every fact","enters the rollup ladder's fold set. Set a number in [0, 1] to fold",diff --git a/src/core/brain/dedup-hash.ts b/src/core/brain/dedup-hash.tsindex c9eefcca..407d7f22 100644--- a/src/core/brain/dedup-hash.ts+++ b/src/core/brain/dedup-hash.ts@@ -18,11 +18,21 @@*/import { createHash } from "node:crypto";-import { existsSync, readdirSync } from "node:fs";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { readFile, stat } from "node:fs/promises";import { join } from "node:path";-import { parseFrontmatter } from "../vault.ts";+import { parseFrontmatterText } from "../vault.ts";+import {+ namesDigest,+ RACY_WINDOW_MS,+ readDedupIndexCache,+ writeDedupIndexCache,+ type CachedDirEntry,+ type CachedFileEntry,+} from "./dedup-index-cache.ts";import { brainDirs } from "./paths.ts";+import type { Safeguard } from "./safeguard.ts";import { normalizeForDedup } from "./text/normalize.ts";export interface DedupHashInput {@@ -37,52 +47,293 @@ export interface DedupIndexEntry {readonly path: string;}+export interface DedupIndexOptions {+ /**+ * Sink for per-file read or parse failures. By default they are skipped+ * silently: the doctor surfaces malformed signals separately, and the+ * dedup builder is best-effort.+ */+ readonly onError?: (path: string, message: string) => void;+ /**+ * Cooperative deadline, checked per directory and per file. The walk is+ * synchronous I/O in {@link buildDedupIndex}, so a timer cannot cut it+ * short; this is how a hook with a host deadline stops it in time.+ */+ readonly safeguard?: Safeguard;+ /**+ * Read every file, trusting nothing from the cache. For a read-back that+ * must measure the disk rather than a record of it (the import census).+ */+ readonly fresh?: boolean;+}++export interface LoadDedupIndexOptions extends DedupIndexOptions {+ /** Parallel file operations for the async walk. Default 32. */+ readonly concurrency?: number;+}++const DEFAULT_CONCURRENCY = 32;+/**- * Read-side complement of {@link computeDedupHash}. Walks- * `Brain/inbox/` and `Brain/inbox/processed/`, parses every- * `sig-*.md`, and builds `hash β {id, path}` (first-seen wins).+ * Read-side complement of {@link computeDedupHash}. Walks `Brain/inbox/`,+ * `Brain/inbox/processed/` and `Brain/inbox/archived/`, and maps every+ * `sig-*.md`'s `dedup_hash` to its `{id, path}` (first seen wins, directories+ * in that order, files in listing order).+ *+ * The archive is included on purpose. It holds inbox signals the dream pass+ * archived because they left the contradiction window unconsumed; they used+ * to stay in the inbox for ever, and so in this index. Leaving them out would+ * let a re-imported old session re-create an archived signal as a fresh+ * inbox signal, which could then count toward a candidate it never earned.*- * Shared between `o2b brain scan-inline` and `o2b brain- * import-session` so the two capture paths cross-deduplicate- * automatically. Both surfaces also mutate the returned map as new- * signals are written, which keeps the index hot for the rest of- * the run.+ * Shared by every capture path (inline scan, session import, session+ * lifecycle, fact extraction, the import census), so they cross-deduplicate.+ * The callers that write also mutate the returned map as they create+ * signals, which keeps it hot for the rest of their run.*- * `onError` is an optional sink for per-file parse failures. By- * default they are silently skipped β the doctor command surfaces- * malformed signals separately, and the dedup builder is best-effort.+ * Revalidated against a machine-local cache (`dedup-index-cache.ts`), so a+ * rebuild reads only what changed. Synchronous; {@link loadDedupIndex} is+ * the same walk with parallel I/O, several times faster on a slow mount.*/export function buildDedupIndex(vault: string,- opts: { onError?: (path: string, message: string) => void } = {},+ opts: DedupIndexOptions = {},): Map<string, DedupIndexEntry> {- const out = new Map<string, DedupIndexEntry>();- const dirs = brainDirs(vault);- for (const dir of [dirs.inbox, dirs.processed]) {+ const started = Date.now();+ const plan = planWalk(vault, opts);+ for (const file of plan.toStat) {+ opts.safeguard?.checkpoint();+ statOne(file);+ }+ for (const file of plan.toParse()) {+ opts.safeguard?.checkpoint();+ parseOne(file, () => readFileSync(file.path, "utf8"), opts.onError);+ }+ return finishWalk(vault, plan, started);+}++/**+ * {@link buildDedupIndex} with the file stats and reads issued in parallel.+ * A slow mount is latency-bound rather than bandwidth-bound: measured on a+ * WSL 9p mount of a Windows drive, 4000 sequential reads took 16 s and the+ * same reads 32 at a time about 1.2 s. It also yields to the event loop, so+ * a process ceiling timer can fire while it runs.+ */+export async function loadDedupIndex(+ vault: string,+ opts: LoadDedupIndexOptions = {},+): Promise<Map<string, DedupIndexEntry>> {+ const started = Date.now();+ const concurrency = Math.max(1, opts.concurrency ?? DEFAULT_CONCURRENCY);+ const plan = planWalk(vault, opts);+ await pool(plan.toStat, concurrency, opts.safeguard, async (file) => {+ try {+ const st = await stat(file.path);+ file.size = st.size;+ file.mtimeMs = st.mtimeMs;+ } catch {+ file.statFailed = true;+ }+ });+ await pool(plan.toParse(), concurrency, opts.safeguard, async (file) => {+ let text: string | null = null;+ try {+ text = await readFile(file.path, "utf8");+ } catch (err) {+ opts.onError?.(file.path, `dedup-index read failed: ${errorText(err)}`);+ return;+ }+ parseOne(file, () => text!, opts.onError);+ });+ return finishWalk(vault, plan, started);+}++// ----- walk internals ------------------------------------------------------++/** One signal file's state during a walk. */+interface WalkFile {+ readonly dir: string;+ readonly name: string;+ readonly path: string;+ size?: number;+ mtimeMs?: number;+ statFailed?: boolean;+ /** Set once the file's fields are known (from the cache or a parse). */+ entry?: CachedFileEntry;+}++interface WalkDir {+ readonly dir: string;+ readonly files: WalkFile[];+ readonly mtimeMs: number | null;+ readonly namesDigest: string;+ readonly fast: boolean;+}++interface WalkPlan {+ readonly dirs: WalkDir[];+ /** Files that need a stat before the cache can vouch for them. */+ readonly toStat: WalkFile[];+ /** Files still unresolved after the stats; computed lazily. */+ toParse(): WalkFile[];+}++function planWalk(vault: string, opts: DedupIndexOptions): WalkPlan {+ const { safeguard } = opts;+ const bd = brainDirs(vault);+ const cache = opts.fresh === true ? null : readDedupIndexCache(vault);+ // Every cached file entry by name, whichever directory it was in: a+ // rename between the three directories keeps size and mtime, so a file+ // the dream pass moved into the archive is reused rather than re-read.+ const byName = new Map<string, CachedFileEntry>();+ if (cache !== null) {+ for (const d of Object.values(cache.dirs)) {+ for (const [name, e] of Object.entries(d.files ?? {})) byName.set(name, e);+ }+ }+ const dirs: WalkDir[] = [];+ const toStat: WalkFile[] = [];+ for (const dir of [bd.inbox, bd.processed, bd.archived]) {+ safeguard?.checkpoint();if (!existsSync(dir)) continue;- for (const name of readdirSync(dir)) {- if (!name.endsWith(".md") || !name.startsWith("sig-")) continue;- const path = join(dir, name);- try {- const [meta] = parseFrontmatter(path);- const hash = meta["dedup_hash"];- const id = meta["id"];- if (- typeof hash === "string" &&- typeof id === "string" &&- hash.length > 0 &&- !out.has(hash)- ) {- out.set(hash, { id, path });+ let names: string[];+ let mtimeMs: number | null = null;+ try {+ names = readdirSync(dir).filter((n) => n.startsWith("sig-") && n.endsWith(".md"));+ mtimeMs = statSync(dir).mtimeMs;+ } catch {+ continue;+ }+ const digest = namesDigest(names);+ const cached = cache?.dirs[dir];+ const fast =+ cached !== undefined &&+ cached.quiet === true &&+ cached.mtimeMs === mtimeMs &&+ cached.count === names.length &&+ cached.namesDigest === digest &&+ names.every((n) => cached.files[n] !== undefined);+ const files: WalkFile[] = names.map((name) => ({ dir, name, path: join(dir, name) }));+ if (fast) {+ for (const f of files) f.entry = cached.files[f.name]!;+ } else {+ toStat.push(...files);+ }+ dirs.push({ dir, files, mtimeMs, namesDigest: digest, fast });+ }+ return {+ dirs,+ toStat,+ toParse: () =>+ toStat.filter((f) => {+ if (f.statFailed === true || f.size === undefined) return true;+ const hit = byName.get(f.name);+ if (hit !== undefined && hit.size === f.size && hit.mtimeMs === f.mtimeMs) {+ f.entry = hit;+ return false;}- } catch (err) {- opts.onError?.(path, `dedup-index parse failed: ${(err as Error).message ?? String(err)}`);+ return true;+ }),+ };+}++function statOne(file: WalkFile): void {+ try {+ const st = statSync(file.path);+ file.size = st.size;+ file.mtimeMs = st.mtimeMs;+ } catch {+ file.statFailed = true;+ }+}++function parseOne(file: WalkFile, read: () => string, onError: DedupIndexOptions["onError"]): void {+ try {+ const [meta] = parseFrontmatterText(read());+ const hash = meta["dedup_hash"];+ const id = meta["id"];+ // A file whose stat failed gets -1, which is never cached (see+ // `finishWalk`), so the next build reads it again.+ file.entry = {+ size: file.size ?? -1,+ mtimeMs: file.mtimeMs ?? -1,+ hash: typeof hash === "string" && hash.length > 0 ? hash : null,+ id: typeof id === "string" ? id : null,+ };+ } catch (err) {+ onError?.(file.path, `dedup-index parse failed: ${errorText(err)}`);+ }+}++function finishWalk(vault: string, plan: WalkPlan, started: number): Map<string, DedupIndexEntry> {+ const out = new Map<string, DedupIndexEntry>();+ const nextDirs: Record<string, CachedDirEntry> = {};+ const racyFloor = started - RACY_WINDOW_MS;+ let changed = false;+ for (const d of plan.dirs) {+ const cachedFiles: Record<string, CachedFileEntry> = {};+ for (const f of d.files) {+ const e = f.entry;+ if (e === undefined) continue;+ if (e.hash !== null && e.id !== null && !out.has(e.hash)) {+ out.set(e.hash, { id: e.id, path: f.path });}+ // Racy-clean: an entry whose mtime is this close to the build could+ // hide a same-tick rewrite, so it is not carried into the cache.+ if (e.size < 0 || e.mtimeMs < 0 || e.mtimeMs > racyFloor) continue;+ cachedFiles[f.name] = e;}+ if (!d.fast) changed = true;+ nextDirs[d.dir] = {+ mtimeMs: d.mtimeMs ?? -1,+ count: d.files.length,+ namesDigest: d.namesDigest,+ quiet: d.mtimeMs !== null && d.mtimeMs <= racyFloor && dirUnchanged(d),+ files: cachedFiles,+ };}+ if (changed) writeDedupIndexCache(vault, nextDirs);return out;}+/** Whether the directory is still as the walk first saw it. */+function dirUnchanged(d: WalkDir): boolean {+ try {+ return statSync(d.dir).mtimeMs === d.mtimeMs;+ } catch {+ return false;+ }+}++/** Run `task` over `items` with at most `limit` in flight; stops on the first error. */+async function pool<T>(+ items: ReadonlyArray<T>,+ limit: number,+ safeguard: Safeguard | undefined,+ task: (item: T) => Promise<void>,+): Promise<void> {+ let next = 0;+ let failed = false;+ const worker = async (): Promise<void> => {+ while (!failed && next < items.length) {+ const item = items[next++]!;+ try {+ safeguard?.checkpoint();+ // oxlint-disable-next-line no-await-in-loop -- a bounded worker pool, sequential per worker by design+ await task(item);+ } catch (err) {+ failed = true;+ throw err;+ }+ }+ };+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));+}++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}+export function computeDedupHash(input: DedupHashInput): string {// Use NUL as the field separator so a topic / principle containing// any printable character can't collide with the next field's prefix.diff --git a/src/core/brain/dedup-index-cache.ts b/src/core/brain/dedup-index-cache.tsnew file mode 100644index 00000000..471847c2--- /dev/null+++ b/src/core/brain/dedup-index-cache.ts@@ -0,0 +1,144 @@+/**+ * Machine-local cache of the signal dedup index (issue #195).+ *+ * `buildDedupIndex` reads the frontmatter of every `sig-*.md` in+ * `inbox/`, `inbox/processed/` and `inbox/archived/`. On a slow mount (WSL's+ * 9p view of a Windows drive) that is roughly 4 ms per file, and the set only+ * grows. This module persists what the walk learned so the next walk reads+ * only what changed.+ *+ * ## Validity+ *+ * The cache must stay correct when a sync tool (Syncthing) rewrites a file+ * under the same name, so it never trusts a file name alone. Two tiers:+ *+ * 1. DIRECTORY. A directory whose listing (count plus a digest of the+ * sorted names) and own mtime are unchanged since a build that saw it+ * QUIET is reused without touching its files. Every way a sync tool or+ * this tool changes a signal file - create, delete, and the+ * write-temp-then-rename a sync tool uses to replace one - changes the+ * directory's mtime, so this tier never serves a replaced file.+ * 2. FILE. Otherwise each file is stat'ed and its entry reused when its+ * size and mtime match the cached ones; any other file is re-read. A+ * replaced file carries a different mtime (a sync tool stamps the+ * remote side's), so it is re-read. The lookup is by file name across+ * all three directories, so a signal the dream pass moved into the+ * archive (a rename keeps size and mtime) is not re-read either.+ *+ * "Quiet" is git's racy-clean rule: a directory or file whose mtime is within+ * {@link RACY_WINDOW_MS} of the build is not trusted by the directory tier or+ * cached at all, because a write in the same timestamp tick would be+ * invisible to the comparison.+ *+ * What neither tier sees: an in-place edit of a signal's `dedup_hash` or `id`+ * frontmatter that keeps the directory listing, the directory mtime, the+ * file size and the file mtime all unchanged. Both fields are written once,+ * when the signal is created, by every writer in this repository.+ *+ * ## Location+ *+ * Outside the vault, under the user cache directory, keyed by a digest of+ * the vault's absolute path: stat data is per machine, and a cache inside a+ * synced vault would be rewritten from every machine in turn. It is listed+ * in the data-ownership statement (`OUT_OF_VAULT_STATE`,+ * `dedup_index_cache`). `OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR` moves it;+ * `OPEN_SECOND_BRAIN_DEDUP_CACHE=0` turns it off.+ *+ * Every read and write here is best-effort: a missing, corrupt, foreign or+ * unwritable cache means a full walk, never a wrong index or a failure.+ */++import { createHash } from "node:crypto";+import { mkdirSync, readFileSync } from "node:fs";+import { join, resolve } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { APP_DIR_NAME, cacheBaseDir } from "../platform-dirs.ts";++/** Bumped whenever the file layout below changes; other versions are ignored. */+const CACHE_VERSION = 1;++/** A timestamp this close to the build is not trusted (racy-clean rule). */+export const RACY_WINDOW_MS = 2_000;++const CACHE_DIR_ENV = "OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR";+const CACHE_SWITCH_ENV = "OPEN_SECOND_BRAIN_DEDUP_CACHE";+const CACHE_SUBDIR = "dedup-index";++/** One file's cached parse: stat identity plus the two fields the index needs. */+export interface CachedFileEntry {+ readonly size: number;+ readonly mtimeMs: number;+ readonly hash: string | null;+ readonly id: string | null;+}++/** One directory's cached state. */+export interface CachedDirEntry {+ readonly mtimeMs: number;+ readonly count: number;+ readonly namesDigest: string;+ /** True when the build saw the directory outside the racy window. */+ readonly quiet: boolean;+ readonly files: Readonly<Record<string, CachedFileEntry>>;+}++export interface DedupIndexCacheData {+ readonly version: number;+ readonly vault: string;+ /** Keyed by the directory's absolute path. */+ readonly dirs: Readonly<Record<string, CachedDirEntry>>;+}++/**+ * Where this vault's cache lives, or null when caching is switched off.+ * Resolved per call so a test (or an operator) can move or disable it.+ */+export function dedupIndexCachePath(+ vault: string,+ env: Record<string, string | undefined> = process.env,+): string | null {+ if (env[CACHE_SWITCH_ENV]?.trim() === "0") return null;+ const override = env[CACHE_DIR_ENV]?.trim();+ const dir = override ? override : join(cacheBaseDir(), APP_DIR_NAME, CACHE_SUBDIR);+ const key = createHash("sha256").update(resolve(vault)).digest("hex").slice(0, 32);+ return join(dir, `${key}.json`);+}++/** Digest of a directory listing, independent of enumeration order. */+export function namesDigest(names: ReadonlyArray<string>): string {+ return createHash("sha256").update(names.toSorted().join("\u0000")).digest("hex");+}++/** Read the cache for `vault`; null when absent, unreadable, foreign or stale-format. */+export function readDedupIndexCache(vault: string): DedupIndexCacheData | null {+ const path = dedupIndexCachePath(vault);+ if (path === null) return null;+ try {+ const data = JSON.parse(readFileSync(path, "utf8")) as Partial<DedupIndexCacheData>;+ if (data.version !== CACHE_VERSION) return null;+ // A digest collision or a copied cache directory must not hand one+ // vault another vault's index.+ if (data.vault !== resolve(vault)) return null;+ if (data.dirs === null || typeof data.dirs !== "object") return null;+ return data as DedupIndexCacheData;+ } catch {+ return null;+ }+}++/** Persist the cache; best-effort, never throws. */+export function writeDedupIndexCache(+ vault: string,+ dirs: Readonly<Record<string, CachedDirEntry>>,+): void {+ const path = dedupIndexCachePath(vault);+ if (path === null) return;+ try {+ mkdirSync(join(path, ".."), { recursive: true, mode: 0o700 });+ const data: DedupIndexCacheData = { version: CACHE_VERSION, vault: resolve(vault), dirs };+ atomicWriteFileSync(path, JSON.stringify(data));+ } catch {+ // A read-only home or a full disk costs the next caller a full walk.+ }+}diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 56a1b304..8adfccc8 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -271,6 +271,14 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain doctor",autoRepairable: false,},+ {+ // GitHub #216. The automatic managed-file upgrade failed and is+ // backing off; the dry run shows the pending change and the error.+ code: "self-heal-upgrade-failed",+ issueClass: "automatic Brain upgrade failed",+ nextCommand: "o2b brain upgrade --dry-run",+ autoRepairable: false,+ },{code: "doctor-warnings",issueClass: "doctor warnings",@@ -515,6 +523,17 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain payload gc",autoRepairable: false,},+ {+ // Inbox signals that left the contradiction window unconsumed+ // (issue #195). Spelled as a literal for the same reason+ // `vault-frozen` above is. The exit is the pass that archives+ // them; `autoRepairable` stays false because the doctor's repair+ // planner does not run dream, the operator does.+ code: "inbox-archivable",+ issueClass: "inbox signals that can no longer become candidates",+ nextCommand: "o2b brain dream",+ autoRepairable: false,+ },{code: "recovery-point-stale",issueClass: "newest recovery point older than the liveness window",diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 6691221c..20828030 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -47,6 +47,7 @@ import { statSync } from "node:fs";import { activeBudgetPressureCheck } from "./doctor/active-budget-check.ts";import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./doctor/check.ts";+import { inboxArchivableCheck } from "./doctor/inbox-archive-check.ts";import { capturePatternCheck, configCheck, vaultIgnoreCheck } from "./doctor/config-checks.ts";import { entityRegistryCheck } from "./doctor/entity-checks.ts";import { brokenBacklinkCheck } from "./doctor/link-checks.ts";@@ -165,6 +166,7 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([syncConflictLogCheck,frozenVaultCheck,secretsSyncExposureCheck,+ inboxArchivableCheck,logChainCheck,symlinkEscapeCheck,frontmatterUncertaintyProbe,diff --git a/src/core/brain/doctor/inbox-archive-check.ts b/src/core/brain/doctor/inbox-archive-check.tsnew file mode 100644index 00000000..6d6e94f0--- /dev/null+++ b/src/core/brain/doctor/inbox-archive-check.ts@@ -0,0 +1,61 @@+/**+ * `inbox-archivable` (issue #195): how many inbox signals can no longer+ * become candidates.+ *+ * The dream pass archives an inbox signal once it is older than+ * `dream.contradiction_window_days` and was never consumed+ * (`signal-archive.ts`). Until a pass runs, those signals sit in the inbox+ * and every capture's dedup walk pays for them. This check states the inbox+ * size and the archivable count, and names the pass that clears them.+ *+ * A WARNING, not an error: nothing is broken, and the next dream pass fixes+ * it without a decision from anyone. Silent when nothing is archivable, when+ * the archive is switched off (`dream.archive_stale_signals: false`), and+ * when `_brain.yaml` could not be loaded (the config check reports that).+ *+ * The selection is the pass's own (`selectArchivableSignals` over the+ * records `scanInboxForArchive` reads the way the scan does), so the count+ * here is exactly what `o2b brain dream --dry-run` would archive less the+ * signals that pass consumes instead. Tombstoned and unparseable inbox files+ * and signals whose archive name is taken are never archived, so they are+ * never counted either, and the warning clears once a pass has run. A file+ * that cannot be read or parsed is skipped on its own; it does not take the+ * check down with it.+ */++import { brainDirs } from "../paths.ts";+import { scanInboxForArchive } from "../dream-scan.ts";+import { archiveEnabled, selectArchivableSignals } from "../signal-archive.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";++/** Inbox signals that left the contradiction window unconsumed. */+export const INBOX_ARCHIVABLE_CODE = "inbox-archivable";++export const inboxArchivableCheck: DoctorCheck = {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ const cfg = ctx.config;+ if (cfg === undefined || !archiveEnabled(cfg)) return;+ const windowDays = cfg.dream.contradiction_window_days;+ const scan = scanInboxForArchive(ctx.vault);+ const archivable = selectArchivableSignals(+ scan.signals,+ scan.archivedNames,+ windowDays,+ ctx.now,+ ).archivable.length;+ if (archivable === 0) return;+ const total = scan.inboxFiles;+ out.issues.push({+ severity: "warning",+ code: INBOX_ARCHIVABLE_CODE,+ path: brainDirs(ctx.vault).inbox,+ message:+ `Brain/inbox/ holds ${total} signal(s); ${archivable} of them are older than ` ++ `dream.contradiction_window_days (${windowDays}) and can no longer become candidates. ` ++ "The next dream pass moves them to Brain/inbox/archived/ unless a preference consumes " ++ "them first; nothing is deleted",+ } satisfies DoctorIssue);+ },+};diff --git a/src/core/brain/doctor/record-checks.ts b/src/core/brain/doctor/record-checks.tsindex 4479a68e..f5d6aaca 100644--- a/src/core/brain/doctor/record-checks.ts+++ b/src/core/brain/doctor/record-checks.ts@@ -28,7 +28,7 @@ export const signalCheck: DoctorCheck = {run({ vault, idIndex }, { issues, uncertain }) {const dirs = brainDirs(vault);const swept = recordSweep("signal", uncertain);- for (const dir of [dirs.inbox, dirs.processed]) {+ for (const dir of [dirs.inbox, dirs.processed, dirs.archived]) {forEachBrainFile(dir, "sig-", swept, (path, filename) => {try {const sig = parseSignal(path);diff --git a/src/core/brain/doctor/records.ts b/src/core/brain/doctor/records.tsindex b856074a..97fa5b09 100644--- a/src/core/brain/doctor/records.ts+++ b/src/core/brain/doctor/records.ts@@ -186,6 +186,7 @@ export function collectAllBasenames(vault: string, swept?: SweptPath): ReadonlySdirs.brain,dirs.inbox,dirs.processed,+ dirs.archived,dirs.preferences,dirs.retired,dirs.log,diff --git a/src/core/brain/doctor/semantic-health-check.ts b/src/core/brain/doctor/semantic-health-check.tsindex e4745ec1..dc6b9464 100644--- a/src/core/brain/doctor/semantic-health-check.ts+++ b/src/core/brain/doctor/semantic-health-check.ts@@ -67,14 +67,14 @@ interface SignalSignRecord {}/**- * Read every `sig-*.md` across `inbox/` and `processed/`, projecting+ * Read every `sig-*.md` across `inbox/`, `processed/` and `archived/`, projecting* each to its id, sign, and principle. Files that fail to parse are* skipped (their schema errors surface through the signal record check).*/function readAllSignalRecords(vault: string): ReadonlyArray<SignalSignRecord> {const dirs = brainDirs(vault);const out: SignalSignRecord[] = [];- for (const dir of [dirs.inbox, dirs.processed]) {+ for (const dir of [dirs.inbox, dirs.processed, dirs.archived]) {if (!existsSync(dir)) continue;for (const name of readdirSync(dir)) {if (!name.endsWith(".md") || !name.startsWith("sig-")) continue;diff --git a/src/core/brain/dream-apply.ts b/src/core/brain/dream-apply.tsindex 272f56f3..c0a0cbc4 100644--- a/src/core/brain/dream-apply.ts+++ b/src/core/brain/dream-apply.ts@@ -23,7 +23,8 @@* knows where that point is.*/-import { existsSync } from "node:fs";+import { existsSync, mkdirSync } from "node:fs";+import { basename } from "node:path";import { appendDecisionChangeReceipt } from "./decisions/receipts.ts";import { preferenceSlug, type PlanState } from "./dream-plan.ts";@@ -35,7 +36,7 @@ import { collectEvidenceForSlug } from "./evidence.ts";import { runHealEnrichment } from "./heal-run.ts";import { CHAIN_DECAY_STALE_DAYS } from "./inject-governor.ts";import { appendLogEvent } from "./log.ts";-import { preferencePath, processedSignalPath } from "./paths.ts";+import { archivedSignalPath, brainDirs, preferencePath, processedSignalPath } from "./paths.ts";import { moveToRetired, parsePreference } from "./preference.ts";import { writePreferenceTxn } from "./preference-txn.ts";import { isoSecond } from "./time.ts";@@ -81,6 +82,8 @@ export interface DreamApplyInput {export interface DreamApplyResult {/** Signal ids actually moved into `processed/`. */readonly moved: string[];+ /** Signal ids actually moved into `inbox/archived/`. */+ readonly archived: string[];/** Retires the destructive-from-confirmed gate declined. */readonly gatedRetires: DreamGatedRetireEntry[];/** User pages the opt-in heal phase enriched. */@@ -95,6 +98,11 @@ export function plannedSignalMoveIds(plan: PlanState): string[] {return Array.from(plan.signalsToMove.values(), (sig) => sig.id);}+/** Signal ids a dry run WOULD archive; the archive step's dry-run count. */+export function plannedSignalArchiveIds(plan: PlanState): string[] {+ return Array.from(plan.signalsToArchive.values(), (sig) => sig.id);+}+export function applyDreamPlan(input: DreamApplyInput): DreamApplyResult {const { vault, cfg, now, plan, refresh, wikilinkToRun, workrun } = input;const agent = input.agentName ?? DEFAULT_DREAM_AGENT;@@ -122,6 +130,7 @@ export function applyDreamPlan(input: DreamApplyInput): DreamApplyResult {workrun?.checkpoint(WORKRUN_PHASE.retireComplete);const moved = moveConsumedSignals(vault, plan);+ const archived = archiveStaleSignals(vault, plan);const healEnriched = input.healEnrichEnabled? runHealEnrichmentSafely(vault, input.safeguard): 0;@@ -131,7 +140,7 @@ export function applyDreamPlan(input: DreamApplyInput): DreamApplyResult {// of the two, so it is never a claim about work still to come.workrun?.checkpoint(WORKRUN_PHASE.healComplete);- return { moved, gatedRetires, healEnriched };+ return { moved, archived, gatedRetires, healEnriched };}/**@@ -355,6 +364,44 @@ function moveConsumedSignals(vault: string, plan: PlanState): string[] {return moved;}+/**+ * Step 4b: move every signal the archive policy selected (see+ * `signal-archive.ts`) from `inbox/` to `inbox/archived/`, byte for byte.+ *+ * Never overwrites: a destination that exists is left alone and the signal+ * stays in the inbox (the planner already skips names it saw in the+ * archive; this covers a file that appeared since the scan). A failed move+ * is reported and the signal stays where it was, so a rerun picks it up.+ *+ * No deadline checkpoint inside the loop, like the processed/ move above: a+ * pass stopped half way would leave archived files the run's log never+ * names. The pass's own post-mutation checkpoint follows immediately.+ */+function archiveStaleSignals(vault: string, plan: PlanState): string[] {+ const archived: string[] = [];+ if (plan.signalsToArchive.size === 0) return archived;+ mkdirSync(brainDirs(vault).archived, { recursive: true });+ for (const sig of plan.signalsToArchive.values()) {+ try {+ const dest = archivedSignalPath(vault, basename(sig.path));+ if (existsSync(dest)) {+ process.stderr.write(+ `warning: archive signal ${sig.id}: ${basename(dest)} already exists in ` ++ `inbox/archived/; left in the inbox\n`,+ );+ continue;+ }+ renameWithRetry(sig.path, dest);+ archived.push(sig.id);+ } catch (err) {+ process.stderr.write(+ `warning: archive signal ${sig.id} to inbox/archived/ failed: ${(err as Error).message}\n`,+ );+ }+ }+ return archived;+}+/*** Heal phase (F6): opt-in deterministic vault enrichment, run after the* retire/move mutations (heal-after-mutations). Off by default so thediff --git a/src/core/brain/dream-plan-topics.ts b/src/core/brain/dream-plan-topics.tsindex 33ad533a..0c130170 100644--- a/src/core/brain/dream-plan-topics.ts+++ b/src/core/brain/dream-plan-topics.ts@@ -65,7 +65,19 @@ export function planTopics(scan: ScanResult, cfg: BrainConfig, now: Date): PlanS// signals for the create/rebut decisions; processed signals stay in the// global log via `evidenced_by` already.const byTopic = new Map<string, TopicGroup>();+ // Archived signals were inbox signals until a previous pass archived them,+ // and the sign derivation below treated them as members of the active+ // group. Kept per key so it still does: archiving must not change which+ // way a preference points (see `deriveActiveSign`).+ const archivedByTopic = new Map<string, SignalRecord[]>();for (const rec of scan.signals) {+ if (rec.archived) {+ const key = topicKey(rec.signal.topic);+ const arr = archivedByTopic.get(key);+ if (arr) arr.push(rec);+ else archivedByTopic.set(key, [rec]);+ continue;+ }if (!rec.active) continue;const raw = rec.signal.topic;const key = topicKey(raw);@@ -104,7 +116,16 @@ export function planTopics(scan: ScanResult, cfg: BrainConfig, now: Date): PlanSconst sigs = group.sigs;const active = prefs.byKey.get(key);if (active) {- handleSignalsOnActivePref(active, sigs, plan, cfg, now, scan.signals, reservedSlugs);+ handleSignalsOnActivePref(+ active,+ sigs,+ archivedByTopic.get(key) ?? [],+ plan,+ cfg,+ now,+ scan.signals,+ reservedSlugs,+ );continue;}const candidateSigs = applySignalSuppression(topic, sigs, retiredByTopic.get(key), plan);@@ -447,13 +468,17 @@ function deriveActiveSign(function handleSignalsOnActivePref(active: PreferenceRecord,sigs: SignalRecord[],+ archivedOnTopic: ReadonlyArray<SignalRecord>,plan: PlanState,cfg: BrainConfig,now: Date,allSignals: ReadonlyArray<SignalRecord>,reservedSlugs: Set<string>,): void {- const activeSign = deriveActiveSign(active, sigs, allSignals);+ // The archived signals on this topic join the group for the sign+ // derivation only: before they were archived they sat in the inbox, and+ // tiers 2 and 3 below read the group as "the inbox signals on this topic".+ const activeSign = deriveActiveSign(active, [...sigs, ...archivedOnTopic], allSignals);const oppositeSign: BrainSignalSign =activeSign === BRAIN_SIGNAL_SIGN.positive? BRAIN_SIGNAL_SIGN.negativediff --git a/src/core/brain/dream-plan.ts b/src/core/brain/dream-plan.tsindex 166ca23a..29736b5b 100644--- a/src/core/brain/dream-plan.ts+++ b/src/core/brain/dream-plan.ts@@ -99,8 +99,13 @@ export function preferenceSlug(id: string): string {export interface SignalRecord {readonly path: string;readonly signal: BrainSignal;- /** True iff the file lives in `inbox/` (not `processed/`). */+ /** True iff the file lives in `inbox/` (not `processed/` or `archived/`). */readonly active: boolean;+ /**+ * True iff the file lives in `inbox/archived/`: an inbox signal a previous+ * pass archived because it had left the contradiction window unconsumed.+ */+ readonly archived?: true;}export interface PreferenceRecord {@@ -138,6 +143,13 @@ export interface ScanResult {readonly preferences: PreferenceRecord[];readonly retired: RetiredRecord[];readonly corrupted: CorruptedEntry[];+ /**+ * Every entry name in `inbox/archived/`, parseable or not. The archive+ * step checks a move's destination name against this listing rather than+ * against the parsed records, so a tombstoned or corrupt file there still+ * takes its name. Absent on a scan built by hand.+ */+ readonly archivedNames?: ReadonlySet<string>;}/**@@ -200,6 +212,18 @@ export interface PlanState {* being resolved by directory-enumeration order.*/readonly topicKeyContentions: TopicKeyContention[];+ /**+ * Inbox signals this pass archives because they can no longer become+ * candidates (see `signal-archive.ts`). Keyed by signal id; never+ * overlaps {@link signalsToMove}.+ */+ readonly signalsToArchive: Map<string, SignalArchivePlan>;+}++export interface SignalArchivePlan {+ readonly id: string;+ /** Absolute path of the inbox file. */+ readonly path: string;}export interface SignalSuppressedPlan {@@ -283,6 +307,7 @@ export function emptyPlan(): PlanState {signalsSuppressed: [],quarantined: [],topicKeyContentions: [],+ signalsToArchive: new Map(),};}diff --git a/src/core/brain/dream-report.ts b/src/core/brain/dream-report.tsindex 78543818..e6e5d303 100644--- a/src/core/brain/dream-report.ts+++ b/src/core/brain/dream-report.ts@@ -40,6 +40,8 @@ export interface DreamReportInput {readonly rollupPlan: RollupLadderPlan;/** Signal ids that actually reached `processed/`. */readonly moved: ReadonlyArray<string>;+ /** Signal ids moved into `inbox/archived/` by this run. */+ readonly archived: ReadonlyArray<string>;/** Retires the evidence gate declined; excluded from the `retired` row. */readonly gatedSlugs: ReadonlySet<string>;/** True when the invoking agent differs from the vault's declared primary. */@@ -208,6 +210,7 @@ function buildSummaryBody(input: DreamReportInput): Record<string, string | Readif (confirmedIds.length > 0) body["confirmed"] = confirmedIds;if (retiredEntries.length > 0) body["retired"] = retiredEntries;if (input.moved.length > 0) body["moved_to_processed"] = input.moved;+ if (input.archived.length > 0) body["archived_signals"] = input.archived;if (plan.contradictionTopics.size > 0) {body["contradictions"] = Array.from(plan.contradictionTopics);}diff --git a/src/core/brain/dream-scan.ts b/src/core/brain/dream-scan.tsindex 1fb40449..cc85e665 100644--- a/src/core/brain/dream-scan.ts+++ b/src/core/brain/dream-scan.ts@@ -97,8 +97,8 @@ function markdownFilesIn(dir: string): string[] {}/**- * Signals from one directory. `inbox/` and `processed/` differ only in- * the `active` flag they stamp on each record, so they share this walk.+ * Signals from one directory. `inbox/`, `processed/` and `archived/` differ+ * only in the flags they stamp on each record, so they share this walk.*/function collectSignals(files: ReadonlyArray<string>,@@ -106,14 +106,20 @@ function collectSignals(signals: SignalRecord[],corrupted: CorruptedEntry[],walk: DirectoryWalk,+ archived = false,): void {for (const full of files) {walk.step();- // Belief lifecycle suite (t_7d5a3589): a tombstoned signal is- // excluded from the dream pass so it is never re-clustered.- if (isTombstoned(parseFrontmatter(full)[0])) continue;try {- signals.push({ path: full, signal: parseSignal(full), active });+ // Belief lifecycle suite (t_7d5a3589): a tombstoned signal is+ // excluded from the dream pass so it is never re-clustered.+ if (isTombstoned(parseFrontmatter(full)[0])) continue;+ signals.push({+ path: full,+ signal: parseSignal(full),+ active,+ ...(archived ? { archived: true as const } : {}),+ });} catch {corrupted.push({ path: full });}@@ -208,11 +214,19 @@ function scanBrainRun(// so an already-elapsed guard leaves a stream that spoke once.const inbox = markdownFilesIn(dirs.inbox);const processed = markdownFilesIn(dirs.processed);+ // Archived signals are read as inactive history: the plan never counts+ // them, but a preference whose evidence link resolves to one still+ // derives its sign from it (see `deriveActiveSign`).+ const archived = markdownFilesIn(dirs.archived);const preferenceFiles = markdownFilesIn(dirs.preferences);const retiredFiles = markdownFilesIn(dirs.retired);progress.start(SCAN_STAGE,- inbox.length + processed.length + preferenceFiles.length + retiredFiles.length,+ inbox.length ++ processed.length ++ archived.length ++ preferenceFiles.length ++ retiredFiles.length,);const signals: SignalRecord[] = [];const preferences: PreferenceRecord[] = [];@@ -239,6 +253,7 @@ function scanBrainRun(const collectors: ReadonlyArray<() => void> = [() => collectSignals(inbox, true, signals, corrupted, walk),() => collectSignals(processed, false, signals, corrupted, walk),+ () => collectSignals(archived, false, signals, corrupted, walk, true),() => collectPreferences(preferenceFiles, preferences, corrupted, walk),() => collectRetired(retiredFiles, retired, corrupted, walk),];@@ -247,5 +262,34 @@ function scanBrainRun(collect();}- return { signals, preferences, retired, corrupted };+ return { signals, preferences, retired, corrupted, archivedNames: entryNamesIn(dirs.archived) };+}++/** Every entry name directly inside `dir`, or none when it does not exist. */+function entryNamesIn(dir: string): ReadonlySet<string> {+ if (!existsSync(dir)) return new Set();+ return new Set(readdirSync(dir));+}++/** What the archive rule needs from the inbox, read the way the pass reads it. */+export interface InboxArchiveScan {+ /** Markdown files directly in `inbox/`, the files the pass walks. */+ readonly inboxFiles: number;+ /** Active inbox signal records: tombstoned and unparseable files left out. */+ readonly signals: ReadonlyArray<SignalRecord>;+ /** Every entry name in `inbox/archived/`. */+ readonly archivedNames: ReadonlySet<string>;+}++/**+ * The inbox half of {@link scanBrain}, for the `inbox-archivable` doctor+ * check: the same walk and the same per-file skips, so the check selects+ * from exactly the records the pass would.+ */+export function scanInboxForArchive(vault: string): InboxArchiveScan {+ const dirs = brainDirs(vault);+ const inbox = markdownFilesIn(dirs.inbox);+ const signals: SignalRecord[] = [];+ collectSignals(inbox, true, signals, [], { step: () => {} });+ return { inboxFiles: inbox.length, signals, archivedNames: entryNamesIn(dirs.archived) };}diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.tsindex 6d9865dd..20ea5a66 100644--- a/src/core/brain/dream-stage.ts+++ b/src/core/brain/dream-stage.ts@@ -66,6 +66,12 @@ export interface DreamStagePlan {readonly retired: ReadonlyArray<{ id: string; reason: string }>;readonly contradictions: ReadonlyArray<string>;readonly moved_to_processed: ReadonlyArray<string>;+ /**+ * Inbox signals the pass would archive (issue #195). Absent when empty.+ * Shown in the report but left out of the drift comparison: the set+ * grows with the clock alone (see `HOUSEKEEPING_PLAN_KEYS`).+ */+ readonly archived_signals?: ReadonlyArray<string>;readonly suppressed: ReadonlyArray<string>;readonly quarantined: ReadonlyArray<{ topic: string; failed_gates: ReadonlyArray<string> }>;readonly gated_retires: ReadonlyArray<{ pref_id: string; attempted_reason: string }>;@@ -171,6 +177,9 @@ export function projectDreamPlan(summary: DreamRunSummary): DreamStagePlan {),contradictions: Object.freeze([...summary.contradictions].toSorted()),moved_to_processed: Object.freeze([...summary.moved_to_processed].toSorted()),+ ...(summary.archived_signals !== undefined && summary.archived_signals.length > 0+ ? { archived_signals: Object.freeze([...summary.archived_signals].toSorted()) }+ : {}),suppressed: Object.freeze([...summary.suppressed].toSorted()),quarantined: Object.freeze(sorted(@@ -238,6 +247,7 @@ function planToProposals(plan: DreamStagePlan): Array<Record<string, unknown>> {for (const r of plan.retired)rows.push({ type: "retire_preference", id: r.id, reason: r.reason });for (const id of plan.moved_to_processed) rows.push({ type: "process_signal", id });+ for (const id of plan.archived_signals ?? []) rows.push({ type: "archive_signal", id });for (const id of plan.suppressed) rows.push({ type: "suppress_signal", id });for (const q of plan.quarantined) {rows.push({ type: "quarantine_cluster", topic: q.topic, failed_gates: q.failed_gates });@@ -282,6 +292,7 @@ function renderReport(plan.retired.map((r) => `${r.id} (${r.reason})`),),...section("Would move to processed", plan.moved_to_processed),+ ...section("Would archive (outside the contradiction window)", plan.archived_signals ?? []),...section("Would suppress", plan.suppressed),...section("Quarantined clusters",@@ -386,6 +397,49 @@ function readManifest(dir: string): Record<string, unknown> | null {}}+/**+ * Plan keys the drift comparison leaves out. `archived_signals` is+ * housekeeping driven by the clock rather than a decision a reviewer+ * approves: a signal staged inside the contradiction window can cross its+ * edge before the bundle is applied, and it can no longer count toward any+ * candidate either way (see `signal-archive.ts`). Comparing it would refuse+ * every bundle staged a day before such a crossing.+ */+const HOUSEKEEPING_PLAN_KEYS: ReadonlySet<string> = new Set(["archived_signals"]);++/**+ * Every difference between a staged and a recomputed plan, over the keys of+ * BOTH plans: a key only the staged plan carries is drift as much as one only+ * the recomputed plan carries. Housekeeping keys are skipped, and so is a+ * `changed` flip from false to true that the archive step alone explains+ * (the recomputed plan archives something and nothing else differs).+ */+function planDrift(staged: DreamStagePlan, recomputed: DreamStagePlan): string[] {+ const stagedMap = staged as unknown as Readonly<Record<string, unknown>>;+ const recomputedMap = recomputed as unknown as Readonly<Record<string, unknown>>;+ const keys = [...new Set([...Object.keys(recomputedMap), ...Object.keys(stagedMap)])];+ const drift: string[] = [];+ let changedDrift: string | null = null;+ for (const key of keys) {+ if (HOUSEKEEPING_PLAN_KEYS.has(key)) continue;+ const before = JSON.stringify(stagedMap[key] ?? null);+ const after = JSON.stringify(recomputedMap[key] ?? null);+ if (before === after) continue;+ const line = `${key}: staged ${before} -> now ${after}`;+ if (key === "changed") changedDrift = line;+ else drift.push(line);+ }+ if (changedDrift !== null) {+ const archiveExplains =+ drift.length === 0 &&+ staged.changed === false &&+ recomputed.changed === true &&+ (recomputed.archived_signals?.length ?? 0) > 0;+ if (!archiveExplains) drift.unshift(changedDrift);+ }+ return drift;+}+/*** Recompute the dry-run plan and compare it to the staged one.* `now` should be the clock the eventual apply will run with - the@@ -433,13 +487,7 @@ export function validateDreamBundle(});const recomputed = projectDreamPlan(summary);- const drift: string[] = [];- const keys = Object.keys(recomputed) as Array<keyof DreamStagePlan>;- for (const key of keys) {- const before = JSON.stringify(staged[key] ?? null);- const after = JSON.stringify(recomputed[key]);- if (before !== after) drift.push(`${key}: staged ${before} -> now ${after}`);- }+ const drift = planDrift(staged, recomputed);return Object.freeze({valid: drift.length === 0,drift: Object.freeze(drift),diff --git a/src/core/brain/dream-step.ts b/src/core/brain/dream-step.tsindex b79122f0..3d38c0ce 100644--- a/src/core/brain/dream-step.ts+++ b/src/core/brain/dream-step.ts@@ -127,6 +127,8 @@ export interface DreamScanStepResult {readonly active_signals: number;/** Signals already in `inbox/processed/`. */readonly processed_signals: number;+ /** Signals in `inbox/archived/` (left the contradiction window unconsumed). */+ readonly archived_signals: number;readonly preferences: number;readonly retired: number;/** Vault-relative paths whose frontmatter would not parse. */@@ -188,7 +190,8 @@ export function runDreamStep(step: DREAM_STEP.scan,partial: true,active_signals: scan.signals.filter((s) => s.active).length,- processed_signals: scan.signals.filter((s) => !s.active).length,+ processed_signals: scan.signals.filter((s) => !s.active && !s.archived).length,+ archived_signals: scan.signals.filter((s) => s.archived).length,preferences: scan.preferences.length,retired: scan.retired.length,corrupted: Object.freeze(scan.corrupted.map((c) => vaultRelative(c.path, vault))),diff --git a/src/core/brain/dream-summary.ts b/src/core/brain/dream-summary.tsindex fcff0dda..393b3c31 100644--- a/src/core/brain/dream-summary.ts+++ b/src/core/brain/dream-summary.ts@@ -97,6 +97,8 @@ export interface DreamChangedSummaryInput {/** Slugs the evidence gate held back; excluded from `retired`. */readonly gatedSlugs: ReadonlySet<string>;readonly moved: ReadonlyArray<string>;+ /** Signal ids archived (or, on a dry run, that would be). */+ readonly archived: ReadonlyArray<string>;readonly healEnriched: number;/** Absent on a dry run, which writes no snapshot. */readonly snapshotPath: string | undefined;@@ -118,6 +120,9 @@ export function buildChangedSummary(input: DreamChangedSummaryInput): DreamRunSu.map((r) => ({ id: `ret-${r.slug}`, reason: r.reason })),contradictions: Array.from(plan.contradictionTopics),moved_to_processed: input.moved,+ // Absent rather than empty, so a run that archived nothing keeps the+ // summary shape it has always had.+ ...(input.archived.length > 0 ? { archived_signals: input.archived } : {}),suppressed: plan.signalsSuppressed.map((s) =>s.signal.replace(/^\[\[/, "").replace(/\]\]$/, ""),),@@ -161,6 +166,7 @@ function buildPhaseSummaries(input: DreamChangedSummaryInput): ReadonlyArray<DrephaseSummary(DREAM_PHASE.log, {moved: input.moved.length,suppressed: plan.signalsSuppressed.length,+ archived: input.archived.length,}),]);}diff --git a/src/core/brain/dream-types.ts b/src/core/brain/dream-types.tsindex a1243afd..90602afc 100644--- a/src/core/brain/dream-types.ts+++ b/src/core/brain/dream-types.ts@@ -79,6 +79,13 @@ export interface DreamRunSummary {readonly contradictions: ReadonlyArray<string>;/** Signal ids moved from inbox/ into inbox/processed/. */readonly moved_to_processed: ReadonlyArray<string>;+ /**+ * Signal ids moved from inbox/ into inbox/archived/ because they had left+ * the contradiction window unconsumed and can no longer become candidates+ * (issue #195). On a dry run, the ids the pass would archive. Absent when+ * the pass archived nothing.+ */+ readonly archived_signals?: ReadonlyArray<string>;/*** Signal ids dropped by Β§6 signal-suppression β a user-rejected* retired pref with the same topic blocked them from re-promotion.diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 6e1feb46..b36d63b6 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -28,6 +28,8 @@* - New / updated files in `Brain/preferences/`.* - Moves into `Brain/retired/`.* - Moves from `Brain/inbox/` into `Brain/inbox/processed/`.+ * - Moves from `Brain/inbox/` into `Brain/inbox/archived/` for signals+ * that left the contradiction window unconsumed (`signal-archive.ts`).* - One appended event in `Brain/log/<today>.md` summarising the* run β **only** if any state actually changed. Idempotent reruns* touch nothing.@@ -55,6 +57,7 @@ import { regenerateActiveQuiet } from "./active.ts";import {applyDreamPlan,gatedRetireSlugs,+ plannedSignalArchiveIds,plannedSignalMoveIds,type DreamApplyResult,} from "./dream-apply.ts";@@ -64,6 +67,7 @@ import type { PlanState } from "./dream-plan.ts";import { planRefresh, scanApplyEvidence, type RefreshResult } from "./dream-refresh.ts";import { writeDreamLog } from "./dream-report.ts";import { scanBrain } from "./dream-scan.ts";+import { planSignalArchive } from "./signal-archive.ts";import { buildChangedSummary, buildNoOpSummary } from "./dream-summary.ts";import type { DreamOptions, DreamRunSummary, DreamWarning } from "./dream-types.ts";import { openWorkrun, WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";@@ -238,6 +242,11 @@ function dreamRun(// one, because a run that decided nothing is exactly the run that must// still explain itself.warnings.push(...topicKeyContentionWarnings(plan));+ // Archive step (issue #195): inbox signals the topic plan did not consume+ // and that have left the contradiction window can never count toward a+ // candidate again, so they leave the inbox for `inbox/archived/`.+ // Planned after the topic plan so a consumed signal is never archived.+ warnings.push(...planSignalArchive(scan, cfg, now, plan));// 3. Plan refresh: applied / violated / last_evidence / confidence,// and unconfirmed β confirmed promotion. We need the log of all@@ -336,7 +345,12 @@ function dreamRun(// Dry-run still reports the move list so the caller's summary is// accurate, but it does not touch disk.opts.safeguard?.checkpoint();- exec = { moved: plannedSignalMoveIds(plan), gatedRetires: [], healEnriched: 0 };+ exec = {+ moved: plannedSignalMoveIds(plan),+ archived: plannedSignalArchiveIds(plan),+ gatedRetires: [],+ healEnriched: 0,+ };} else {const baseRunId = runId;const gated = withDestructiveSnapshot(@@ -418,6 +432,7 @@ function dreamRun(reconcile,rollupPlan,moved: exec.moved,+ archived: exec.archived,gatedSlugs,isNonPrimary,callerAgent,@@ -470,6 +485,7 @@ function dreamRun(gatedRetires: exec.gatedRetires,gatedSlugs,moved: exec.moved,+ archived: exec.archived,healEnriched: exec.healEnriched,snapshotPath: snapshotPathStr,});@@ -505,6 +521,7 @@ function collectWarnings(* - a refreshed pref (counters/confidence/status changed)* - a retire* - a same-sign signal noted on an active pref (move + log)+ * - an inbox signal archived because it left the contradiction window* - a corrupted frontmatter (we want the skip event recorded)* - any pinned-rebut-attempt warning* - a fired rollup-ladder rung (S3)@@ -522,6 +539,7 @@ function hasStateChange(plan.retires.length > 0 ||plan.notedRedundant.length > 0 ||plan.signalsToMove.size > 0 ||+ plan.signalsToArchive.size > 0 ||plan.retainPinned.length > 0 ||plan.signalsSuppressed.length > 0 ||// v0.10.16: quarantine is a recorded decision (deferred-but-noted),diff --git a/src/core/brain/expiration-set.ts b/src/core/brain/expiration-set.tsindex d6eb0240..55266db5 100644--- a/src/core/brain/expiration-set.ts+++ b/src/core/brain/expiration-set.ts@@ -171,12 +171,13 @@ function candidatePaths(vault: string, id: string): { kind: ExpirationTargetKindconst dirs = brainDirsForWrite(vault);if (SIGNAL_ID_RE.test(id)) {// A signal outlives the inbox: the dream pass moves consumed signals- // to `inbox/processed/` and `retireSignal` moves retired ones to- // `Brain/retired/`. All three are still readable memories, so all- // three can carry a lifetime.+ // to `inbox/processed/`, archives unconsumed ones that left the+ // contradiction window to `inbox/archived/`, and `retireSignal` moves+ // retired ones to `Brain/retired/`. All four are still readable+ // memories, so all four can carry a lifetime.return {kind: EXPIRATION_TARGET_KIND.signal,- dirs: [dirs.inbox, dirs.processed, dirs.retired],+ dirs: [dirs.inbox, dirs.processed, dirs.archived, dirs.retired],};}if (PREFERENCE_ID_RE.test(id)) {diff --git a/src/core/brain/git/store.ts b/src/core/brain/git/store.tsindex 504d5f76..7e48813f 100644--- a/src/core/brain/git/store.ts+++ b/src/core/brain/git/store.ts@@ -27,7 +27,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { isFullSha } from "./reader.ts";-import { acquireLockSyncWithRetry } from "../sync-lockfile.ts";+import { acquireLockSyncWithRetry, ingestLockRemedy } from "../sync-lockfile.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";export interface GitCommitRecord {@@ -190,7 +190,9 @@ export function appendGitRecords(): AppendGitRecordsResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);- const handle = acquireLockSyncWithRetry(commitsPath(vault, repoKey));+ const handle = acquireLockSyncWithRetry(commitsPath(vault, repoKey), undefined, {+ remedy: ingestLockRemedy,+ });try {return appendGitRecordsLocked(vault, repoKey, records);} finally {diff --git a/src/core/brain/governance/forget-plan.ts b/src/core/brain/governance/forget-plan.tsindex 84725a61..290259b0 100644--- a/src/core/brain/governance/forget-plan.ts+++ b/src/core/brain/governance/forget-plan.ts@@ -8,7 +8,7 @@ import { brainDirs, vaultRelative } from "../paths.ts";export interface ForgetPlanEntry {readonly id: string;readonly path: string;- readonly kind: "inbox" | "processed" | "preference" | "retired" | "log" | "other";+ readonly kind: "inbox" | "processed" | "archived" | "preference" | "retired" | "log" | "other";readonly action: "would-remove-source-support";readonly sha256: string;}@@ -109,6 +109,7 @@ function readId(path: string): string {function classify(vault: string, path: string): ForgetPlanEntry["kind"] {const dirs = brainDirs(vault);if (insideDir(path, dirs.processed)) return "processed";+ if (insideDir(path, dirs.archived)) return "archived";if (insideDir(path, dirs.inbox)) return "inbox";if (insideDir(path, dirs.preferences)) return "preference";if (insideDir(path, dirs.retired)) return "retired";diff --git a/src/core/brain/import-census.ts b/src/core/brain/import-census.tsindex b22d4244..8254d814 100644--- a/src/core/brain/import-census.ts+++ b/src/core/brain/import-census.ts@@ -20,8 +20,10 @@* Both lanes read back over the key the lane already keys on:** - sessions: the signal dedup hash ({@link ./dedup-hash.ts}), read back- * through the same `buildDedupIndex` walk of `Brain/inbox/` and- * `Brain/inbox/processed/` that the import consults before every write.+ * through the same `buildDedupIndex` walk of `Brain/inbox/`,+ * `Brain/inbox/processed/` and `Brain/inbox/archived/` that the import+ * consults before every write (with `fresh: true`, so no cached entry+ * answers for a file).* A hash the index cannot find is a signal that is not on disk.* - ingest: the content-hash manifest ({@link ./ingest/content-manifest.ts}),* read back through the same `classifyPaths`. A claimed path counts as@@ -106,7 +108,7 @@ export function censusSessionSignals(claimedHashes: ReadonlyArray<string>,): ImportCensus {if (claimedHashes.length === 0) return buildReadBackCensus([], () => true);- const index = buildDedupIndex(vault);+ const index = buildDedupIndex(vault, { fresh: true });return buildReadBackCensus(claimedHashes, (hash) => index.has(hash));}diff --git a/src/core/brain/ingest/content-manifest.ts b/src/core/brain/ingest/content-manifest.tsindex ab684b03..c4266e5b 100644--- a/src/core/brain/ingest/content-manifest.ts+++ b/src/core/brain/ingest/content-manifest.ts@@ -34,7 +34,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { canonicalNotePath } from "../../path-safety.ts";-import { acquireLockSyncWithRetry } from "../sync-lockfile.ts";+import { acquireLockSyncWithRetry, ingestLockRemedy } from "../sync-lockfile.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";/** Only schema version currently understood. Unknown versions are refused. */@@ -234,7 +234,9 @@ export function classifyPaths(* overlap is the designed case rather than a rare one.*/export function updateManifest(vault: string, paths: readonly string[]): boolean {- const handle = acquireLockSyncWithRetry(manifestPath(vault));+ const handle = acquireLockSyncWithRetry(manifestPath(vault), undefined, {+ remedy: ingestLockRemedy,+ });try {const entries: Record<string, string> = { ...readManifest(vault).entries };for (const path of paths) {diff --git a/src/core/brain/init.ts b/src/core/brain/init.tsindex 45353b74..4333748f 100644--- a/src/core/brain/init.ts+++ b/src/core/brain/init.ts@@ -208,14 +208,14 @@ export function copyStarterBundle(}// "Non-empty" means anything the user (or a prior dream pass)// could have left here. The only acceptable non-dotfile entry- // bootstrap places under a starter target is `inbox/processed/` β- // we whitelist that one explicitly so a freshly initialised vault+ // bootstrap places under a starter target is `inbox/processed/` (and+ // its sibling `inbox/archived/`) β we whitelist those explicitly so a freshly initialised vault// does not trip the guard, but any other subdirectory (e.g. a// user-created `preferences/custom/`) counts as content and// refuses the starter.const hasUserContent = entries.some((e) => {if (e.name.startsWith(".")) return false;- if (sub === "inbox" && e.isDirectory() && e.name === "processed") {+ if (sub === "inbox" && e.isDirectory() && (e.name === "processed" || e.name === "archived")) {return false;}return true;diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.tsindex c3fb721c..089edc45 100644--- a/src/core/brain/inline-scan.ts+++ b/src/core/brain/inline-scan.ts@@ -45,7 +45,7 @@ import { readFileSync } from "node:fs";import { relative, sep } from "node:path";import { emitIngestDedupReport, type IngestDedupSourceCount } from "./dedup-telemetry.ts";-import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";+import { computeDedupHash, loadDedupIndex, type DedupIndexEntry } from "./dedup-hash.ts";import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";import { previewCaptureMarker, routeCaptureMarker, ROUTED_MARKER_KINDS } from "./marker-routing.ts";@@ -148,7 +148,7 @@ export async function scanInline(// Build dedup index once per run. Parse failures get surfaced// through the per-file errors array so the JSON report exposes// them; doctor flags malformed signals separately.- const dedupIndex: Map<string, DedupIndexEntry> = buildDedupIndex(vault, {+ const dedupIndex: Map<string, DedupIndexEntry> = await loadDedupIndex(vault, {onError: (path, message) => errors.push({ path, message }),});diff --git a/src/core/brain/operator-snapshot.ts b/src/core/brain/operator-snapshot.tsindex 8646c04f..2ee43c0d 100644--- a/src/core/brain/operator-snapshot.ts+++ b/src/core/brain/operator-snapshot.ts@@ -22,6 +22,11 @@ import { resolveSearchConfig } from "../search/index.ts";import { FREEZE_NEXT_COMMAND, readFreezeMarker, type FreezeMarker } from "./freeze-marker.ts";import { runDoctor } from "./doctor.ts";import { resolveSignal } from "./diagnostics.ts";+import {+ describeSelfHealUpgradeFailure,+ readSelfHealUpgradeFailure,+ type SelfHealUpgradeFailure,+} from "../maintenance/self-heal-upgrade-state.ts";import { runHygieneScan } from "./hygiene/scan.ts";import { brainConfigPath, brainDirs } from "./paths.ts";import { loadTemporalConfigSafe } from "./policy.ts";@@ -80,6 +85,12 @@ export interface OperatorSnapshot {* condition belongs.*/readonly frozen: FreezeMarker | null;+ /**+ * The last failure of the automatic managed-file upgrade on this device,+ * or `null` when none is recorded. It is also a problem line: a failed+ * self-heal leaves a pending upgrade behind and nothing else says so.+ */+ readonly selfHealUpgradeFailure: SelfHealUpgradeFailure | null;}export interface BuildOperatorSnapshotOptions {@@ -117,6 +128,12 @@ export async function buildOperatorSnapshot(problem("state-file", "Brain config `_brain.yaml` is missing");}+ // --- Automatic upgrade ---+ const selfHealUpgradeFailure = readSelfHealUpgradeFailure(vault);+ if (selfHealUpgradeFailure !== null) {+ problem("self-heal-upgrade-failed", describeSelfHealUpgradeFailure(selfHealUpgradeFailure));+ }+// --- Doctor + semantic health ---let healthVerdict = "clean";try {@@ -204,6 +221,7 @@ export async function buildOperatorSnapshot(problems: Object.freeze(problems),healthy: problems.length === 0,frozen: readFreezeMarker(vault),+ selfHealUpgradeFailure,});}diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.tsindex 6011ebce..99fc394a 100644--- a/src/core/brain/path-constants.ts+++ b/src/core/brain/path-constants.ts@@ -24,6 +24,12 @@ export const BRAIN_ROOT_REL = "Brain";/** Vault-relative Brain subdirectory names. */export const BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");export const BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");+/**+ * Archive of inbox signals that can no longer become candidates: older than+ * `dream.contradiction_window_days` and never consumed by a preference. The+ * dream pass moves them here byte for byte; nothing is ever deleted.+ */+export const BRAIN_ARCHIVED_SIGNALS_REL = posix.join(BRAIN_INBOX_REL, "archived");/** Write-approval staging area: `Brain/pending/sig-*.md` (A3, t_e540b093). */export const BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");export const BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex 3ff339b3..3c8021a3 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -8,6 +8,7 @@* inbox/* sig-<date>-<slug>.md* processed/sig-<date>-<slug>.md+ * archived/sig-<date>-<slug>.md* preferences/* pref-<slug>.md* retired/@@ -33,6 +34,7 @@ import { resolveAppendShardId, shardedFileName } from "./ledger-shards.ts";import {BRAIN_ARTIFACTS_REL,BRAIN_ACTIVE_FILE,+ BRAIN_ARCHIVED_SIGNALS_REL,BRAIN_ATTENTION_REL,BRAIN_BASES_REL,BRAIN_CAPTURES_PROCESSED_REL,@@ -130,6 +132,11 @@ export interface BrainDirs {readonly inbox: string;/** Holding area for signals already folded into a preference. */readonly processed: string;+ /**+ * Inbox signals that can no longer become candidates (outside the+ * contradiction window, never consumed). Moved here by dream.+ */+ readonly archived: string;/** Write-approval staging area for extracted signals awaiting review. */readonly pending: string;readonly preferences: string;@@ -154,6 +161,7 @@ export function brainDirs(vault: string): BrainDirs {brain,inbox: ensureInsideVault(join(vault, BRAIN_INBOX_REL), vault),processed: ensureInsideVault(join(vault, BRAIN_PROCESSED_REL), vault),+ archived: ensureInsideVault(join(vault, BRAIN_ARCHIVED_SIGNALS_REL), vault),pending: ensureInsideVault(join(vault, BRAIN_PENDING_REL), vault),preferences: ensureInsideVault(join(vault, BRAIN_PREFERENCES_REL), vault),retired: ensureInsideVault(join(vault, BRAIN_RETIRED_REL), vault),@@ -338,6 +346,17 @@ export function signalPath(vault: string, date: string, slug: string): string {return ensureInsideVault(join(brainDirs(vault).inbox, `sig-${d}-${s}.md`), vault);}+/**+ * Archived-signal path: `Brain/inbox/archived/<basename>`. Takes the file's+ * own basename rather than an id so the move preserves the name exactly.+ */+export function archivedSignalPath(vault: string, basename: string): string {+ if (!basename.startsWith("sig-") || !basename.endsWith(".md") || /[\\/]/.test(basename)) {+ throw new Error(`not a signal file name: ${JSON.stringify(basename)}`);+ }+ return ensureInsideVault(join(brainDirs(vault).archived, basename), vault);+}+/** Processed-signal path: `Brain/inbox/processed/sig-<date>-<slug>.md`. */export function processedSignalPath(vault: string, date: string, slug: string): string {const d = validateIsoDate(date);diff --git a/src/core/brain/payload-registry.ts b/src/core/brain/payload-registry.tsindex 0f2964d3..6068b785 100644--- a/src/core/brain/payload-registry.ts+++ b/src/core/brain/payload-registry.ts@@ -44,7 +44,7 @@ import { atomicWriteFileSync } from "../fs-atomic.ts";import { sha256Hex } from "../integrity/digest.ts";import { redactRawOutput, stripPrivateRegions } from "../redactor.ts";import { payloadPath, payloadsDir } from "./paths.ts";-import { acquireLockSyncWithRetry, LOCK_WAIT_BUDGET_MS } from "./sync-lockfile.ts";+import { acquireLockSyncWithRetry } from "./sync-lockfile.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";export interface PayloadRegistryOptions {@@ -279,13 +279,10 @@ export const PAYLOAD_GC_GRACE_MS = 10 * 60 * 1000;* row naming it is appended, and the gc holds it while it re-plans and* removes, so a removal can never land between the two halves of an* import. `budgetMs` is how long to wait for a holder (see- * `sync-lockfile.ts`); the operator-run gc passes the interactive budget.+ * `sync-lockfile.ts`; omitted, the default budget and its environment+ * override apply); the operator-run gc passes the interactive budget.*/-export function withPayloadStoreLock<T>(- vault: string,- fn: () => T,- budgetMs: number = LOCK_WAIT_BUDGET_MS,-): T {+export function withPayloadStoreLock<T>(vault: string, fn: () => T, budgetMs?: number): T {const handle = acquireLockSyncWithRetry(payloadsDir(vault), budgetMs);try {return fn();diff --git a/src/core/brain/policy/blocks/lifecycle.ts b/src/core/brain/policy/blocks/lifecycle.tsindex ef28e17b..52a66dda 100644--- a/src/core/brain/policy/blocks/lifecycle.ts+++ b/src/core/brain/policy/blocks/lifecycle.ts@@ -32,7 +32,19 @@ import { DEFAULT_BRAIN_CONFIG } from "../defaults.ts";const RETIRE_OPTIONAL_KEYS = ["confirmed_evidence_min_threshold"] as const;/** Optional `dream:` sub-key with no default, for the same reason. */-const DREAM_OPTIONAL_KEYS = ["salience_threshold"] as const;+const DREAM_OPTIONAL_KEYS = ["salience_threshold", "archive_stale_signals"] as const;++/** A boolean key; anything else is refused rather than coerced. */+function requireBoolean(field: string, value: unknown, source: string | null): boolean {+ if (typeof value !== "boolean") {+ throw new BrainConfigError(+ `${field} must be true or false; got ${JSON.stringify(value)}`,+ field,+ source,+ );+ }+ return value;+}/*** Merge one lifecycle block onto its slice of {@link DEFAULT_BRAIN_CONFIG}.@@ -83,6 +95,18 @@ export function parseDreamBlock(ctx: BlockParseContext): BrainDreamConfig {// or non-boolean coerces to false so the default install stays// byte-identical (the heal phase becomes a checkpoint-only no-op).heal_enrich_enabled: dream.heal_enrich_enabled === true,+ // Inbox archive (issue #195): on unless explicitly `false`. A+ // non-boolean is refused rather than coerced, so a typo cannot+ // silently switch the archive off. Absent stays absent.+ ...(dream.archive_stale_signals !== undefined+ ? {+ archive_stale_signals: requireBoolean(+ "dream.archive_stale_signals",+ dream.archive_stale_signals,+ ctx.source,+ ),+ }+ : {}),// Absent stays absent: `undefined` is the documented open-gate// state `salience-gate.ts` branches on, so spreading the key in// unconditionally would change `dream` from omitting it to carryingdiff --git a/src/core/brain/portability/sources.ts b/src/core/brain/portability/sources.tsindex ef9ae837..60afe1d1 100644--- a/src/core/brain/portability/sources.ts+++ b/src/core/brain/portability/sources.ts@@ -1,9 +1,9 @@/*** Sources dashboard projection (Vault portability suite, Feature 2).*- * A pure, read-only aggregation over the brain's signals (inbox +- * processed), grouped by (agent, source_type) with active/processed and- * distinct-topic counts. No new store, no writes; deterministic ordering.+ * A pure, read-only aggregation over the brain's signals (inbox,+ * processed and archived), grouped by (agent, source_type) with+ * active/processed/archived and distinct-topic counts. No new store, no writes; deterministic ordering.** (The parallel multi-source sync worker pool + connection-budget warning* from the upstream inspiration are intentionally out of scope - only this@@ -22,6 +22,8 @@ export interface SourceRow {readonly source_type: string;readonly active: number;readonly processed: number;+ /** Signals in `inbox/archived/`: left the contradiction window unconsumed. */+ readonly archived: number;readonly distinct_topics: number;}@@ -29,6 +31,7 @@ export interface SourcesReport {readonly sources: ReadonlyArray<SourceRow>;readonly total_active: number;readonly total_processed: number;+ readonly total_archived: number;}interface Bucket {@@ -36,10 +39,13 @@ interface Bucket {source_type: string;active: number;processed: number;+ archived: number;topics: Set<string>;}-function scanDir(dir: string, active: boolean, buckets: Map<string, Bucket>): void {+type SignalDirKind = "active" | "processed" | "archived";++function scanDir(dir: string, kind: SignalDirKind, buckets: Map<string, Bucket>): void {if (!existsSync(dir)) return;for (const name of readdirSync(dir)) {if (!name.endsWith(".md")) continue;@@ -56,11 +62,17 @@ function scanDir(dir: string, active: boolean, buckets: Map<string, Bucket>): voconst key = JSON.stringify([agent, sourceType]);let bucket = buckets.get(key);if (!bucket) {- bucket = { agent, source_type: sourceType, active: 0, processed: 0, topics: new Set() };+ bucket = {+ agent,+ source_type: sourceType,+ active: 0,+ processed: 0,+ archived: 0,+ topics: new Set(),+ };buckets.set(key, bucket);}- if (active) bucket.active += 1;- else bucket.processed += 1;+ bucket[kind] += 1;bucket.topics.add(sig.topic);}}@@ -71,8 +83,9 @@ function scanDir(dir: string, active: boolean, buckets: Map<string, Bucket>): voexport function aggregateSources(vault: string): SourcesReport {const dirs = brainDirs(vault);const buckets = new Map<string, Bucket>();- scanDir(dirs.inbox, true, buckets);- scanDir(dirs.processed, false, buckets);+ scanDir(dirs.inbox, "active", buckets);+ scanDir(dirs.processed, "processed", buckets);+ scanDir(dirs.archived, "archived", buckets);const sources = [...buckets.values()].map((b) => ({@@ -80,6 +93,7 @@ export function aggregateSources(vault: string): SourcesReport {source_type: b.source_type,active: b.active,processed: b.processed,+ archived: b.archived,distinct_topics: b.topics.size,})).toSorted((a, b) =>@@ -98,5 +112,6 @@ export function aggregateSources(vault: string): SourcesReport {sources,total_active: sources.reduce((n, s) => n + s.active, 0),total_processed: sources.reduce((n, s) => n + s.processed, 0),+ total_archived: sources.reduce((n, s) => n + s.archived, 0),};}diff --git a/src/core/brain/query.ts b/src/core/brain/query.tsindex 5874df02..35d16d47 100644--- a/src/core/brain/query.ts+++ b/src/core/brain/query.ts@@ -251,12 +251,13 @@ export function queryByTopic(const dirs = brainDirs(vault);let signals: BrainSignal[] = [];- // Collect signals from both inbox/ and inbox/processed/. We do not- // recurse β `inbox/processed/` is the only allowed sub-folder of+ // Collect signals from inbox/, inbox/processed/ and inbox/archived/.+ // We do not recurse β those two are the only allowed sub-folders of// `inbox/` and `readdirSync` with `withFileTypes` lets us pick file// vs directory entries deterministically.collectSignals(dirs.inbox, want, signals);collectSignals(dirs.processed, want, signals);+ collectSignals(dirs.archived, want, signals);signals.sort((a, b) => a.created_at.localeCompare(b.created_at));// Expiration filter (C5): drop signals past their expiration_date// unless the caller opts into showExpired. The files stay on disk βdiff --git a/src/core/brain/schema-report.ts b/src/core/brain/schema-report.tsindex 40445274..77c87384 100644--- a/src/core/brain/schema-report.ts+++ b/src/core/brain/schema-report.ts@@ -212,7 +212,7 @@ function scanSignals(findings: SchemaReportFinding[],): void {const dirs = brainDirs(vault);- for (const dir of [dirs.inbox, dirs.processed]) {+ for (const dir of [dirs.inbox, dirs.processed, dirs.archived]) {for (const path of listMarkdown(dir, "sig-")) {const signal = readArtifact(vault, path, "signal_types", findings, parseSignal);if (signal === undefined) continue;diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.tsindex 093617c2..74acc328 100644--- a/src/core/brain/session-lifecycle.ts+++ b/src/core/brain/session-lifecycle.ts@@ -8,7 +8,13 @@ import { brainDirsForWrite } from "./paths.ts";import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";import { extractFacts, routeExtractedFacts } from "./fact-extract.ts";import { emitIngestDedupReport } from "./dedup-telemetry.ts";-import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";+import {+ buildDedupIndex,+ computeDedupHash,+ loadDedupIndex,+ type DedupIndexEntry,+} from "./dedup-hash.ts";+import type { Safeguard } from "./safeguard.ts";import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";import { writeSignal } from "./signal.ts";import { isoDate, isoSecond } from "./time.ts";@@ -41,6 +47,12 @@ export interface CaptureSessionLifecycleOptions {readonly agent: string;readonly now?: Date;readonly dryRun?: boolean;+ /**+ * Cooperative deadline for the dedup index walk, the one step whose cost+ * grows with the vault. A hook passes its process ceiling here so a walk+ * that would outlast the host's timeout stops at a file boundary.+ */+ readonly safeguard?: Safeguard;}export interface CaptureSessionLifecycleResult {@@ -177,10 +189,14 @@ export async function captureSessionLifecycleEvent(// alone outlasted the UserPromptSubmit hook's host timeout, and it ran// for every prompt although almost none carries a marker or a fact.// So it is built on first USE - when there is a signal to dedup - and- // shared by every capture in this event after that.+ // shared by every capture in this event after that. An event that may+ // need it (see `lifecycleEventNeedsDedup`) loads it up front with+ // parallel I/O below; the synchronous build here is the fallback for+ // anything that approximation missed.+ const dedupOpts = opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {};let dedup: Map<string, DedupIndexEntry> | undefined;const ensureDedup: DedupSource = () => {- dedup ??= buildDedupIndex(vault);+ dedup ??= buildDedupIndex(vault, dedupOpts);return dedup;};const counters = {@@ -200,6 +216,9 @@ export async function captureSessionLifecycleEvent(const boundary = buildCaptureBoundary(vault);const decision = boundary.sessionDecision(normalized.sessionId, normalized.transcriptPath);const mayWrite = decision === "capture";+ if ((mayWrite || opts.dryRun === true) && lifecycleEventNeedsDedup(payload)) {+ dedup = await loadDedupIndex(vault, dedupOpts);+ }// Delegation boundary (t_0c6f31ee): `SubagentStop` is the one event that// names a sub-agent, and a sub-agent reuses its parent's session id - sodiff --git a/src/core/brain/sessions/discover.ts b/src/core/brain/sessions/discover.tsindex 648b73e9..2ae79499 100644--- a/src/core/brain/sessions/discover.ts+++ b/src/core/brain/sessions/discover.ts@@ -67,7 +67,7 @@ import { hashFile } from "../ingest/content-manifest.ts";import { DERIVED_STORE_DIR } from "../path-constants.ts";import { progressCounter, type ProgressSink } from "../progress.ts";import { OPERATION, type Safeguard } from "../safeguard.ts";-import { acquireLockSyncWithRetry } from "../sync-lockfile.ts";+import { acquireLockSyncWithRetry, ingestLockRemedy } from "../sync-lockfile.ts";import { isoSecond } from "../time.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";@@ -267,7 +267,7 @@ export function recordSessionImports(): boolean {assertVaultIdentityForWrite(vault);const path = sessionLedgerPath(vault);- const handle = acquireLockSyncWithRetry(path);+ const handle = acquireLockSyncWithRetry(path, undefined, { remedy: ingestLockRemedy });try {const entries: Record<string, SessionLedgerEntry> = { ...readSessionLedger(vault).entries };const stamp = isoSecond(now);diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsindex d127579d..2f040ae6 100644--- a/src/core/brain/sessions/import.ts+++ b/src/core/brain/sessions/import.ts@@ -57,7 +57,7 @@ import { basename, resolve } from "node:path";import { delegatedAgentName } from "../../agent-identity.ts";import { readSkillOfferId, SKILL_OFFER_ID_KEY } from "../../surface/skill-offer.ts";import { checkpointingEnabled } from "../checkpoint-store.ts";-import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";+import { computeDedupHash, loadDedupIndex, type DedupIndexEntry } from "../dedup-hash.ts";import { censusSessionSignals, type ImportCensus } from "../import-census.ts";import { appendContinuityRecord } from "../continuity/store.ts";import { discoverMarkersDetailed, isFeedbackMarker } from "../inline.ts";@@ -313,7 +313,7 @@ export async function importSession(const adapter = await chooseAdapter(path, readHead, opts.format);// Reuse the caller-supplied index when present (directory walk lifts// the build out of the per-file loop). Otherwise build our own.- const dedup = opts.dedupIndex ?? buildDedupIndex(vault);+ const dedup = opts.dedupIndex ?? (await loadDedupIndex(vault));const now = opts.now ?? new Date();const sinceMs = opts.since ? opts.since.getTime() : undefined;@@ -825,7 +825,7 @@ export async function importSessionPath(// session log is and neither can quietly widen the rule alone.const queue = sessionFilesUnder(path);- const sharedDedup = opts.dedupIndex ?? buildDedupIndex(vault);+ const sharedDedup = opts.dedupIndex ?? (await loadDedupIndex(vault));const perFileOpts: ImportSessionOptions = {...opts,dedupIndex: sharedDedup,diff --git a/src/core/brain/signal-archive.ts b/src/core/brain/signal-archive.tsnew file mode 100644index 00000000..f68423bd--- /dev/null+++ b/src/core/brain/signal-archive.ts@@ -0,0 +1,172 @@+/**+ * Inbox archive policy (issue #195): which inbox signals can no longer+ * become candidates, and so leave `Brain/inbox/` for `Brain/inbox/archived/`.+ *+ * ## The rule+ *+ * An inbox signal is archivable when its `created_at` parses and lies+ * strictly before `now - dream.contradiction_window_days`.+ *+ * That is exactly the complement of `filterWithinWindow`, the filter every+ * counting path of the dream pass goes through: promotion, redundancy,+ * rebuttal and the contradiction classifier all count windowed signals only.+ * A signal outside the window therefore contributes to no candidate, and+ * because time only moves forward it never will again. Singletons, topics+ * below the promotion threshold, quarantined clusters and contended keys all+ * reduce to this one rule: while a signal is inside the window it stays,+ * whatever its topic's state, and once it has left the window no state of+ * its topic can make it count.+ *+ * Deliberately NOT archivable:+ *+ * - a signal whose `created_at` does not parse. It can never count either,+ * but it is malformed, and moving it would hide the defect from the+ * doctor checks that report it;+ * - a signal past its `expiration_date` but still inside the window. The+ * dream pass does not read `expiration_date` (expiry filters READ+ * surfaces, see `expiration.ts`), so such a signal still counts toward a+ * candidate today, and archiving it would change a promotion outcome.+ * Once it leaves the window it is archived like any other;+ * - a signal the same pass consumes (promotes, notes redundant, suppresses+ * or spends on a rebuttal). Those go to `processed/` as before;+ * - a signal whose file name is already taken in the archive, by any+ * entry of `inbox/archived/` (a tombstoned or unparseable file there+ * takes the name as much as a live one). The move never overwrites; the+ * collision is reported as a warning instead and plans nothing;+ * - a tombstoned inbox signal. The scan never reads one, so it is not a+ * candidate and not a record the plan can move. A tombstone is an+ * operator decision about that file, recorded in place, and tombstones+ * are bounded by operator actions rather than by capture volume, so the+ * inbox stays bounded without moving them.+ *+ * ## The clock+ *+ * The rule runs against `min(now, wall clock)` ({@link archiveClock}). A+ * pass run with `--now` in the future plans promotions for that instant,+ * but a move to the archive is not undone by a later pass, so it never+ * archives a signal that is still inside the window at the real time.+ *+ * Archiving is a move of the file, byte for byte. Nothing is deleted, and the+ * archive stays readable by the provenance and history readers.+ *+ * Pure: no I/O. The only clock read is {@link archiveClock}'s default+ * wall clock, which a caller can inject.+ */++import { basename } from "node:path";++import type { PlanState, ScanResult, SignalRecord } from "./dream-plan.ts";+import type { DreamWarning } from "./dream-types.ts";+import type { BrainConfig } from "./types.ts";++const DAY_MS = 24 * 60 * 60 * 1000;++/** Warning code for an inbox signal whose archive name is already taken. */+export const ARCHIVE_NAME_COLLISION_CODE = "archive-name-collision";++/** Whether the archive step is enabled; absent means enabled. */+export function archiveEnabled(cfg: BrainConfig): boolean {+ return cfg.dream.archive_stale_signals !== false;+}++/**+ * Whether one signal's `created_at` lies outside the contradiction window.+ * The exact complement of `filterWithinWindow` for a parseable timestamp;+ * an unparseable one is neither inside nor archivable.+ */+export function isOutsideWindow(createdAt: string, windowDays: number, now: Date): boolean {+ const t = Date.parse(createdAt);+ if (!Number.isFinite(t)) return false;+ return t < now.getTime() - windowDays * DAY_MS;+}++/**+ * The instant the archive rule runs against: `now`, or the wall clock when+ * `now` lies ahead of it (see "The clock" above).+ */+export function archiveClock(now: Date, wallClock: Date = new Date()): Date {+ return now.getTime() > wallClock.getTime() ? wallClock : now;+}++/** The archive rule's verdict over a set of signal records. */+export interface ArchiveSelection {+ /** Active inbox signals the rule archives, in record order. */+ readonly archivable: ReadonlyArray<SignalRecord>;+ /** Active inbox signals the rule would archive but whose name is taken. */+ readonly collisions: ReadonlyArray<SignalRecord>;+}++/**+ * Apply the archive rule to `signals`: every active record whose+ * `created_at` lies outside the window at {@link archiveClock}`(now)`,+ * split by whether its file name is free in the archive. `archivedNames`+ * is the listing of `inbox/archived/`, every entry of it.+ *+ * The one selection both the dream plan and the `inbox-archivable` doctor+ * check go through, so the doctor's count is what a dry run archives less+ * the signals that pass consumes instead.+ */+export function selectArchivableSignals(+ signals: ReadonlyArray<SignalRecord>,+ archivedNames: ReadonlySet<string>,+ windowDays: number,+ now: Date,+): ArchiveSelection {+ const clock = archiveClock(now);+ const archivable: SignalRecord[] = [];+ const collisions: SignalRecord[] = [];+ for (const rec of signals) {+ if (!rec.active || !isOutsideWindow(rec.signal.created_at, windowDays, clock)) continue;+ if (archivedNames.has(basename(rec.path))) collisions.push(rec);+ else archivable.push(rec);+ }+ return { archivable, collisions };+}++/**+ * Plan the archive step onto `plan.signalsToArchive`. Runs after the topic+ * plan, so a signal the pass consumes is never archived. Returns the+ * warnings the step raised (name collisions).+ */+export function planSignalArchive(+ scan: ScanResult,+ cfg: BrainConfig,+ now: Date,+ plan: PlanState,+): DreamWarning[] {+ if (!archiveEnabled(cfg)) return [];+ const { archivable, collisions } = selectArchivableSignals(+ scan.signals,+ scan.archivedNames ?? archivedRecordNames(scan),+ cfg.dream.contradiction_window_days,+ now,+ );+ const consumed = (rec: SignalRecord): boolean =>+ plan.signalsToMove.has(rec.signal.id) || plan.signalsToArchive.has(rec.signal.id);+ const warnings: DreamWarning[] = [];+ for (const rec of collisions) {+ if (consumed(rec)) continue;+ const name = basename(rec.path);+ warnings.push({+ code: ARCHIVE_NAME_COLLISION_CODE,+ message:+ `signal ${rec.signal.id} is outside the contradiction window but inbox/archived/${name} ` ++ `already exists; it stays in the inbox. Compare the two files and remove the ` ++ `duplicate by hand.`,+ });+ }+ for (const rec of archivable) {+ if (consumed(rec)) continue;+ const id = rec.signal.id;+ plan.signalsToArchive.set(id, { id, path: rec.path });+ }+ return warnings;+}++/**+ * Fallback for a scan built without a directory listing (a hand-made+ * fixture): the names of the archived records it holds.+ */+function archivedRecordNames(scan: ScanResult): ReadonlySet<string> {+ return new Set(scan.signals.filter((r) => r.archived).map((r) => basename(r.path)));+}diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.tsindex d7f73c61..46e26005 100644--- a/src/core/brain/snapshot.ts+++ b/src/core/brain/snapshot.ts@@ -74,11 +74,13 @@import { Database } from "bun:sqlite";import { spawnSync } from "node:child_process";+import { randomBytes } from "node:crypto";import { gunzipSync, gzipSync } from "node:zlib";import {closeSync,cpSync,existsSync,+ linkSync,lstatSync,mkdirSync,mkdtempSync,@@ -90,14 +92,14 @@ import {realpathSync,rmSync,statSync,- unlinkSync,writeFileSync,+ writeSync,type Dirent,} from "node:fs";import { tmpdir } from "node:os";import { basename, dirname, join, relative, resolve, sep } from "node:path";-import { FileAlreadyExistsError, renameWithRetry } from "../fs-atomic.ts";+import { FileAlreadyExistsError, renameWithRetry, unlinkWithRetry } from "../fs-atomic.ts";import { classifyRecoverability, type RecoverabilityVerdict } from "./gates/recoverability.ts";import { sha256Hex } from "../integrity/digest.ts";import { resolveConfiguredIndexPath } from "../search/paths.ts";@@ -812,12 +814,13 @@ export function createSnapshot("-T",tarPathArg(listPath),];- compressInto(- { kind: "buffer", bytes: runArchiveProducer("tar", tarArgs, runId) },- outPath,- tools,- runId,- );+ // tar writes into a staging file beside the member list rather than+ // into a captured pipe, and the compressor reads that file: neither+ // the tar stream nor the compressed archive ever sits in this+ // process's memory, so the size of `Brain/` sets no ceiling here.+ const tarPath = join(listDir, "brain.tar");+ runArchiveProducer("tar", tarArgs, tarPath, runId);+ compressInto({ kind: "file", path: tarPath }, outPath, tools, runId);if (!existsSync(outPath)) {throw new BrainSnapshotError(`archive write reported success but ${outPath} is absent`,@@ -1090,12 +1093,6 @@ function writeStoreArchive(): void {const tmp = mkdtempSync(join(tmpdir(), `o2b-store-vacuum-${runId}-`));const vacuumed = join(tmp, DERIVED_STORE_VACUUM_FILE);- // Whether the destination was ALREADY taken when this call began. It- // decides whether the cleanup below may touch it: an archive a racing- // process wrote is the very thing the overwrite refusal protects, and- // removing it in the name of cleaning up after that refusal would- // reintroduce the data-loss path by the back door.- const preexisting = existsSync(archivePath);try {const db = new Database(sourcePath, { readonly: true });try {@@ -1105,16 +1102,10 @@ function writeStoreArchive(}compressInto({ kind: "file", path: vacuumed }, archivePath, tools, runId);} catch (err) {- // A failed compression may have left a partial archive of OUR making;- // the snapshot is about to be refused, so nothing may survive that a- // later read could mistake for a recovery point.- if (!preexisting) {- try {- unlinkSync(archivePath);- } catch {- // Nothing was written, or it is already gone. Either is fine.- }- }+ // Nothing to remove here: the compressor wrote a partial file that+ // `compressInto` discards, and the archive name is only ever created by+ // a successful publish. A failure on that name is a peer's archive,+ // which must survive the refusal.if (err instanceof BrainSnapshotError) throw err;throw new BrainSnapshotError(`failed to archive the derived store: ${(err as Error).message ?? String(err)}`,@@ -1166,9 +1157,11 @@ function discardStoreArchive(** The refusal is therefore made explicit here, before either compressor* runs, so both paths fail with the same typed error and the same- * message. The gzip write additionally opens with `wx` (exclusive- * create), which closes the window between the check and the write that- * a probe alone would leave open.+ * message. Both compressors then write a partial file, and+ * {@link publishArchive} gives it the final name with an exclusive hard+ * link, which closes the window between the check and the publish that a+ * probe alone would leave open and means a killed compression never+ * leaves a truncated archive under a recovery point's name.** The on-disk extension stays `.tar.zst` under gzip. The restore probes* the magic bytes rather than the name, and one suffix keeps listing and@@ -1180,41 +1173,223 @@ function compressInto(tools: ToolAvailability,runId: string,): void {- if (existsSync(outPath)) {- // The refusal carries an EEXIST-shaped cause because the id allocator- // above ladders past a taken name and needs to recognise this as the- // collision it is. Without it the allocator sees an opaque snapshot- // failure, declines to retry, and aborts the destructive operation the- // snapshot exists to protect.- throw new BrainSnapshotError(`refusing to overwrite an existing archive: ${outPath}`, runId, {- cause: new FileAlreadyExistsError(outPath, { kind: "snapshot archive" }),- });+ if (existsSync(outPath)) throw archiveCollision(outPath, runId);+ // The compressor writes a partial name beside the archive, and the+ // archive appears under its final name only once the compressor has+ // exited cleanly. A process killed part-way through compression (an+ // operator's kill, a host timeout, a power cut) used to leave a+ // truncated `<run_id>.tar.zst` with no manifest, which the listing,+ // retention and rollback all treat as a recovery point. A partial file+ // never ends in the archive suffix, so nothing lists it.+ const partial = `${outPath}${PARTIAL_ARCHIVE_INFIX}${process.pid}-${randomBytes(4).toString("hex")}`;+ try {+ if (tools.zstd) {+ runCompressor("zstd", ["-19", "-q", "-o", partial, payload.path], runId);+ } else {+ // No zstd: gzip in-process. `node:zlib` ships with every runtime this+ // tool supports, so a snapshot never depends on a `gzip` binary -+ // which native Windows does not have. Level 9 matches the `gzip -9`+ // this replaced, byte format included, so older readers restore it+ // unchanged.+ gzipFileExclusive(payload.path, partial, runId);+ }+ publishArchive(partial, outPath, runId);+ } finally {+ discardPartial(partial);}- if (tools.zstd) {- // `zstd -o` opens the destination itself and refuses an existing one.- const args =- payload.kind === "file"- ? ["-19", "-q", "-o", outPath, payload.path]- : ["-19", "-q", "-o", outPath, "-"];- runCompressor("zstd", args, payload, runId, null);+}++/**+ * Remove a partial archive this process wrote. Best-effort and never+ * throwing: it runs in a `finally`, where a throw would replace the real+ * outcome - turning a published archive into a failed snapshot, or hiding+ * the typed collision the run-id allocator ladders on. A partial left+ * behind is never listed, and {@link pruneSnapshots} removes stale ones.+ */+function discardPartial(partial: string): void {+ try {+ unlinkWithRetry(partial);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return;+ process.stderr.write(+ `warning: could not remove the partial snapshot archive ${partial}: ` ++ `${(err as Error).message ?? String(err)}\n`,+ );+ }+}++/** Infix of a partial archive's name: `<archive>.partial-<pid>-<hex>`. */+const PARTIAL_ARCHIVE_INFIX = ".partial-";++/**+ * A partial archive older than this is left over from a process that was+ * killed during compression. Generous against the longest compression a+ * live snapshot could still be running.+ */+const STALE_PARTIAL_MS = 24 * 60 * 60 * 1000;++/**+ * Remove partial archives a killed snapshot left in `.snapshots/`. They are+ * this tool's own unfinished output, never a recovery point (nothing lists+ * them), and each can be as large as the whole Brain tar. Best-effort.+ */+function removeStalePartials(snapshotsDirPath: string, now: number): void {+ let names: string[];+ try {+ names = readdirSync(snapshotsDirPath);+ } catch {return;}- // No zstd: gzip in-process. `node:zlib` ships with every runtime this- // tool supports, so a snapshot never depends on a `gzip` binary - which- // native Windows does not have. Level 9 matches the `gzip -9` this- // replaced, byte format included, so older readers restore it unchanged.- const raw = payload.kind === "buffer" ? payload.bytes : readFileSync(payload.path);- writeArchiveExclusive(outPath, gzipSync(raw, { level: 9 }), runId);+ for (const name of names) {+ if (!name.includes(PARTIAL_ARCHIVE_INFIX)) continue;+ const full = join(snapshotsDirPath, name);+ try {+ const st = lstatSync(full);+ if (!st.isFile() || now - st.mtimeMs < STALE_PARTIAL_MS) continue;+ unlinkWithRetry(full);+ } catch {+ // gone already, or not ours to remove right now; the next prune retries+ }+ }+}++/**+ * The typed "this name is taken" refusal. It carries an EEXIST-shaped+ * cause because the id allocator in `snapshot-gate.ts` ladders past a+ * taken name and needs to recognise this as the collision it is. Without+ * it the allocator sees an opaque snapshot failure, declines to retry, and+ * aborts the destructive operation the snapshot exists to protect.+ */+function archiveCollision(outPath: string, runId: string): BrainSnapshotError {+ return new BrainSnapshotError(`refusing to overwrite an existing archive: ${outPath}`, runId, {+ cause: new FileAlreadyExistsError(outPath, { kind: "snapshot archive" }),+ });+}++/**+ * errno values from the hard link that rule out the rename fallback too: the+ * partial file or the directory is gone, the volume is full or read-only.+ * Every other failure (a filesystem without hard links reports EPERM,+ * ENOTSUP, or on Windows FAT and exFAT an `ERROR_INVALID_FUNCTION` that+ * libuv maps to EISDIR) falls through to the checked rename.+ */+const LINK_FATAL_CODES: ReadonlySet<string> = new Set(["ENOENT", "ENOSPC", "EROFS"]);++/**+ * Give the finished `partial` file its final archive name, refusing a name+ * that is already taken.+ *+ * A hard link is an exclusive create of the name with the content already+ * in place: it fails with EEXIST when a peer published first and never+ * replaces anything, on POSIX and on NTFS alike. `rename` would replace an+ * existing archive silently, so it is used only when the link fails for+ * another reason (typically a filesystem without hard links), behind an+ * existence check. That leaves a window between+ * the check and the rename on such a volume; the run id already carries+ * the second it was taken in, and the allocator probes the name first.+ * The partial file itself is removed by the caller.+ */+function publishArchive(partial: string, outPath: string, runId: string): void {+ try {+ linkSync(partial, outPath);+ return;+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code ?? "";+ if (code === "EEXIST") throw archiveCollision(outPath, runId);+ if (LINK_FATAL_CODES.has(code)) {+ throw new BrainSnapshotError(+ `failed to publish ${outPath}: ${(err as Error).message ?? String(err)}`,+ runId,+ { cause: err },+ );+ }+ }+ if (existsSync(outPath)) throw archiveCollision(outPath, runId);+ try {+ renameWithRetry(partial, outPath);+ } catch (err) {+ throw new BrainSnapshotError(+ `failed to publish ${outPath}: ${(err as Error).message ?? String(err)}`,+ runId,+ { cause: err },+ );+ }+}++/**+ * Input read per gzip member by {@link gzipFileExclusive}. Bounds the+ * memory the gzip fallback holds at once, whatever the archive's size.+ */+const GZIP_MEMBER_INPUT_BYTES = 8 * 1024 * 1024;++/**+ * gzip `source` into `outPath` one bounded chunk at a time.+ *+ * `node:zlib` has no synchronous streaming API, and the snapshot path is+ * synchronous by contract (the destructive gate runs it inline before the+ * mutation it protects). So each chunk is compressed on its own and the+ * results are written back to back: a multi-member gzip file (RFC 1952,+ * section 2.2), which `gunzip`, `node:zlib` and every `tar -z` read as the+ * concatenation of the members. The restore path reads it unchanged.+ *+ * The destination is opened `wx`, so the exclusivity {@link compressInto}+ * relies on holds here exactly as it did for the single-buffer write. A+ * file this call created and could not finish is removed: it is ours, and+ * left behind it would read as a recovery point.+ */+function gzipFileExclusive(source: string, outPath: string, runId: string): void {+ let out: number;+ try {+ out = openSync(outPath, "wx");+ } catch (err) {+ throw new BrainSnapshotError(+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,+ runId,+ { cause: err },+ );+ }+ let finished = false;+ try {+ const input = openSync(source, "r");+ try {+ const chunk = Buffer.allocUnsafe(GZIP_MEMBER_INPUT_BYTES);+ let wroteMember = false;+ for (;;) {+ const read = readSync(input, chunk, 0, chunk.length, null);+ if (read === 0) break;+ writeFully(out, gzipSync(chunk.subarray(0, read), { level: 9 }));+ wroteMember = true;+ }+ // An empty source still produces a valid (one-member) gzip file.+ if (!wroteMember) writeFully(out, gzipSync(Buffer.alloc(0), { level: 9 }));+ } finally {+ closeSync(input);+ }+ finished = true;+ } catch (err) {+ throw new BrainSnapshotError(+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,+ runId,+ { cause: err },+ );+ } finally {+ closeSync(out);+ if (!finished) rmSync(outPath, { force: true });+ }+}++/** `writeSync` until every byte of `bytes` is on `fd`. */+function writeFully(fd: number, bytes: Buffer): void {+ let offset = 0;+ while (offset < bytes.length) {+ offset += writeSync(fd, bytes, offset, bytes.length - offset);+ }}/**- * Exclusive create of a finished archive. `wx` is what makes the gzip path- * refuse an existing archive the way `zstd -o` always has; see- * {@link compressInto} for why that refusal is load-bearing rather than- * tidy. A torn write remains possible (worst case: a corrupt archive that- * fails on restore, the same outcome as any other interrupted snapshot) -- * what is no longer possible is silently replacing someone else's- * recovery point.+ * Exclusive create of a decompressed payload. `wx` refuses an existing+ * destination the way `zstd -o` does, so neither decompressor can replace+ * a file it did not create.*/function writeArchiveExclusive(outPath: string, bytes: Buffer, runId: string): void {try {@@ -1229,48 +1404,29 @@ function writeArchiveExclusive(outPath: string, bytes: Buffer, runId: string): v}/**- * What a compressor reads. A `buffer` is the tar stream we already hold;- * a `file` is the vacuumed store copy, handed over by path so a- * multi-hundred-megabyte database never round-trips through memory.+ * What a compressor reads: a file, handed over by path - the staged tar+ * stream or the vacuumed store copy - so a multi-hundred-megabyte payload+ * never round-trips through memory.*/-type CompressionSource =- | { readonly kind: "buffer"; readonly bytes: Buffer }- | { readonly kind: "file"; readonly path: string };--/** Hard ceiling on any single captured subprocess stream. */-const SUBPROCESS_MAX_BUFFER_BYTES = 256 * 1024 * 1024;+type CompressionSource = { readonly kind: "file"; readonly path: string };/**- * Run one compressor over `payload`. When `outPath` is non-null the- * compressor writes to stdout and we own the destination file; when it- * is null the compressor was given the destination itself.+ * Hard ceiling on any single CAPTURED subprocess stream. Only diagnostic+ * output (stderr) is captured on the archive path; archive bytes go+ * through files, so this never bounds the size of a snapshot.*/+const SUBPROCESS_MAX_BUFFER_BYTES = 256 * 1024 * 1024;+/**- * The path a `-o <path>` compressor invocation was told to write.- *- * Read back off the argv rather than threaded separately, because the argv is- * what the process actually acted on: a second copy of the path could drift- * from the one the command used and then misclassify the failure.+ * Run one compressor that writes the destination named after its `-o`+ * itself, so only its stderr is captured. Every destination handed to it+ * is a name this process owns: a partial file with a random suffix, or a+ * file in a private temp directory. A collision on the published archive+ * name is detected by {@link publishArchive}, not here.*/-function destinationOf(args: ReadonlyArray<string>): string {- const flag = args.indexOf("-o");- return flag >= 0 ? (args[flag + 1] ?? "") : "";-}--function runCompressor(- cmd: string,- args: ReadonlyArray<string>,- payload: CompressionSource,- runId: string,- outPath: string | null,-): void {+function runCompressor(cmd: string, args: ReadonlyArray<string>, runId: string): void {const r = spawnSync(cmd, [...args], {- ...(payload.kind === "buffer" ? { input: payload.bytes } : {}),- stdio: [- payload.kind === "buffer" ? "pipe" : "ignore",- outPath === null ? "inherit" : "pipe",- "pipe",- ],+ stdio: ["ignore", "ignore", "pipe"],maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES,});if (r.error) {@@ -1278,62 +1434,58 @@ function runCompressor(}if (r.status !== 0) {const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();- // `zstd -o` opens the destination itself and refuses one that already- // exists, and it reports that refusal the same way it reports every other- // failure: a non-zero status and a sentence. So when the command has- // ALREADY failed and the destination is now present, the failure is- // classified as a collision rather than left opaque.- //- // This is not the discredited "check existsSync after the throw and- // swallow" pattern: the error is thrown either way and nothing is- // retried here. Only its `cause` differs, which is what lets the id- // allocator ladder to the next name instead of aborting a destructive- // operation because a peer won the same second.- const lostRace = outPath === null && existsSync(destinationOf(args));- throw new BrainSnapshotError(- `${cmd} exited with status ${r.status}: ${stderr}`,- runId,- lostRace- ? { cause: new FileAlreadyExistsError(destinationOf(args), { kind: "snapshot archive" }) }- : undefined,- );+ throw new BrainSnapshotError(`${cmd} exited with status ${r.status}: ${stderr}`, runId);}- if (outPath === null) return;- writeArchiveExclusive(outPath, r.stdout ?? Buffer.from(""), runId);}/**- * Run the archive producer and capture its stdout.+ * Run the archive producer with its stdout on `outFile`.*- * We avoid a shell pipe entirely: spawn `tar`, capture its stdout into a- * Buffer (acceptable: Brain trees are Markdown and stay small), then- * feed the compressor synchronously. The previous approach used- * `sh -c "tar ... | zstd ..."` and broke on quoting of paths with- * whitespace; buffering through Node is simpler and verifiably correct.+ * No shell pipe (the old `sh -c "tar ... | zstd ..."` broke on quoting of+ * paths with whitespace, and native Windows has no `sh`), and no captured+ * pipe either: tar's stdout is a file descriptor opened here, so the+ * stream goes straight to disk. It used to be captured through+ * `spawnSync` with a 256 MB `maxBuffer`, which a `Brain/` tree past that+ * size overran with `ENOBUFS` after tar had already done all of its work.+ * Only stderr is captured, for the error message.+ *+ * `outFile` is opened `wx`: it lives in a private temp directory, so an+ * existing file there is a bug to surface rather than a file to reuse.** Argument quoting: we deliberately do NOT shell-escape paths, because* `tar -C <vault>` already roots everything relative to the vault, and* the only user-supplied bytes in `tarArgs` are the run id (which- * `validateRunId` constrains to `[A-Za-z0-9._-]`) and the top-level- * `Brain/` entries (`inbox`, `preferences`, β¦) which are themselves- * filesystem names produced by our own writers.+ * `validateRunId` constrains to `[A-Za-z0-9._-]`) and the member list,+ * which travels through a file.*/-function runArchiveProducer(cmd: string, args: ReadonlyArray<string>, runId: string): Buffer {- const r = spawnSync(cmd, [...args], {- maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES,- stdio: ["ignore", "pipe", "pipe"],- });+function runArchiveProducer(+ cmd: string,+ args: ReadonlyArray<string>,+ outFile: string,+ runId: string,+): void {+ const fd = openSync(outFile, "wx");+ let r: ReturnType<typeof spawnSync>;+ try {+ r = spawnSync(cmd, [...args], {+ maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES,+ stdio: ["ignore", fd, "pipe"],+ });+ } finally {+ closeSync(fd);+ }if (r.error) {throw new BrainSnapshotError(`${cmd} failed to start: ${r.error.message}`, runId);}if (r.status !== 0) {- const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();+ const stderr = Buffer.from(r.stderr ?? "")+ .toString("utf8")+ .trim();throw new BrainSnapshotError(`${cmd} exited with status ${r.status}: ${stderr}`, runId);}- if (!r.stdout) {+ if (statSync(outFile).size === 0) {throw new BrainSnapshotError(`${cmd} produced no stdout`, runId);}- return r.stdout;}// ----- listSnapshots / pruneSnapshots --------------------------------------@@ -1476,6 +1628,7 @@ export function pruneSnapshots(if (!Number.isInteger(retentionCount)) {throw new Error(`pruneSnapshots: retentionCount must be an integer; got ${retentionCount}`);}+ removeStalePartials(brainDirs(vault).snapshots, Date.now());if (retentionCount < SNAPSHOT_RETENTION_FLOOR) {// Refused, not obeyed, and not thrown: see the docblock.return Object.freeze({@@ -1609,27 +1762,38 @@ export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnap}if (decompressor === "zstd") {- const zstd = spawnSync("zstd", ["-d", "-c", archive], {- maxBuffer: 256 * 1024 * 1024,- stdio: ["ignore", "pipe", "pipe"],- });- if (zstd.error || zstd.status !== 0) {- const stderr = (zstd.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(- `zstd decompress failed: ${zstd.error?.message ?? stderr}`,- runId,- );- }- // `-f -` is explicit stdin: GNU tar defaults to stdin without- // it, but BSD tar and busybox tar do not, so passing the flag- // keeps the extraction portable across hosts.- const tar = spawnSync("tar", ["-x", "-f", "-", "-C", tarPathArg(tmp)], {- input: zstd.stdout,- stdio: ["pipe", "inherit", "pipe"],- });- if (tar.error || tar.status !== 0) {- const stderr = (tar.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(`tar extract failed: ${tar.error?.message ?? stderr}`, runId);+ // Decompressed to a staging file OUTSIDE the extraction root, then+ // handed to tar as its stdin descriptor: neither stream is captured+ // in memory, so an archive whose tar stream is larger than any+ // capture buffer restores as well as a small one. Captured through+ // a 256 MB `maxBuffer` before, which such an archive overran.+ const staging = mkdtempSync(join(tmpdir(), `o2b-brain-extract-tar-${runId}-`));+ try {+ const tarball = join(staging, "brain.tar");+ runCompressor("zstd", ["-d", "-q", "-o", tarball, archive], runId);+ const input = openSync(tarball, "r");+ let tar: ReturnType<typeof spawnSync>;+ try {+ // `-f -` is explicit stdin: GNU tar defaults to stdin without+ // it, but BSD tar and busybox tar do not, so passing the flag+ // keeps the extraction portable across hosts.+ tar = spawnSync("tar", ["-x", "-f", "-", "-C", tarPathArg(tmp)], {+ stdio: [input, "inherit", "pipe"],+ });+ } finally {+ closeSync(input);+ }+ if (tar.error || tar.status !== 0) {+ const stderr = Buffer.from(tar.stderr ?? "")+ .toString("utf8")+ .trim();+ throw new BrainSnapshotError(+ `tar extract failed: ${tar.error?.message ?? stderr}`,+ runId,+ );+ }+ } finally {+ rmSync(staging, { recursive: true, force: true });}} else {// gzip is inflated in-process and piped to `tar -f -`, like the zstd@@ -2080,13 +2244,7 @@ function decompressArchiveTo(archive: string, outPath: string, runId: string): v}if (compressor === "zstd") {// `zstd -o` opens the destination itself and refuses an existing one.- runCompressor(- "zstd",- ["-d", "-q", "-o", outPath, archive],- { kind: "file", path: archive },- runId,- null,- );+ runCompressor("zstd", ["-d", "-q", "-o", outPath, archive], runId);return;}// gzip is inflated in-process (no `gzip` binary on native Windows);diff --git a/src/core/brain/stale-dependency.ts b/src/core/brain/stale-dependency.tsindex 873d3368..e664ce7d 100644--- a/src/core/brain/stale-dependency.ts+++ b/src/core/brain/stale-dependency.ts@@ -336,7 +336,7 @@ interface BrainArtifactFile {*/function artifactDirs(vault: string): ReadonlyArray<string> {const dirs = brainDirs(vault);- return [dirs.brain, dirs.preferences, dirs.retired, dirs.inbox, dirs.processed];+ return [dirs.brain, dirs.preferences, dirs.retired, dirs.inbox, dirs.processed, dirs.archived];}/**diff --git a/src/core/brain/status.ts b/src/core/brain/status.tsindex f5120b06..fc645f5c 100644--- a/src/core/brain/status.ts+++ b/src/core/brain/status.ts@@ -74,6 +74,8 @@ import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "./types.ts";export interface BrainStatusCounts {readonly inbox: number;readonly inbox_processed: number;+ /** Signals in `inbox/archived/` (left the contradiction window unconsumed). */+ readonly inbox_archived: number;readonly preferences: number;readonly preferences_by_status: Readonly<Record<string, number>>;readonly retired: number;@@ -149,6 +151,7 @@ export function computeBrainStatus(counts: {inbox: 0,inbox_processed: 0,+ inbox_archived: 0,preferences: 0,preferences_by_status: Object.freeze({}),retired: 0,@@ -230,6 +233,7 @@ function countArtifacts(vault: string): BrainStatusCounts {const dirs = brainDirs(vault);const inbox = countMd(dirs.inbox);const inbox_processed = countMd(dirs.processed);+ const inbox_archived = countMd(dirs.archived);const retired = countMd(dirs.retired);// Shard-aware: count distinct DAYS, not files (several shards share a day).const log_days = listLogDates(vault).length;@@ -258,6 +262,7 @@ function countArtifacts(vault: string): BrainStatusCounts {return {inbox,inbox_processed,+ inbox_archived,preferences,preferences_by_status: Object.freeze(preferences_by_status),retired,diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.tsindex f46d0876..aea7fdc0 100644--- a/src/core/brain/sync-lockfile.ts+++ b/src/core/brain/sync-lockfile.ts@@ -54,6 +54,8 @@import {closeSync,+ constants as fsConstants,+ fstatSync,lstatSync,mkdirSync,openSync,@@ -182,9 +184,10 @@ export function acquireLockSync(target: string): LockHandle {// purely diagnostic - the doctor surface reads them when reporting// stale locks. Failure to write is non-fatal: the lock semantics// come from the exclusive create, not from the body.+ let stampBytes = 0;try {const stamp = Buffer.from(`${process.pid}\n${new Date().toISOString()}\n`, "utf8");- writeSync(fd, stamp, 0, stamp.byteLength);+ stampBytes = writeSync(fd, stamp, 0, stamp.byteLength);} catch {// ignore; diagnostic-only payload} finally {@@ -203,11 +206,21 @@ export function acquireLockSync(target: string): LockHandle {if (released) return;released = true;heldLocks.delete(lockPath);+ // Anything past our own stamp was appended by a waiter (see+ // `markWaiting`): someone is queued for this lock, so a re-acquire from+ // this process steps back first. Best-effort, like the stamp itself.+ let waitedOn = false;+ try {+ waitedOn = lstatSync(lockPath).size > stampBytes;+ } catch {+ // gone already; nobody to hand over to+ }try {unlinkSync(lockPath);} catch {// already gone (race with exit hook or manual cleanup); ignore}+ if (waitedOn) contendedReleases.set(lockPath, Date.now());},};}@@ -246,9 +259,35 @@ export function acquireLockSync(target: string): LockHandle {* 400-entry manifest (100 acquisitions), the WAIT distribution is* `p50 = 0 ms, p90 = 1 ms, p99 = 732 ms, max = 732 ms`: almost every* acquisition is uncontended, and the tail is set by queueing, not by one- * hold. The tail is long because nothing here is fair - a writer in a loop- * re-acquires with no backoff at all while every waiter is mid-sleep, so a- * waiter can lose many draws in a row.+ * hold. The tail was long because nothing here was fair - a writer in a loop+ * re-acquired with no backoff at all while every waiter was mid-sleep, so a+ * waiter could lose many draws in a row. On a host whose hold is slower (the+ * Windows runner, about 80 ms per checkpoint write) that same unfairness+ * spent the whole budget: the checkpoint race was refused there, and a local+ * replay with an 80 ms hold refused 2 of 300 writes at 5 000 ms.+ *+ * ## The hand-over, and what it measured+ *+ * A waiter now marks the held lock file ({@link markWaiting}); a holder that+ * releases a marked lock and comes straight back for it steps back for longer+ * than any waiter sleeps, and a waiter that has already waited a while polls+ * on a shorter ceiling. The four-process checkpoint race, 100 acquisitions+ * per run, before and after:+ *+ * | host | before p50 / p99 / max | after p50 / p99 / max |+ * |---|---|---|+ * | Linux, 8 ms hold | 0 / 395 / 604 ms | 62 / 155 / 185 ms |+ * | Linux, 80 ms hold | 0 / 4 582 / 5 012 ms, 2 refused | 247 / 508 / 753 ms |+ * | Linux, 210 ms hold | 1 / 5 016 / 5 017 ms, 4 refused | 427 / 1 905 / 2 124 ms |+ * | WSL on an NTFS drive, 26 ms hold | 9 / 654 / 881 ms | 97 / 313 / 328 ms |+ *+ * The median rises because a waiter now actually waits its turn instead of+ * the looping writer taking every draw; the tail, which is what the budget+ * has to cover, falls to a few holds. The cost is idle time at each+ * hand-over (until the next waiter wakes, at most one sleep ceiling), paid+ * only when someone is waiting. The default stays at five seconds: after the+ * hand-over it is more than six times the longest wait at the Windows pace.+ * A slower host moves it with {@link LOCK_WAIT_BUDGET_ENV}.** That tail is why the budget cannot simply be made small: at 1 000 ms the* branch's own designed-contention test (`updateManifest - concurrent@@ -265,6 +304,39 @@ export function acquireLockSync(target: string): LockHandle {*/export const LOCK_WAIT_BUDGET_MS = 5_000;+/**+ * The environment variable that moves {@link LOCK_WAIT_BUDGET_MS} for every+ * caller that does not pass its own budget - the ingest writers, the session+ * ledger, the payload store. A host where one critical section is slow (an+ * antivirus scanning every write, a network or synced folder) can give+ * parallel ingest a longer wait without a rebuild. It never touches+ * {@link LOCK_WAIT_INTERACTIVE_MS}: a caller that chose to refuse rather+ * than freeze keeps that choice.+ */+export const LOCK_WAIT_BUDGET_ENV = "OPEN_SECOND_BRAIN_LOCK_WAIT_MS";++/**+ * The default wait budget this process uses, in milliseconds.+ *+ * A value that is not a non-negative integer THROWS rather than falling+ * back to the default, in the same discipline as `O2B_MCP_DRAIN_MS`: an+ * operator who set the variable did so to change the wait, and quietly+ * waiting five seconds because they typed `20s` would hide that.+ */+export function resolveLockWaitBudgetMs(env: NodeJS.ProcessEnv = process.env): number {+ const raw = env[LOCK_WAIT_BUDGET_ENV];+ if (raw === undefined || raw.trim() === "") return LOCK_WAIT_BUDGET_MS;+ const text = raw.trim();+ const parsed = /^\d+$/.test(text) ? Number(text) : Number.NaN;+ if (!Number.isSafeInteger(parsed)) {+ throw new Error(+ `${LOCK_WAIT_BUDGET_ENV}=${raw} is not a lock wait; set it to a whole number of ` ++ `milliseconds >= 0 (the default is ${LOCK_WAIT_BUDGET_MS}), or unset it`,+ );+ }+ return parsed;+}+/*** The budget for a caller whose contention is RARE and whose freeze is* expensive - an interactive CLI pass with a progress stream and a Ctrl-C@@ -286,6 +358,114 @@ export const LOCK_WAIT_INTERACTIVE_MS = 1_000;const RETRY_SLEEP_CEILING_MS = 25;+/**+ * Lock paths this process released while another process was waiting on+ * them, with the release time. Read (and cleared) by the next+ * {@link acquireLockSyncWithRetry} of the same path.+ */+const contendedReleases = new Map<string, number>();++/**+ * How long after a contended release a re-acquire still counts as "coming+ * straight back". A waiter sleeps at most {@link RETRY_SLEEP_CEILING_MS}+ * between draws, so past a few ceilings every waiter has had its turn and+ * stepping back would only slow the returning writer down.+ */+const HANDOFF_WINDOW_MS = RETRY_SLEEP_CEILING_MS * 4;++/**+ * The pause a returning writer takes before it re-acquires a lock it just+ * released while someone waited: always longer than a waiter's longest+ * sleep, so at least one waiter wakes and draws inside it, and randomised so+ * two returning writers do not step back in lockstep.+ */+function handoffPauseMs(): number {+ return RETRY_SLEEP_CEILING_MS * 2 + Math.floor(Math.random() * RETRY_SLEEP_CEILING_MS);+}++/**+ * How long an aged waiter's ceiling is. After a hand-over the lock goes to+ * whichever waiter draws first, so a waiter that has already waited through+ * several hand-overs polls on a shorter ceiling and wins the next one more+ * often: an approximation of first come, first served without a queue file+ * a crash could strand.+ */+const AGED_WAITER_AFTER_MS = RETRY_SLEEP_CEILING_MS * 10;+const AGED_WAITER_CEILING_MS = 5;++function waiterSleepMs(waitedMs: number): number {+ const ceiling =+ waitedMs >= AGED_WAITER_AFTER_MS ? AGED_WAITER_CEILING_MS : RETRY_SLEEP_CEILING_MS;+ return 1 + Math.floor(Math.random() * ceiling);+}++/** Upper bound on the bytes waiters append to one lock file. */+const WAITER_MARK_LIMIT = 4_096;+const WAITER_MARK = Buffer.from("w", "utf8");+/** Read-write, never create, and never follow a symlink where the platform can refuse one. */+const MARK_OPEN_FLAGS = fsConstants.O_RDWR | (fsConstants.O_NOFOLLOW ?? 0);++/**+ * Tell the holder of `lockPath` that someone is waiting, by appending one+ * byte to its lock file. The file is opened WITHOUT create: a lock+ * released a moment ago must never be re-created by a waiter, which would be+ * a lock nobody holds. Every failure is ignored - the mark only buys+ * fairness, and the exclusive create is still what grants the lock.+ */+function markWaiting(lockPath: string): void {+ let fd = -1;+ try {+ fd = openSync(lockPath, MARK_OPEN_FLAGS);+ const stat = fstatSync(fd);+ // Only a lock file this module could have created: a regular file with+ // one name. A symlink or hard link planted at the lock path (a synced+ // vault can carry one) must not turn the mark into a write elsewhere.+ if (!stat.isFile() || stat.nlink !== 1) return;+ if (stat.size < WAITER_MARK_LIMIT) {+ writeSync(fd, WAITER_MARK, 0, WAITER_MARK.byteLength, stat.size);+ }+ } catch {+ // released, delete-pending or unreadable: nothing to mark+ } finally {+ if (fd >= 0) {+ try {+ closeSync(fd);+ } catch {+ // ignore+ }+ }+ }+}++/** What an expired wait tells the operator to do next, by who set the budget. */+const REMEDY_EXPLICIT_BUDGET = "retry once the other writer finishes";++function defaultBudgetRemedy(budgetMs: number): string {+ return (+ `retry once the other writer finishes, or allow a longer wait with ` ++ `${LOCK_WAIT_BUDGET_ENV}=<milliseconds> (now ${budgetMs})`+ );+}++/**+ * The next step a refused INGEST write names. Passed by the writers the+ * parallel ingest fan-out shares (the content manifest, the plan and session+ * checkpoints, the git record store, the session ledger), where running the+ * workers one at a time is the other honest answer.+ */+export function ingestLockRemedy(budgetMs: number = resolveLockWaitBudgetMs()): string {+ return (+ `another process is writing the same file: retry the ingest, run parallel ingests ` ++ `one at a time, or allow a longer wait with ${LOCK_WAIT_BUDGET_ENV}=<milliseconds> ` ++ `(now ${budgetMs})`+ );+}++export interface LockWaitOptions {+ /** What the refusal tells the operator to do next, replacing the generic advice. */+ readonly remedy?: (budgetMs: number) => string;+}+/*** {@link acquireLockSync} with a bounded wait, for the shared files that* PARALLEL processes write by design.@@ -299,9 +479,12 @@ const RETRY_SLEEP_CEILING_MS = 25;* overlap into a failed ingest.** Waiting is bounded and still loud: only `ELOCKED` is retried, any other- * error propagates at once, and an expired budget rethrows the last- * `ELOCKED` (which names the lock file) rather than proceeding unlocked.- * Nothing is ever silently skipped.+ * error propagates at once, and an expired budget throws an `ELOCKED`+ * (`lock busy: <lock file>`, how long it waited, and what to do next; the+ * last collision rides along as `cause`) rather than proceeding unlocked.+ * Nothing is ever silently skipped. `budget` omitted means the default,+ * moved by {@link LOCK_WAIT_BUDGET_ENV}; `options.remedy` replaces the+ * generic advice with the caller's own (see {@link ingestLockRemedy}).** ## The wait is a FREEZE, and that is the cost*@@ -337,8 +520,10 @@ const RETRY_SLEEP_CEILING_MS = 25;*/export function acquireLockSyncWithRetry(target: string,- budgetMs: number = LOCK_WAIT_BUDGET_MS,+ budget?: number,+ options: LockWaitOptions = {},): LockHandle {+ const budgetMs = budget ?? resolveLockWaitBudgetMs();// A budget this loop cannot honour is named rather than quietly// reinterpreted, in the same discipline as `requireCap` and the lease's// TTL guard. `NaN` is the reason the guard exists: `Date.now() >= NaN` is@@ -348,14 +533,40 @@ export function acquireLockSyncWithRetry(if (!Number.isInteger(budgetMs) || budgetMs < 0) {throw new Error(`lock wait budgetMs must be an integer >= 0, got ${budgetMs}`);}- const deadline = Date.now() + budgetMs;+ const lockPath = target + LOCK_SUFFIX;+ const started = Date.now();+ const deadline = started + budgetMs;+ // Fairness: a writer in a loop re-creates the lock file microseconds after+ // it unlinks it, while every waiter is mid-sleep, so without this a waiter+ // loses draw after draw until its budget runs out on a healthy race. When+ // this process released the lock while someone waited, it steps back for+ // longer than any waiter sleeps, so one of them takes the lock first.+ const releasedAt = contendedReleases.get(lockPath);+ if (releasedAt !== undefined) {+ contendedReleases.delete(lockPath);+ if (started - releasedAt < HANDOFF_WINDOW_MS && budgetMs > 0) {+ Bun.sleepSync(Math.min(handoffPauseMs(), budgetMs));+ }+ }for (;;) {try {return acquireLockSync(target);} catch (err) {if ((err as NodeJS.ErrnoException).code !== "ELOCKED") throw err;- if (Date.now() >= deadline) throw err;- Bun.sleepSync(1 + Math.floor(Math.random() * RETRY_SLEEP_CEILING_MS));+ if (Date.now() >= deadline) {+ const remedy =+ options.remedy?.(budgetMs) ??+ (budget === undefined ? defaultBudgetRemedy(budgetMs) : REMEDY_EXPLICIT_BUDGET);+ const refused: NodeJS.ErrnoException = new Error(+ `lock busy: ${lockPath}: still held after waiting ${Date.now() - started} ms; ${remedy}`,+ { cause: err },+ );+ refused.code = "ELOCKED";+ refused.path = lockPath;+ throw refused;+ }+ markWaiting(lockPath);+ Bun.sleepSync(waiterSleepMs(Date.now() - started));}}}diff --git a/src/core/brain/templates.ts b/src/core/brain/templates.tsindex e7a70df5..2ef9d68a 100644--- a/src/core/brain/templates.ts+++ b/src/core/brain/templates.ts@@ -9,7 +9,7 @@* rendered file rather than disappearing silently.*/-import { readFileSync } from "node:fs";+import { readFileSync, statSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -124,6 +124,59 @@ export function renderBrainManual();}+/**+ * Render the manual for `vault`, keeping the `vault_name` spelling an+ * existing manual already carries when that spelling names the SAME+ * directory as `vault`.+ *+ * The display name is the basename as the caller spelled the path. On a+ * case-insensitive filesystem (macOS, Windows) `.../vault` and `.../Vault`+ * open one directory, so two runtimes configured with the two spellings+ * rendered two different manuals for one vault. Each saw the other's as a+ * pending upgrade, and the start-up self-heal re-ran that upgrade, snapshot+ * included, on every start.+ *+ * The filesystem decides, not a platform guess: the existing spelling is+ * kept only when it differs from ours by case alone AND a `stat` of the+ * path under that spelling reaches the same file (device and inode, read as+ * bigints so Windows file ids compare exactly). On a case-sensitive+ * filesystem where `vault` and `Vault` are two directories the probe says+ * so, and the manual is re-rendered as before.+ */+export function renderBrainManualFor(+ vault: string,+ existing: string | null,+ config: BrainConfig = DEFAULT_BRAIN_CONFIG,+): string {+ const rendered = renderBrainManual(vault, config);+ if (existing === null) return rendered;+ const ours = vaultDisplayName(vault);+ const theirs = recordedVaultName(existing);+ if (theirs === null || theirs === ours) return rendered;+ if (theirs.toLowerCase() !== ours.toLowerCase()) return rendered;+ if (!sameDirectory(vault, join(dirname(resolve(vault)), theirs))) return rendered;+ const substitutions = new Map(buildSubstitutions(vault, config));+ substitutions.set("vault_name", theirs);+ return renderTemplate(readTemplate(BRAIN_MANUAL_TEMPLATE_PATH), substitutions);+}++/** The `vault_name:` value a rendered manual carries, or null. */+function recordedVaultName(manual: string): string | null {+ const match = /^vault_name: (.+)$/m.exec(manual);+ return match === null ? null : match[1]!.trim();+}++/** Whether two paths open the same file, by device and inode. */+function sameDirectory(a: string, b: string): boolean {+ try {+ const sa = statSync(a, { bigint: true });+ const sb = statSync(b, { bigint: true });+ return sa.dev === sb.dev && sa.ino === sb.ino;+ } catch {+ return false;+ }+}+/*** Best-effort display name for the vault: the trailing directory name* with separators stripped. Falls back to the literal `Second Brain`diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tplindex c4b16586..4c6fbeb6 100644--- a/src/core/brain/templates/_BRAIN.md.tpl+++ b/src/core/brain/templates/_BRAIN.md.tpl@@ -22,6 +22,7 @@ Brain/_BRAIN.md # this fileinbox/ # raw signals captured during workprocessed/ # signals already folded into a preference+ archived/ # signals that left the contradiction window unconsumedpreferences/ # active rules (unconfirmed or confirmed)retired/ # superseded / expired / rebutted / rejected ruleslog/ # daily ledger of every state change@@ -102,6 +103,9 @@ and `--now`. It:- flips first-applied unconfirmed prefs to confirmed;- retires expired, stale, rebutted, or user-rejected prefs;- moves consumed signals into `inbox/processed/`;+- moves signals older than `contradiction_window_days` that nothing+ consumed into `inbox/archived/` (they can no longer count toward a+ candidate; nothing is deleted);- archives Brain into `.snapshots/<run_id>.tar.zst` before mutating;- appends one summary entry to `log/<today>.md` if anything changed.diff --git a/src/core/brain/token-footprint.ts b/src/core/brain/token-footprint.tsindex 8ea6c648..2a47f5e7 100644--- a/src/core/brain/token-footprint.ts+++ b/src/core/brain/token-footprint.ts@@ -90,6 +90,7 @@ export function computeTokenFootprint(["retired", dirs.retired],["inbox", dirs.inbox],["processed", dirs.processed],+ ["archived", dirs.archived],["log", dirs.log],];diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex e1b9e067..2f81b8c7 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -1389,6 +1389,14 @@ export interface BrainDreamConfig {* byte-identical. Absent is treated as `false`.*/readonly heal_enrich_enabled?: boolean;+ /**+ * Inbox archive policy (issue #195). When not `false`, the dream pass+ * moves inbox signals that are older than `contradiction_window_days`+ * and were never consumed into `Brain/inbox/archived/`, because they can+ * no longer contribute to a candidate. `false` keeps them in the inbox+ * (the behaviour before the archive existed). Absent means enabled.+ */+ readonly archive_stale_signals?: boolean;/*** Salience-lifecycle-enrichment (unit 1). Minimum combined salience* score, in `[0, 1]`, a fact must reach to enter the rollup ladder'sdiff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.tsindex fcbc601a..bf96dc5c 100644--- a/src/core/brain/upgrade.ts+++ b/src/core/brain/upgrade.ts@@ -27,7 +27,7 @@ import { brainConfigPath, brainManualPath, vaultRelative } from "./paths.ts";import { BrainConfigError, loadBrainConfig } from "./policy.ts";import { DEFAULT_BRAIN_CONFIG_YAML } from "./config-template.ts";import { createSnapshot } from "./snapshot.ts";-import { renderBrainManual } from "./templates.ts";+import { renderBrainManualFor } from "./templates.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "./types.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";@@ -98,7 +98,7 @@ export function planUpgrade(vault: string): UpgradePlan {vault,brainManualPath(vault),vaultRelative(brainManualPath(vault), vault),- () => renderBrainManual(vault),+ (existing) => renderBrainManualFor(vault, existing),),...planCorruptedPreferences(vault),];@@ -249,13 +249,12 @@ function planManagedPath(_vault: string,absolutePath: string,relPath: string,- renderTarget: () => string,+ renderTarget: (existing: string | null) => string,): UpgradeFilePlan {- const after = renderTarget();if (!existsSync(absolutePath)) {// File missing entirely: an upgrade should restore it. Treat as// update with empty `before` so the diff shows the full body.- return makeUpdate(relPath, "", after);+ return makeUpdate(relPath, "", renderTarget(null));}let before: string;try {@@ -263,6 +262,10 @@ function planManagedPath(} catch (err) {return makeError(relPath, `read failed: ${(err as Error).message}`);}+ // The target is rendered against what is on disk, so a rendering that+ // may legitimately keep an existing spelling (the vault name on a+ // case-insensitive filesystem) can.+ const after = renderTarget(before);if (before === after) {return makeNoop(relPath);}diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.tsindex 497c2a52..5989a8d1 100644--- a/src/core/install/ownership.ts+++ b/src/core/install/ownership.ts@@ -175,6 +175,23 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze("reading it leaves that text in the temp directory until the OS or you remove it.",sources: ["hooks/session-capture.ts"],},+ {+ id: "dedup_index_cache",+ label: "signal dedup index cache",+ location: WINDOWS+ ? `%OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR%, else (${describeBaseDir("cache", "win32")})\\open-second-brain\\dedup-index\\<vault-digest>.json`+ : "$OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR, else ${XDG_CACHE_HOME:-~/.cache}/open-second-brain/dedup-index/<vault-digest>.json",+ carries_memory: true,+ created_by:+ "any capture that deduplicates signals (session import, inline scan, session capture, " ++ "signal extraction), once per vault; OPEN_SECOND_BRAIN_DEDUP_CACHE=0 turns it off",+ removed_by: "deleting that file; the next capture rebuilds it from the vault",+ note:+ "Per signal file: its name, size, modification time, id and dedup hash. No principle " ++ "text, but every signal id embeds its topic slug. Stat data is per machine, which is why " ++ "it is not kept in the vault a sync tool shares.",+ sources: ["src/core/brain/dedup-index-cache.ts"],+ },{id: "machine_config",label: "machine-local plugin config",@@ -469,6 +486,12 @@ export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Ma* claim about a census.*/export const SOURCES_INVISIBLE_TO_THE_SWEEP: ReadonlyMap<string, string> = new Map([+ [+ "src/core/brain/dedup-index-cache.ts",+ "the cache root comes from `cacheBaseDir()` in `core/platform-dirs.ts`, or from " ++ "OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR, so there is no home or XDG token in this file for the " ++ "sweep to match on",+ ],["src/cli/install-cli.ts","it still writes the launchers, but the bin directory it writes into now comes from " +diff --git a/src/core/maintenance/ensure-current.ts b/src/core/maintenance/ensure-current.tsindex 3ec0ecf4..cd470a50 100644--- a/src/core/maintenance/ensure-current.ts+++ b/src/core/maintenance/ensure-current.ts@@ -23,7 +23,6 @@ import { Database } from "bun:sqlite";import { defaultConfigPath } from "../config.ts";import { brainConfigPath } from "../brain/paths.ts";-import { planUpgrade, applyUpgrade } from "../brain/upgrade.ts";import { resolveSearchConfig } from "../search/index.ts";import { reindexVault } from "../search/indexer.ts";import { CHUNKER_VERSION } from "../search/chunker.ts";@@ -38,6 +37,17 @@ import {type SelfHealSpawnDecision,} from "./self-heal-reindex.ts";import { closeDatabase } from "../sqlite-close.ts";+import {+ runSelfHealUpgrade,+ SELF_HEAL_UPGRADE_OUTCOME,+ type SelfHealUpgradeOutcome,+} from "./self-heal-upgrade.ts";+import {+ claimSelfHealUpgradeLock,+ readSelfHealUpgradeFailure,+ releaseSelfHealUpgradeLock,+ selfHealUpgradeBackoffActive,+} from "./self-heal-upgrade-state.ts";/*** The flag that tells the child to record its own terminal outcome. It@@ -46,9 +56,36 @@ import { closeDatabase } from "../sqlite-close.ts";*/const SELF_HEAL_FLAG = "--self-heal";+/**+ * What a background run did about the Brain managed-file upgrade. The+ * worker's own outcome is recorded by the worker; see+ * `self-heal-upgrade.ts`.+ */+export const SELF_HEAL_UPGRADE_SPAWN = Object.freeze({+ /** A detached `o2b brain upgrade --self-heal` worker was started. */+ spawned: "spawned",+ /** A recorded failure's cooldown has not run out; nothing was started. */+ skippedBackoff: "skipped_backoff",+ /** Another worker holds this vault's lock; nothing was started. */+ skippedRunning: "skipped_running",+} as const);++export type SelfHealUpgradeSpawnDecision =+ (typeof SELF_HEAL_UPGRADE_SPAWN)[keyof typeof SELF_HEAL_UPGRADE_SPAWN];+export interface EnsureCurrentResult {- /** Vault-relative paths of Brain managed files migrated this run. */+ /**+ * Vault-relative paths of Brain managed files migrated this run. Always+ * empty in `background` mode: the upgrade runs in a detached worker.+ */readonly brainUpgraded: ReadonlyArray<string>;+ /**+ * In `background` mode, what was done about the managed-file upgrade;+ * `null` in the foreground, where {@link brainUpgradeOutcome} answers.+ */+ readonly brainUpgradeSpawn: SelfHealUpgradeSpawnDecision | null;+ /** In the foreground, how the upgrade attempt ended; `null` in `background` mode. */+ readonly brainUpgradeOutcome: SelfHealUpgradeOutcome | null;/** A search reindex was started (background) or completed (foreground). */readonly reindexTriggered: boolean;/**@@ -130,6 +167,58 @@ function o2bCommand(): string[] {return [join(repo, "scripts", "o2b")];}+/**+ * Start the managed-file upgrade in a detached worker, unless a recorded+ * failure is cooling down or another worker has the vault.+ *+ * The lock is CLAIMED here, before the spawn, and the claim token handed+ * to the worker, which releases it when it ends: N sessions starting at+ * once make N exclusive creates, and only the one that wins spawns. The+ * worker plans on its own (planning alone reads every preference file,+ * hundreds of milliseconds on a large vault), so nothing here reads more+ * than the failure marker.+ *+ * Streams are ignored and the child is `unref`ed, as for the reindex; its+ * outcome goes to the failure marker and the `self_heal_upgrade` metrics+ * surface.+ */+function startSelfHealUpgrade(+ vault: string,+ configPath: string | undefined,+ now: Date,+): SelfHealUpgradeSpawnDecision {+ if (selfHealUpgradeBackoffActive(readSelfHealUpgradeFailure(vault), now)) {+ return SELF_HEAL_UPGRADE_SPAWN.skippedBackoff;+ }+ const token = claimSelfHealUpgradeLock(vault, now);+ if (token === null) return SELF_HEAL_UPGRADE_SPAWN.skippedRunning;+ try {+ const proc = Bun.spawn(+ [...o2bCommand(), "brain", "upgrade", "--vault", vault, SELF_HEAL_FLAG, token],+ {+ stdin: "ignore",+ stdout: "ignore",+ stderr: "ignore",+ windowsHide: true,+ detached: process.platform === "win32",+ // The live environment, for the reason given in+ // `startSelfHealReindex`; the config path travels the way every+ // brain verb reads it.+ env: {+ ...process.env,+ ...(configPath !== undefined ? { OPEN_SECOND_BRAIN_CONFIG: configPath } : {}),+ },+ },+ );+ proc.unref();+ } catch (e) {+ // Nothing was started, so nothing else will release the claim.+ releaseSelfHealUpgradeLock(vault, token);+ throw e;+ }+ return SELF_HEAL_UPGRADE_SPAWN.spawned;+}+/*** Start a reindex without blocking, unless the writer lock is already held.*@@ -244,8 +333,16 @@ export async function ensureVaultCurrent(opts: EnsureCurrentOptions = {},): Promise<EnsureCurrentResult> {const background = opts.background ?? true;+ if (background) {+ // Yield first: callers start this and go straight on to serving+ // (`void ensureVaultCurrent(...)`), and everything below up to the+ // first `await` would otherwise run before they do.+ await new Promise<void>((resolveYield) => setImmediate(resolveYield));+ }const errors: string[] = [];let brainUpgraded: ReadonlyArray<string> = [];+ let brainUpgradeSpawn: SelfHealUpgradeSpawnDecision | null = null;+ let brainUpgradeOutcome: SelfHealUpgradeOutcome | null = null;let reindexTriggered = false;let reindexSpawn: SelfHealSpawnDecision | null = null;@@ -254,6 +351,8 @@ export async function ensureVaultCurrent(if (!existsSync(brainConfigPath(vault))) {return {brainUpgraded: [],+ brainUpgradeSpawn: null,+ brainUpgradeOutcome: null,reindexTriggered: false,reindexSpawn: null,skipped: "not-initialized",@@ -263,10 +362,18 @@ export async function ensureVaultCurrent(// 1. Brain managed-file upgrade - idempotent; only when changes are pending// and the plan is clean (a half-mergeable plan is left for the operator).+ // In the background it runs in a detached worker; a failure is recorded+ // by the worker and backs off the next automatic attempt.try {- const plan = planUpgrade(vault);- if (plan.errors === 0 && plan.pending > 0) {- brainUpgraded = applyUpgrade(vault).files_updated;+ if (background) {+ brainUpgradeSpawn = startSelfHealUpgrade(vault, opts.configPath, new Date());+ } else {+ const upgrade = runSelfHealUpgrade(vault);+ brainUpgradeOutcome = upgrade.outcome;+ brainUpgraded = upgrade.filesUpdated;+ if (upgrade.outcome === SELF_HEAL_UPGRADE_OUTCOME.failed) {+ errors.push(`brain-upgrade: ${upgrade.error ?? "failed"}`);+ }}} catch (e) {errors.push(`brain-upgrade: ${message(e)}`);@@ -292,5 +399,13 @@ export async function ensureVaultCurrent(errors.push(`search-reindex: ${message(e)}`);}- return { brainUpgraded, reindexTriggered, reindexSpawn, skipped: "", errors };+ return {+ brainUpgraded,+ brainUpgradeSpawn,+ brainUpgradeOutcome,+ reindexTriggered,+ reindexSpawn,+ skipped: "",+ errors,+ };}diff --git a/src/core/maintenance/self-heal-upgrade-state.ts b/src/core/maintenance/self-heal-upgrade-state.tsnew file mode 100644index 00000000..2811824c--- /dev/null+++ b/src/core/maintenance/self-heal-upgrade-state.ts@@ -0,0 +1,326 @@+/**+ * What the automatic Brain upgrade last failed with, and when it may try+ * again.+ *+ * `ensureVaultCurrent` hands a pending `_brain.yaml` / `_BRAIN.md` upgrade+ * to a detached worker (`self-heal-upgrade.ts`). A worker whose upgrade+ * failed used to leave no trace anywhere an operator looks: the error went+ * into a result nobody read, the next start ran the same failing upgrade+ * again (snapshot included), and `o2b doctor` reported everything OK. This+ * module is the record that closes that gap:+ *+ * - a FAILURE MARKER, `<vault>/.open-second-brain/self-heal-upgrade.json`,+ * holding the last error, when it happened, how many attempts in a row+ * failed and when the next automatic attempt is due. `o2b doctor`,+ * `o2b brain status` and `o2b brain upgrade --dry-run` read it.+ * - a BACKOFF read off that marker: a failed upgrade is retried+ * automatically only after a cooldown that doubles with each consecutive+ * failure ({@link selfHealUpgradeCooldownMs}). An explicit+ * `o2b brain upgrade --apply` ignores it and clears it on success.+ * - the WORKER LOCK, `<vault>/.open-second-brain/self-heal-upgrade.lock`,+ * one per vault per device, so N sessions starting at once start one+ * worker, not N.+ *+ * ## Why the marker is per device+ *+ * It lives beside the search index under `.open-second-brain/`, the+ * per-device directory, not under `Brain/`, which syncs to peers. A failure+ * is often a property of the device (a missing tool, a full disk, a+ * read-only mount), and a synced marker would make a healthy peer back off+ * from an upgrade it could apply. It is also not a "done" stamp: it only+ * ever delays a retry, never skips a pending upgrade, so the state-driven+ * rule in `ensure-current.ts` still holds.+ *+ * Leaf module on purpose: the doctor and the operator snapshot read the+ * marker without pulling the upgrade and snapshot machinery in.+ */++import { randomBytes } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { DERIVED_STORE_DIR } from "../brain/path-constants.ts";+import type { CheckResult } from "../types.ts";++/** Marker file name inside the per-device `.open-second-brain/` directory. */+export const SELF_HEAL_UPGRADE_MARKER_FILE = "self-heal-upgrade.json";++/** First cooldown after a failure. */+export const SELF_HEAL_UPGRADE_BASE_COOLDOWN_MS = 60 * 60_000;++/** Longest cooldown, however many attempts failed in a row. */+export const SELF_HEAL_UPGRADE_MAX_COOLDOWN_MS = 24 * 60 * 60_000;++/**+ * A worker lock older than this belongs to a worker that died (or hung in+ * a subprocess) and is taken over. It is the ceiling on how long one stuck+ * worker can keep every later start from trying.+ */+export const SELF_HEAL_UPGRADE_LOCK_STALE_MS = 60 * 60_000;++/** The command that shows the pending item and this record. */+export const SELF_HEAL_UPGRADE_NEXT_COMMAND = "o2b brain upgrade --dry-run";++/** One recorded failure of the automatic upgrade. */+export interface SelfHealUpgradeFailure {+ /** ISO-8601 instant of the last failed attempt. */+ readonly failedAt: string;+ /** The failure, as the upgrade reported it. */+ readonly error: string;+ /** Attempts in a row that failed, this one included. At least 1. */+ readonly consecutiveFailures: number;+ /** Vault-relative paths the failed attempt was going to rewrite. */+ readonly pending: ReadonlyArray<string>;+ /** ISO-8601 instant from which an automatic attempt is due again. */+ readonly retryAfter: string;+}++export function selfHealUpgradeMarkerPath(vault: string): string {+ return join(vault, DERIVED_STORE_DIR, SELF_HEAL_UPGRADE_MARKER_FILE);+}++/** Cooldown after `consecutiveFailures` failures in a row. */+export function selfHealUpgradeCooldownMs(consecutiveFailures: number): number {+ const exponent = Math.max(0, Math.min(consecutiveFailures - 1, 16));+ return Math.min(+ SELF_HEAL_UPGRADE_BASE_COOLDOWN_MS * 2 ** exponent,+ SELF_HEAL_UPGRADE_MAX_COOLDOWN_MS,+ );+}++/**+ * The recorded failure, or null when none is recorded.+ *+ * A marker that exists and cannot be read or parsed is reported as a+ * failure of its own rather than as "none": it was written because an+ * upgrade failed, and reading it back as healthy is the silence this+ * module exists to end. Its `retryAfter` is the epoch, so it never blocks+ * a retry either.+ */+export function readSelfHealUpgradeFailure(vault: string): SelfHealUpgradeFailure | null {+ const path = selfHealUpgradeMarkerPath(vault);+ if (!existsSync(path)) return null;+ try {+ const raw: unknown = JSON.parse(readFileSync(path, "utf8"));+ if (typeof raw !== "object" || raw === null) throw new Error("not a JSON object");+ const r = raw as Record<string, unknown>;+ if (typeof r["failed_at"] !== "string" || typeof r["error"] !== "string") {+ throw new Error("missing failed_at or error");+ }+ const consecutive =+ typeof r["consecutive_failures"] === "number" && r["consecutive_failures"] >= 1+ ? Math.floor(r["consecutive_failures"])+ : 1;+ const pending = Array.isArray(r["pending"])+ ? r["pending"].filter((p): p is string => typeof p === "string")+ : [];+ const retryAfter =+ typeof r["retry_after"] === "string" ? r["retry_after"] : new Date(0).toISOString();+ return Object.freeze({+ failedAt: r["failed_at"],+ error: r["error"],+ consecutiveFailures: consecutive,+ pending: Object.freeze(pending),+ retryAfter,+ });+ } catch (err) {+ return Object.freeze({+ failedAt: new Date(0).toISOString(),+ error: `unreadable failure marker (${(err as Error).message ?? String(err)})`,+ consecutiveFailures: 1,+ pending: Object.freeze([]),+ retryAfter: new Date(0).toISOString(),+ });+ }+}++/**+ * Whether an automatic attempt must wait: a failure is recorded and its+ * cooldown has not run out at `now`.+ */+export function selfHealUpgradeBackoffActive(+ failure: SelfHealUpgradeFailure | null,+ now: Date,+): boolean {+ if (failure === null) return false;+ const until = Date.parse(failure.retryAfter);+ if (!Number.isFinite(until)) return false;+ // Never longer than the longest cooldown after the recorded failure, and+ // never from a failure dated in the future: a marker this build did not+ // write (another release, a hand edit, a copied vault) cannot hold the+ // automatic upgrade off indefinitely.+ const failedAt = Date.parse(failure.failedAt);+ if (!Number.isFinite(failedAt) || failedAt > now.getTime()) return false;+ const ceiling = failedAt + SELF_HEAL_UPGRADE_MAX_COOLDOWN_MS;+ return now.getTime() < Math.min(until, ceiling);+}++/** Record a failed attempt; returns what was written. */+export function recordSelfHealUpgradeFailure(+ vault: string,+ error: string,+ pending: ReadonlyArray<string>,+ now: Date,+): SelfHealUpgradeFailure {+ const previous = readSelfHealUpgradeFailure(vault);+ const consecutiveFailures = (previous?.consecutiveFailures ?? 0) + 1;+ const retryAfter = new Date(now.getTime() + selfHealUpgradeCooldownMs(consecutiveFailures));+ const record = {+ failed_at: now.toISOString(),+ error,+ consecutive_failures: consecutiveFailures,+ pending: [...pending],+ retry_after: retryAfter.toISOString(),+ };+ const path = selfHealUpgradeMarkerPath(vault);+ mkdirSync(dirname(path), { recursive: true });+ atomicWriteFileSync(path, JSON.stringify(record, null, 2) + "\n");+ return Object.freeze({+ failedAt: record.failed_at,+ error,+ consecutiveFailures,+ pending: Object.freeze([...pending]),+ retryAfter: record.retry_after,+ });+}++/**+ * Drop the failure record once the upgrade it describes is no longer+ * pending (applied, or made moot). The marker is this tool's own state+ * file, never vault content.+ */+export function clearSelfHealUpgradeFailure(vault: string): void {+ try {+ unlinkSync(selfHealUpgradeMarkerPath(vault));+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;+ }+}++/** One-line operator description of a recorded failure. */+export function describeSelfHealUpgradeFailure(failure: SelfHealUpgradeFailure): string {+ const pending =+ failure.pending.length > 0 ? ` (pending: ${printable(failure.pending.join(", "))})` : "";+ return (+ `the automatic Brain upgrade failed at ${printable(failure.failedAt)}${pending}: ` ++ `${printable(failure.error)}; ` ++ `${failure.consecutiveFailures} consecutive failure(s), next automatic attempt after ` ++ `${printable(failure.retryAfter)}`+ );+}++/**+ * The marker is read back off disk and printed to a terminal, so control+ * characters (an escape sequence included) are replaced before they reach it.+ */+function printable(text: string): string {+ // oxlint-disable-next-line no-control-regex -- matching control characters is the point+ return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");+}++/** Name of the `o2b doctor` check that reports a recorded failure. */+export const SELF_HEAL_UPGRADE_CHECK = "self_heal_upgrade";++/**+ * The `o2b doctor` check: failed while a failure is recorded, with the+ * error, the time and the next automatic attempt in the message.+ */+export function checkSelfHealUpgrade(vault: string): CheckResult {+ const failure = readSelfHealUpgradeFailure(vault);+ if (failure === null) {+ return {+ name: SELF_HEAL_UPGRADE_CHECK,+ ok: true,+ message: "no failed automatic Brain upgrade is recorded",+ };+ }+ return {+ name: SELF_HEAL_UPGRADE_CHECK,+ ok: false,+ message: describeSelfHealUpgradeFailure(failure),+ fix: SELF_HEAL_UPGRADE_NEXT_COMMAND,+ };+}++// ----- Worker lock ---------------------------------------------------------++/** Lock file name inside the per-device `.open-second-brain/` directory. */+export const SELF_HEAL_UPGRADE_LOCK_FILE = "self-heal-upgrade.lock";++/**+ * Lock path for `vault`'s worker: beside the marker in the per-device+ * `.open-second-brain/`, where the search writer lock also lives. Derived+ * from the vault alone, never from the environment: the MCP server, a hook+ * and the worker each run with their own `TMPDIR`, and a lock whose path+ * depended on it would be a different lock in each of them.+ */+export function selfHealUpgradeLockPath(vault: string): string {+ return join(vault, DERIVED_STORE_DIR, SELF_HEAL_UPGRADE_LOCK_FILE);+}++/**+ * Claim `vault`'s worker lock without waiting: an exclusive create+ * (`O_EXCL`) of a file holding a fresh random token. Returns the token, or+ * null when a live (not stale) claim exists. A stale claim is removed and+ * the create retried once.+ *+ * The claim is a FILE, not a held descriptor, so it can be handed on: the+ * process that starts a detached worker claims first and passes the token+ * on the worker's command line. That closes the window a probe-then-spawn+ * leaves open - N sessions starting at once make N exclusive creates, one+ * wins, and only the winner spawns - and the worker, not its parent,+ * releases it when it ends.+ */+export function claimSelfHealUpgradeLock(vault: string, now: Date): string | null {+ const path = selfHealUpgradeLockPath(vault);+ mkdirSync(dirname(path), { recursive: true });+ const token = randomBytes(16).toString("hex");+ for (let attempt = 0; attempt < 2; attempt++) {+ try {+ writeFileSync(path, token, { flag: "wx" });+ return token;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;+ if (selfHealUpgradeLockHeld(vault, now)) return null;+ try {+ unlinkSync(path);+ } catch {+ // raced with the holder's release or another takeover; retry+ }+ }+ }+ return null;+}++/** Whether a live (not stale) claim on `vault`'s lock exists at `now`. */+export function selfHealUpgradeLockHeld(vault: string, now: Date): boolean {+ try {+ const age = now.getTime() - statSync(selfHealUpgradeLockPath(vault)).mtimeMs;+ return age <= SELF_HEAL_UPGRADE_LOCK_STALE_MS;+ } catch {+ return false;+ }+}++/** Whether `token` is the claim on `vault`'s lock right now. */+export function ownsSelfHealUpgradeLock(vault: string, token: string): boolean {+ try {+ return readFileSync(selfHealUpgradeLockPath(vault), "utf8") === token;+ } catch {+ return false;+ }+}++/**+ * Release the claim `token` made. A lock that is no longer ours (taken+ * over as stale by another process) is left alone.+ */+export function releaseSelfHealUpgradeLock(vault: string, token: string): void {+ if (!ownsSelfHealUpgradeLock(vault, token)) return;+ try {+ unlinkSync(selfHealUpgradeLockPath(vault));+ } catch {+ // already gone+ }+}diff --git a/src/core/maintenance/self-heal-upgrade.ts b/src/core/maintenance/self-heal-upgrade.tsnew file mode 100644index 00000000..5acb9422--- /dev/null+++ b/src/core/maintenance/self-heal-upgrade.ts@@ -0,0 +1,190 @@+/**+ * The automatic Brain managed-file upgrade, run off the start-up path.+ *+ * `ensureVaultCurrent` used to plan and apply a pending `_brain.yaml` /+ * `_BRAIN.md` upgrade inside the process that called it - the full-scope+ * MCP server and the `SessionStart` hook. Both calls were written as+ * fire-and-forget, but planning, the pre-apply snapshot and the rewrite are+ * synchronous, so all of it ran before the server read its first request:+ * seconds on a large `Brain/`, and past the host's connect timeout when the+ * snapshot was big enough to fail (GitHub #216).+ *+ * Now the caller claims a per-vault worker lock and starts a detached+ * `o2b brain upgrade --self-heal <token>`, which runs {@link runSelfHealUpgrade}+ * in its own process. The upgrade itself is unchanged - the same+ * `planUpgrade` / `applyUpgrade`, the same pre-apply snapshot, the same+ * writer lock that snapshot takes on the derived store - so the guarantees+ * the in-process path relied on hold in the worker; the worker lock adds+ * one it never had: one automatic upgrade per vault per machine at a time.+ *+ * ## What a run records+ *+ * A failed attempt writes the failure marker (`self-heal-upgrade-state.ts`)+ * that `o2b doctor`, `o2b brain status` and `o2b brain upgrade --dry-run`+ * read, and starts a cooldown before the next automatic attempt. Applied and+ * failed attempts also append one row to the `self_heal_upgrade` metrics+ * surface, the log of what the worker did. An attempt that finds nothing+ * pending writes nothing, so a start on a current vault leaves no trace.+ */++import { existsSync } from "node:fs";++import { appendMetric } from "../brain/metrics.ts";+import { brainConfigPath } from "../brain/paths.ts";+import { applyUpgrade, planUpgrade } from "../brain/upgrade.ts";+import {+ claimSelfHealUpgradeLock,+ clearSelfHealUpgradeFailure,+ ownsSelfHealUpgradeLock,+ readSelfHealUpgradeFailure,+ recordSelfHealUpgradeFailure,+ releaseSelfHealUpgradeLock,+ selfHealUpgradeBackoffActive,+} from "./self-heal-upgrade-state.ts";++/** Metrics surface the worker's applied and failed attempts go to. */+export const SELF_HEAL_UPGRADE_SURFACE = "self_heal_upgrade";++/** How one automatic upgrade attempt ended. */+export const SELF_HEAL_UPGRADE_OUTCOME = Object.freeze({+ /** Pending files were rewritten. */+ applied: "applied",+ /** Nothing was pending; any recorded failure was cleared. */+ current: "current",+ /** The plan or the apply failed; the failure marker was written. */+ failed: "failed",+ /** The plan has errors (a malformed `_brain.yaml`): left for the operator, as before. */+ planErrors: "plan_errors",+ /** A recorded failure's cooldown has not run out. */+ backoff: "backoff",+ /** Another worker holds this vault's lock. */+ running: "running",+ /** The vault is not (or no longer) initialised; nothing was touched. */+ notInitialized: "not_initialized",+} as const);++export type SelfHealUpgradeOutcome =+ (typeof SELF_HEAL_UPGRADE_OUTCOME)[keyof typeof SELF_HEAL_UPGRADE_OUTCOME];++export interface SelfHealUpgradeRun {+ readonly outcome: SelfHealUpgradeOutcome;+ /** Vault-relative paths rewritten; empty unless `applied`. */+ readonly filesUpdated: ReadonlyArray<string>;+ /** The failure; null unless `failed`. */+ readonly error: string | null;+}++export interface RunSelfHealUpgradeOptions {+ /** Clock for the backoff and the marker. Defaults to wall clock. */+ readonly now?: Date;+ /**+ * The lock claim a parent made and handed over (`--self-heal <token>`).+ * Absent, the run claims the lock itself.+ */+ readonly lockToken?: string;+}++function message(e: unknown): string {+ return e instanceof Error ? (e.message ?? String(e)) : String(e);+}++function run(+ outcome: SelfHealUpgradeOutcome,+ filesUpdated: ReadonlyArray<string> = [],+ error: string | null = null,+): SelfHealUpgradeRun {+ return Object.freeze({ outcome, filesUpdated: Object.freeze([...filesUpdated]), error });+}++/**+ * One automatic upgrade attempt for `vault`. Never throws: it runs where+ * nothing is left to catch (a detached worker with its streams ignored),+ * and every way it can end is an outcome.+ */+export function runSelfHealUpgrade(+ vault: string,+ opts: RunSelfHealUpgradeOptions = {},+): SelfHealUpgradeRun {+ const now = opts.now ?? new Date();+ let token: string | null;+ if (opts.lockToken !== undefined) {+ // A claim taken over as stale while this worker was starting is no+ // longer ours; the process that took it over does the work.+ token = ownsSelfHealUpgradeLock(vault, opts.lockToken) ? opts.lockToken : null;+ } else {+ try {+ token = claimSelfHealUpgradeLock(vault, now);+ } catch (e) {+ return run(SELF_HEAL_UPGRADE_OUTCOME.failed, [], `worker lock: ${message(e)}`);+ }+ }+ if (token === null) return run(SELF_HEAL_UPGRADE_OUTCOME.running);+ if (opts.lockToken !== undefined) {+ // A claim handed to a worker process covers that whole process, not+ // just this call: whatever the process still does on its way out is+ // part of the run whose end the lock's release announces.+ const held = token;+ process.once("exit", () => releaseSelfHealUpgradeLock(vault, held));+ return attempt(vault, now);+ }+ try {+ return attempt(vault, now);+ } finally {+ releaseSelfHealUpgradeLock(vault, token);+ }+}++function attempt(vault: string, now: Date): SelfHealUpgradeRun {+ // A vault removed or moved since the spawn: writing a marker would+ // recreate a directory nobody wants, so nothing is written at all.+ if (!existsSync(brainConfigPath(vault))) return run(SELF_HEAL_UPGRADE_OUTCOME.notInitialized);+ if (selfHealUpgradeBackoffActive(readSelfHealUpgradeFailure(vault), now)) {+ return run(SELF_HEAL_UPGRADE_OUTCOME.backoff);+ }+ const started = performance.now();+ let pending: string[] = [];+ try {+ const plan = planUpgrade(vault);+ if (plan.errors > 0) return run(SELF_HEAL_UPGRADE_OUTCOME.planErrors);+ if (plan.pending === 0) {+ clearSelfHealUpgradeFailure(vault);+ return run(SELF_HEAL_UPGRADE_OUTCOME.current);+ }+ pending = plan.files.filter((f) => f.status === "update").map((f) => f.path);+ const applied = applyUpgrade(vault, { now });+ clearSelfHealUpgradeFailure(vault);+ recordRow(vault, {+ outcome: SELF_HEAL_UPGRADE_OUTCOME.applied,+ duration_ms: Math.round(performance.now() - started),+ files: [...applied.files_updated],+ });+ return run(SELF_HEAL_UPGRADE_OUTCOME.applied, applied.files_updated);+ } catch (e) {+ const error = message(e);+ try {+ recordSelfHealUpgradeFailure(vault, error, pending, now);+ } catch {+ // The marker could not be written (read-only vault, full disk).+ // The metrics row below is the remaining record.+ }+ recordRow(vault, {+ outcome: SELF_HEAL_UPGRADE_OUTCOME.failed,+ duration_ms: Math.round(performance.now() - started),+ files: pending,+ error,+ });+ return run(SELF_HEAL_UPGRADE_OUTCOME.failed, [], error);+ }+}++function recordRow(vault: string, payload: Readonly<Record<string, unknown>>): void {+ try {+ appendMetric(vault, {+ surface: SELF_HEAL_UPGRADE_SURFACE,+ runAt: new Date().toISOString(),+ payload,+ });+ } catch {+ // Observability never fails the pass it observes.+ }+}diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.tsindex d197bb8d..330be935 100644--- a/src/core/state/surfaces.ts+++ b/src/core/state/surfaces.ts@@ -114,6 +114,7 @@ export const STATE_SURFACE_ID = Object.freeze({maintenanceJournal: "maintenance_journal",hookAudit: "hook_audit",hookSessionState: "hook_session_state",+ selfHealUpgradeMarker: "self_heal_upgrade_marker",watchdogAudit: "watchdog_audit",injectFailopenCache: "inject_failopen_cache",aiderContext: "aider_context_artifact",@@ -267,6 +268,7 @@ const PROTECT_MANIFEST_FILE = "protect.lock.json";const MAINTENANCE_LEASE_FILE = "maintenance.sqlite";const MAINTENANCE_JOURNAL_FILE = "maintenance-runs.jsonl";const HOOK_STATE_DIR = "hook-state";+const SELF_HEAL_UPGRADE_MARKER_FILE = "self-heal-upgrade.json";const WATCHDOG_AUDIT_DIR = "watchdog-audit";const INJECT_CACHE_DIR = "inject-cache";const AIDER_CONTEXT_FILE = "aider-context.md";@@ -558,6 +560,20 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze(["worth of once-per-session work.",sources: ["hooks/lib/session-state.ts"],},+ {+ id: STATE_SURFACE_ID.selfHealUpgradeMarker,+ label: "failed automatic upgrade marker",+ tier: STATE_TIER.derived,+ derive: derivedStore(SELF_HEAL_UPGRADE_MARKER_FILE),+ override_env: null,+ override_config_key: null,+ carries_memory: false,+ reason:+ "Present only after the automatic Brain upgrade failed on this device: the error, when, " ++ "and when the next automatic attempt is due. Deleting it ends the cooldown early and " ++ "drops the failure from `o2b doctor`; the next start simply tries again.",+ sources: ["src/core/maintenance/self-heal-upgrade-state.ts"],+ },{id: STATE_SURFACE_ID.watchdogAudit,label: "watchdog audit fallback",diff --git a/src/mcp/brain/extract-tools.ts b/src/mcp/brain/extract-tools.tsindex 18b4dbc2..78e1f08f 100644--- a/src/mcp/brain/extract-tools.ts+++ b/src/mcp/brain/extract-tools.ts@@ -10,6 +10,7 @@*/import { commitExtractedSignals, ExtractSignalsError } from "../../core/brain/extract-signals.ts";+import { loadDedupIndex } from "../../core/brain/dedup-hash.ts";import {planExtractSignalsPrefiltered,recordExtractPrefilterCommit,@@ -82,7 +83,8 @@ async function toolBrainExtractSignals(ctx.vault,session,{ items: args["items"] },- { agent, now },+ // Loaded with parallel I/O here, where the tool can await it.+ { agent, now, dedup: await loadDedupIndex(ctx.vault) },);recordExtractPrefilterCommit(ctx.vault, decisionModel, res, now);return {diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 9bfcc0e5..da8b6349 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -677,6 +677,10 @@ async function toolBrainDream(changed_count: dryRun ? 0 : changeList.length,dry_run: dryRun,...scopedDreamRows(dreamView, summary),+ // Inbox archive (issue #195): a count, not the ids. A first pass over a+ // long-lived vault archives thousands of signals; the run's log event+ // names every one of them.+ archived_signals_count: summary.archived_signals?.length ?? 0,contradictions: [...summary.contradictions],warnings: summary.warnings.map((w) => ({code: w.code,diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.tsindex e6d20a67..c6068eca 100644--- a/src/mcp/brain/query-tools.ts+++ b/src/mcp/brain/query-tools.ts@@ -585,6 +585,7 @@ async function toolBrainSources(sources: report.sources,total_active: report.total_active,total_processed: report.total_processed,+ total_archived: report.total_archived,};}diff --git a/src/mcp/resources.ts b/src/mcp/resources.tsindex bdd45156..4515feec 100644--- a/src/mcp/resources.ts+++ b/src/mcp/resources.ts@@ -614,7 +614,10 @@ function renderStatusMarkdown(s: BrainStatusSnapshot): string {}lines.push("## Counts");lines.push("");- lines.push(`- inbox: ${s.counts.inbox} (processed: ${s.counts.inbox_processed})`);+ lines.push(+ `- inbox: ${s.counts.inbox} (processed: ${s.counts.inbox_processed}, ` ++ `archived: ${s.counts.inbox_archived})`,+ );lines.push(`- preferences: ${s.counts.preferences}`);for (const [status, n] of Object.entries(s.counts.preferences_by_status).toSorted()) {lines.push(` - ${status}: ${n}`);diff --git a/tests/core/architecture/progress-census.test.ts b/tests/core/architecture/progress-census.test.tsindex 706b6d37..51738d0a 100644--- a/tests/core/architecture/progress-census.test.ts+++ b/tests/core/architecture/progress-census.test.ts@@ -114,6 +114,18 @@ const DECLARED_EXEMPTIONS: ReadonlyMap<string, string> = new Map<string, string>"DreamApplyInput","The dream pass's MUTATION STAGE, not a run: dream() owns the counter and has an `apply` stage open across this whole call. It takes the safeguard because the one sub-unit it dispatches - the opt-in heal enrichment - walks every user page in the vault and so needs a deadline inside a pass exactly as it does on its own; it takes no sink for the same reason scanBrain takes none from dream(), namely that a second stream would put two terminators on one run.",],+ [+ "DedupIndexOptions",+ "A SUB-STEP of a capture, not a run: the signal dedup walk is called inside session import, inline scan, session capture and signal extraction, each of which owns its own reporting. It takes the safeguard so a hook can stop the synchronous walk before the host kills it; a sink here would open a second stream inside the caller's.",+ ],+ [+ "LoadDedupIndexOptions",+ "The parallel-I/O form of DedupIndexOptions (it extends it with a concurrency bound) and a sub-step for the same reason: the capture that calls it owns the run and its stream, and the safeguard is there so a hook's ceiling reaches the walk.",+ ],+ [+ "CaptureSessionLifecycleOptions",+ "One lifecycle HOOK EVENT, not a long operation: the host runs it inside a 10 s timeout and reads no progress stream from it. The safeguard is the hook's process ceiling handed to the one step that grows with the vault (the dedup walk), so that step stops at a file boundary instead of being killed by the host.",+ ],["EmbeddingPhaseOptions","A PHASE, not a run: called from indexInto and standalone by the vector backfill. Given a sink it would build a second counter, and a stream carrying two terminators cannot say which one ended the run - so it borrows the run owner's ProgressCounter instead, which is strictly more wiring than a sink, not less.",diff --git a/tests/core/architecture/state-surface-census.test.ts b/tests/core/architecture/state-surface-census.test.tsindex d06c7443..6536d77d 100644--- a/tests/core/architecture/state-surface-census.test.ts+++ b/tests/core/architecture/state-surface-census.test.ts@@ -77,10 +77,10 @@ const STORE_DIR_IDENTIFIER = "DERIVED_STORE_DIR";* glob that stopped matching would sweep an empty set clean and every* assertion below would pass over nothing.*/-const SWEPT_POPULATION_SIZE = 21;+const SWEPT_POPULATION_SIZE = 22;/** Declared surfaces today. Pinned for the same reason. */-const DECLARED_SURFACE_COUNT = 44;+const DECLARED_SURFACE_COUNT = 45;/** An exclusion reason has to be an argument, not a label. */const MIN_REASON_LENGTH = 80;diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex 75245393..bfccc84d 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -877,7 +877,15 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object},"src/core/brain/snapshot.ts": {categories: [C.archiveTransfer, C.retentionDelete],- calls: ["cpSync", "renameSync", "rmSync", "unlinkSync", "writeFileSync"],+ 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 " +@@ -886,7 +894,22 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object"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.",+ "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/state/migrate.ts": {@@ -1183,8 +1206,12 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);* 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.*/-const DIRECT_WRITE_ROWS = 74;+const DIRECT_WRITE_ROWS = 75;/*** Measured modules reaching a write through a shared helper. An equality.@@ -1232,8 +1259,16 @@ const DIRECT_WRITE_ROWS = 74;* 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).*/-const SHARED_HELPER_ROWS = 104;+const SHARED_HELPER_ROWS = 106;// ----- Origin-channel coverage boundary (Unit C) ----------------------------@@ -1302,8 +1337,9 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(* 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).*/-const UNSTAMPED_DIRECT_ROWS = 73;+const UNSTAMPED_DIRECT_ROWS = 74;/*** Shared-helper write sites the stamp does not reach, measured the same@@ -1311,9 +1347,11 @@ const UNSTAMPED_DIRECT_ROWS = 73;* 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).+ * 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).*/-const UNSTAMPED_SHARED_ROWS = 101;+const UNSTAMPED_SHARED_ROWS = 103;describe("in-vault write-site census", () => {test("every direct-fs write site carries a written exclusion", () => {diff --git a/tests/core/brain/claim-graph-archived.test.ts b/tests/core/brain/claim-graph-archived.test.tsnew file mode 100644index 00000000..aa5c0500--- /dev/null+++ b/tests/core/brain/claim-graph-archived.test.ts@@ -0,0 +1,49 @@+/**+ * The claim graph keeps a signal the dream pass archived (issue #195).+ *+ * Archiving moves an inbox signal into `Brain/inbox/archived/` byte for+ * byte; the claim it carries is history, not deleted, so the projection+ * reads the archive the way it reads `inbox/processed/`.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildClaimGraph } from "../../../src/core/brain/claim-graph.ts";+import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";++const NOW = new Date("2026-06-30T12:00:00Z");++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-claim-graph-archived-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("a signal archived by the dream pass stays in the claim graph", () => {+ const { id } = writeSignal(vault, {+ topic: "old-claim",+ signal: "positive",+ agent: "claude",+ principle: "Principle for old-claim",+ created_at: "2026-05-01T10:00:00Z",+ date: "2026-05-01",+ slug: "old-claim",+ });+ expect(buildClaimGraph(vault).nodes.find((n) => n.id === id)?.path).toBe(`Brain/inbox/${id}.md`);++ expect(dream(vault, { now: NOW }).archived_signals).toEqual([id]);++ const node = buildClaimGraph(vault).nodes.find((n) => n.id === id);+ expect(node?.path).toBe(`Brain/inbox/archived/${id}.md`);+ expect(node?.principle).toBe("Principle for old-claim");+});diff --git a/tests/core/brain/dedup-index-cache.test.ts b/tests/core/brain/dedup-index-cache.test.tsnew file mode 100644index 00000000..f1feec72--- /dev/null+++ b/tests/core/brain/dedup-index-cache.test.ts@@ -0,0 +1,290 @@+/**+ * The signal dedup index and its machine-local cache (issue #195).+ *+ * The index maps a signal's `dedup_hash` to the first signal carrying it,+ * across `inbox/`, `inbox/processed/` and `inbox/archived/`. It includes the+ * archive on purpose: a re-imported old session must not re-create a signal+ * the dream pass archived. Building it reads every signal file, which on a+ * slow mount outlasted the session-capture hook, so the result is cached+ * outside the vault and revalidated per directory (listing, count, mtime)+ * and per file (size, mtime). These tests pin that the cached index always+ * equals a fresh walk, including after a sync tool replaces a file under+ * the same name, and that the walk honours a deadline.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ renameSync,+ rmSync,+ statSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ buildDedupIndex,+ loadDedupIndex,+ type DedupIndexEntry,+} from "../../../src/core/brain/dedup-hash.ts";+import { dedupIndexCachePath } from "../../../src/core/brain/dedup-index-cache.ts";+import { createSafeguard, SafeguardTimeoutError } from "../../../src/core/brain/safeguard.ts";++const HOUR_S = 3600;++let root: string;+let vault: string;+let cacheDir: string;+const savedEnv: Record<string, string | undefined> = {};++function setEnv(key: string, value: string | undefined): void {+ if (!(key in savedEnv)) savedEnv[key] = process.env[key];+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+}++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-dedup-cache-"));+ vault = join(root, "vault");+ cacheDir = join(root, "cache");+ for (const sub of ["", "processed", "archived"]) {+ mkdirSync(join(vault, "Brain", "inbox", sub), { recursive: true });+ }+ setEnv("OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR", cacheDir);+ setEnv("OPEN_SECOND_BRAIN_DEDUP_CACHE", undefined);+});++afterEach(() => {+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ delete savedEnv[key];+ }+ rmSync(root, { recursive: true, force: true });+});++function dir(sub: "" | "processed" | "archived"): string {+ return join(vault, "Brain", "inbox", sub);+}++function signalText(id: string, hash: string | null): string {+ return [+ "---",+ "kind: brain-signal",+ `id: ${id}`,+ 'created_at: "2026-05-01T00:00:00Z"',+ "topic: t",+ "signal: positive",+ "agent: a",+ "principle: p",+ ...(hash === null ? [] : [`dedup_hash: ${hash}`]),+ "---",+ "",+ ].join("\n");+}++function put(sub: "" | "processed" | "archived", id: string, hash: string | null): string {+ const path = join(dir(sub), `${id}.md`);+ writeFileSync(path, signalText(id, hash));+ return path;+}++/** Push every file and directory mtime an hour back: past the racy window. */+function settle(): void {+ const past = Date.now() / 1000 - HOUR_S;+ for (const sub of ["", "processed", "archived"] as const) {+ for (const name of readdirSync(dir(sub))) {+ const p = join(dir(sub), name);+ if (statSync(p).isFile()) utimesSync(p, past, past);+ }+ utimesSync(dir(sub), past, past);+ }+}++function plain(index: Map<string, DedupIndexEntry>): Array<[string, string, string]> {+ return [...index].map(([hash, e]) => [hash, e.id, e.path]);+}++function uncached(): Map<string, DedupIndexEntry> {+ setEnv("OPEN_SECOND_BRAIN_DEDUP_CACHE", "0");+ try {+ return buildDedupIndex(vault);+ } finally {+ setEnv("OPEN_SECOND_BRAIN_DEDUP_CACHE", undefined);+ }+}++/**+ * Rewrite a signal's `dedup_hash` in place with a value of the same length,+ * then put back the file's and its directory's modification times (or give+ * the file `mtimeS` instead). No sync tool or writer in this repository does+ * this; the tests use it because an index built from the cache still+ * reports the OLD hash, which proves the file was not re-read.+ */+function rewriteInPlace(path: string, id: string, hash: string, mtimeS?: number): void {+ const parent = join(path, "..");+ const before = statSync(path);+ const parentBefore = statSync(parent);+ writeFileSync(path, signalText(id, hash));+ expect(statSync(path).size).toBe(before.size);+ const fileTime = mtimeS ?? before.mtimeMs / 1000;+ utimesSync(path, fileTime, fileTime);+ utimesSync(parent, parentBefore.atimeMs / 1000, parentBefore.mtimeMs / 1000);+}++function seed(): void {+ put("", "sig-2026-05-01-a", "h-a");+ put("", "sig-2026-05-01-nohash", null);+ put("processed", "sig-2026-05-01-b", "h-b");+ put("archived", "sig-2026-05-01-c", "h-c");+ // Same hash in two directories: the inbox copy is seen first and wins.+ put("archived", "sig-2026-05-01-dup", "h-a");+}++describe("buildDedupIndex", () => {+ test("indexes inbox, processed and archived; first seen wins", () => {+ seed();+ const index = buildDedupIndex(vault);+ expect(index.get("h-a")?.id).toBe("sig-2026-05-01-a");+ expect(index.get("h-b")?.id).toBe("sig-2026-05-01-b");+ expect(index.get("h-c")?.id).toBe("sig-2026-05-01-c");+ expect(index.size).toBe(3);+ });++ test("a quiet directory is served from the cache without a per-file stat", () => {+ seed();+ settle();+ buildDedupIndex(vault);+ expect(existsSync(dedupIndexCachePath(vault)!)).toBe(true);+ // A new file mtime is what the per-file tier would notice; the directory+ // tier never stats the file, so it still serves the cached hash.+ const a = join(dir(""), "sig-2026-05-01-a.md");+ rewriteInPlace(a, "sig-2026-05-01-a", "h-X", Date.now() / 1000 - HOUR_S / 2);++ const warm = buildDedupIndex(vault);+ expect(warm.get("h-a")?.path).toBe(a);+ expect(warm.has("h-X")).toBe(false);+ expect(uncached().get("h-X")?.path).toBe(a);+ });++ test("files written inside the racy window are never trusted from the cache", () => {+ seed();+ buildDedupIndex(vault);+ const a = join(dir(""), "sig-2026-05-01-a.md");+ rewriteInPlace(a, "sig-2026-05-01-a", "h-X");+ const index = buildDedupIndex(vault);+ expect(index.get("h-X")?.path).toBe(a);+ expect(plain(index)).toEqual(plain(uncached()));+ });++ test("a file replaced under the same name by rename is re-read", () => {+ seed();+ settle();+ buildDedupIndex(vault);+ // What a sync tool does: write a temp file, rename it over the+ // original, and stamp the remote side's (older) modification time.+ const target = join(dir(""), "sig-2026-05-01-a.md");+ const temp = join(dir(""), ".syncthing.sig-2026-05-01-a.md.tmp");+ writeFileSync(temp, signalText("sig-2026-05-01-a", "h-remote"));+ const remoteTime = Date.now() / 1000 - 2 * HOUR_S;+ utimesSync(temp, remoteTime, remoteTime);+ renameSync(temp, target);++ const index = buildDedupIndex(vault);+ expect(index.get("h-remote")?.id).toBe("sig-2026-05-01-a");+ expect(plain(index)).toEqual(plain(uncached()));+ });++ test("added and removed files are picked up", () => {+ seed();+ settle();+ buildDedupIndex(vault);+ rmSync(join(dir("processed"), "sig-2026-05-01-b.md"));+ put("", "sig-2026-05-02-new", "h-new");+ const index = buildDedupIndex(vault);+ expect(index.has("h-b")).toBe(false);+ expect(index.get("h-new")?.id).toBe("sig-2026-05-02-new");+ expect(plain(index)).toEqual(plain(uncached()));+ });++ test("a file moved into the archive is reused, not re-read", () => {+ seed();+ settle();+ buildDedupIndex(vault);+ rewriteInPlace(join(dir(""), "sig-2026-05-01-a.md"), "sig-2026-05-01-a", "h-X");+ renameSync(join(dir(""), "sig-2026-05-01-a.md"), join(dir("archived"), "sig-2026-05-01-a.md"));+ const index = buildDedupIndex(vault);+ expect(index.get("h-a")?.path).toBe(join(dir("archived"), "sig-2026-05-01-a.md"));+ expect(index.has("h-X")).toBe(false);+ expect(uncached().has("h-X")).toBe(true);+ });++ test("a corrupt cache file is ignored and replaced", () => {+ seed();+ settle();+ const cachePath = dedupIndexCachePath(vault)!;+ mkdirSync(cacheDir, { recursive: true });+ writeFileSync(cachePath, "{not json");+ expect(plain(buildDedupIndex(vault))).toEqual(plain(uncached()));+ // The rebuilt cache is in use: an in-place rewrite is not re-read.+ rewriteInPlace(join(dir(""), "sig-2026-05-01-a.md"), "sig-2026-05-01-a", "h-X");+ expect(buildDedupIndex(vault).has("h-X")).toBe(false);+ });++ test("OPEN_SECOND_BRAIN_DEDUP_CACHE=0 writes no cache", () => {+ seed();+ settle();+ setEnv("OPEN_SECOND_BRAIN_DEDUP_CACHE", "0");+ expect(dedupIndexCachePath(vault)).toBeNull();+ buildDedupIndex(vault);+ expect(existsSync(cacheDir)).toBe(false);+ });++ test("the async loader returns the same index", async () => {+ seed();+ const cold = await loadDedupIndex(vault);+ expect(plain(cold)).toEqual(plain(uncached()));+ settle();+ const settled = await loadDedupIndex(vault);+ expect(plain(settled)).toEqual(plain(uncached()));+ rewriteInPlace(join(dir(""), "sig-2026-05-01-a.md"), "sig-2026-05-01-a", "h-X");+ const warm = await loadDedupIndex(vault);+ expect(warm.get("h-a")?.id).toBe("sig-2026-05-01-a");+ expect(warm.has("h-X")).toBe(false);+ });+});++/** A clock that advances one second per reading: a synthetic slow walk. */+function slowClock(): () => number {+ let t = 0;+ return () => (t += 1000);+}++function manySignals(n: number): void {+ for (let i = 0; i < n; i++) put("", `sig-2026-05-01-s${i}`, `h-${i}`);+}++describe("the walk honours a deadline", () => {+ test("a walk past its budget stops at a checkpoint", () => {+ manySignals(50);+ const safeguard = createSafeguard({ operation: "hook", timeoutMs: 5_000, now: slowClock() });+ expect(() => buildDedupIndex(vault, { safeguard })).toThrow(SafeguardTimeoutError);+ });++ test("the async walk stops too", async () => {+ manySignals(50);+ const safeguard = createSafeguard({ operation: "hook", timeoutMs: 5_000, now: slowClock() });+ await expect(loadDedupIndex(vault, { safeguard })).rejects.toThrow(SafeguardTimeoutError);+ });++ test("under budget the guarded walk returns the full index", () => {+ manySignals(50);+ const safeguard = createSafeguard({ operation: "hook", timeoutMs: 60_000 });+ expect(buildDedupIndex(vault, { safeguard }).size).toBe(50);+ });+});diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.tsindex d418d46b..c5adcd4c 100644--- a/tests/core/brain/doctor-exit-census.test.ts+++ b/tests/core/brain/doctor-exit-census.test.ts@@ -187,6 +187,7 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = ["embedding-model-sunset-announced","entity-label-malformed","entity-quote-variant-collision",+ "inbox-archivable","log-chain-broken","low-evidence-confirmed","orphan-evidence",diff --git a/tests/core/brain/doctor-inbox-archivable.test.ts b/tests/core/brain/doctor-inbox-archivable.test.tsnew file mode 100644index 00000000..d272c23a--- /dev/null+++ b/tests/core/brain/doctor-inbox-archivable.test.ts@@ -0,0 +1,86 @@+/**+ * `inbox-archivable` (issue #195): the doctor names how many inbox signals+ * can no longer become candidates, and points at the dream pass that+ * archives them.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";+import { runDoctor } from "../../../src/core/brain/doctor.ts";+import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainConfigPath } from "../../../src/core/brain/paths.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const NOW = new Date("2026-06-30T12:00:00Z");+const CODE = "inbox-archivable";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-doctor-archivable-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function sig(topic: string, createdAt: string): void {+ writeSignal(vault, {+ topic,+ signal: "positive",+ agent: "claude",+ principle: `Principle for ${topic}`,+ created_at: createdAt,+ date: createdAt.slice(0, 10),+ slug: topic,+ });+}++function finding() {+ return runDoctor(vault, { now: NOW }).warnings.find((w) => w.code === CODE);+}++describe("inbox-archivable", () => {+ test("reports the inbox size and the archivable count", () => {+ sig("fresh", "2026-06-25T10:00:00Z");+ sig("old-one", "2026-05-01T10:00:00Z");+ sig("old-two", "2026-05-02T10:00:00Z");+ const w = finding();+ expect(w).toBeDefined();+ expect(w!.message).toContain("3 signal");+ expect(w!.message).toContain("2 of them");+ expect(DIAGNOSTIC_SIGNALS.get(CODE)?.nextCommand).toBe("o2b brain dream");+ });++ test("is silent when every inbox signal is inside the window", () => {+ sig("fresh", "2026-06-25T10:00:00Z");+ expect(finding()).toBeUndefined();+ });++ test("is silent after the dream pass archived them", () => {+ sig("old-one", "2026-05-01T10:00:00Z");+ expect(finding()).toBeDefined();+ dream(vault, { now: NOW });+ expect(finding()).toBeUndefined();+ });++ test("is silent when the archive is switched off", () => {+ sig("old-one", "2026-05-01T10:00:00Z");+ const path = brainConfigPath(vault);+ atomicWriteFileSync(+ path,+ readFileSync(path, "utf8").replace(+ /^ {2}contradiction_window_days: 14$/m,+ " contradiction_window_days: 14\n archive_stale_signals: false",+ ),+ );+ expect(finding()).toBeUndefined();+ });+});diff --git a/tests/core/brain/dream-checkpoints.test.ts b/tests/core/brain/dream-checkpoints.test.tsindex 1d9c2ee4..57e6d591 100644--- a/tests/core/brain/dream-checkpoints.test.ts+++ b/tests/core/brain/dream-checkpoints.test.ts@@ -352,6 +352,7 @@ describe("the mutation stage does not absorb a safeguard stop", () => {signalsSuppressed: [],quarantined: [],topicKeyContentions: [],+ signalsToArchive: new Map(),};}diff --git a/tests/core/brain/dream-phase-refusal.test.ts b/tests/core/brain/dream-phase-refusal.test.tsindex 027553d9..23bf3bc2 100644--- a/tests/core/brain/dream-phase-refusal.test.ts+++ b/tests/core/brain/dream-phase-refusal.test.ts@@ -188,6 +188,7 @@ describe("runDreamStep performs exactly the step requested", () => {partial: true,active_signals: 3,processed_signals: 0,+ archived_signals: 0,preferences: 0,retired: 0,corrupted: [],diff --git a/tests/core/brain/dream-stage-archive-drift.test.ts b/tests/core/brain/dream-stage-archive-drift.test.tsnew file mode 100644index 00000000..6a777e08--- /dev/null+++ b/tests/core/brain/dream-stage-archive-drift.test.ts@@ -0,0 +1,89 @@+/**+ * Staged dream bundles and the inbox archive (issue #195).+ *+ * The archive step is housekeeping driven by the clock: a signal staged+ * inside the contradiction window can cross its edge before the bundle is+ * validated or applied. That must not read as drift, or every bundle staged+ * a day earlier would be refused. The comparison of every other key stays+ * strict, and it runs over the keys of both plans, not only the recomputed+ * one.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ applyDreamBundle,+ stageDream,+ validateDreamBundle,+} from "../../../src/core/brain/dream-stage.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const STAGED_AT = new Date("2026-06-05T12:00:00Z");+// Two days later: a signal created 13 days before STAGED_AT has left the+// 14-day window by then.+const APPLIED_AT = new Date("2026-06-07T12:00:00Z");++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-dream-stage-archive-"));+ vault = join(tmp, "vault");+ const configPath = join(tmp, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function edgeSignal(): string {+ return writeSignal(vault, {+ topic: "edge-topic",+ signal: "positive",+ agent: "claude",+ principle: "Rule for edge-topic.",+ created_at: "2026-05-23T12:00:00Z",+ date: "2026-05-23",+ slug: "edge-topic",+ }).id;+}++describe("staged bundle and the archive step", () => {+ test("a signal that crossed the window edge after staging is not drift", () => {+ const id = edgeSignal();+ const bundle = stageDream(vault, { now: STAGED_AT });+ expect(bundle.plan.archived_signals).toBeUndefined();++ const validation = validateDreamBundle(vault, bundle.runId, { now: APPLIED_AT });+ expect(validation.drift).toEqual([]);+ expect(validation.valid).toBe(true);++ const outcome = applyDreamBundle(vault, bundle.runId, { now: APPLIED_AT });+ expect(outcome.applied).toBe(true);+ expect(existsSync(join(brainDirs(vault).archived, `${id}.md`))).toBe(true);+ });++ test("a key only the staged plan carries is reported as drift", () => {+ edgeSignal();+ const bundle = stageDream(vault, { now: STAGED_AT });+ const manifestPath = join(bundle.dir, "manifest.json");+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as Record<string, unknown>;+ const plan = manifest["plan"] as Record<string, unknown>;+ atomicWriteFileSync(+ manifestPath,+ JSON.stringify({ ...manifest, plan: { ...plan, stale_key: ["x"] } }, null, 2) + "\n",+ );++ const validation = validateDreamBundle(vault, bundle.runId, { now: STAGED_AT });+ expect(validation.valid).toBe(false);+ expect(validation.drift.some((d) => d.startsWith("stale_key:"))).toBe(true);+ });+});diff --git a/tests/core/brain/ingest/concurrent-shared-writes.test.ts b/tests/core/brain/ingest/concurrent-shared-writes.test.tsindex d99e6d24..846ba5fe 100644--- a/tests/core/brain/ingest/concurrent-shared-writes.test.ts+++ b/tests/core/brain/ingest/concurrent-shared-writes.test.ts@@ -66,35 +66,21 @@ function srcModule(rel: string): string {const BARRIER_LEAD_MS = 1_500;/**- * How many named refusals one write absorbs before the child fails. Each- * refusal already waited out the whole `LOCK_WAIT_BUDGET_MS`, so this bounds- * a lock that never frees, not the pace of the race.- */-const MAX_REFUSALS = 5;--/**- * Preamble every child script starts with: parse argv, spin until the- * shared start instant so all four enter the critical section together, and- * define `retryRefused`.+ * Preamble every child script starts with: parse argv, then spin until the+ * shared start instant so all four enter the critical section together.*- * `retryRefused` re-runs a write the lock REFUSED (`ELOCKED`, after the- * waiter spent its budget). A refusal writes nothing and says so, which is- * the lock working - not the lost update these tests hunt. The lock is not- * fair, so how often a waiter loses every draw for a whole budget depends on- * the runner: the Windows job lost one after ~10 s of a four-process- * checkpoint race, and the test failed on an update that was refused, not- * lost. Only `ELOCKED` is retried, so a writer that skipped the lock would- * still lose updates and still fail the tallies below.+ * There is deliberately no retry around the writes. A refusal (`ELOCKED`+ * after a whole wait budget) on this healthy race fails the test, because it+ * is the starvation issue #198 fixed: before the hand-over, a writer in a+ * loop re-acquired the lock the instant it released it, and the Windows job+ * refused a checkpoint write after five seconds of losing every draw.+ * Measured on the checkpoint race with an 80 ms hold (the Windows runner's+ * pace), the longest wait fell from 5 017 ms, with refusals, to 753 ms over+ * 500 acquisitions, against a 5 000 ms budget.*/const BARRIER_PREAMBLE: ReadonlyArray<string> = Object.freeze(["const [vault, tag, count, startAt] = process.argv.slice(2);","while (Date.now() < Number(startAt)) Bun.sleepSync(1);",- "const retryRefused = (write) => {",- " for (let attempt = 1; ; attempt += 1) {",- " try { return write(); }",- ` catch (e) { if (e?.code !== "ELOCKED" || attempt >= ${MAX_REFUSALS}) throw e; }`,- " }",- "};",]);/** Write a child script and run `WRITERS` copies of it concurrently. */@@ -147,7 +133,7 @@ describe("updateManifest β concurrent writers", () => {await runWriters("manifest-writer.ts", [`import { updateManifest } from ${JSON.stringify(srcModule("core/brain/ingest/content-manifest.ts"))};`,"for (let i = 0; i < Number(count); i++) {",- " retryRefused(() => updateManifest(vault, [`sources/${tag}-${i}.md`]));",+ " updateManifest(vault, [`sources/${tag}-${i}.md`]);","}",]);@@ -181,7 +167,7 @@ describe("recordCompleted β concurrent writers", () => {await runWriters("checkpoint-writer.ts", [`import { recordCompleted } from ${JSON.stringify(srcModule("core/brain/ingest/checkpoint.ts"))};`,"for (let i = 0; i < Number(count); i++) {",- ` retryRefused(() => recordCompleted(vault, ${JSON.stringify(PLAN_ID)}, "sources", [\`sources/\${tag}-\${i}.md\`], new Date()));`,+ ` recordCompleted(vault, ${JSON.stringify(PLAN_ID)}, "sources", [\`sources/\${tag}-\${i}.md\`], new Date());`,"}",]);@@ -230,12 +216,12 @@ describe("appendGitRecords β concurrent writers", () => {`import { appendGitRecords } from ${JSON.stringify(srcModule("core/brain/git/store.ts"))};`,`const shaFor = (t, i) => \`\${t}\${i}\`.padEnd(40, "0").slice(0, 40).replace(/[^0-9a-f]/g, "a");`,"for (let i = 0; i < Number(count); i++) {",- ` retryRefused(() => appendGitRecords(vault, ${JSON.stringify(REPO_KEY)}, [`,+ ` appendGitRecords(vault, ${JSON.stringify(REPO_KEY)}, [`," { kind: 'commit', sha: shaFor(tag, i), authorName: tag, authorEmail: '[email protected]',"," committedAt: '2026-02-02T00:00:00Z', subject: `c ${i}`, body: '', files: [], release: null },",` { kind: 'commit', sha: ${JSON.stringify(SHARED_SHA)}, authorName: 'shared', authorEmail: '[email protected]',`," committedAt: '2026-02-02T00:00:00Z', subject: 'shared', body: '', files: [], release: null },",- " ]));",+ " ]);","}",]);diff --git a/tests/core/brain/signal-archive-edges.test.ts b/tests/core/brain/signal-archive-edges.test.tsnew file mode 100644index 00000000..808923dc--- /dev/null+++ b/tests/core/brain/signal-archive-edges.test.ts@@ -0,0 +1,150 @@+/**+ * Inbox archive edges (issue #195): the files the archive step leaves in+ * the inbox on purpose, the archive names it cannot take, and the clock it+ * runs against.+ *+ * The doctor's `inbox-archivable` count is the dream pass's own selection,+ * so the warning clears once a pass has run whatever else the inbox holds.+ * A name already present in `inbox/archived/` - whether that file parses or+ * not - is a collision the plan reports instead of planning a move the apply+ * step would then refuse. And a pass run with `--now` in the future archives+ * nothing that is still inside the window at the real time.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runDoctor } from "../../../src/core/brain/doctor.ts";+import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { ARCHIVE_NAME_COLLISION_CODE } from "../../../src/core/brain/signal-archive.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const NOW = new Date("2026-06-30T12:00:00Z");+const STALE = "2026-05-01T10:00:00Z";+const CODE = "inbox-archivable";+const DAY_MS = 24 * 60 * 60 * 1000;++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-archive-edges-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function sig(topic: string, createdAt: string): { id: string; path: string } {+ return writeSignal(vault, {+ topic,+ signal: "positive",+ agent: "claude",+ principle: `Principle for ${topic}`,+ created_at: createdAt,+ date: createdAt.slice(0, 10),+ slug: topic,+ });+}++function tombstoned(text: string): string {+ return text.replace(/^---\n/, "---\n_status: tombstoned\n");+}++/** Inbox signals the pass must leave alone, each for a different reason. */+function seedLeftovers(): { tombstonedPath: string; corruptPath: string; collidingPath: string } {+ const dirs = brainDirs(vault);+ const tomb = sig("tombstoned-old", STALE);+ atomicWriteFileSync(tomb.path, tombstoned(readFileSync(tomb.path, "utf8")));+ const corruptPath = join(dirs.inbox, "sig-2026-05-01-corrupt-old.md");+ atomicWriteFileSync(corruptPath, `---\ncreated_at: ${STALE}\ntopic: corrupt-old\n---\n`);+ const colliding = sig("colliding-old", STALE);+ mkdirSync(dirs.archived, { recursive: true });+ atomicWriteFileSync(+ join(dirs.archived, `${colliding.id}.md`),+ tombstoned(readFileSync(colliding.path, "utf8")),+ );+ return { tombstonedPath: tomb.path, corruptPath, collidingPath: colliding.path };+}++function finding(now: Date = NOW) {+ return runDoctor(vault, { now }).warnings.find((w) => w.code === CODE);+}++describe("inbox-archivable counts what the pass archives", () => {+ test("the count equals the dry-run archive set", () => {+ seedLeftovers();+ sig("plain-old", STALE);+ const planned = dream(vault, { now: NOW, dryRun: true }).archived_signals ?? [];+ expect(planned.length).toBe(1);+ const w = finding();+ expect(w).toBeDefined();+ expect(w!.message).toContain("1 of them");+ });++ test("clears after a pass although tombstoned, corrupt and colliding files remain", () => {+ const left = seedLeftovers();+ sig("plain-old", STALE);+ dream(vault, { now: NOW });+ expect(existsSync(left.tombstonedPath)).toBe(true);+ expect(existsSync(left.corruptPath)).toBe(true);+ expect(existsSync(left.collidingPath)).toBe(true);+ expect(finding()).toBeUndefined();+ });+});++describe("archive name collisions", () => {+ test("a tombstoned archive file of the same name is a collision, not a planned move", () => {+ const colliding = sig("colliding-old", STALE);+ const dirs = brainDirs(vault);+ mkdirSync(dirs.archived, { recursive: true });+ atomicWriteFileSync(+ join(dirs.archived, `${colliding.id}.md`),+ tombstoned(readFileSync(colliding.path, "utf8")),+ );++ const summary = dream(vault, { now: NOW });+ expect(summary.archived_signals ?? []).toEqual([]);+ expect(summary.changed).toBe(false);+ expect(summary.warnings.some((w) => w.code === ARCHIVE_NAME_COLLISION_CODE)).toBe(true);+ expect(existsSync(colliding.path)).toBe(true);+ });++ test("an unparseable archive file of the same name is a collision too", () => {+ const colliding = sig("colliding-old", STALE);+ const dirs = brainDirs(vault);+ mkdirSync(dirs.archived, { recursive: true });+ atomicWriteFileSync(join(dirs.archived, `${colliding.id}.md`), "---\ntopic: broken\n---\n");++ const summary = dream(vault, { now: NOW, dryRun: true });+ expect(summary.archived_signals ?? []).toEqual([]);+ expect(summary.warnings.some((w) => w.code === ARCHIVE_NAME_COLLISION_CODE)).toBe(true);+ });+});++describe("a future --now does not archive against a clock that has not come", () => {+ test("a signal inside the window at the real time stays in the inbox", () => {+ const createdAt = new Date(Date.now() - DAY_MS).toISOString();+ const recent = sig("recent", createdAt);+ const future = new Date(Date.now() + 60 * DAY_MS);++ const summary = dream(vault, { now: future });+ expect(summary.archived_signals ?? []).toEqual([]);+ expect(existsSync(recent.path)).toBe(true);+ expect(finding(future)).toBeUndefined();+ });++ test("a signal outside the window at the real time is still archived", () => {+ const createdAt = new Date(Date.now() - 60 * DAY_MS).toISOString();+ const old = sig("old", createdAt);+ const future = new Date(Date.now() + 60 * DAY_MS);++ const summary = dream(vault, { now: future });+ expect(summary.archived_signals ?? []).toEqual([old.id]);+ });+});diff --git a/tests/core/brain/signal-archive.test.ts b/tests/core/brain/signal-archive.test.tsnew file mode 100644index 00000000..075cd683--- /dev/null+++ b/tests/core/brain/signal-archive.test.ts@@ -0,0 +1,287 @@+/**+ * Inbox archive policy (issue #195).+ *+ * A signal in `Brain/inbox/` whose `created_at` lies outside+ * `dream.contradiction_window_days` can never contribute to a candidate+ * again: every counting path in the dream pass filters through+ * `filterWithinWindow`, and time only moves forward. The pass moves such+ * signals into `Brain/inbox/archived/` instead of leaving them in the inbox+ * for ever. These tests pin the rule's boundaries, the run's idempotency and+ * dry-run preview, and - the property the issue insists on - that archiving+ * changes no promotion outcome for signals still inside the window.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainConfigPath, brainDirs, logPath } from "../../../src/core/brain/paths.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const NOW_1 = new Date("2026-06-30T12:00:00Z");+const NOW_2 = new Date("2026-07-03T12:00:00Z");++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-signal-archive-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function newVault(name: string, opts: { archive?: boolean } = {}): string {+ const vault = join(tmp, name);+ const configPath = join(tmp, `${name}.yaml`);+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+ const path = brainConfigPath(vault);+ let yaml = readFileSync(path, "utf8").replace(+ /^ {2}candidate_threshold: \d+$/m,+ " candidate_threshold: 2",+ );+ if (opts.archive === false) {+ yaml = yaml.replace(+ /^ {2}contradiction_window_days: 14$/m,+ " contradiction_window_days: 14\n archive_stale_signals: false",+ );+ }+ atomicWriteFileSync(path, yaml);+ return vault;+}++function sig(+ vault: string,+ topic: string,+ sign: "positive" | "negative",+ createdAt: string,+ extra: { slug?: string; expiration_date?: string } = {},+): string {+ return writeSignal(vault, {+ topic,+ signal: sign,+ agent: "claude",+ principle: `Principle for ${topic}`,+ created_at: createdAt,+ date: createdAt.slice(0, 10),+ slug: extra.slug ?? topic,+ ...(extra.expiration_date ? { expiration_date: extra.expiration_date } : {}),+ }).id;+}++function confirmedPref(vault: string, slug: string, evidencedBy: ReadonlyArray<string>): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `Rule of record for ${slug}.`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-15T00:00:00Z",+ confirmed_at: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: evidencedBy.map((id) => `[[${id}]]`),+ applied_count: 2,+ violated_count: 0,+ last_evidence_at: "2026-06-25T00:00:00Z",+ confidence: "medium",+ });+}++function names(dir: string): string[] {+ if (!existsSync(dir)) return [];+ return readdirSync(dir)+ .filter((n) => n.endsWith(".md"))+ .toSorted();+}++function contents(dir: string): Record<string, string> {+ const out: Record<string, string> = {};+ for (const n of names(dir)) out[n] = readFileSync(join(dir, n), "utf8");+ return out;+}++/** The fixture every test starts from; returns the ids by role. */+function seed(vault: string) {+ const ids = {+ insideSingleton: sig(vault, "inside-singleton", "positive", "2026-06-25T10:00:00Z"),+ outsideSingleton: sig(vault, "outside-singleton", "positive", "2026-06-01T10:00:00Z"),+ // The window's lower bound is inclusive: exactly `now - 14d` still counts.+ edgeIn: sig(vault, "edge-in", "positive", "2026-06-16T12:00:00Z"),+ edgeOut: sig(vault, "edge-out", "positive", "2026-06-16T11:59:59Z"),+ promotedA: sig(vault, "promoted-topic", "positive", "2026-06-20T10:00:00Z", {+ slug: "promoted-topic-a",+ }),+ promotedB: sig(vault, "promoted-topic", "positive", "2026-06-22T10:00:00Z", {+ slug: "promoted-topic-b",+ }),+ promotedStale: sig(vault, "promoted-topic", "positive", "2026-05-20T10:00:00Z", {+ slug: "promoted-topic-stale",+ }),+ redundantIn: sig(vault, "redundant-topic", "positive", "2026-06-26T10:00:00Z"),+ redundantOut: sig(vault, "redundant-topic", "positive", "2026-05-26T10:00:00Z", {+ slug: "redundant-topic-old",+ }),+ // A preference whose only evidence link resolves to an old inbox signal:+ // the pass derives the rule's sign from it, archived or not.+ signEvidence: sig(vault, "sign-topic", "negative", "2026-05-10T10:00:00Z"),+ // A preference with no evidence links: the pass falls back to the+ // topic's other signals for its sign. Three old positives made it a+ // negative rule while they sat in the inbox; archived, they must still.+ fallbackOld1: sig(vault, "fallback-topic", "positive", "2026-05-02T10:00:00Z", {+ slug: "fallback-topic-1",+ }),+ fallbackOld2: sig(vault, "fallback-topic", "positive", "2026-05-03T10:00:00Z", {+ slug: "fallback-topic-2",+ }),+ fallbackOld3: sig(vault, "fallback-topic", "positive", "2026-05-04T10:00:00Z", {+ slug: "fallback-topic-3",+ }),+ expiredInWindow: sig(vault, "expired-in-window", "positive", "2026-06-18T10:00:00Z", {+ expiration_date: "2026-06-19",+ }),+ };+ confirmedPref(vault, "redundant-topic", [ids.redundantIn]);+ confirmedPref(vault, "sign-topic", [ids.signEvidence]);+ confirmedPref(vault, "fallback-topic", []);+ return ids;+}++describe("dream archives inbox signals that can no longer become candidates", () => {+ test("rule boundaries: inside, outside, edge, promoted, redundant", () => {+ const vault = newVault("v");+ const ids = seed(vault);+ const dirs = brainDirs(vault);++ const summary = dream(vault, { now: NOW_1 });++ const archivedExpected = [+ ids.fallbackOld1,+ ids.fallbackOld2,+ ids.fallbackOld3,+ ids.outsideSingleton,+ ids.edgeOut,+ ids.promotedStale,+ ids.redundantOut,+ ids.signEvidence,+ ].toSorted();+ expect([...(summary.archived_signals ?? [])].toSorted()).toEqual(archivedExpected);+ expect(names(dirs.archived)).toEqual(archivedExpected.map((id) => `${id}.md`));+ // Still able to contribute: stays in the inbox.+ expect(names(dirs.inbox)).toEqual(+ [ids.insideSingleton, ids.edgeIn, ids.expiredInWindow].toSorted().map((id) => `${id}.md`),+ );+ // Promoted and redundant signals go to processed/, never to the archive.+ expect(names(dirs.processed)).toEqual(+ [ids.promotedA, ids.promotedB, ids.redundantIn].toSorted().map((id) => `${id}.md`),+ );+ // The run's audit trail names every archived signal.+ const log = readFileSync(logPath(vault, "2026-06-30"), "utf8");+ for (const id of archivedExpected) expect(log).toContain(id);+ expect(log).toContain("archived_signals");+ });++ test("archiving moves the file byte for byte", () => {+ const vault = newVault("v");+ const ids = seed(vault);+ const dirs = brainDirs(vault);+ const before = readFileSync(join(dirs.inbox, `${ids.outsideSingleton}.md`), "utf8");+ dream(vault, { now: NOW_1 });+ expect(readFileSync(join(dirs.archived, `${ids.outsideSingleton}.md`), "utf8")).toBe(before);+ });++ test("a second pass archives nothing and changes nothing", () => {+ const vault = newVault("v");+ seed(vault);+ dream(vault, { now: NOW_1 });+ const archivedBefore = contents(brainDirs(vault).archived);+ const second = dream(vault, { now: NOW_1 });+ expect(second.changed).toBe(false);+ expect(second.archived_signals ?? []).toEqual([]);+ expect(contents(brainDirs(vault).archived)).toEqual(archivedBefore);+ });++ test("dry run reports the archivable count and touches nothing", () => {+ const vault = newVault("v");+ const ids = seed(vault);+ const dirs = brainDirs(vault);+ const inboxBefore = names(dirs.inbox);+ const preview = dream(vault, { now: NOW_1, dryRun: true });+ expect([...(preview.archived_signals ?? [])].toSorted()).toContain(ids.outsideSingleton);+ expect(preview.archived_signals?.length).toBe(8);+ expect(names(dirs.inbox)).toEqual(inboxBefore);+ expect(names(dirs.archived)).toEqual([]);+ });++ test("a pass whose only work is archiving still runs and logs", () => {+ const vault = newVault("v");+ const id = sig(vault, "lonely", "positive", "2026-05-01T10:00:00Z");+ const summary = dream(vault, { now: NOW_1 });+ expect(summary.changed).toBe(true);+ expect(summary.archived_signals).toEqual([id]);+ });++ test("an existing file in the archive is never overwritten", () => {+ const vault = newVault("v");+ const id = sig(vault, "clash", "positive", "2026-05-01T10:00:00Z");+ const dirs = brainDirs(vault);+ atomicWriteFileSync(join(dirs.archived, `${id}.md`), "operator copy\n");+ const summary = dream(vault, { now: NOW_1 });+ expect(summary.archived_signals ?? []).toEqual([]);+ expect(readFileSync(join(dirs.archived, `${id}.md`), "utf8")).toBe("operator copy\n");+ expect(names(dirs.inbox)).toEqual([`${id}.md`]);+ });++ test("archive_stale_signals: false keeps the historical behaviour", () => {+ const vault = newVault("v", { archive: false });+ seed(vault);+ const summary = dream(vault, { now: NOW_1 });+ expect(summary.archived_signals ?? []).toEqual([]);+ expect(names(brainDirs(vault).archived)).toEqual([]);+ });+});++describe("archiving changes no promotion outcome", () => {+ test("two passes produce the same preferences with and without the archive", () => {+ const archiving = newVault("archiving");+ const keeping = newVault("keeping", { archive: false });++ for (const vault of [archiving, keeping]) {+ seed(vault);+ dream(vault, { now: NOW_1 });+ // Between the passes: a restatement of an archived singleton's topic,+ // two signals agreeing with the sign-evidenced rule, and a fresh+ // cluster that promotes.+ sig(vault, "outside-singleton", "positive", "2026-07-02T10:00:00Z", {+ slug: "outside-singleton-again",+ });+ sig(vault, "sign-topic", "negative", "2026-07-02T10:00:00Z", { slug: "sign-topic-a" });+ sig(vault, "sign-topic", "negative", "2026-07-02T11:00:00Z", { slug: "sign-topic-b" });+ sig(vault, "fallback-topic", "negative", "2026-07-02T10:00:00Z", {+ slug: "fallback-topic-a",+ });+ sig(vault, "fallback-topic", "negative", "2026-07-02T11:00:00Z", {+ slug: "fallback-topic-b",+ });+ sig(vault, "fresh-topic", "positive", "2026-07-01T10:00:00Z", { slug: "fresh-topic-a" });+ sig(vault, "fresh-topic", "positive", "2026-07-02T10:00:00Z", { slug: "fresh-topic-b" });+ dream(vault, { now: NOW_2 });+ }++ const a = brainDirs(archiving);+ const k = brainDirs(keeping);+ expect(contents(a.preferences)).toEqual(contents(k.preferences));+ expect(contents(a.retired)).toEqual(contents(k.retired));+ expect(contents(a.processed)).toEqual(contents(k.processed));+ // Both rules kept their sign: the agreeing pairs were noted redundant+ // rather than read as rebuttals.+ expect(names(a.retired)).toEqual([]);+ // The union of inbox and archive is the historical inbox.+ expect([...names(a.inbox), ...names(a.archived)].toSorted()).toEqual(names(k.inbox));+ expect(names(a.archived).length).toBeGreaterThan(0);+ });+});diff --git a/tests/core/brain/snapshot-atomic-publish.test.ts b/tests/core/brain/snapshot-atomic-publish.test.tsnew file mode 100644index 00000000..4ca57d01--- /dev/null+++ b/tests/core/brain/snapshot-atomic-publish.test.ts@@ -0,0 +1,181 @@+/**+ * A snapshot archive appears under its final name only once it is complete.+ *+ * The zstd path used to hand `zstd -o` the final `<run_id>.tar.zst`, so a+ * process killed during compression left a truncated archive under the+ * name a listing, the retention pass and a rollback treat as a recovery+ * point, with no manifest beside it. The compressor now writes a partial+ * name in `.snapshots/` and the archive is published by an exclusive+ * link (or a checked rename) once the compressor has exited cleanly, and+ * the manifest follows the published archive.+ *+ * The compressor here is a stand-in `zstd` shell script, so the tests run+ * on POSIX hosts only.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ symlinkSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { manifestSidecarPath } from "../../../src/core/brain/manifest.ts";+import { snapshotPath, snapshotsDir } from "../../../src/core/brain/paths.ts";+import { createSnapshot, listSnapshots, pruneSnapshots } from "../../../src/core/brain/snapshot.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++const RUN_ID = "upgrade-atomic-publish";++let root: string;+let vault: string;+let bin: string;+let originalPath: string | undefined;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-snap-atomic-"));+ vault = join(root, "vault");+ mkdirSync(vault);+ const configPath = join(root, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ bin = join(root, "bin");+ mkdirSync(bin);+ const tar = Bun.which("tar");+ if (tar === null) throw new Error("test prerequisite missing from this machine: tar");+ symlinkSync(tar, join(bin, "tar"));+ originalPath = process.env["PATH"];+});++afterEach(() => {+ process.env["PATH"] = originalPath;+ rmSync(root, { recursive: true, force: true });+});++/**+ * Install a stand-in `zstd` whose body runs with `$out` set to the path it+ * was told to write (`-o <path>`). It records that path in `zstd-target`.+ */+function fakeZstd(body: string): void {+ const script = [+ "#!/bin/sh",+ 'out=""',+ 'while [ "$#" -gt 0 ]; do',+ ' if [ "$1" = "-o" ]; then out="$2"; shift; fi',+ " shift",+ "done",+ `printf '%s' "$out" > '${join(root, "zstd-target")}'`,+ body,+ "",+ ].join("\n");+ const path = join(bin, "zstd");+ writeFileSync(path, script);+ chmodSync(path, 0o755);+}++function snapshotEntries(): string[] {+ return readdirSync(snapshotsDir(vault)).toSorted();+}++describe.skipIf(process.platform === "win32")("publishing a zstd snapshot", () => {+ test("the compressor never writes the final archive name", () => {+ const final = snapshotPath(vault, RUN_ID);+ // The stand-in fails loudly if the final name already exists while it+ // runs, which is the window a kill used to leave a torn archive in.+ fakeZstd(`[ -e '${final}' ] && exit 9\nprintf 'archive-bytes' > "$out"`);+ process.env["PATH"] = bin;++ const snap = createSnapshot(vault, RUN_ID, { reason: BRAIN_SNAPSHOT_REASON.upgrade });++ const target = readFileSync(join(root, "zstd-target"), "utf8");+ expect(target).not.toBe(final);+ expect(target.startsWith(snapshotsDir(vault))).toBe(true);+ expect(snap.path).toBe(final);+ expect(readFileSync(final, "utf8")).toBe("archive-bytes");+ expect(existsSync(target)).toBe(false);+ expect(existsSync(manifestSidecarPath(vault, RUN_ID))).toBe(true);+ expect(snapshotEntries()).toEqual([`${RUN_ID}.manifest.json`, `${RUN_ID}.tar.zst`]);+ });++ test("a failed compressor leaves neither the archive nor its partial file", () => {+ fakeZstd(`printf 'torn' > "$out"\nexit 3`);+ process.env["PATH"] = bin;++ expect(() => createSnapshot(vault, RUN_ID, { reason: BRAIN_SNAPSHOT_REASON.upgrade })).toThrow(+ /zstd exited with status 3/,+ );++ expect(snapshotEntries()).toEqual([]);+ });++ test("a process killed during compression leaves no recovery point behind", () => {+ // The stand-in writes half an archive and then kills the process that+ // is taking the snapshot, the way an operator's kill or a host timeout+ // would, before the compressor could finish.+ fakeZstd(`printf 'torn' > "$out"\nkill -9 "$PPID"\nsleep 5`);+ const runner = join(root, "run-snapshot.ts");+ writeFileSync(+ runner,+ [+ `import { createSnapshot } from ${JSON.stringify(join(import.meta.dir, "../../../src/core/brain/snapshot.ts"))};`,+ `createSnapshot(${JSON.stringify(vault)}, ${JSON.stringify(RUN_ID)}, { reason: "upgrade" });`,+ "",+ ].join("\n"),+ );++ // The killed child cannot clean its own temp directories, so they go+ // under this test's root rather than the shared temp directory.+ const childTmp = join(root, "tmp");+ mkdirSync(childTmp);+ const child = Bun.spawnSync([process.execPath, runner], {+ env: { ...process.env, PATH: bin, TMPDIR: childTmp, TMP: childTmp, TEMP: childTmp },+ stdout: "ignore",+ stderr: "pipe",+ });++ expect(child.signalCode).toBe("SIGKILL");+ expect(existsSync(snapshotPath(vault, RUN_ID))).toBe(false);+ expect(listSnapshots(vault).snapshots).toEqual([]);+ });++ test("an archive already under the final name is refused and kept", () => {+ const final = snapshotPath(vault, RUN_ID);+ mkdirSync(snapshotsDir(vault), { recursive: true });+ writeFileSync(final, "someone-else");+ fakeZstd(`printf 'mine' > "$out"`);+ process.env["PATH"] = bin;++ expect(() => createSnapshot(vault, RUN_ID, { reason: BRAIN_SNAPSHOT_REASON.upgrade })).toThrow(+ /refusing to overwrite an existing archive/,+ );++ expect(readFileSync(final, "utf8")).toBe("someone-else");+ expect(snapshotEntries()).toEqual([`${RUN_ID}.tar.zst`]);+ });++ test("retention removes a partial a killed snapshot left behind, once it is stale", () => {+ mkdirSync(snapshotsDir(vault), { recursive: true });+ const stale = join(snapshotsDir(vault), `${RUN_ID}.tar.zst.partial-4242-0a0b0c0d`);+ const fresh = join(snapshotsDir(vault), "upgrade-live.tar.zst.partial-4343-01020304");+ writeFileSync(stale, "torn");+ writeFileSync(fresh, "still being written");+ const twoDaysAgo = Date.now() / 1000 - 2 * 24 * 3600;+ utimesSync(stale, twoDaysAgo, twoDaysAgo);++ pruneSnapshots(vault, 10);++ expect(existsSync(stale)).toBe(false);+ expect(existsSync(fresh)).toBe(true);+ });+});diff --git a/tests/core/brain/snapshot-gate-coverage.test.ts b/tests/core/brain/snapshot-gate-coverage.test.tsindex 0e4d0e5a..1301b15c 100644--- a/tests/core/brain/snapshot-gate-coverage.test.ts+++ b/tests/core/brain/snapshot-gate-coverage.test.ts@@ -249,10 +249,18 @@ describe("the dream pass runs behind the gate, not beside it", () => {// `dreamOutputRows` is what keeps it a guard rather than a coin// flip: `size_bytes` is inside the hashed payload, so without the// mask this digest would differ on every run.+ //+ // Re-measured a FOURTH time, for the inbox archive (issue #195), and+ // for two named reasons only: the fixture's signal is 18 days old at+ // NOW, outside the 14-day contradiction window, so the pass now moves+ // it to `inbox/archived/` and lists it in the dream event; and the+ // bootstrapped `_BRAIN.md` names the new directory. Verified before+ // updating: with `dream.archive_stale_signals: false` and the previous+ // manual template this branch reproduces the previous literal exactly.seedSignal("tidy");dream(vault, { now: NOW, agentName: "tester" });expect(dreamOutputDigest(join(vault, "Brain"))).toBe(- "595e933323e01c1d2d9c15b5c1b8e1bcede298740cf9ef543c8fdc8845048bc0",+ "cc900f3916b844d2fb04f8156b04a5e0ee6f70115035f790580742e036477f61",);});diff --git a/tests/core/brain/snapshot-streaming.test.ts b/tests/core/brain/snapshot-streaming.test.tsnew file mode 100644index 00000000..8d5b5224--- /dev/null+++ b/tests/core/brain/snapshot-streaming.test.ts@@ -0,0 +1,147 @@+/**+ * A snapshot never holds the whole tar stream in memory.+ *+ * `createSnapshot` used to capture tar's stdout through `spawnSync` with a+ * 256 MB `maxBuffer`, so a `Brain/` tree whose archive crossed that size+ * failed with `ENOBUFS` after tar had already done all of its work - and a+ * self-heal upgrade that needed that snapshot failed the same way on every+ * start. The producer now writes to a file descriptor and the compressor+ * reads the file, so no buffer cap applies to the archive path.+ *+ * The producer here is a stand-in `tar` that writes 300 MB of zero bytes,+ * which is a valid (empty) tar stream: it is larger than the old cap and+ * costs no disk in the fixture tree.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ chmodSync,+ closeSync,+ createReadStream,+ existsSync,+ mkdirSync,+ mkdtempSync,+ openSync,+ readFileSync,+ readSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { randomBytes } from "node:crypto";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createGunzip } from "node:zlib";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { createSnapshot, extractSnapshotToTemp } from "../../../src/core/brain/snapshot.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++/** Above the 256 MB buffer the archive path used to be capped at. */+const PRODUCED_BYTES = 300 * 1024 * 1024;++let root: string;+let vault: string;+let originalPath: string | undefined;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-snap-stream-"));+ vault = join(root, "vault");+ mkdirSync(vault);+ const configPath = join(root, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ originalPath = process.env["PATH"];+});++afterEach(() => {+ process.env["PATH"] = originalPath;+ rmSync(root, { recursive: true, force: true });+});++/** A PATH directory whose `tar` writes `bytes` zero bytes to stdout and exits 0. */+function oversizedTarPath(bytes: number): string {+ const bin = join(root, "bin");+ mkdirSync(bin);+ const tar = join(bin, "tar");+ writeFileSync(tar, `#!/bin/sh\nexec head -c ${bytes} /dev/zero\n`);+ chmodSync(tar, 0o755);+ // `head` itself, for a PATH that holds nothing else.+ const head = Bun.which("head");+ if (head === null) throw new Error("test prerequisite missing from this machine: head");+ symlinkSync(head, join(bin, "head"));+ return bin;+}++/** Decompressed length of a gzip archive, streamed so the test stays small too. */+async function gunzippedLength(archive: string): Promise<number> {+ let total = 0;+ const stream = createReadStream(archive).pipe(createGunzip());+ for await (const chunk of stream) total += (chunk as Buffer).length;+ return total;+}++function magic(archive: string): [number, number] {+ const buf = Buffer.alloc(2);+ const fd = openSync(archive, "r");+ try {+ readSync(fd, buf, 0, 2, 0);+ } finally {+ closeSync(fd);+ }+ return [buf[0]!, buf[1]!];+}++describe("a tar stream larger than the old 256 MB capture buffer", () => {+ // The stand-in producer is a POSIX shell script.+ test.skipIf(process.platform === "win32")(+ "is archived instead of failing with ENOBUFS, and decompresses to every byte",+ async () => {+ // No zstd on this PATH, so the in-process gzip fallback runs: the+ // path that used to hold the whole stream AND a compressed copy.+ process.env["PATH"] = oversizedTarPath(PRODUCED_BYTES);++ const snap = createSnapshot(vault, "upgrade-stream-oversized", {+ reason: BRAIN_SNAPSHOT_REASON.upgrade,+ });++ expect(magic(snap.path)).toEqual([0x1f, 0x8b]);+ expect(statSync(snap.path).size).toBeLessThan(PRODUCED_BYTES / 100);+ expect(await gunzippedLength(snap.path)).toBe(PRODUCED_BYTES);+ },+ 60_000,+ );+});++describe("the gzip fallback on a real tree", () => {+ test("writes a multi-member archive the restore path extracts byte for byte", () => {+ const tarOnly = join(root, "tar-only");+ mkdirSync(tarOnly);+ const tar = Bun.which("tar");+ if (tar === null) throw new Error("test prerequisite missing from this machine: tar");+ if (process.platform === "win32") {+ // `System32\tar.exe` needs only system libraries; see the note in+ // snapshot-derived-store.test.ts about Git for Windows' tar.+ process.env["PATH"] = join(process.env["SystemRoot"] ?? "C:\\Windows", "System32");+ } else {+ symlinkSync(tar, join(tarOnly, "tar"));+ process.env["PATH"] = tarOnly;+ }+ // More than one gzip member's worth of incompressible bytes, so the+ // archive is several members long and a reader must accept that.+ const big = randomBytes(20 * 1024 * 1024);+ writeFileSync(join(vault, "Brain", "log", "big.md"), big);++ createSnapshot(vault, "upgrade-stream-members", { reason: BRAIN_SNAPSHOT_REASON.upgrade });++ const extracted = extractSnapshotToTemp(vault, "upgrade-stream-members");+ try {+ expect(readFileSync(join(extracted.brainRoot, "log", "big.md")).equals(big)).toBe(true);+ expect(existsSync(join(extracted.brainRoot, "_brain.yaml"))).toBe(true);+ } finally {+ extracted.cleanup();+ }+ });+});diff --git a/tests/core/brain/sync-lockfile-fairness.test.ts b/tests/core/brain/sync-lockfile-fairness.test.tsnew file mode 100644index 00000000..fd15988d--- /dev/null+++ b/tests/core/brain/sync-lockfile-fairness.test.ts@@ -0,0 +1,216 @@+/**+ * The waiting lock's fairness, its budget override and what a refusal tells+ * the operator (issue #198).+ *+ * The wait loop used to be unfair in one specific way: a writer that+ * released a lock and came straight back for it re-created the lock file+ * before any sleeping waiter woke, so under a steady stream of writes one+ * waiter could lose every draw for the whole budget and be refused on a+ * perfectly healthy race. A waiter now marks the held lock file, and a+ * holder that releases a marked lock steps back before it re-acquires.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { manifestPath, updateManifest } from "../../../src/core/brain/ingest/content-manifest.ts";+import {+ acquireLockSync,+ acquireLockSyncWithRetry,+ LOCK_WAIT_BUDGET_ENV,+ LOCK_WAIT_BUDGET_MS,+ resolveLockWaitBudgetMs,+} from "../../../src/core/brain/sync-lockfile.ts";++let root: string;+let savedEnv: string | undefined;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-lock-fair-"));+ savedEnv = process.env[LOCK_WAIT_BUDGET_ENV];+ delete process.env[LOCK_WAIT_BUDGET_ENV];+});++afterEach(() => {+ if (savedEnv === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];+ else process.env[LOCK_WAIT_BUDGET_ENV] = savedEnv;+ rmSync(root, { recursive: true, force: true });+});++/** Refusal raised by `fn`, or a failed expectation if it did not throw. */+function refusal(fn: () => unknown): NodeJS.ErrnoException {+ try {+ fn();+ } catch (err) {+ return err as NodeJS.ErrnoException;+ }+ throw new Error("expected a lock refusal, got none");+}++describe("resolveLockWaitBudgetMs β the environment override", () => {+ test("unset or blank means the built-in default", () => {+ expect(resolveLockWaitBudgetMs({})).toBe(LOCK_WAIT_BUDGET_MS);+ expect(resolveLockWaitBudgetMs({ [LOCK_WAIT_BUDGET_ENV]: " " })).toBe(LOCK_WAIT_BUDGET_MS);+ });++ test.each([+ ["20000", 20_000],+ [" 750 ", 750],+ ["0", 0],+ ])("%p is a budget of %p ms", (raw, expected) => {+ expect(resolveLockWaitBudgetMs({ [LOCK_WAIT_BUDGET_ENV]: raw })).toBe(expected);+ });++ test.each(["5s", "-1", "1.5", "NaN", "Infinity", "1e400"])(+ "%p is refused by name rather than replaced with the default",+ (raw) => {+ expect(() => resolveLockWaitBudgetMs({ [LOCK_WAIT_BUDGET_ENV]: raw })).toThrow(+ LOCK_WAIT_BUDGET_ENV,+ );+ },+ );++ test("a caller that passes no budget waits for the override, not the default", () => {+ const target = join(root, "override.json");+ const held = acquireLockSync(target);+ try {+ process.env[LOCK_WAIT_BUDGET_ENV] = "60";+ const started = Date.now();+ const err = refusal(() => acquireLockSyncWithRetry(target));+ expect(err.code).toBe("ELOCKED");+ expect(Date.now() - started).toBeLessThan(LOCK_WAIT_BUDGET_MS / 2);+ } finally {+ held.release();+ }+ });+});++describe("acquireLockSyncWithRetry β a refusal says what to do next", () => {+ test("names the lock, the wait, the retry and the override", () => {+ const target = join(root, "remedy.json");+ const held = acquireLockSync(target);+ try {+ process.env[LOCK_WAIT_BUDGET_ENV] = "40";+ const err = refusal(() => acquireLockSyncWithRetry(target));+ expect(err.code).toBe("ELOCKED");+ expect(err.path).toBe(`${target}.lock`);+ expect(err.message).toContain(`lock busy: ${target}.lock`);+ expect(err.message).toMatch(/after waiting \d+ ms/);+ expect(err.message).toContain("retry");+ expect(err.message).toContain(`${LOCK_WAIT_BUDGET_ENV}`);+ // The original single-attempt collision stays reachable.+ expect((err.cause as NodeJS.ErrnoException).code).toBe("ELOCKED");+ } finally {+ held.release();+ }+ });++ test("an explicit short budget does not point at the override it ignores", () => {+ const target = join(root, "interactive.json");+ const held = acquireLockSync(target);+ try {+ const err = refusal(() => acquireLockSyncWithRetry(target, 30));+ expect(err.message).toContain("retry");+ expect(err.message).not.toContain(LOCK_WAIT_BUDGET_ENV);+ } finally {+ held.release();+ }+ });++ test("a refused ingest write tells the operator to retry, serialize or wait longer", () => {+ const vault = root;+ writeFileSync(join(vault, "source.md"), "body", "utf8");+ const manifestLock = acquireLockSync(manifestPath(vault));+ try {+ process.env[LOCK_WAIT_BUDGET_ENV] = "40";+ const err = refusal(() => updateManifest(vault, ["source.md"]));+ expect(err.code).toBe("ELOCKED");+ expect(err.message).toContain("lock busy");+ expect(err.message).toContain("retry the ingest");+ expect(err.message).toContain("one at a time");+ expect(err.message).toContain(LOCK_WAIT_BUDGET_ENV);+ } finally {+ manifestLock.release();+ }+ });+});++describe("acquireLockSyncWithRetry β a waiter is not starved by a returning holder", () => {+ test("a holder that releases a lock someone waits on hands it over before re-acquiring", async () => {+ const target = join(root, "handoff.json");+ const lockPath = `${target}.lock`;+ const marker = join(root, "waiter-acquired");+ const child = join(root, "waiter.ts");+ writeFileSync(+ child,+ [+ `import { acquireLockSyncWithRetry } from ${JSON.stringify(join(import.meta.dir, "../../../src/core/brain/sync-lockfile.ts"))};`,+ "const [target, marker] = process.argv.slice(2);",+ "const h = acquireLockSyncWithRetry(target, 20000);",+ `require("node:fs").writeFileSync(marker, String(Date.now()));`,+ "Bun.sleepSync(50);",+ "h.release();",+ ].join("\n"),+ "utf8",+ );++ let held = acquireLockSync(target);+ const baseSize = statSync(lockPath).size;+ const proc = Bun.spawn(["bun", child, target, marker], {+ stdout: "pipe",+ stderr: "pipe",+ env: { ...process.env },+ });+ try {+ // Wait until the child has failed at least one draw and marked the lock.+ const until = Date.now() + 20_000;+ while (statSync(lockPath).size <= baseSize) {+ if (Date.now() > until) throw new Error("the waiter never marked the held lock");+ // oxlint-disable-next-line no-await-in-loop -- polling the child's progress, one wait at a time by design+ await Bun.sleep(5);+ }+ // Release and come straight back, as a writer in a loop does. Without+ // the hand-over this re-acquire wins before the sleeping waiter wakes.+ held.release();+ held = acquireLockSyncWithRetry(target);+ expect(existsSync(marker)).toBe(true);+ } finally {+ held.release();+ const code = await proc.exited;+ const err = await new Response(proc.stderr).text();+ expect(`${code} ${err.trim()}`).toBe("0 ");+ }+ }, 60_000);++ test.skipIf(process.platform === "win32")(+ "a waiter's mark never writes through a symlink planted at the lock path",+ () => {+ const victim = join(root, "victim.txt");+ writeFileSync(victim, "unchanged", "utf8");+ const target = join(root, "planted.json");+ symlinkSync(victim, `${target}.lock`);+ const err = refusal(() => acquireLockSyncWithRetry(target, 60));+ expect(err.code).toBe("ELOCKED");+ expect(readFileSync(victim, "utf8")).toBe("unchanged");+ },+ );++ test("an uncontended writer in a loop does not pay the hand-over pause", () => {+ const target = join(root, "loop.json");+ const rounds = 40;+ const started = Date.now();+ for (let i = 0; i < rounds; i++) acquireLockSyncWithRetry(target).release();+ // A pause on every round would cost at least rounds x 50 ms.+ expect(Date.now() - started).toBeLessThan(rounds * 25);+ });+});diff --git a/tests/core/brain/vault-guard-census.test.ts b/tests/core/brain/vault-guard-census.test.tsindex be9f2b3f..f270628e 100644--- a/tests/core/brain/vault-guard-census.test.ts+++ b/tests/core/brain/vault-guard-census.test.ts@@ -62,6 +62,10 @@ const GUARD_RE = /assertVaultIdentityForWrite|brainDirsForWrite/;* be wrong, never because asserting was inconvenient.*/const UNGUARDED_WITH_REASON: Readonly<Record<string, string>> = Object.freeze({+ "src/core/brain/dedup-index-cache.ts":+ "machine-local derived cache OUTSIDE the vault (the user cache dir). It " ++ "writes nothing under Brain/, and a refusal would only cost the next " ++ "capture a full walk, so there is no vault identity to assert.","src/core/brain/init.ts":"bootstrap. This is the path that CREATES the tree and stamps the marker; " +"gating it on the marker it is about to write would refuse `o2b brain init` " +diff --git a/tests/core/brain/vault-name-case.test.ts b/tests/core/brain/vault-name-case.test.tsnew file mode 100644index 00000000..88116527--- /dev/null+++ b/tests/core/brain/vault-name-case.test.ts@@ -0,0 +1,110 @@+/**+ * `vault_name` in `Brain/_BRAIN.md` does not flip between two spellings of+ * the same vault directory.+ *+ * The display name is the basename of the vault path as the caller spelled+ * it. On a case-insensitive filesystem (macOS, Windows) `.../vault` and+ * `.../Vault` open the same directory, so one runtime rendering `vault` and+ * another rendering `Vault` made `o2b brain upgrade` see a pending change+ * that no apply could ever settle - and the self-heal upgrade re-ran it+ * (snapshot included) on every start.+ *+ * A symlink with the other spelling reproduces "two spellings, one+ * directory" on a case-sensitive filesystem too, so these tests run on every+ * host and exercise the real filesystem probe rather than a stub.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ copyFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainManualPath } from "../../../src/core/brain/paths.ts";+import { planUpgrade } from "../../../src/core/brain/upgrade.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let root: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-vault-name-case-"));+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function bootstrap(vault: string): void {+ mkdirSync(vault, { recursive: true });+ const configPath = join(root, `config-${Math.random().toString(36).slice(2)}.yaml`);+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+}++function manualPlan(vault: string) {+ return planUpgrade(vault).files.find((f) => f.path === "Brain/_BRAIN.md")!;+}++/** Whether `root` itself treats `Vault` and `vault` as one name. */+function rootIsCaseInsensitive(): boolean {+ mkdirSync(join(root, "Probe"));+ const insensitive = existsSync(join(root, "probe"));+ rmSync(join(root, "Probe"), { recursive: true });+ return insensitive;+}++describe("vault_name under two spellings of one vault directory", () => {+ test("a manual rendered under the other spelling is not a pending change", () => {+ const canonical = join(root, "Vault");+ bootstrap(canonical);+ const other = join(root, "vault");+ if (!existsSync(other)) {+ // A case-sensitive filesystem: make `vault` open the same directory.+ symlinkSync(canonical, other, "dir");+ }+ expect(readFileSync(brainManualPath(canonical), "utf8")).toContain("vault_name: Vault");++ const plan = planUpgrade(other);++ expect(plan.pending).toBe(0);+ });+});++describe("vault_name for two different directories", () => {+ test.skipIf(process.platform === "win32" || process.platform === "darwin")(+ "a case-only difference that names ANOTHER directory is still a pending change",+ () => {+ if (rootIsCaseInsensitive()) return;+ // Two real vaults whose names differ only in case. The manual copied+ // from `Vault` into `vault` really is stale there.+ const upper = join(root, "Vault");+ const lower = join(root, "vault");+ bootstrap(upper);+ bootstrap(lower);+ copyFileSync(brainManualPath(upper), brainManualPath(lower));++ const plan = manualPlan(lower);++ expect(plan.status).toBe("update");+ expect(plan.after).toContain("vault_name: vault");+ },+ );++ test("a manual naming an unrelated vault is still a pending change", () => {+ const vault = join(root, "notes");+ bootstrap(vault);+ const path = brainManualPath(vault);+ const body = readFileSync(path, "utf8").replace("vault_name: notes", "vault_name: Elsewhere");+ atomicWriteFileSync(path, body);++ expect(manualPlan(vault).status).toBe("update");+ });+});diff --git a/tests/core/maintenance/self-heal-upgrade.test.ts b/tests/core/maintenance/self-heal-upgrade.test.tsnew file mode 100644index 00000000..cbc71f3b--- /dev/null+++ b/tests/core/maintenance/self-heal-upgrade.test.ts@@ -0,0 +1,315 @@+/**+ * The automatic Brain upgrade runs off the start-up path, records a failure+ * where an operator looks, and backs off instead of retrying on every start+ * (GitHub #216).+ *+ * The failure used here is a real one the snapshot step hits: a regular file+ * where `Brain/.snapshots/` should be a directory, so the pre-apply snapshot+ * (and with it the whole upgrade) cannot proceed.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { listMetrics } from "../../../src/core/brain/metrics.ts";+import { brainDirs, brainManualPath } from "../../../src/core/brain/paths.ts";+import { planUpgrade } from "../../../src/core/brain/upgrade.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import {+ ensureVaultCurrent,+ SELF_HEAL_UPGRADE_SPAWN,+} from "../../../src/core/maintenance/ensure-current.ts";+import {+ runSelfHealUpgrade,+ SELF_HEAL_UPGRADE_OUTCOME,+ SELF_HEAL_UPGRADE_SURFACE,+} from "../../../src/core/maintenance/self-heal-upgrade.ts";+import {+ checkSelfHealUpgrade,+ claimSelfHealUpgradeLock,+ selfHealUpgradeMarkerPath,+ readSelfHealUpgradeFailure,+ releaseSelfHealUpgradeLock,+ selfHealUpgradeLockPath,+ SELF_HEAL_UPGRADE_BASE_COOLDOWN_MS,+} from "../../../src/core/maintenance/self-heal-upgrade-state.ts";+import { runCli } from "../../helpers/run-cli.ts";+import { waitForSelfHealChildren } from "../../helpers/self-heal-children.ts";++const HOUR = 60 * 60_000;+const T0 = new Date("2026-09-28T10:00:00.000Z");++let root: string;+let vault: string;+let configPath: string;+let prevConfigEnv: string | undefined;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-self-heal-upgrade-"));+ vault = join(root, "vault");+ configPath = join(root, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ prevConfigEnv = process.env["OPEN_SECOND_BRAIN_CONFIG"];+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ bootstrapBrain(vault, { configPath });+});++afterEach(async () => {+ await waitForSelfHealChildren(vault);+ if (prevConfigEnv === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = prevConfigEnv;+ rmSync(root, { recursive: true, force: true });+});++/** A detached worker releases the lock it was handed when it ends. */+async function waitForWorker(budgetMs = 60_000): Promise<void> {+ const deadline = Date.now() + budgetMs;+ while (existsSync(selfHealUpgradeLockPath(vault)) && Date.now() < deadline) {+ // Nothing in-process holds the detached worker; looking again is the+ // only way to learn it ended.+ // eslint-disable-next-line no-await-in-loop+ await Bun.sleep(50);+ }+ if (existsSync(selfHealUpgradeLockPath(vault))) throw new Error("worker never released its lock");+}++function makeManualStale(): void {+ writeFileSync(brainManualPath(vault), "stale operator copy\n");+}++function breakSnapshots(): void {+ const snapshots = brainDirs(vault).snapshots;+ rmSync(snapshots, { recursive: true, force: true });+ writeFileSync(snapshots, "not a directory\n");+}++function repairSnapshots(): void {+ rmSync(brainDirs(vault).snapshots, { force: true });+}++function upgradeRows(): ReadonlyArray<Record<string, unknown>> {+ return listMetrics(vault, { surface: SELF_HEAL_UPGRADE_SURFACE }).map((r) => r.payload);+}++describe("a failed automatic upgrade", () => {+ test("is recorded with its error, the pending files and a retry time", () => {+ makeManualStale();+ breakSnapshots();++ const run = runSelfHealUpgrade(vault, { now: T0 });++ expect(run.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.failed);+ const failure = readSelfHealUpgradeFailure(vault);+ expect(failure).not.toBeNull();+ expect(failure!.failedAt).toBe(T0.toISOString());+ expect(failure!.error).toContain(".snapshots");+ expect(failure!.pending).toEqual(["Brain/_BRAIN.md"]);+ expect(failure!.consecutiveFailures).toBe(1);+ expect(failure!.retryAfter).toBe(+ new Date(T0.getTime() + SELF_HEAL_UPGRADE_BASE_COOLDOWN_MS).toISOString(),+ );+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("stale operator copy\n");+ expect(upgradeRows().map((r) => r["outcome"])).toEqual([SELF_HEAL_UPGRADE_OUTCOME.failed]);+ });++ test("is not retried before its cooldown runs out", () => {+ makeManualStale();+ breakSnapshots();+ runSelfHealUpgrade(vault, { now: T0 });++ const again = runSelfHealUpgrade(vault, { now: new Date(T0.getTime() + HOUR / 2) });++ expect(again.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.backoff);+ expect(readSelfHealUpgradeFailure(vault)!.consecutiveFailures).toBe(1);+ expect(upgradeRows()).toHaveLength(1);+ });++ test("is retried after the cooldown, and a repeat failure doubles it", () => {+ makeManualStale();+ breakSnapshots();+ runSelfHealUpgrade(vault, { now: T0 });+ const later = new Date(T0.getTime() + HOUR + 1);++ const again = runSelfHealUpgrade(vault, { now: later });++ expect(again.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.failed);+ const failure = readSelfHealUpgradeFailure(vault)!;+ expect(failure.consecutiveFailures).toBe(2);+ expect(failure.retryAfter).toBe(new Date(later.getTime() + 2 * HOUR).toISOString());+ });++ test("is cleared by the retry that succeeds", () => {+ makeManualStale();+ breakSnapshots();+ runSelfHealUpgrade(vault, { now: T0 });+ repairSnapshots();++ const again = runSelfHealUpgrade(vault, { now: new Date(T0.getTime() + HOUR + 1) });++ expect(again.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.applied);+ expect(again.filesUpdated).toEqual(["Brain/_BRAIN.md"]);+ expect(readSelfHealUpgradeFailure(vault)).toBeNull();+ expect(planUpgrade(vault).pending).toBe(0);+ });+});++function plantMarker(record: Record<string, unknown>): void {+ mkdirSync(dirname(selfHealUpgradeMarkerPath(vault)), { recursive: true });+ writeFileSync(selfHealUpgradeMarkerPath(vault), JSON.stringify(record));+}++describe("a failure marker this build did not write", () => {+ test("cannot hold the automatic upgrade off past the longest cooldown", () => {+ makeManualStale();+ plantMarker({+ failed_at: T0.toISOString(),+ error: "copied from another vault",+ consecutive_failures: 1,+ retry_after: "2099-01-01T00:00:00.000Z",+ });++ const run = runSelfHealUpgrade(vault, { now: new Date(T0.getTime() + 25 * HOUR) });++ expect(run.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.applied);+ });++ test("reaches the doctor without its control characters", () => {+ plantMarker({+ failed_at: T0.toISOString(),+ error: "boom \u001b]0;title\u0007 \u001b[31mred",+ consecutive_failures: 1,+ retry_after: T0.toISOString(),+ });++ const check = checkSelfHealUpgrade(vault);++ expect(check.ok).toBe(false);+ expect(check.message).toContain("boom");+ // oxlint-disable-next-line no-control-regex -- asserting their absence is the point+ expect(check.message).not.toMatch(/[\u0000-\u001f\u007f]/);+ });+});++describe("the worker lock", () => {+ test("a second worker does not run while one holds the vault", () => {+ makeManualStale();+ const token = claimSelfHealUpgradeLock(vault, T0);+ expect(token).not.toBeNull();+ try {+ expect(runSelfHealUpgrade(vault, { now: T0 }).outcome).toBe(+ SELF_HEAL_UPGRADE_OUTCOME.running,+ );+ expect(planUpgrade(vault).pending).toBe(1);+ // The holder's own token is what lets the handed-over worker run.+ expect(runSelfHealUpgrade(vault, { now: T0, lockToken: token! }).outcome).toBe(+ SELF_HEAL_UPGRADE_OUTCOME.applied,+ );+ } finally {+ releaseSelfHealUpgradeLock(vault, token!);+ }+ expect(existsSync(selfHealUpgradeLockPath(vault))).toBe(false);+ });++ test("a claim older than the staleness ceiling is taken over", () => {+ expect(claimSelfHealUpgradeLock(vault, T0)).not.toBeNull();+ expect(claimSelfHealUpgradeLock(vault, new Date())).toBeNull();+ const muchLater = new Date(Date.now() + 2 * HOUR);+ const takeover = claimSelfHealUpgradeLock(vault, muchLater);+ expect(takeover).not.toBeNull();+ releaseSelfHealUpgradeLock(vault, takeover!);+ });+});++describe("ensureVaultCurrent in the background", () => {+ test("hands a pending upgrade to a detached worker instead of applying it inline", async () => {+ makeManualStale();++ const r = await ensureVaultCurrent(vault, { background: true, configPath });++ expect(r.brainUpgradeSpawn).toBe(SELF_HEAL_UPGRADE_SPAWN.spawned);+ expect(r.brainUpgraded).toEqual([]);+ await waitForWorker();+ expect(planUpgrade(vault).pending).toBe(0);+ expect(upgradeRows().map((row) => row["outcome"])).toEqual([SELF_HEAL_UPGRADE_OUTCOME.applied]);+ }, 60_000);++ test("starts nothing while a recorded failure is cooling down", async () => {+ makeManualStale();+ breakSnapshots();+ runSelfHealUpgrade(vault, { now: new Date() });++ const r = await ensureVaultCurrent(vault, { background: true, configPath });++ expect(r.brainUpgradeSpawn).toBe(SELF_HEAL_UPGRADE_SPAWN.skippedBackoff);+ expect(existsSync(selfHealUpgradeLockPath(vault))).toBe(false);+ });+});++function failOnce(): void {+ makeManualStale();+ breakSnapshots();+ runSelfHealUpgrade(vault, { now: T0 });+}++describe("operator surfaces after a failure", () => {+ test("`o2b brain upgrade --dry-run` shows the pending item and the last failure", async () => {+ failOnce();++ const r = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });++ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("Brain/_BRAIN.md: update");+ expect(r.stdout).toContain(`automatic Brain upgrade failed at ${T0.toISOString()}`);+ expect(r.stdout).toContain(".snapshots");+ });++ test("`o2b doctor` reports the failure as a named check", async () => {+ failOnce();++ const r = await runCli(["doctor", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });++ const checks = JSON.parse(r.stdout).checks as Array<{+ name: string;+ ok: boolean;+ message: string;+ fix?: string;+ }>;+ const check = checks.find((c) => c.name === "self_heal_upgrade");+ expect(check?.ok).toBe(false);+ expect(check?.message).toContain(T0.toISOString());+ expect(check?.message).toContain(".snapshots");+ expect(check?.fix).toBe("o2b brain upgrade --dry-run");+ });++ test("`o2b brain status` lists it as a problem", async () => {+ failOnce();++ const r = await runCli(["brain", "status", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });++ expect(r.stdout).toContain("[self-heal-upgrade-failed]");+ expect(r.stdout).toContain(T0.toISOString());+ expect(r.stdout).toContain("-> next: o2b brain upgrade --dry-run");+ });++ test("an explicit `--apply` ignores the cooldown and clears the record", async () => {+ failOnce();+ repairSnapshots();++ const r = await runCli(["brain", "upgrade", "--vault", vault, "--apply", "--yes"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });++ expect(r.returncode).toBe(0);+ expect(readSelfHealUpgradeFailure(vault)).toBeNull();+ expect(planUpgrade(vault).pending).toBe(0);+ });+});diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.tsindex d06f5a8e..ada355f8 100644--- a/tests/core/state/surfaces.test.ts+++ b/tests/core/state/surfaces.test.ts@@ -29,6 +29,7 @@*/import { afterEach, describe, expect, test } from "bun:test";+import { selfHealUpgradeMarkerPath } from "../../../src/core/maintenance/self-heal-upgrade-state.ts";import { existsSync, mkdirSync, statSync, symlinkSync, writeFileSync } from "node:fs";import { dirname, join, resolve, sep } from "node:path";@@ -258,6 +259,7 @@ const RESOLVER_BINDINGS: ReadonlyArray<readonly [StateSurfaceId, (vault: string)["install_manifest", (v) => installManifestPath(v)],["hook_audit", (v) => hookAuditDir(v)],["hook_session_state", (v) => dirname(hookStateFilePath(v, null))],+ ["self_heal_upgrade_marker", (v) => selfHealUpgradeMarkerPath(v)],["aider_context_artifact", (v) => resolveAiderSidecarPath({ vault: v } as InstallEnv, {})],// --- Under `<vault>/Brain/` --------------------------------------------["brain_log", (v) => brainDirs(v).log],diff --git a/tests/helpers/self-heal-children.ts b/tests/helpers/self-heal-children.tsindex 235eb124..99177332 100644--- a/tests/helpers/self-heal-children.ts+++ b/tests/helpers/self-heal-children.ts@@ -1,5 +1,5 @@/**- * Wait for the detached self-heal reindex children a test started.+ * Wait for the detached self-heal children a test started: search reindex children and the managed-file upgrade worker.** A `SessionStart` hook (or a full-scope server start) on an initialised* vault with no search index spawns a detached `o2b search reindex` and@@ -15,10 +15,13 @@* recording, and is reported when it is spent.*/+import { existsSync } from "node:fs";+import {readSelfHealReindexRows,SELF_HEAL_SPAWN,} from "../../src/core/maintenance/self-heal-reindex.ts";+import { selfHealUpgradeLockPath } from "../../src/core/maintenance/self-heal-upgrade-state.ts";/** A cold Bun start plus a rebuild of a near-empty vault, with headroom for a slow runner. */const CHILD_BUDGET_MS = 60_000;@@ -49,4 +52,13 @@ export async function waitForSelfHealChildren(if (pending.length > 0) {throw new Error(`self-heal reindex children never finished: ${pending.join(", ")}`);}+ // The detached managed-file upgrade worker (#216) holds a lock its parent+ // claimed before the spawn and releases it when it ends, so the lock's+ // absence is that worker's completion event.+ const lock = selfHealUpgradeLockPath(vault);+ while (existsSync(lock) && Date.now() < deadline) {+ // eslint-disable-next-line no-await-in-loop+ await Bun.sleep(POLL_INTERVAL_MS);+ }+ if (existsSync(lock)) throw new Error("self-heal upgrade worker never finished");}diff --git a/tests/hooks/process-ceiling-cooperative.test.ts b/tests/hooks/process-ceiling-cooperative.test.tsnew file mode 100644index 00000000..fb317e8e--- /dev/null+++ b/tests/hooks/process-ceiling-cooperative.test.ts@@ -0,0 +1,103 @@+/**+ * The hook ceiling reaches synchronous work (issue #195).+ *+ * `armProcessCeiling` is a timer, and a timer cannot fire while the event+ * loop is blocked by synchronous I/O - which is what the signal dedup walk+ * is. `ceilingSafeguard` hands that work the same deadline as a cooperative+ * checkpoint. These tests drive a synthetic slow walk (a clock that advances+ * one second per reading) through the real lifecycle capture and assert+ * that it stops at a file boundary without writing, and that under budget+ * the capture is unchanged.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { ceilingSafeguard, HOOK_CEILING_OPERATION } from "../../hooks/lib/process-ceiling.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { SafeguardTimeoutError } from "../../src/core/brain/safeguard.ts";+import { captureSessionLifecycleEvent } from "../../src/core/brain/session-lifecycle.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";++const NOW = new Date("2026-06-02T10:00:00Z");+const MARKER_PROMPT =+ '@osb feedback positive topic=ceiling-check principle="stop the walk before the host does"';++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-ceiling-coop-"));+ bootstrapBrain(vault);+ for (let i = 0; i < 40; i++) {+ writeSignal(vault, {+ topic: `history-${i}`,+ signal: "positive",+ agent: "claude",+ principle: `Historical principle ${i}`,+ created_at: "2026-05-01T10:00:00Z",+ date: "2026-05-01",+ slug: `history-${i}`,+ dedup_hash: `h-${i}`,+ });+ }+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++/** A clock that advances one second per reading: every file costs a second. */+function slowClock(): () => number {+ let t = 0;+ return () => (t += 1000);+}++function inboxCount(): number {+ const dir = brainDirs(vault).inbox;+ if (!existsSync(dir)) return 0;+ return readdirSync(dir).filter((n) => n.startsWith("sig-")).length;+}++function markerEvent(): Record<string, unknown> {+ return { hook_event_name: "UserPromptSubmit", session_id: "s-1", prompt: MARKER_PROMPT };+}++describe("ceilingSafeguard", () => {+ test("is silent under budget and throws at the first checkpoint past it", () => {+ let t = 0;+ const guard = ceilingSafeguard(3_000, () => t);+ t = 2_999;+ guard.checkpoint();+ t = 3_001;+ expect(() => guard.checkpoint()).toThrow(SafeguardTimeoutError);+ expect(guard.operation).toBe(HOOK_CEILING_OPERATION);+ });+});++describe("the lifecycle capture under the cooperative ceiling", () => {+ test("a slow dedup walk stops at a file boundary and writes nothing", async () => {+ const before = inboxCount();+ await expect(+ captureSessionLifecycleEvent(vault, markerEvent(), {+ agent: "claude",+ now: NOW,+ safeguard: ceilingSafeguard(8_000, slowClock()),+ }),+ ).rejects.toThrow(SafeguardTimeoutError);+ expect(inboxCount()).toBe(before);+ });++ test("under budget the capture is unchanged", async () => {+ const before = inboxCount();+ const result = await captureSessionLifecycleEvent(vault, markerEvent(), {+ agent: "claude",+ now: NOW,+ safeguard: ceilingSafeguard(60_000),+ });+ expect(result.signals_created).toBe(1);+ expect(inboxCount()).toBe(before + 1);+ });+});diff --git a/tests/mcp/mcp-json.test.ts b/tests/mcp/mcp-json.test.tsdeleted file mode 100644index 634b0427..00000000--- a/tests/mcp/mcp-json.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { readFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";-import { describe, expect, test } from "bun:test";--// Resolve relative to this test file so the suite runs from any checkout-// path (CI / contributor clones / worktrees) β not just `/srv/projects/...`.-const HERE = dirname(fileURLToPath(import.meta.url));-const MCP_JSON_PATH = resolve(HERE, "..", "..", ".mcp.json");--describe(".mcp.json shipped with the plugin", () => {- const file = JSON.parse(readFileSync(MCP_JSON_PATH, "utf8"));- test("declares both open-second-brain and -writer entries", () => {- expect(Object.keys(file.mcpServers).toSorted()).toEqual([- "open-second-brain",- "open-second-brain-writer",- ]);- });- test("writer entry passes --scope writer and alwaysLoad: true", () => {- const w = file.mcpServers["open-second-brain-writer"];- expect(w.command).toBe("${CLAUDE_PLUGIN_ROOT}/scripts/o2b");- expect(w.args).toEqual(["mcp", "--scope", "writer"]);- expect(w.alwaysLoad).toBe(true);- });- test("full server has no alwaysLoad flag", () => {- const f = file.mcpServers["open-second-brain"];- expect(f.alwaysLoad).toBeUndefined();- });-});diff --git a/tests/mcp/plugin-mcp-servers.test.ts b/tests/mcp/plugin-mcp-servers.test.tsnew file mode 100644index 00000000..0c7e219e--- /dev/null+++ b/tests/mcp/plugin-mcp-servers.test.ts@@ -0,0 +1,51 @@+import { existsSync, readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, test } from "bun:test";++// Resolve relative to this test file so the suite runs from any checkout+// path (CI, contributor clones, worktrees).+const HERE = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(HERE, "..", "..");+const PLUGIN_JSON_PATH = resolve(REPO_ROOT, ".claude-plugin", "plugin.json");++interface ServerEntry {+ command: string;+ args: string[];+ alwaysLoad?: boolean;+}++describe("Claude Code plugin MCP servers", () => {+ const manifest = JSON.parse(readFileSync(PLUGIN_JSON_PATH, "utf8")) as {+ mcpServers: Record<string, ServerEntry>;+ };+ const servers = manifest.mcpServers;++ test("are declared inline in plugin.json", () => {+ expect(Object.keys(servers).toSorted()).toEqual([+ "open-second-brain",+ "open-second-brain-writer",+ ]);+ });++ test("full server runs o2b mcp from the plugin root without alwaysLoad", () => {+ const f = servers["open-second-brain"]!;+ expect(f).toEqual({ command: "${CLAUDE_PLUGIN_ROOT}/scripts/o2b", args: ["mcp"] });+ expect(f.alwaysLoad).toBeUndefined();+ });++ test("writer server passes --scope writer and alwaysLoad: true", () => {+ expect(servers["open-second-brain-writer"]).toEqual({+ command: "${CLAUDE_PLUGIN_ROOT}/scripts/o2b",+ args: ["mcp", "--scope", "writer"],+ alwaysLoad: true,+ });+ });++ // Claude Code also reads a `.mcp.json` in the working directory as a+ // project-scoped config. At the repository root `CLAUDE_PLUGIN_ROOT` is+ // unset there, so a root manifest spawns `/scripts/o2b` and fails.+ test("no .mcp.json at the repository root", () => {+ expect(existsSync(resolve(REPO_ROOT, ".mcp.json"))).toBe(false);+ });+});diff --git a/tests/setup.ts b/tests/setup.tsindex 5cb50d0b..d33a5e5e 100644--- a/tests/setup.ts+++ b/tests/setup.ts@@ -93,6 +93,16 @@ if (process.platform === "win32") {}}+// The signal dedup index keeps a machine-local cache under the user cache+// directory (`src/core/brain/dedup-index-cache.ts`). Every capture test+// would otherwise leave one file per throwaway vault in the developer's+// real cache, so the suite points it at a root of its own.+if (process.env["OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR"] === undefined) {+ const cacheRoot = mkdtempSync(join(tmpdir(), "osb-test-dedup-cache-"));+ afterAll(() => rmSync(cacheRoot, REMOVE_TREE));+ process.env["OPEN_SECOND_BRAIN_DEDUP_CACHE_DIR"] = cacheRoot;+}+// Every temp entry a test mints lands under ONE per-run root, and the run// fails if any of them is still there after the last file (issue #194).//diff --git a/uv.lock b/uv.lockindex 1c5f3aac..b319c327 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.60.0"+version = "1.61.0"source = { editable = "." }