Skip to content

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

TypeScript

feat: Continuity, Hygiene & Freshness Suite - session lineage, memory hygiene, anticipatory cache (v1.3.0) (#87)

Sol Aitken03405606f8b7
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 9fc93b51..067a76a8 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.2.0",
+ "version": "1.3.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 30e134b9..997d8d44 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.2.0",
+ "version": "1.3.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8e4f7635..35747d43 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,83 @@ 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.3.0] - 2026-06-10
+
+Continuity, Hygiene & Freshness Suite: one conversation stays one
+session across host context compressions, and the Brain gains a
+remediation pipeline for the entropy it accumulates - contested facts,
+near-duplicate rules, stale derived pages, never-recalled memories.
+Two kernels carry the release: a session-lineage resolver consumed by
+capture, recall, and the new anticipatory cache, and a hygiene
+findings pipeline composing pure detectors behind one scan/apply
+surface.
+
+### Added
+
+- **Session lineage kernel** (`src/core/brain/lineage/`): every session
+ id resolves to a lineage (root id, parent segment, compression
+ depth). Native path reads the new optional `parent_session_id` /
+ `root_session_id` / `compression_depth` hook-payload fields (ready
+ for upstream Hermes PR #42940); until the deployed host emits them,
+ a conservative interim inference - isolated in one file and marked
+ `CRUTCH(t_1459706f)` - links a brand-new session to a predecessor
+ only on compression evidence plus same cwd inside a bounded window.
+ Time proximity alone never stitches; every ambiguous case stays flat.
+- **Compression-aware session recall**: imported session records carry
+ additive lineage payload fields, and `brain_session_grep` /
+ `brain_session_describe` resolve any segment id to the whole stitched
+ conversation. Describe exposes the segment chain with its continuity
+ edges; never-compacted sessions keep the exact pre-lineage shapes.
+- **Staged degradation ladder** for over-budget recall entries:
+ `recall.degradation: staged` in `_brain.yaml` trims at the last
+ sentence terminator (structural multi-script punctuation), then whole
+ leading lines, then the historical hard cut - which stays the
+ byte-identical default.
+- **Anticipatory context cache**: lifecycle hooks keep a small
+ turn-specific bundle (active context pack + session-recall hits for
+ the latest prompt) warm under `Brain/.state/`, keyed by the lineage
+ root, TTL-debounced, atomically written - no daemon, no watcher. New
+ `brain_anticipatory_context` MCP tool and `o2b brain anticipate` verb
+ read it cache-or-live with an explicit `cache_state`.
+- **Source-freshness contract**: derived pages record `source_paths` +
+ `source_hashes` at derivation (handoff notes stamp their transcript
+ automatically); freshness computes on demand as fresh / stale /
+ orphaned with no background jobs.
+- **Hygiene findings pipeline** (`src/core/brain/hygiene/`): pure
+ detectors - truth-layer value conflicts, semantic near-duplicate
+ preferences (embedding cosine with a labeled lexical fallback),
+ freshness, never-recalled low-usefulness candidates - compose into a
+ read-only scan digest; apply executes only explicitly selected
+ finding ids through existing primitives (preference merge, claim
+ append, targeted recompile, archive-never-delete) with an audit
+ record per run. New `brain_hygiene` MCP tool and `o2b brain hygiene
+ scan|apply` verbs.
+- **Advisory conflict resolution** through the shared external-command
+ bridge: when the operator configures `hygiene.resolver_cmd`, contested
+ truth slots get supersede / merge / flag verdicts with recorded
+ rationale; without it (or on any failure) every conflict stays
+ flagged for review. The command comes exclusively from operator
+ config - never from tool arguments.
+- **Targeted recompile**: `o2b brain refresh --stale [--dry-run]`
+ re-derives only pages whose recorded sources changed (handoff notes
+ re-derive in place from their transcript), archives orphans into
+ `Brain/.snapshots/`, and reports unknown pipelines as manual.
+- **Config blocks** `hygiene` (resolver_cmd, dedup_threshold),
+ `anticipatory` (ttl_seconds, max_tokens), and `recall` (degradation)
+ parse through the existing YAML subset with hard shape errors.
+- **Shared external-command JSON bridge**
+ (`src/core/reliability/command-bridge.ts`) extracted from the bench
+ judge: one sanctioned fail-open boundary for every external-judgment
+ consumer.
+
+### Changed
+
+- The frozen Brain MCP tool surface grows deliberately from 54 to 56
+ names (`brain_hygiene`, `brain_anticipatory_context`); the parity,
+ name-list, and count guards were updated in the same change.
+- `HookPayloadBase` gains optional lineage fields and the SessionStart
+ `source` discriminator; hosts without them behave byte-identically.
+
## [1.2.0] - 2026-06-09
Codebase-wide SOLID/DRY refactor: god modules decomposed into cohesive
diff --git a/README.md b/README.md
index 143c29a8..2e52fb12 100644
--- a/README.md
+++ b/README.md
@@ -81,6 +81,8 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra
- **One brain, every agent.** Teach a rule in one agent and the next one already knows it - Hermes, Claude Code, Codex, Cursor, and the rest read and write the same vault.
- **You stay in control.** Pin, merge, retire, or roll back any rule from the `o2b` CLI. Every Brain mutation takes a verified snapshot first, so a bad change is one `o2b brain rollback` away.
- **Search that explains itself.** Keyword plus an optional semantic layer over your vault, with results that show why they surfaced and what was missing - not a black box.
+- **Conversations survive compaction.** When the host compresses context and rotates the session id, capture and recall stitch the segments back into one conversation - any segment id returns the whole lineage.
+- **Memory that cleans itself, on your terms.** `o2b brain hygiene scan` surfaces contested facts, near-duplicate rules, stale derived pages, and never-recalled memories; `apply` executes only the findings you select, and stale pages recompile from their recorded sources with a dry-run preview.
That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.
diff --git a/docs/architecture.md b/docs/architecture.md
index 0bb20961..7e6cad2c 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -167,6 +167,10 @@ Brain/
retired/ # ret-<slug>.md with retired_reason
log/ # YYYY-MM-DD.md, append-only event log (dream / apply-evidence / etc.)
.snapshots/ # <run_id>.tar.zst, pre-run snapshots for o2b brain rollback
+ # plus hygiene-<date>/ archives (pages moved, never deleted)
+ .state/ # machine state, excluded from indexing (since v1.3.0):
+ # session-lineage.jsonl (compression-chain ledger)
+ # anticipatory/<root>.json (hook-warmed context cache)
```
This layout is intentionally agent-owned: every artefact Open Second
@@ -178,7 +182,7 @@ the vault is read-only to the agent and stays under operator control.
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.
+- **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.
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/brainstorm/continuity-hygiene-freshness/cli-output/claude.md b/docs/brainstorm/continuity-hygiene-freshness/cli-output/claude.md
new file mode 100644
index 00000000..d39109a4
--- /dev/null
+++ b/docs/brainstorm/continuity-hygiene-freshness/cli-output/claude.md
@@ -0,0 +1,38 @@
+### Variant 1: Extend-in-place (substrate growth, no new kernels)
+
+- **Approach**: Every feature lands as an extension of the module that already owns the nearest behavior. A1's lineage fields go onto `HookPayloadBase` with the crutch as one file under `hooks/lib/`; A2 extends `session-recall.ts` and capture with optional lineage fields on existing continuity records (additive, no schema bump); A3 grows `applyCharBudget` into a ladder inside `recall-budget.ts`; A4 is one small cache module on existing hook events. Cluster B becomes a single `src/core/brain/hygiene/` domain module that directly calls `reconcile-outcomes.ts`, recall-telemetry readers, the search embeddings registry (B2), and `sourceRefs.hash` comparisons (B4), with B5 as an apply action inside it.
+- **Trade-offs**:
+ - Pro: smallest diff surface; no new abstractions to design or test; follows the existing pattern of pure helpers plus domain modules established in the v1.2.0 decomposition.
+ - Pro: A3 stays a drop-in upgrade for both `context-pack.ts` and `pre-compress-pack.ts` since both already call the same budget primitive.
+ - Con: the hygiene module accretes four unrelated detection concerns (contradiction, usefulness, dedup, freshness) behind one wall; B5's recompile logic entangles hygiene with the import and indexer pipelines.
+ - Con: lineage resolution logic gets duplicated across capture, recall, and the A4 cache unless extracted later anyway; the CRUTCH boundary risks leaking into `session-recall.ts`.
+ - Con: B2's embeddings fallback and B3's resolver bridge each reinvent plumbing (`bench/judge.ts` gets copied rather than shared).
+- **Complexity**: medium
+- **Risk**: medium
+
+### Variant 2: Two shared kernels (lineage resolver plus findings pipeline)
+
+- **Approach**: Introduce exactly two new substrates. First, a `lineage` module (`src/core/brain/lineage/`) exposing `resolveLineage(payload) -> {rootId, parentId, depth}` with the native path reading the extended `HookPayloadBase` and the interim Hermes crutch isolated in one file marked `CRUTCH(t_1459706f)`; capture (A2), recall and session-read tools (A2), and the anticipatory cache key (A4) all consume it, while A3 stays an independent upgrade of `recall-budget.ts`. Second, a `hygiene` module built around a small detector contract: each detector (`dedup` B2, `freshness` B4, `conflicts` B3 wrapping `reconcile-outcomes.ts`, `usefulness` from recall-telemetry) is a pure function returning typed `Finding[]`; `scan` fans out over detectors, `apply` executes a typed remediation plan, B5 is the freshness-findings executor that calls into existing import/indexer entry points, and B3's resolver reuses a shared external-command bridge extracted from `bench/judge.ts`.
+- **Trade-offs**:
+ - Pro: the crutch isolation constraint is satisfied by construction, and lineage semantics live in one place for all three consumers instead of three copies.
+ - Pro: the detector contract matches B1's actual job description (integrate heterogeneous signals into one digest) and makes scan-versus-apply, dry-run, and the audit trail uniform across B2 through B5.
+ - Pro: extracting the judge bridge gives B3 the fail-open external-LLM pattern without duplicating spawn/timeout/JSON plumbing, keeping the deterministic-core rule auditable in one file.
+ - Con: two new abstractions designed up front; the detector interface could be over-fitted if a future detector needs streaming or cross-detector state.
+ - Con: more files and more parity-list churn (new MCP tools and CLI verbs for hygiene, lineage-aware session tools, cache commands) in one release.
+- **Complexity**: medium-large (closest single label: large)
+- **Risk**: low
+
+### Variant 3: Feature-siloed modules composed at the surface
+
+- **Approach**: Each of the nine features ships as its own self-contained module with its own CLI verbs and MCP tools: `lineage/`, `session-stitch/`, `budget-ladder/`, `context-cache/`, `hygiene-scan/`, `dedup/`, `conflict-resolve/`, `freshness/`, `recompile/`. There is no shared detector contract; B1's scan composes by calling the public functions of the sibling modules and concatenating their reports, and B5 calls B4's public freshness API directly. Sharing happens only through already-existing primitives (continuity store, search index, `applyCharBudget`).
+- **Trade-offs**:
+ - Pro: maximally parallelizable development (nine kanban tasks map one-to-one to modules); each module is small, independently testable, and independently revertable if a feature slips the release.
+ - Pro: no speculative abstractions; seams follow the kanban decomposition exactly.
+ - Con: B1 degrades from an integration surface into a report concatenator; consolidate/forget/archive remediation and the audit trail get reimplemented per detector, or apply-mode ends up inconsistent across dedup, freshness, and conflicts.
+ - Con: lineage resolution is still needed by three modules, so either `session-stitch/` and `context-cache/` both depend on `lineage/` (recreating Variant 2's kernel informally) or they duplicate it.
+ - Con: nine new tool surfaces inflate the frozen 54-tool parity list and the 76-verb CLI more than the features warrant, contradicting the recent consolidation direction of the v1.2.0 refactor.
+- **Complexity**: large
+- **Risk**: medium
+
+### Recommended: Variant 2
+**Rationale**: The task's own structure already names the two real seams: A1/A2/A4 share lineage resolution (and the crutch must be isolated in one module regardless, so the kernel costs almost nothing extra), and B1 is explicitly the umbrella through which B2/B3/B4 findings surface, which is precisely a detector-and-plan pipeline. Variant 1 saves little while smearing the crutch and the remediation audit trail across existing modules, and Variant 3 rediscovers both kernels informally while bloating the frozen tool surface. Variant 2 also aligns with the project's current trajectory (v1.2.0 SOLID/DRY domain modules, pure deterministic detectors, the `bench_judge_cmd` fail-open bridge as the sanctioned LLM boundary) and keeps every constraint - no daemon, deterministic core, additive surfaces - enforceable at module boundaries rather than by convention.
diff --git a/docs/brainstorm/continuity-hygiene-freshness/cli-output/prompt.md b/docs/brainstorm/continuity-hygiene-freshness/cli-output/prompt.md
new file mode 100644
index 00000000..e16f033b
--- /dev/null
+++ b/docs/brainstorm/continuity-hygiene-freshness/cli-output/prompt.md
@@ -0,0 +1,94 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+One release ships nine features in two clusters. The architectural question is how the nine features map onto modules and shared substrates: which features share a store, which get their own module, where the seams are.
+
+## Cluster A - session continuity
+
+### A1. Hook-payload session lineage plumbing (kanban t_d08ccc5a)
+Carry Hermes session lineage (parent/root id, compression depth) into the plugin hook payload boundary so capture and recall can stitch a conversation that Hermes split across a compression boundary. Verified: the deployed Hermes builds the shell-hook payload in `_serialize_payload` and emits only `hook_event_name, tool_name, tool_input, session_id (= session_id OR parent_session_id), cwd, extra` - no distinct lineage field, no transcript_path. Upstream PR NousResearch/hermes-agent#42940 (adds `parent_session_id` to the payload) is still open. So: extend `HookPayloadBase` with optional `parent_session_id` / `root_session_id` / `compression_depth` (native path, ready for the merged PR), plus an interim lineage-resolution crutch for today's Hermes, isolated and marked `CRUTCH(t_1459706f)` so it can be deleted wholesale later. Fail-soft: missing lineage degrades to current flat-id behaviour, never errors.
+
+### A2. Compression-aware session capture and recall keyed on lineage root (kanban t_a94623ad)
+Today `src/core/brain/session-recall.ts` filters records by exact `record.payload["session_id"] === sessionId`, and capture keys everything on the flat id, so each post-compaction segment becomes a separate disconnected Brain session. Adopt a lineage-root key: store `parent_session_id` / `root_session_id` / `compression_depth` on captured session records; key recall and the session-read tools (brain_session_expand / grep / describe) on the lineage root so a query over any segment id returns the full stitched conversation; preserve a continuity edge between adjacent segments. Acceptance: a conversation compacted once is recallable as one session via either the root id or the child id; no regression for never-compacted sessions.
+
+### A3. Depth-aware summary escalation ladder for over-budget context items (kanban t_05f5dc12)
+Inspired by hermes-lcm. OSB's per-entry budget today is a hard character cut (`applyCharBudget` in `src/core/brain/recall-budget.ts`, used by context-pack and pre-compress-pack). Add a staged degradation ladder: when an item exceeds its budget, degrade it progressively (e.g. full text -> sentence-boundary-trimmed prose -> first-lines/bullet extract -> hard truncate) instead of cutting mid-sentence. Deterministic, pure, language-agnostic (no language-specific sentence heuristics beyond punctuation/structure).
+
+### A4. Anticipatory Brain context cache for active agent turns (kanban t_4cee9df5)
+Inspired by FlowState-QMD. Keep a small, inspectable, turn-specific context pack warm while an agent is working, so the next turn's memory evidence is ready before the agent asks. OSB constraint: NO daemon, NO file watcher (explicit design decision). So the cache must be refreshed on existing hook events (tool-use / prompt-submit hooks already fire) or on explicit command, written atomically to a well-known location, and consumed by a read-the-cache-or-fall-back-to-live-query path.
+
+## Cluster B - hygiene and freshness
+
+### B1. Memory hygiene tool: scan and apply (kanban t_698db8f7)
+A hygiene surface with `scan` (diagnostic digest: open contradictions, low-usefulness candidates, near-duplicates, stale pages) and `apply` (remediation: consolidate, forget, archive) modes. Integrates existing substrates: dream-pass contradiction classification (`reconcile-outcomes.ts`), recall-telemetry usefulness signals, plus the new dedup/freshness detectors below. Scan is read-only; apply mutates with an explicit plan and audit trail.
+
+### B2. Semantic deduplication of near-duplicate memories (kanban t_da3f138f)
+Detect near-duplicate memory pages/observations via embedding similarity with a configurable threshold (upstream default 0.97). OSB has an embeddings provider registry (local / openai-compat / null). Dedup must work when embeddings are unavailable (fall back to lexical similarity or skip with a clear report). Child of B1: dedup findings surface through hygiene scan; merging happens through hygiene apply.
+
+### B3. LLM-based episodic conflict resolution (kanban t_db375a60)
+When episodic memories conflict (contradictory facts about the same entity), resolve by superseding, merging, or flagging for review. OSB hard rule: the Brain core stays deterministic - no LLM runs inside the harness. The existing pattern is an external command bridge (`bench_judge_cmd`: command gets JSON on stdin, returns JSON verdict on stdout, fail-open). Conflict DETECTION must be deterministic; RESOLUTION may consult a configured external resolver command, and with no resolver configured every conflict is flagged for operator review.
+
+### B4. Source freshness detection for stale and orphaned pages (kanban t_d9624ef6)
+Pages derived from external sources (ingested docs, imported sessions) can go stale. Track source identity + content hash at ingest; compute freshness on demand (`stale` = source changed since derivation, `orphaned` = all sources gone); surface freshness in lint-style checks and in search/recall result metadata. No background jobs - freshness computed on demand from recorded state. There is an existing `source_invalidation` continuity record kind and `sourceRefs` with optional `hash` on every continuity record.
+
+### B5. Targeted recompile of stale pages with dry-run preview (kanban t_fe490119)
+Given freshness state from B4, refresh only the affected derived pages: recompile pages whose owning sources changed, clean up orphans, skip unrelated content. `--dry-run` previews the full plan with zero writes. Integrates with the session import and search indexer pipelines (full re-import / full re-index exist today; this adds the selective path).
+
+# Project context
+
+Open Second Brain: a TypeScript + Bun memory system (CLI `o2b`, MCP server, hooks) over an Obsidian-style markdown vault. v1.2.0, 4140 tests.
+
+Recent commits:
+8972f13 refactor: SOLID/DRY decomposition - domain modules, unified helpers, surface guards (v1.2.0) (#86)
+6651228 refactor: language-agnostic fact extraction + README slim (v1.1.0) (#85)
+9886d9a refactor: make search and classification language-agnostic (#84)
+618870e refactor!: remove the pay.sh integration and the Pay Memory layer (#83)
+72bac52 fix(hermes): advertise static tool schemas so the provider registers with its full tool set (#81)
+
+Related files:
+- hooks/lib/stdin.ts (HookPayloadBase: session_id, transcript_path, cwd, hook_event_name, tool_name, tool_input)
+- src/core/brain/session-lifecycle.ts (captureSessionLifecycleEvent -> normalizePayload -> capture boundary -> marker/fact extraction)
+- src/core/brain/capture-boundary.ts, src/core/brain/sessions/import.ts, src/core/brain/session-recall.ts
+- src/core/brain/continuity/{types,store,read-model}.ts (append-only JSONL Brain/continuity/<month>.jsonl; ContinuityRecord {schema "o2b.continuity.v1", id, kind, createdAt, sourceRefs[{id,path,hash,kind}], payload, private, redacted}; kinds: context_receipt, recall_telemetry, gate_telemetry, pre_compact_extract, session_turn, session_summary_node, source_invalidation; additive optional fields do NOT bump the schema version)
+- src/core/brain/recall-budget.ts (applyCharBudget - pure shared budget primitive, per-entry trim is a hard code-point cut)
+- src/core/brain/context-pack.ts (packContext), src/core/brain/pre-compress-pack.ts
+- src/core/brain/dream.ts + dream-refresh.ts + reconcile-outcomes.ts (deterministic dream pass, contradiction classification)
+- src/core/brain/recall-telemetry.ts (recall_telemetry records, usefulness signals)
+- src/core/search/ (bun:sqlite store, FTS + embeddings provider registry local/openai-compat/null, RRF fusion, query cache keyed by corpus-generation revision, indexer with incremental content-hash fastpath)
+- src/core/bench/judge.ts (the external-command LLM bridge pattern: spawnSync sh -c, JSON stdin/stdout, 60s timeout, fail-open)
+- src/mcp/brain/*.ts (16 domain tool modules, 54 MCP tools, aggregated by brain-tools.ts)
+- src/cli/brain/verbs/ (76 CLI verb files sharing brainVerbContext)
+
+Conventions:
+- Fail-soft everywhere: a broken subsystem never blocks capture, search, or hooks; telemetry/metrics failures are swallowed.
+- Pure deterministic core helpers; Object.freeze on returned aggregates; no Date.now()/randomness inside pure functions (clock passed in).
+- src/core never calls process.exit / console.log (layering guard test).
+- A frozen-surface parity test pins the exact 54 MCP tool names; adding tools is allowed but must deliberately update the parity list.
+- Language-agnostic: no hardcoded natural-language phrases for content processing; all output strings English.
+- Append-only JSONL for continuity data; markdown + frontmatter for Brain pages; SQLite only for the derived search index (rebuildable).
+- Conventional commits; TDD (failing test first).
+
+Constraints:
+- No new external dependencies (runtime deps today: proper-lockfile only).
+- No background daemons, no file watchers ("No daemon, no watcher" - explicit design decision; index updates happen on explicit commands or existing hook events).
+- The Hermes lineage crutch must be isolated in one module and marked CRUTCH(t_1459706f).
+- LLM-dependent behavior must degrade to flag-for-review when no external resolver command is configured.
+- Do not change existing public CLI verb/MCP tool semantics; additive surfaces only.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/continuity-hygiene-freshness/design.md b/docs/brainstorm/continuity-hygiene-freshness/design.md
new file mode 100644
index 00000000..dcabb64b
--- /dev/null
+++ b/docs/brainstorm/continuity-hygiene-freshness/design.md
@@ -0,0 +1,89 @@
+# Continuity, Hygiene & Freshness Suite - design
+
+**Status:** approved
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+**Kanban:** t_d08ccc5a, t_a94623ad, t_05f5dc12, t_4cee9df5, t_698db8f7, t_da3f138f, t_db375a60, t_d9624ef6, t_fe490119
+
+## Problem statement
+
+Two structural gaps. First, Hermes rotates `session_id` on context compression while Open Second Brain keys the whole session subsystem on the flat id, so one logical conversation fragments into disconnected Brain sessions that `brain_session_expand` / `grep` / `describe` cannot stitch. Second, the Brain accumulates entropy with no remediation surface: near-duplicate memories, contradictory episodic facts, and pages derived from sources that changed or disappeared all persist silently, and over-budget recall items are truncated mid-sentence instead of degrading gracefully.
+
+## Scope
+
+Nine features in two clusters, structured around two new kernels (consultant Variant 2):
+
+**Kernel 1 - session lineage (`src/core/brain/lineage/`)**
+- A1 `t_d08ccc5a`: `HookPayloadBase` gains optional `parent_session_id` / `root_session_id` / `compression_depth` (the native path, ready for upstream Hermes PR #42940). `resolveSessionLineage()` is the single resolution point; the interim resolution for today's Hermes lives in one crutch file marked `CRUTCH(t_1459706f)`.
+- A2 `t_a94623ad`: capture stamps lineage onto `session_turn` / `session_summary_node` continuity records (additive payload fields, no schema bump); session recall and the session-read tools key on the lineage root so any segment id returns the stitched conversation.
+- A3 `t_05f5dc12`: `recall-budget.ts` grows a staged degradation ladder (sentence-boundary trim -> line extract -> hard cut), opt-in, default behavior byte-identical.
+- A4 `t_4cee9df5`: an anticipatory context cache refreshed from existing hook events (no daemon, no watcher), written atomically, consumed cache-or-live by a new MCP tool / CLI verb.
+
+**Kernel 2 - hygiene findings pipeline (`src/core/brain/hygiene/`)**
+- B1 `t_698db8f7`: `scan` fans out over pure detectors and composes a digest; `apply` executes a typed remediation plan with an audit trail and a dry-run mode.
+- B2 `t_da3f138f`: dedup detector - embedding cosine similarity (provider registry) with deterministic lexical fallback when embeddings are unavailable.
+- B3 `t_db375a60`: conflict detector is deterministic; resolution consults an optional external resolver command via a shared command bridge extracted from `bench/judge.ts`; unresolved or unconfigured conflicts are flagged for review.
+- B4 `t_d9624ef6`: freshness detector - pages declaring a `sources:` frontmatter contract (path + sha256 recorded at derivation) are reported `stale` when a source's current hash differs and `orphaned` when every source is gone. Computed on demand, no background jobs.
+- B5 `t_fe490119`: targeted recompile - `o2b brain refresh --stale [--dry-run]` re-derives only pages whose owning sources changed and stages cleanup for orphans, skipping unrelated content.
+
+**Shared**
+- `src/core/reliability/command-bridge.ts`: the external-command JSON bridge (spawn, timeout, JSON stdin/stdout, fail-open) extracted from `bench/judge.ts`; `judge.ts` becomes a thin caller with unchanged behavior.
+- New MCP tools (deliberate parity-list update): `brain_hygiene`, `brain_anticipatory_context`. Session tools gain additive optional lineage parameters only.
+- New CLI verbs: `brain hygiene`, `brain refresh`, `brain anticipate`; additive `--lineage` flags on session verbs.
+- New brain-config keys (one-level YAML blocks): `hygiene` (resolver_cmd, dedup_threshold), `anticipatory` (ttl_seconds, max_tokens), `recall` (degradation).
+
+## Out of scope
+
+- Hermes-side changes; removing the crutch (tracked separately in t_1459706f, gated on upstream PR #42940).
+- File-watcher index sync (explicitly rejected by the brain-search design: no daemon, no watcher).
+- Learning-to-rank / reinforce recall (separate kanban task, different release).
+- Retrofitting every existing page writer with the `sources:` contract - only writers that already derive from on-disk artifacts (session import, handoff notes) stamp it in this release.
+- Cross-vault hygiene; everything operates on the active vault.
+
+## Chosen approach
+
+Consultant Variant 2 ("two shared kernels"), accepted without override.
+
+The lineage kernel exposes `resolveSessionLineage(hints, deps) -> { rootId, parentId, depth, source }` where `source` is `"payload" | "crutch" | "flat"`. The native path reads the three new optional payload fields. When they are absent, the crutch path consults a local lineage ledger (`Brain/state/session-lineage.jsonl`, append-only, fail-soft): capture records each session's first/last activity and compression-indicating events (PreCompact / pre-compact-extract activity, or a structured `end_reason`-style field when the payload carries one); a new session id links to a predecessor only when the predecessor (a) shares the same `cwd`, (b) ended with a compression indicator, and (c) its last activity falls within a bounded window. No indicator means no link - a conversation is never stitched on time proximity alone. Every crutch call site carries the `CRUTCH(t_1459706f)` marker. Missing lineage always degrades to flat-id behavior.
+
+Recall stitching builds a root index from record payloads (plus the ledger) and filters session records by resolved root, falling back to exact-id filtering for flat sessions, so never-compacted sessions are byte-identical to today.
+
+The hygiene kernel defines one detector contract: `(vault, deps) -> HygieneFinding[]` where a finding carries `detector`, `severity`, `targets`, `evidence`, and a `proposedAction` from a closed set (`merge` / `supersede` / `archive` / `recompile` / `review` / `forget`). `scan` is read-only composition; `apply` consumes an explicit plan (finding ids selected from a scan), executes via existing primitives (merge, archive, recompile entry points), appends audit records, and supports `--dry-run`. The conflict resolver and any future LLM-adjacent step go through the shared command bridge: deterministic detection in core, advisory external resolution, flag-for-review default.
+
+## Design decisions
+
+- **Lineage as additive payload fields, not a new record kind**: `session_turn` / `session_summary_node` records gain optional `parent_session_id` / `root_session_id` / `compression_depth` payload fields. Additive optional fields do not bump `o2b.continuity.v1`, and legacy records read as flat sessions.
+- **Crutch never guesses on time alone**: a false stitch (two unrelated sessions merged) is worse than a missed stitch (status quo). The ledger links only on compression evidence + same cwd + bounded window.
+- **Ladder defaults off**: `applyCharBudget` keeps its hard-cut default so every existing caller stays byte-identical; staged degradation is an explicit option wired through context-pack / pre-compress config. Stage boundaries are structural (sentence-terminator punctuation across scripts, line boundaries), never language-specific wordlists.
+- **Anticipatory cache is hook-driven, TTL-guarded**: refresh runs inside existing hook handlers (prompt-submit / post-tool-use paths), skips when the cache is younger than the configured TTL (debounce without timers), writes via the atomic temp-file + rename pipeline, and the read path falls back to a live pack on miss or staleness. A broken cache never blocks the hook (fail-soft).
+- **One MCP tool per kernel surface, not per feature**: `brain_hygiene` exposes scan/apply via a `mode` parameter; freshness, dedup, conflicts, and usefulness are detector selectors inside it. `brain_anticipatory_context` exposes the cache-or-live read. This keeps the parity-list delta at two and matches the mcp-context-economy direction.
+- **`sources:` frontmatter is the freshness truth**: recorded at derivation time on the derived page itself (path + sha256), so freshness survives index rebuilds and is inspectable in the vault. The search index only caches freshness status for result metadata; the index stays rebuildable.
+- **Recompile reuses derivation pipelines**: session-derived pages re-import from their recorded transcript source; index entries refresh via the existing incremental indexer. No new compilation engine; B5 is a planner + executor over existing entry points.
+- **Command bridge is reliability infrastructure**: extraction from `bench/judge.ts` is a pure refactor (same spawn semantics, timeout, fail-open contract) proven by the existing judge tests before B3 builds on it.
+
+## File changes
+
+New modules:
+- `src/core/brain/lineage/{types,resolve,ledger,crutch}.ts` (+ tests)
+- `src/core/brain/hygiene/{types,scan,apply,plan}.ts`, `src/core/brain/hygiene/detectors/{conflicts,dedup,freshness,usefulness}.ts`, `src/core/brain/hygiene/resolve-conflicts.ts` (+ tests)
+- `src/core/brain/anticipatory-cache.ts`, `src/core/brain/freshness.ts`, `src/core/brain/recompile.ts` (+ tests)
+- `src/core/reliability/command-bridge.ts` (+ tests)
+- `src/mcp/brain/hygiene-tools.ts`
+- `src/cli/brain/verbs/{hygiene,refresh,anticipate}.ts` (paths per existing verb layout)
+
+Modified:
+- `hooks/lib/stdin.ts` (HookPayloadBase lineage fields), hook entry points that forward lifecycle events
+- `src/core/brain/session-lifecycle.ts`, `src/core/brain/sessions/import.ts`, `src/core/brain/session-recall.ts`, `src/core/brain/handoff.ts` (sources stamp)
+- `src/core/brain/recall-budget.ts`, `src/core/brain/context-pack.ts`, `src/core/brain/pre-compress-pack.ts`, `src/core/brain/context-presets.ts` (degradation option plumb)
+- `src/core/brain/policy.ts` (config keys), `src/core/bench/judge.ts` (bridge extraction)
+- `src/mcp/brain/recall-tools.ts`, `src/mcp/brain/pack-tools.ts`, `src/mcp/brain-tools.ts` (aggregation), MCP parity test (deliberate +2)
+- CLI command manifest / completions / help-text, session verbs (lineage flags)
+- `README.md`, `CHANGELOG.md`, `docs/mcp.md`, `docs/cli-reference.md`, `docs/architecture.md`
+
+## Risks and open questions
+
+- **Crutch precision**: compression indicators visible to our hooks differ between hosts (Claude Code fires PreCompact; Hermes may only show a rotated id). The conservative rule means Hermes sessions without a visible indicator stay flat - acceptable, documented, and exactly what t_1459706f later fixes natively.
+- **Dedup cost**: embedding similarity over all memory pages is O(n^2) at the margin; bound the candidate set (same-topic / same-entity buckets via existing index) before pairwise comparison.
+- **Hygiene apply safety**: every destructive action goes through the plan + audit + dry-run path; `forget` archives rather than deletes (vault pages are never unlinked from git history anyway).
+- **Parity test churn**: +2 tools is a deliberate, reviewed surface change; the parity list update is its own commit trailer line in the implementation commit that adds the tools.
+- **Sentence-boundary detection across scripts**: terminator set must cover Latin/CJK/Arabic punctuation structurally; covered by dedicated multi-script tests.
diff --git a/docs/brainstorm/continuity-hygiene-freshness/plan.md b/docs/brainstorm/continuity-hygiene-freshness/plan.md
new file mode 100644
index 00000000..b3a020a1
--- /dev/null
+++ b/docs/brainstorm/continuity-hygiene-freshness/plan.md
@@ -0,0 +1,75 @@
+# Continuity, Hygiene & Freshness Suite - implementation plan
+
+TDD per task: failing test first, implement, refactor, formatter + linter green before every commit. One conventional commit per task.
+
+## Tasks
+
+### Task 1: Command bridge extraction
+- **Files**: `src/core/reliability/command-bridge.ts` (new), `src/core/bench/judge.ts` (refactor to thin caller), `tests/core/reliability/command-bridge.test.ts` (new)
+- **Acceptance**: existing judge tests pass unchanged; bridge unit tests cover ok / non-zero exit / timeout / malformed JSON / signal kill, all fail-open.
+- **Depends on**: none
+
+### Task 2: Lineage kernel (types, resolve, ledger, crutch)
+- **Files**: `src/core/brain/lineage/types.ts`, `lineage/resolve.ts`, `lineage/ledger.ts`, `lineage/crutch.ts` (all new), `tests/core/brain/lineage.test.ts` (new)
+- **Acceptance**: resolve prefers payload fields (source `payload`); falls back to crutch only on compression evidence + same cwd + bounded window (source `crutch`); otherwise flat (source `flat`). Ledger is append-only JSONL under Brain/state, fail-soft on unreadable state. Every crutch site carries `CRUTCH(t_1459706f)`.
+- **Depends on**: none
+
+### Task 3: Hook payload lineage plumbing (A1, t_d08ccc5a)
+- **Files**: `hooks/lib/stdin.ts`, `src/core/brain/session-lifecycle.ts`, `tests/core/brain/session-lifecycle*.test.ts`
+- **Acceptance**: `HookPayloadBase` exposes optional `parent_session_id` / `root_session_id` / `compression_depth`; lifecycle capture normalizes them, feeds the ledger, and stamps lineage into the audit/log rows; a payload without lineage behaves byte-identically to today.
+- **Depends on**: Task 2
+
+### Task 4: Compression-aware capture & recall (A2, t_a94623ad)
+- **Files**: `src/core/brain/sessions/import.ts`, `src/core/brain/session-recall.ts`, `src/mcp/brain/recall-tools.ts`, session CLI verbs, `tests/core/brain/session-recall*.test.ts`
+- **Acceptance**: imported records carry lineage payload fields; expand/grep/describe over any segment id return turns from the whole lineage; flat sessions regress nothing (characterization test pinned before change); adjacent segments expose a continuity edge (segment list with parent/child ids).
+- **Depends on**: Task 2, Task 3
+
+### Task 5: Degradation ladder (A3, t_05f5dc12)
+- **Files**: `src/core/brain/recall-budget.ts`, `src/core/brain/context-pack.ts`, `src/core/brain/pre-compress-pack.ts`, `src/core/brain/context-presets.ts`, config plumb, `tests/core/brain/recall-budget*.test.ts`
+- **Acceptance**: default = hard cut, byte-identical (characterization test); staged mode degrades sentence-boundary -> line extract -> hard cut, reported per entry; multi-script terminator tests (Latin, CJK) pass; pure and deterministic.
+- **Depends on**: none
+
+### Task 6: Anticipatory context cache (A4, t_4cee9df5)
+- **Files**: `src/core/brain/anticipatory-cache.ts` (new), hook entry wiring, `src/mcp/brain/pack-tools.ts` (`brain_anticipatory_context` lives in the context-pack domain), CLI verb, `tests/core/brain/anticipatory-cache.test.ts`
+- **Acceptance**: refresh debounced by TTL (clock injected), atomic write, keyed by lineage root; read returns warm cache or falls back to live pack with `cache_state` reported; broken cache never propagates an error to the hook.
+- **Depends on**: Task 2
+
+### Task 7: Freshness substrate (B4, t_d9624ef6)
+- **Files**: `src/core/brain/freshness.ts` (new), `src/core/brain/handoff.ts` + `src/core/brain/sessions/import.ts` (sources stamp), `tests/core/brain/freshness.test.ts`
+- **Acceptance**: `sources:` frontmatter contract (path + sha256) documented and stamped by session-derived writers; on-demand check classifies fresh / stale / orphaned; pages without the contract are skipped silently.
+- **Depends on**: none
+
+### Task 8: Hygiene kernel + conflicts & usefulness detectors (B1 core + B3 detection, t_698db8f7 / t_db375a60)
+- **Files**: `src/core/brain/hygiene/types.ts`, `hygiene/scan.ts`, `hygiene/detectors/conflicts.ts`, `hygiene/detectors/usefulness.ts`, `hygiene/detectors/freshness.ts` (wraps the Task 7 substrate as a detector), `tests/core/brain/hygiene-scan.test.ts`
+- **Acceptance**: scan composes detector findings into one frozen digest; conflict detection is deterministic (contradiction classification + `contradicts` relations); usefulness reads recall-telemetry (never-surfaced / always-skipped candidates); freshness findings map stale -> `recompile` and orphaned -> `review` proposed actions; scan is read-only.
+- **Depends on**: Task 7
+
+### Task 9: Dedup detector (B2, t_da3f138f)
+- **Files**: `src/core/brain/hygiene/detectors/dedup.ts`, `tests/core/brain/hygiene-dedup.test.ts`
+- **Acceptance**: embedding-similarity pairs above threshold (default 0.97) reported with evidence; lexical fallback when the provider is null/unavailable, clearly labeled; candidate set bounded before pairwise comparison.
+- **Depends on**: Task 8
+
+### Task 10: Conflict resolution via resolver bridge (B3, t_db375a60)
+- **Files**: `src/core/brain/hygiene/resolve-conflicts.ts`, config key `hygiene.resolver_cmd`, `tests/core/brain/hygiene-resolve.test.ts`
+- **Acceptance**: with resolver configured, verdicts (supersede / merge / flag) validate and attach to findings; without resolver every conflict is `review`; resolver failure is fail-open to `review`.
+- **Depends on**: Task 1, Task 8
+
+### Task 11: Hygiene apply + audit (B1 completion, t_698db8f7)
+- **Files**: `src/core/brain/hygiene/apply.ts`, `hygiene/plan.ts`, `tests/core/brain/hygiene-apply.test.ts`
+- **Acceptance**: apply executes a typed plan selected from scan findings; every action lands an audit record; `--dry-run` previews with zero writes; `forget` archives, never deletes.
+- **Depends on**: Task 8, Task 9, Task 10
+
+### Task 12: Targeted recompile (B5, t_fe490119)
+- **Files**: `src/core/brain/recompile.ts` (new), `tests/core/brain/recompile.test.ts`
+- **Acceptance**: plan lists stale pages with owning-source diffs and orphan cleanups, skipping unrelated pages; dry-run previews with zero writes and zero external calls; execution re-derives via existing import/indexer entry points.
+- **Depends on**: Task 7
+
+### Task 13: Surfaces - MCP tools, CLI verbs, parity list
+- **Files**: `src/mcp/brain/hygiene-tools.ts` (new), `src/mcp/brain-tools.ts`, MCP parity test (+2: `brain_hygiene`, `brain_anticipatory_context`), CLI verbs `hygiene` / `refresh` / `anticipate`, command manifest, completions, help text
+- **Acceptance**: parity test updated deliberately to the new set; CLI verbs route to kernel functions with stable JSON output; `o2b brain refresh --stale --dry-run` works end-to-end on a fixture vault.
+- **Depends on**: Tasks 4, 6, 11, 12
+
+### Task 14: Config keys + docs
+- **Files**: `src/core/brain/policy.ts`, `README.md`, `CHANGELOG.md`, `docs/mcp.md`, `docs/cli-reference.md`, `docs/architecture.md`
+- **Acceptance**: new one-level config blocks parse via the existing YAML subset grammar with defaults documented; docs describe all nine capabilities; CHANGELOG carries one version entry for the whole PR.
+- **Depends on**: Task 13
diff --git a/docs/brainstorm/continuity-hygiene-freshness/variants.md b/docs/brainstorm/continuity-hygiene-freshness/variants.md
new file mode 100644
index 00000000..4532f5f1
--- /dev/null
+++ b/docs/brainstorm/continuity-hygiene-freshness/variants.md
@@ -0,0 +1,47 @@
+# Continuity, Hygiene & Freshness Suite - variants audit trail
+
+Primary consultant: Claude Code (`claude -p`), 2026-06-10. Raw output: `cli-output/claude.md`. Fallback consultant not invoked (primary returned 3 parseable variants).
+
+## Variant 1: Extend-in-place (substrate growth, no new kernels)
+
+- **Approach**: Every feature lands as an extension of the module that already owns the nearest behavior. A1's lineage fields go onto `HookPayloadBase` with the crutch as one file under `hooks/lib/`; A2 extends `session-recall.ts` and capture with optional lineage fields on existing continuity records (additive, no schema bump); A3 grows `applyCharBudget` into a ladder inside `recall-budget.ts`; A4 is one small cache module on existing hook events. Cluster B becomes a single `src/core/brain/hygiene/` domain module that directly calls `reconcile-outcomes.ts`, recall-telemetry readers, the search embeddings registry (B2), and `sourceRefs.hash` comparisons (B4), with B5 as an apply action inside it.
+- **Trade-offs**:
+ - Pro: smallest diff surface; no new abstractions to design or test; follows the existing pattern of pure helpers plus domain modules established in the v1.2.0 decomposition.
+ - Pro: A3 stays a drop-in upgrade for both `context-pack.ts` and `pre-compress-pack.ts` since both already call the same budget primitive.
+ - Con: the hygiene module accretes four unrelated detection concerns (contradiction, usefulness, dedup, freshness) behind one wall; B5's recompile logic entangles hygiene with the import and indexer pipelines.
+ - Con: lineage resolution logic gets duplicated across capture, recall, and the A4 cache unless extracted later anyway; the CRUTCH boundary risks leaking into `session-recall.ts`.
+ - Con: B2's embeddings fallback and B3's resolver bridge each reinvent plumbing (`bench/judge.ts` gets copied rather than shared).
+- **Complexity**: medium
+- **Risk**: medium
+
+## Variant 2: Two shared kernels (lineage resolver plus findings pipeline)
+
+- **Approach**: Introduce exactly two new substrates. First, a `lineage` module (`src/core/brain/lineage/`) exposing `resolveLineage(payload) -> {rootId, parentId, depth}` with the native path reading the extended `HookPayloadBase` and the interim Hermes crutch isolated in one file marked `CRUTCH(t_1459706f)`; capture (A2), recall and session-read tools (A2), and the anticipatory cache key (A4) all consume it, while A3 stays an independent upgrade of `recall-budget.ts`. Second, a `hygiene` module built around a small detector contract: each detector (`dedup` B2, `freshness` B4, `conflicts` B3 wrapping `reconcile-outcomes.ts`, `usefulness` from recall-telemetry) is a pure function returning typed `Finding[]`; `scan` fans out over detectors, `apply` executes a typed remediation plan, B5 is the freshness-findings executor that calls into existing import/indexer entry points, and B3's resolver reuses a shared external-command bridge extracted from `bench/judge.ts`.
+- **Trade-offs**:
+ - Pro: the crutch isolation constraint is satisfied by construction, and lineage semantics live in one place for all three consumers instead of three copies.
+ - Pro: the detector contract matches B1's actual job description (integrate heterogeneous signals into one digest) and makes scan-versus-apply, dry-run, and the audit trail uniform across B2 through B5.
+ - Pro: extracting the judge bridge gives B3 the fail-open external-LLM pattern without duplicating spawn/timeout/JSON plumbing, keeping the deterministic-core rule auditable in one file.
+ - Con: two new abstractions designed up front; the detector interface could be over-fitted if a future detector needs streaming or cross-detector state.
+ - Con: more files and more parity-list churn (new MCP tools and CLI verbs for hygiene, lineage-aware session tools, cache commands) in one release.
+- **Complexity**: medium-large (closest single label: large)
+- **Risk**: low
+
+## Variant 3: Feature-siloed modules composed at the surface
+
+- **Approach**: Each of the nine features ships as its own self-contained module with its own CLI verbs and MCP tools: `lineage/`, `session-stitch/`, `budget-ladder/`, `context-cache/`, `hygiene-scan/`, `dedup/`, `conflict-resolve/`, `freshness/`, `recompile/`. There is no shared detector contract; B1's scan composes by calling the public functions of the sibling modules and concatenating their reports, and B5 calls B4's public freshness API directly. Sharing happens only through already-existing primitives (continuity store, search index, `applyCharBudget`).
+- **Trade-offs**:
+ - Pro: maximally parallelizable development (nine kanban tasks map one-to-one to modules); each module is small, independently testable, and independently revertable if a feature slips the release.
+ - Pro: no speculative abstractions; seams follow the kanban decomposition exactly.
+ - Con: B1 degrades from an integration surface into a report concatenator; consolidate/forget/archive remediation and the audit trail get reimplemented per detector, or apply-mode ends up inconsistent across dedup, freshness, and conflicts.
+ - Con: lineage resolution is still needed by three modules, so either `session-stitch/` and `context-cache/` both depend on `lineage/` (recreating Variant 2's kernel informally) or they duplicate it.
+ - Con: nine new tool surfaces inflate the frozen 54-tool parity list and the 76-verb CLI more than the features warrant, contradicting the recent consolidation direction of the v1.2.0 refactor.
+- **Complexity**: large
+- **Risk**: medium
+
+## Consultant recommendation
+
+Variant 2. "The task's own structure already names the two real seams: A1/A2/A4 share lineage resolution (and the crutch must be isolated in one module regardless, so the kernel costs almost nothing extra), and B1 is explicitly the umbrella through which B2/B3/B4 findings surface, which is precisely a detector-and-plan pipeline. Variant 1 saves little while smearing the crutch and the remediation audit trail across existing modules, and Variant 3 rediscovers both kernels informally while bloating the frozen tool surface. Variant 2 also aligns with the project's current trajectory (v1.2.0 SOLID/DRY domain modules, pure deterministic detectors, the `bench_judge_cmd` fail-open bridge as the sanctioned LLM boundary) and keeps every constraint - no daemon, deterministic core, additive surfaces - enforceable at module boundaries rather than by convention."
+
+## Orchestrator decision
+
+Variant 2, accepted without override. Project context confirms the consultant's reasoning on every point that matters here: the crutch-isolation requirement comes from kanban t_1459706f and is satisfied structurally; the +2 MCP tool delta (`brain_hygiene`, `brain_anticipatory_context`) is the smallest surface among the variants that still ships all nine features; and the detector contract directly reuses the deterministic substrates that already exist (reconcile-outcomes, recall-telemetry, embeddings registry, sourceRefs hashes) instead of wrapping them per-feature.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 8a3d113c..85acec9f 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -114,6 +114,9 @@ o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [
o2b brain session-describe --session-id <id> [--json]
o2b brain session-expand <record-id> [--raw-limit <n>] [--cursor <offset>] [--json]
o2b brain handoff <session-file> [--session-id <id>] [--format auto|claude|codex|hermes] [--json] - write Brain/handoffs/<date>-<scope>.md (since v0.37.0)
+o2b brain hygiene scan | apply --ids <id,...> [--detectors conflicts,dedup,freshness,usefulness] [--dry-run] [--json] - hygiene findings pipeline; review findings never execute (since v1.3.0)
+o2b brain refresh --stale [--dry-run] [--json] - targeted recompile of stale derived pages; orphans archive into Brain/.snapshots (since v1.3.0)
+o2b brain anticipate --session <id> [--refresh] [--signal <text>] [--json] - read or warm the anticipatory context cache for the session's lineage root (since v1.3.0)
o2b brain intention set|show|list|move [--scope S] [--text T] [--json] - scoped current-intention chains under Brain/intentions/ (since v0.37.0)
```
diff --git a/docs/mcp.md b/docs/mcp.md
index 5b889c3f..92d8736f 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -49,6 +49,8 @@ flags for a narrower per-process full server.
| `brain_recall_telemetry` | List or summarise opt-in recall telemetry records for search, context-pack, and pre-compress calls. | `operation` |
| `brain_context_presets` | Show, suggest, or diff read-only context budget presets (`tight-context`, `long-context`) without writing config. | `operation` |
| `brain_pre_compact_extract` | Extract decision/commitment/outcome/rule/open-question records from bounded text into continuity storage. | `session_id`, `turn_start`, `turn_end`, `text` |
+| `brain_hygiene` | Memory hygiene: `scan` findings (conflicts, dedup, freshness, usefulness), `apply` selected ids, `refresh` stale pages. Resolver command comes from `_brain.yaml` only. | `mode` |
+| `brain_anticipatory_context` | Turn-specific context bundle kept warm by lifecycle hooks, keyed by the session's lineage root; reports `cache_state` warm / stale / miss. | `session_id` |
| `brain_session_grep` | Search imported session recall raw turns and deterministic summary nodes. | `query` |
| `brain_session_describe` | Describe raw-turn counts and summary depths for one imported session recall DAG. | `session_id` |
| `brain_session_expand` | Expand a raw or summary session recall node to immediate sources and paginated raw turn content. | `id` |
diff --git a/hooks/lib/stdin.ts b/hooks/lib/stdin.ts
index 43e74c94..cf5fb4c3 100644
--- a/hooks/lib/stdin.ts
+++ b/hooks/lib/stdin.ts
@@ -17,6 +17,19 @@ export async function readHookInput(): Promise<unknown> {
export interface HookPayloadBase {
readonly session_id?: string;
+ /**
+ * Native session-lineage fields (continuity-hygiene-freshness
+ * suite). Hosts that rotate the session id across a context
+ * compression report the predecessor here; upstream Hermes PR
+ * NousResearch/hermes-agent#42940 adds `parent_session_id` to the
+ * shell-hook payload. All optional - a host without lineage simply
+ * omits them and capture degrades to flat-id behavior.
+ */
+ readonly parent_session_id?: string | null;
+ readonly root_session_id?: string | null;
+ readonly compression_depth?: number | null;
+ /** SessionStart discriminator (`startup|resume|clear|compact`). */
+ readonly source?: string;
readonly transcript_path?: string | null;
readonly cwd?: string;
readonly hook_event_name?: string;
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 97ee6791..795b2542 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.2.0",
+ "version": "1.3.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index c47dc577..c7e08948 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.2.0",
+ "version": "1.3.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index eac2abdd..503c2324 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.2.0"
+version: "1.3.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index ff04e261..2af94d4a 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.2.0",
+ "version": "1.3.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index eac2abdd..503c2324 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.2.0"
+version: "1.3.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index fa6fac47..01e59e88 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.2.0"
+version = "1.3.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.ts b/src/cli/brain.ts
index fe8f3e43..0fb9039f 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -29,6 +29,9 @@ import {
cmdBrainUnprotect,
cmdBrainRollback,
cmdBrainDoctor,
+ cmdBrainHygiene,
+ cmdBrainRefresh,
+ cmdBrainAnticipate,
cmdBrainWatchdog,
cmdBrainHealth,
cmdBrainHistory,
@@ -172,6 +175,12 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainRollback(rest);
case "doctor":
return await cmdBrainDoctor(rest);
+ case "hygiene":
+ return await cmdBrainHygiene(rest);
+ case "refresh":
+ return await cmdBrainRefresh(rest);
+ case "anticipate":
+ return await cmdBrainAnticipate(rest);
case "watchdog":
return await cmdBrainWatchdog(rest);
case "health":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 56039997..bd628bf7 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -36,6 +36,9 @@ Brain verbs (observing memory):
rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;
--dry-run previews via the same diff renderer)
doctor Validate Brain invariants (--strict; --remediate [--dry-run])
+ hygiene Hygiene pipeline: scan findings; apply by ids (--dry-run)
+ refresh Targeted recompile of stale derived pages (--stale [--dry-run])
+ anticipate Inspect or refresh the anticipatory context cache (--session)
watchdog Probe Brain health and plan safe recovery (--remediate, --restore, --force-restore)
health Semantic-health report: contradictions, concept gaps, stale claims
history Render a preference's edit-history timeline
@@ -205,6 +208,24 @@ export const VERB_HELP: Record<string, string> = {
" [--vault <path>] [--json]\n" +
"Read-only diff between two snapshots, or between a snapshot and\n" +
"the live Brain/ tree (when <run_id_b> is omitted).\n",
+ hygiene:
+ "usage: o2b brain hygiene <scan|apply> [--vault <path>] [--json]\n" +
+ " [--detectors conflicts,dedup,freshness,usefulness]\n" +
+ " [--ids <finding-id,...>] [--dry-run]\n" +
+ "Scan is read-only: contested truth slots, near-duplicate preferences,\n" +
+ "stale/orphaned derived pages, low-usefulness candidates. Apply executes\n" +
+ "only explicitly selected finding ids; review findings never execute.\n" +
+ "The conflict resolver command comes from _brain.yaml (hygiene.resolver_cmd).\n",
+ refresh:
+ "usage: o2b brain refresh --stale [--vault <path>] [--dry-run] [--json]\n" +
+ "Targeted recompile: re-derive stale pages from their recorded sources\n" +
+ "(handoff notes re-derive in place), archive orphans into Brain/.snapshots,\n" +
+ "report unknown pipelines as manual. --dry-run previews with zero writes.\n",
+ anticipate:
+ "usage: o2b brain anticipate --session <id> [--refresh] [--signal <text>]\n" +
+ " [--vault <path>] [--json]\n" +
+ "Read the anticipatory context cache for the session's lineage root\n" +
+ "(warm | stale | miss), or force a refresh first (TTL debounce applies).\n",
doctor:
"usage: o2b brain doctor [--vault <path>] [--json] [--strict]\n" +
" [--remediate [--dry-run]]\n" +
diff --git a/src/cli/brain/verbs/anticipate.ts b/src/cli/brain/verbs/anticipate.ts
new file mode 100644
index 00000000..1275c216
--- /dev/null
+++ b/src/cli/brain/verbs/anticipate.ts
@@ -0,0 +1,76 @@
+/**
+ * `o2b brain anticipate` - inspect or refresh the anticipatory
+ * context cache (continuity-hygiene-freshness suite).
+ *
+ * o2b brain anticipate --session <id> [--refresh] [--signal <text>] [--json]
+ *
+ * Reads the warm cache for the session's lineage root (or a live
+ * fallback) and reports `cache_state`. `--refresh` forces a refresh
+ * first; the TTL debounce still applies.
+ */
+
+import {
+ readAnticipatoryContext,
+ refreshAnticipatoryCache,
+} from "../../../core/brain/anticipatory-cache.ts";
+import { loadBrainConfig } from "../../../core/brain/policy.ts";
+import { brainVerbContext, fail, parse } from "../helpers.ts";
+
+export async function cmdBrainAnticipate(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ session: { type: "string" },
+ refresh: { type: "boolean" },
+ signal: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const sessionId = flags["session"] as string | undefined;
+ if (sessionId === undefined || sessionId.trim() === "") {
+ return fail("usage: o2b brain anticipate --session <id> [--refresh] [--signal <text>]");
+ }
+ const { vault } = brainVerbContext(flags);
+
+ let ttlSeconds: number | undefined;
+ let maxTokens: number | undefined;
+ try {
+ const anticipatory = loadBrainConfig(vault).anticipatory;
+ ttlSeconds = anticipatory?.ttl_seconds;
+ maxTokens = anticipatory?.max_tokens;
+ } catch {
+ // defaults apply
+ }
+ const now = new Date();
+ if (flags["refresh"]) {
+ const signal = flags["signal"] as string | undefined;
+ refreshAnticipatoryCache(vault, {
+ sessionId,
+ ...(signal !== undefined && signal.trim() !== "" ? { signalText: signal } : {}),
+ now,
+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
+ });
+ }
+ const result = readAnticipatoryContext(vault, {
+ sessionId,
+ now,
+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
+ });
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
+ return 0;
+ }
+ process.stdout.write(
+ `cache: ${result.cache_state} (root ${result.root_session_id}${
+ result.generated_at !== undefined ? `, generated ${result.generated_at}` : ""
+ })\n`,
+ );
+ process.stdout.write(
+ `items: ${result.context.items.length}, session hits: ${result.context.session_hits.length}\n`,
+ );
+ for (const item of result.context.items) {
+ process.stdout.write(`- [${item.tier}] ${item.id} (${item.tokens} tokens)\n`);
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/hygiene.ts b/src/cli/brain/verbs/hygiene.ts
new file mode 100644
index 00000000..c779c8ad
--- /dev/null
+++ b/src/cli/brain/verbs/hygiene.ts
@@ -0,0 +1,142 @@
+/**
+ * `o2b brain hygiene` - scan / apply over the hygiene findings
+ * pipeline (continuity-hygiene-freshness suite).
+ *
+ * o2b brain hygiene scan [--detectors a,b] [--json]
+ * o2b brain hygiene apply --ids id1,id2 [--dry-run] [--json]
+ *
+ * Scan is read-only; apply executes only explicitly selected finding
+ * ids, and review findings never execute. The conflict resolver
+ * command comes from `_brain.yaml` (`hygiene.resolver_cmd`) only.
+ */
+
+import { applyHygienePlan } from "../../../core/brain/hygiene/apply.ts";
+import { buildHygienePlan } from "../../../core/brain/hygiene/plan.ts";
+import { resolveConflictFindings } from "../../../core/brain/hygiene/resolve-conflicts.ts";
+import { runHygieneScan } from "../../../core/brain/hygiene/scan.ts";
+import {
+ isHygieneDetectorId,
+ type HygieneDetectorId,
+ type HygieneScanReport,
+} from "../../../core/brain/hygiene/types.ts";
+import { loadBrainConfig } from "../../../core/brain/policy.ts";
+import { brainVerbContext, fail, parse, resolveBrainAgent } from "../helpers.ts";
+
+function parseDetectors(raw: string | undefined): HygieneDetectorId[] | undefined {
+ if (raw === undefined || raw.trim() === "") return undefined;
+ const parts = raw.split(",").map((part) => part.trim());
+ const detectors = parts.filter(isHygieneDetectorId);
+ if (detectors.length !== parts.length) {
+ throw new Error("--detectors entries must be: conflicts, dedup, freshness, usefulness");
+ }
+ return detectors;
+}
+
+function scanReport(vault: string, detectors: HygieneDetectorId[] | undefined): HygieneScanReport {
+ const report = runHygieneScan(vault, {
+ ...(detectors !== undefined && detectors.length > 0 ? { detectors } : {}),
+ now: new Date(),
+ });
+ let resolverCmd: string | undefined;
+ try {
+ resolverCmd = loadBrainConfig(vault).hygiene?.resolver_cmd;
+ } catch {
+ resolverCmd = undefined;
+ }
+ if (resolverCmd === undefined) return report;
+ return Object.freeze({
+ ...report,
+ findings: resolveConflictFindings(vault, report.findings, { resolverCmd }),
+ });
+}
+
+export async function cmdBrainHygiene(argv: string[]): Promise<number> {
+ const sub = argv[0];
+ if (sub !== "scan" && sub !== "apply") {
+ return fail("usage: o2b brain hygiene <scan|apply> [options]");
+ }
+ const { flags } = parse(argv.slice(1), {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ detectors: { type: "string" },
+ ids: { type: "string" },
+ "dry-run": { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+
+ let detectors: HygieneDetectorId[] | undefined;
+ try {
+ detectors = parseDetectors(flags["detectors"] as string | undefined);
+ } catch (exc) {
+ return fail((exc as Error).message);
+ }
+
+ let report: HygieneScanReport;
+ try {
+ report = scanReport(vault, detectors);
+ } catch (exc) {
+ return fail(`hygiene scan failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (sub === "scan") {
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
+ return 0;
+ }
+ process.stdout.write(`Hygiene scan @ ${report.generated_at}\n`);
+ for (const [detector, count] of Object.entries(report.counts)) {
+ process.stdout.write(` ${detector}: ${count} finding(s)\n`);
+ }
+ for (const finding of report.findings) {
+ process.stdout.write(
+ `- [${finding.detector}] ${finding.id} -> ${finding.proposed_action}\n ${finding.title}\n`,
+ );
+ }
+ for (const error of report.errors) {
+ process.stdout.write(`! ${error.detector}: ${error.message}\n`);
+ }
+ return 0;
+ }
+
+ const idsRaw = flags["ids"] as string | undefined;
+ const ids = idsRaw
+ ?.split(",")
+ .map((id) => id.trim())
+ .filter((id) => id.length > 0);
+ if (ids === undefined || ids.length === 0) {
+ return fail("apply requires --ids <finding-id,...> from a prior scan");
+ }
+ const plan = buildHygienePlan(report, { ids });
+ let result;
+ try {
+ result = await applyHygienePlan(vault, plan, {
+ dryRun: Boolean(flags["dry-run"]),
+ agent: resolveBrainAgent(flags, config),
+ now: new Date(),
+ });
+ } catch (exc) {
+ return fail(`hygiene apply failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ plan, result }, null, 2) + "\n");
+ return result.errors.length === 0 ? 0 : 1;
+ }
+ for (const action of result.planned) {
+ process.stdout.write(`would ${action.action}: ${action.detail} (${action.finding_id})\n`);
+ }
+ for (const action of result.applied) {
+ process.stdout.write(`${action.action}: ${action.detail} (${action.finding_id})\n`);
+ }
+ for (const id of plan.excluded_review) {
+ process.stdout.write(`skipped review-only finding ${id}\n`);
+ }
+ for (const id of plan.unknown_ids) {
+ process.stdout.write(`unknown finding id ${id}\n`);
+ }
+ for (const error of result.errors) {
+ process.stdout.write(`error on ${error.finding_id}: ${error.message}\n`);
+ }
+ return result.errors.length === 0 ? 0 : 1;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index ba43f619..055c5bd4 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -97,3 +97,6 @@ export { cmdBrainEvolution } from "./temporal-evolution.ts";
export { cmdBrainStale } from "./temporal-stale.ts";
export { cmdBrainDaily } from "./temporal-daily.ts";
export { cmdBrainWeekly } from "./temporal-weekly.ts";
+export { cmdBrainHygiene } from "./hygiene.ts";
+export { cmdBrainRefresh } from "./refresh.ts";
+export { cmdBrainAnticipate } from "./anticipate.ts";
diff --git a/src/cli/brain/verbs/refresh.ts b/src/cli/brain/verbs/refresh.ts
new file mode 100644
index 00000000..350f6b06
--- /dev/null
+++ b/src/cli/brain/verbs/refresh.ts
@@ -0,0 +1,65 @@
+/**
+ * `o2b brain refresh` - targeted recompile of stale derived pages
+ * (continuity-hygiene-freshness suite).
+ *
+ * o2b brain refresh --stale [--dry-run] [--json]
+ *
+ * Re-derives only pages whose recorded sources changed (handoff notes
+ * re-derive in place from their transcript), stages orphan cleanup
+ * into Brain/.snapshots, and leaves unknown pipelines as `manual`.
+ * `--dry-run` previews the plan with zero writes.
+ */
+
+import { executeRecompile, planRecompile } from "../../../core/brain/recompile.ts";
+import { brainVerbContext, fail, parse, resolveBrainAgent } from "../helpers.ts";
+
+export async function cmdBrainRefresh(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ stale: { type: "boolean" },
+ "dry-run": { type: "boolean" },
+ json: { type: "boolean" },
+ });
+ if (!flags["stale"]) {
+ return fail("usage: o2b brain refresh --stale [--dry-run] [--json]");
+ }
+ const { config, vault } = brainVerbContext(flags);
+
+ let plan;
+ let result;
+ try {
+ plan = planRecompile(vault);
+ result = await executeRecompile(vault, plan, {
+ dryRun: Boolean(flags["dry-run"]),
+ agent: resolveBrainAgent(flags, config),
+ now: new Date(),
+ });
+ } catch (exc) {
+ return fail(`refresh failed: ${(exc as Error).message ?? exc}`);
+ }
+
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify({ plan, result }, null, 2) + "\n");
+ return result.errors.length === 0 ? 0 : 1;
+ }
+
+ if (plan.entries.length === 0) {
+ process.stdout.write("nothing to refresh: every tracked page is fresh\n");
+ return 0;
+ }
+ for (const entry of plan.entries) {
+ process.stdout.write(`${entry.kind}: ${entry.page}\n ${entry.reason}\n`);
+ }
+ if (result.dry_run) {
+ process.stdout.write(`dry run: ${plan.entries.length} entr(y/ies) planned, nothing written\n`);
+ return 0;
+ }
+ process.stdout.write(
+ `rederived ${result.rederived.length}, archived ${result.archived.length}, manual ${result.manual.length}\n`,
+ );
+ for (const error of result.errors) {
+ process.stdout.write(`error on ${error.page}: ${error.message}\n`);
+ }
+ return result.errors.length === 0 ? 0 : 1;
+}
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
index 43025b0c..47096bad 100644
--- a/src/cli/command-manifest.ts
+++ b/src/cli/command-manifest.ts
@@ -113,6 +113,9 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
command("export", "Export active preferences"),
command("explorer", "Open or export Brain graph explorer"),
command("doctor", "Check Brain invariants"),
+ command("hygiene", "Hygiene pipeline: scan findings, apply remediation plan"),
+ command("refresh", "Targeted recompile of stale derived pages"),
+ command("anticipate", "Inspect or refresh the anticipatory context cache"),
command("watchdog", "Probe Brain recovery status"),
command("health", "Render semantic Brain health"),
command("history", "Render preference edit history"),
diff --git a/src/core/bench/judge.ts b/src/core/bench/judge.ts
index a9483af1..e3249f1e 100644
--- a/src/core/bench/judge.ts
+++ b/src/core/bench/judge.ts
@@ -10,9 +10,13 @@
* verdicts land in the report for comparison. Absent config means the
* judge phase is skipped and marked as such; a failing command marks
* `error` without failing the run (fail-open, like all telemetry).
+ *
+ * Spawn/timeout/JSON plumbing lives in the shared
+ * `runJsonCommandBridge` (reliability/command-bridge.ts); this module
+ * keeps only the verdict-shape validation.
*/
-import { spawnSync } from "node:child_process";
+import { runJsonCommandBridge } from "../reliability/command-bridge.ts";
import type { BenchQuestionResult, BenchReport } from "./types.ts";
@@ -26,29 +30,18 @@ export function runJudge(
cmd: string | undefined,
questions: ReadonlyArray<BenchQuestionResult>,
): JudgeOutcome {
- if (cmd === undefined || cmd.trim() === "") return Object.freeze({ status: "skipped" });
- try {
- const proc = spawnSync("sh", ["-c", cmd], {
- input: JSON.stringify({ questions }),
- encoding: "utf8",
- timeout: 60_000,
- });
- if (proc.status !== 0) {
- return Object.freeze({
- status: "error",
- detail: `judge command exited ${proc.status ?? "by signal"}`,
- });
- }
- const parsed = JSON.parse(proc.stdout) as { verdicts?: Record<string, unknown> };
- const verdicts: Record<string, boolean> = {};
- for (const [id, value] of Object.entries(parsed.verdicts ?? {})) {
- if (typeof value === "boolean") verdicts[id] = value;
- }
- return Object.freeze({ status: "ran", verdicts: Object.freeze(verdicts) });
- } catch (error) {
- return Object.freeze({
- status: "error",
- detail: error instanceof Error ? error.message : "judge command failed",
- });
+ const result = runJsonCommandBridge(cmd, { questions }, { label: "judge command" });
+ if (result.status === "skipped") return Object.freeze({ status: "skipped" });
+ if (result.status === "error") {
+ return Object.freeze({ status: "error", detail: result.detail });
+ }
+ if (result.output === null || typeof result.output !== "object") {
+ return Object.freeze({ status: "error", detail: "judge output is not an object" });
+ }
+ const parsed = result.output as { verdicts?: Record<string, unknown> };
+ const verdicts: Record<string, boolean> = {};
+ for (const [id, value] of Object.entries(parsed.verdicts ?? {})) {
+ if (typeof value === "boolean") verdicts[id] = value;
}
+ return Object.freeze({ status: "ran", verdicts: Object.freeze(verdicts) });
}
diff --git a/src/core/brain/anticipatory-cache.ts b/src/core/brain/anticipatory-cache.ts
new file mode 100644
index 00000000..fb991448
--- /dev/null
+++ b/src/core/brain/anticipatory-cache.ts
@@ -0,0 +1,239 @@
+/**
+ * Anticipatory Brain context cache
+ * (continuity-hygiene-freshness suite; kanban t_4cee9df5).
+ *
+ * Prepare the next turn's memory evidence while the agent is still
+ * working, instead of waiting for an explicit search. Lifecycle hook
+ * events (prompt submit, tool use) refresh a small context bundle -
+ * the active context pack plus session-recall hits for the latest
+ * signal text - debounced by a TTL with an injected clock, written
+ * atomically under `Brain/.state/anticipatory/`, and keyed by the
+ * session's lineage root so one conversation keeps one cache across
+ * compression boundaries.
+ *
+ * Hard constraints honored here: NO daemon and NO file watcher
+ * (refresh piggybacks on events that already fire), and fail-soft
+ * everywhere - a broken cache is a miss, never an error that could
+ * block a hook.
+ */
+
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { join, posix } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { packContext, type ContextPackItem } from "./context-pack.ts";
+import { readLineageLedger } from "./lineage/ledger.ts";
+import { resolveSessionLineage } from "./lineage/resolve.ts";
+import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";
+import { searchSessionRecall, type SessionRecallHit } from "./session-recall.ts";
+
+export const ANTICIPATORY_SCHEMA_VERSION = "o2b.anticipatory.v1";
+
+/** Default debounce/freshness window. */
+export const DEFAULT_ANTICIPATORY_TTL_SECONDS = 120;
+/** Default token budget for the cached context pack. */
+export const DEFAULT_ANTICIPATORY_MAX_TOKENS = 2_000;
+const DEFAULT_SESSION_HITS = 5;
+
+const CACHE_DIR_REL = posix.join(BRAIN_ROOT_REL, ".state", "anticipatory");
+
+export interface AnticipatoryContext {
+ readonly items: ReadonlyArray<ContextPackItem>;
+ readonly session_hits: ReadonlyArray<SessionRecallHit>;
+}
+
+export interface RefreshAnticipatoryCacheInput {
+ readonly sessionId: string;
+ /** Latest user-visible signal (prompt text) steering the bundle. */
+ readonly signalText?: string;
+ /** Injected clock - hooks pass their event time. */
+ readonly now: Date;
+ readonly ttlSeconds?: number;
+ readonly maxTokens?: number;
+}
+
+export interface RefreshAnticipatoryCacheResult {
+ readonly refreshed: boolean;
+ readonly rootSessionId: string;
+ readonly path: string;
+}
+
+export type AnticipatoryCacheState = "warm" | "stale" | "miss";
+
+export interface ReadAnticipatoryContextInput {
+ readonly sessionId: string;
+ readonly now: Date;
+ readonly ttlSeconds?: number;
+ readonly maxTokens?: number;
+}
+
+export interface ReadAnticipatoryContextResult {
+ readonly cache_state: AnticipatoryCacheState;
+ readonly root_session_id: string;
+ /** Stamp of the cache that answered (warm reads only). */
+ readonly generated_at?: string;
+ readonly context: AnticipatoryContext;
+}
+
+interface CacheFile {
+ readonly schema: string;
+ readonly root_session_id: string;
+ readonly session_id: string;
+ readonly generated_at: string;
+ /** Token budget the cached pack was built under (variant field). */
+ readonly max_tokens: number;
+ readonly signal?: string;
+ readonly context: AnticipatoryContext;
+}
+
+/**
+ * Collision-resistant flat filename for any root id: a readable
+ * sanitized prefix plus a content digest, so distinct roots that
+ * sanitize identically (`a/b` vs `a:b`) or differ only past the
+ * prefix never share a cache file.
+ */
+function safeCacheKey(rootId: string): string {
+ const prefix = rootId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 80) || "_";
+ const digest = createHash("sha256").update(rootId).digest("hex").slice(0, 16);
+ return `${prefix}-${digest}`;
+}
+
+export function anticipatoryCachePath(vault: string, rootSessionId: string): string {
+ return ensureInsideVault(
+ join(vault, CACHE_DIR_REL, `${safeCacheKey(rootSessionId)}.json`),
+ vault,
+ );
+}
+
+function resolveRootId(vault: string, sessionId: string): string {
+ try {
+ return resolveSessionLineage({ sessionId }, { ledger: readLineageLedger(vault) }).rootId;
+ } catch {
+ return sessionId;
+ }
+}
+
+function readCacheFile(path: string): CacheFile | null {
+ if (!existsSync(path)) return null;
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as unknown;
+ if (parsed === null || typeof parsed !== "object") return null;
+ const cache = parsed as CacheFile;
+ if (cache.schema !== ANTICIPATORY_SCHEMA_VERSION) return null;
+ if (typeof cache.generated_at !== "string") return null;
+ if (typeof cache.max_tokens !== "number") return null;
+ if (cache.context === null || typeof cache.context !== "object") return null;
+ if (!Array.isArray(cache.context.items) || !Array.isArray(cache.context.session_hits)) {
+ return null;
+ }
+ return cache;
+ } catch {
+ return null; // corrupt cache reads as a miss by contract
+ }
+}
+
+function buildContext(
+ vault: string,
+ sessionId: string,
+ signalText: string | undefined,
+ maxTokens: number,
+): AnticipatoryContext {
+ const pack = packContext(vault, { maxTokens });
+ const signal = signalText?.trim() ?? "";
+ const hits =
+ signal.length > 0
+ ? searchSessionRecall(vault, { query: signal, sessionId, limit: DEFAULT_SESSION_HITS }).hits
+ : Object.freeze([] as SessionRecallHit[]);
+ return Object.freeze({ items: pack.items, session_hits: hits });
+}
+
+/**
+ * Refresh the cache for the session's lineage root unless a fresh copy
+ * already exists (TTL debounce). Never throws.
+ */
+export function refreshAnticipatoryCache(
+ vault: string,
+ input: RefreshAnticipatoryCacheInput,
+): RefreshAnticipatoryCacheResult {
+ const rootId = resolveRootId(vault, input.sessionId);
+ const path = anticipatoryCachePath(vault, rootId);
+ const ttlMs = (input.ttlSeconds ?? DEFAULT_ANTICIPATORY_TTL_SECONDS) * 1_000;
+ const maxTokens = input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS;
+ try {
+ const existing = readCacheFile(path);
+ // TTL debounce applies only to a cache built under the same token
+ // budget; a budget change always rebuilds. The signal text is
+ // deliberately NOT part of the cache identity - it changes every
+ // prompt, and invalidating on it would defeat the debounce that
+ // makes hook-driven refresh affordable.
+ if (existing !== null && existing.max_tokens === maxTokens) {
+ const age = input.now.getTime() - Date.parse(existing.generated_at);
+ if (Number.isFinite(age) && age >= 0 && age < ttlMs) {
+ return Object.freeze({ refreshed: false, rootSessionId: rootId, path });
+ }
+ }
+ const context = buildContext(vault, input.sessionId, input.signalText, maxTokens);
+ const signal = input.signalText?.trim();
+ const cache: CacheFile = {
+ schema: ANTICIPATORY_SCHEMA_VERSION,
+ root_session_id: rootId,
+ session_id: input.sessionId,
+ generated_at: input.now.toISOString(),
+ max_tokens: maxTokens,
+ ...(signal !== undefined && signal.length > 0 ? { signal } : {}),
+ context,
+ };
+ mkdirSync(join(vault, CACHE_DIR_REL), { recursive: true });
+ atomicWriteFileSync(path, `${JSON.stringify(cache, null, 2)}\n`);
+ return Object.freeze({ refreshed: true, rootSessionId: rootId, path });
+ } catch {
+ return Object.freeze({ refreshed: false, rootSessionId: rootId, path });
+ }
+}
+
+/**
+ * Read the warm cache for the session's lineage root, falling back to
+ * a live bundle on miss or staleness. Never throws.
+ */
+export function readAnticipatoryContext(
+ vault: string,
+ input: ReadAnticipatoryContextInput,
+): ReadAnticipatoryContextResult {
+ const rootId = resolveRootId(vault, input.sessionId);
+ const path = anticipatoryCachePath(vault, rootId);
+ const ttlMs = (input.ttlSeconds ?? DEFAULT_ANTICIPATORY_TTL_SECONDS) * 1_000;
+ const requestedTokens = input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS;
+ const cached = readCacheFile(path);
+ if (cached !== null) {
+ const age = input.now.getTime() - Date.parse(cached.generated_at);
+ if (cached.max_tokens === requestedTokens && Number.isFinite(age) && age >= 0 && age < ttlMs) {
+ return Object.freeze({
+ cache_state: "warm" as const,
+ root_session_id: rootId,
+ generated_at: cached.generated_at,
+ context: cached.context,
+ });
+ }
+ return Object.freeze({
+ cache_state: "stale" as const,
+ root_session_id: rootId,
+ context: buildContext(
+ vault,
+ input.sessionId,
+ cached.signal,
+ input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS,
+ ),
+ });
+ }
+ return Object.freeze({
+ cache_state: "miss" as const,
+ root_session_id: rootId,
+ context: buildContext(
+ vault,
+ input.sessionId,
+ undefined,
+ input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS,
+ ),
+ });
+}
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index 430de204..b74efa51 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -26,7 +26,7 @@ import { brainDirs } from "./paths.ts";
import { PAGE_TIER, readTier, type PageTier } from "./page-meta/tier.ts";
import { estimateTokens } from "./text/tokenizer.ts";
import { normalizeForDedup } from "./text/normalize.ts";
-import { applyCharBudget } from "./recall-budget.ts";
+import { applyCharBudget, type CharBudgetDegradationMode } from "./recall-budget.ts";
import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
import { emitGatedTelemetry } from "./continuity/emit.ts";
import { emitRecallTelemetry, type RecallTelemetryOptions } from "./recall-telemetry.ts";
@@ -101,6 +101,12 @@ export interface ContextPackOptions {
* `over-char-budget` skip reason. <= 0 / undefined disables.
*/
readonly maxTotalChars?: number;
+ /**
+ * Per-memory trim strategy (continuity-hygiene-freshness suite):
+ * `staged` degrades an over-budget body at structural boundaries
+ * instead of cutting mid-sentence. Default keeps the hard cut.
+ */
+ readonly degradation?: CharBudgetDegradationMode;
/** Opt-in polarity-aware lanes. Omitted preserves the legacy flat output shape. */
readonly includeLanes?: boolean;
/** Opt-in audit receipt for the final emitted context. */
@@ -263,7 +269,10 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
// so the token budget charges the emitted text, not the original.
const budgeted = applyCharBudget(
candidates.map((c) => ({ item: c, text: c.body })),
- { maxCharsPerEntry: opts.maxCharsPerMemory },
+ {
+ maxCharsPerEntry: opts.maxCharsPerMemory,
+ ...(opts.degradation !== undefined ? { degradation: opts.degradation } : {}),
+ },
);
const items: ContextPackItem[] = [];
diff --git a/src/core/brain/freshness.ts b/src/core/brain/freshness.ts
new file mode 100644
index 00000000..c43e4197
--- /dev/null
+++ b/src/core/brain/freshness.ts
@@ -0,0 +1,202 @@
+/**
+ * Source-freshness substrate
+ * (continuity-hygiene-freshness suite; kanban t_d9624ef6).
+ *
+ * Pages derived from on-disk artifacts (session transcripts, ingested
+ * documents) record their provenance in frontmatter at derivation
+ * time: `source_paths` (vault-relative or absolute paths) and the
+ * parallel `source_hashes` (sha256 of each source's content, or the
+ * literal `missing` marker). Freshness is then computable on demand -
+ * no background jobs, no watcher:
+ *
+ * - `fresh`: every recorded source still hashes the same;
+ * - `stale`: at least one source changed (or some, but not all,
+ * disappeared);
+ * - `orphaned`: every recorded source is gone.
+ *
+ * The truth lives on the page itself, so freshness survives search
+ * index rebuilds and stays inspectable in the vault. Pages without the
+ * contract are skipped silently; a malformed contract (length
+ * mismatch) is reported, never thrown.
+ */
+
+import { createHash } from "node:crypto";
+import { existsSync, readFileSync } from "node:fs";
+import { isAbsolute, join } from "node:path";
+
+import { listVaultPages, parseFrontmatter } from "../vault.ts";
+
+/** Hash value recorded for a source that did not exist at derivation. */
+export const MISSING_SOURCE_HASH = "missing";
+/** Sentinel for a source that exists but cannot be read right now. */
+export const UNREADABLE_SOURCE_HASH = "unreadable";
+
+export interface SourceStamp {
+ readonly source_paths: ReadonlyArray<string>;
+ readonly source_hashes: ReadonlyArray<string>;
+}
+
+export type FreshnessStatus = "fresh" | "stale" | "orphaned";
+
+export interface PageFreshness {
+ readonly page: string;
+ readonly status: FreshnessStatus;
+ /** Sources whose current content hash differs from the recorded one. */
+ readonly changed_sources: ReadonlyArray<string>;
+ /** Recorded sources that no longer exist. */
+ readonly missing_sources: ReadonlyArray<string>;
+ /** Sources that exist but could not be read (transient I/O). */
+ readonly unreadable_sources: ReadonlyArray<string>;
+}
+
+export interface FreshnessReport {
+ readonly pages_checked: number;
+ readonly with_contract: number;
+ readonly fresh: number;
+ readonly stale: ReadonlyArray<PageFreshness>;
+ readonly orphaned: ReadonlyArray<string>;
+ /** Pages whose contract is malformed (array length mismatch). */
+ readonly invalid_contract: ReadonlyArray<string>;
+}
+
+function sha256(content: string): string {
+ return createHash("sha256").update(content).digest("hex");
+}
+
+function resolveSourcePath(vault: string, source: string): string {
+ return isAbsolute(source) ? source : join(vault, source);
+}
+
+function hashSource(vault: string, source: string): string {
+ const path = resolveSourcePath(vault, source);
+ try {
+ if (!existsSync(path)) return MISSING_SOURCE_HASH;
+ return sha256(readFileSync(path, "utf8"));
+ } catch {
+ // A transient permission / I/O failure is NOT a deleted source -
+ // it must never feed orphan detection (and the cleanup/archive
+ // path behind it).
+ return UNREADABLE_SOURCE_HASH;
+ }
+}
+
+/**
+ * Build the provenance stamp a derived-page writer records at
+ * derivation time. Missing sources stamp the `missing` marker instead
+ * of throwing, so a writer never fails on provenance bookkeeping.
+ */
+export function computeSourceStamp(vault: string, sources: ReadonlyArray<string>): SourceStamp {
+ return Object.freeze({
+ source_paths: Object.freeze([...sources]),
+ source_hashes: Object.freeze(sources.map((source) => hashSource(vault, source))),
+ });
+}
+
+/**
+ * Render the stamp as frontmatter lines (no surrounding `---`),
+ * matching the flat inline-array grammar `parseFrontmatter` reads
+ * back. Paths are JSON-quoted so YAML-significant characters in a
+ * filename cannot break or inject frontmatter fields.
+ */
+export function formatSourceStampFrontmatter(stamp: SourceStamp): string {
+ const paths = stamp.source_paths.map((p) => JSON.stringify(p)).join(", ");
+ const hashes = stamp.source_hashes.map((h) => JSON.stringify(h)).join(", ");
+ return `source_paths: [${paths}]\nsource_hashes: [${hashes}]`;
+}
+
+function readContract(meta: Record<string, unknown>): SourceStamp | "absent" | "invalid" {
+ const paths = meta["source_paths"];
+ const hashes = meta["source_hashes"];
+ if (paths === undefined && hashes === undefined) return "absent";
+ if (!Array.isArray(paths) || !Array.isArray(hashes)) return "invalid";
+ if (paths.length === 0 || paths.length !== hashes.length) return "invalid";
+ if (![...paths, ...hashes].every((value) => typeof value === "string")) return "invalid";
+ return Object.freeze({
+ source_paths: Object.freeze(paths as string[]),
+ source_hashes: Object.freeze(hashes as string[]),
+ });
+}
+
+/**
+ * Compute one page's freshness from its recorded contract. Returns
+ * `null` when the page carries no contract (or a malformed one) -
+ * callers that need the distinction use {@link scanFreshness}.
+ */
+export function checkPageFreshness(vault: string, pagePath: string): PageFreshness | null {
+ const [meta] = parseFrontmatter(pagePath);
+ const contract = readContract(meta);
+ if (contract === "absent" || contract === "invalid") return null;
+ return freshnessOf(vault, pagePath, contract);
+}
+
+function freshnessOf(vault: string, pagePath: string, contract: SourceStamp): PageFreshness {
+ const changed: string[] = [];
+ const missing: string[] = [];
+ const unreadable: string[] = [];
+ for (let i = 0; i < contract.source_paths.length; i++) {
+ const source = contract.source_paths[i]!;
+ const recorded = contract.source_hashes[i]!;
+ const current = hashSource(vault, source);
+ if (current === MISSING_SOURCE_HASH) {
+ // Gone is gone - even a source that was already missing at
+ // derivation leaves the page without a living origin.
+ missing.push(source);
+ continue;
+ }
+ if (current === UNREADABLE_SOURCE_HASH) {
+ // Cannot verify right now: report it, classify the page stale at
+ // worst, and keep it OUT of orphan detection.
+ unreadable.push(source);
+ continue;
+ }
+ if (current !== recorded) changed.push(source);
+ }
+ const status: FreshnessStatus =
+ missing.length === contract.source_paths.length
+ ? "orphaned"
+ : changed.length > 0 || missing.length > 0 || unreadable.length > 0
+ ? "stale"
+ : "fresh";
+ return Object.freeze({
+ page: pagePath,
+ status,
+ changed_sources: Object.freeze(changed),
+ missing_sources: Object.freeze(missing),
+ unreadable_sources: Object.freeze(unreadable),
+ });
+}
+
+/**
+ * Walk every markdown page in the vault and classify the ones carrying
+ * the contract. On-demand and read-only.
+ */
+export function scanFreshness(vault: string): FreshnessReport {
+ const pages = listVaultPages(vault);
+ let withContract = 0;
+ let fresh = 0;
+ const stale: PageFreshness[] = [];
+ const orphaned: string[] = [];
+ const invalid: string[] = [];
+ for (const page of pages) {
+ const [meta] = parseFrontmatter(page.path);
+ const contract = readContract(meta);
+ if (contract === "absent") continue;
+ if (contract === "invalid") {
+ invalid.push(page.path);
+ continue;
+ }
+ withContract++;
+ const freshness = freshnessOf(vault, page.path, contract);
+ if (freshness.status === "fresh") fresh++;
+ else if (freshness.status === "orphaned") orphaned.push(page.path);
+ else stale.push(freshness);
+ }
+ return Object.freeze({
+ pages_checked: pages.length,
+ with_contract: withContract,
+ fresh,
+ stale: Object.freeze(stale),
+ orphaned: Object.freeze(orphaned),
+ invalid_contract: Object.freeze(invalid),
+ });
+}
diff --git a/src/core/brain/handoff.ts b/src/core/brain/handoff.ts
index bfea2150..a7ee8c4c 100644
--- a/src/core/brain/handoff.ts
+++ b/src/core/brain/handoff.ts
@@ -12,6 +12,7 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
+import { computeSourceStamp, formatSourceStampFrontmatter } from "./freshness.ts";
import { isoDate, isoSecond } from "./time.ts";
import { resolveSessionScope } from "./session-scope.ts";
import type { SessionTurn } from "./sessions/types.ts";
@@ -25,6 +26,21 @@ export interface HandoffNoteOptions {
export interface WriteHandoffNoteInput extends HandoffNoteOptions {
readonly turns: ReadonlyArray<SessionTurn>;
+ /**
+ * On-disk artifacts this note derives from (the recorded transcript,
+ * typically). When present, the source-freshness contract
+ * (`source_paths` / `source_hashes`) is stamped into the frontmatter
+ * so the note participates in stale/orphaned detection
+ * (continuity-hygiene-freshness suite).
+ */
+ readonly sourcePaths?: ReadonlyArray<string>;
+ /**
+ * Exact page path to (over)write instead of the default
+ * `Brain/handoffs/<date>-<scope>.md` - the targeted-recompile
+ * executor re-derives a stale note IN PLACE so its identity and
+ * backlinks survive.
+ */
+ readonly targetPath?: string;
}
export interface HandoffNoteResult {
@@ -125,7 +141,7 @@ export function writeHandoffNote(vault: string, input: WriteHandoffNoteInput): H
const scope = resolveSessionScope(input.sessionId);
const dir = join(vault, "Brain", "handoffs");
mkdirSync(dir, { recursive: true });
- const path = join(dir, `${isoDate(now)}-${scope}.md`);
+ const path = input.targetPath ?? join(dir, `${isoDate(now)}-${scope}.md`);
const body = buildHandoffNote(input.turns, input);
// JSON.stringify-quote the caller-supplied scalars: YAML-significant
// characters or newlines in a session id / agent name must not be
@@ -137,6 +153,9 @@ export function writeHandoffNote(vault: string, input: WriteHandoffNoteInput): H
`agent: ${JSON.stringify(input.agent)}`,
`created_at: ${isoSecond(now)}`,
`turns: ${input.turns.length}`,
+ ...(input.sourcePaths !== undefined && input.sourcePaths.length > 0
+ ? [formatSourceStampFrontmatter(computeSourceStamp(vault, input.sourcePaths))]
+ : []),
"---",
"",
body,
diff --git a/src/core/brain/hygiene/apply.ts b/src/core/brain/hygiene/apply.ts
new file mode 100644
index 00000000..5f32f96d
--- /dev/null
+++ b/src/core/brain/hygiene/apply.ts
@@ -0,0 +1,185 @@
+/**
+ * Hygiene apply - execute an explicit remediation plan
+ * (continuity-hygiene-freshness suite; kanban t_698db8f7).
+ *
+ * Routing by proposed action, every executor an existing primitive:
+ *
+ * - `merge` -> `mergePreferences` (keep = first target);
+ * - `supersede` -> append the resolver-chosen winning claim with
+ * hygiene provenance (the conflict's slot then
+ * reads the winner as current truth);
+ * - `recompile` -> the targeted-recompile executor, scoped to the
+ * finding's page;
+ * - `archive` / `forget` -> move the page into a dated
+ * `Brain/.snapshots/` directory - never delete.
+ *
+ * Dry-run previews the routed actions with zero writes. Per-finding
+ * fail-soft; one audit record per non-dry run.
+ */
+
+import { join } from "node:path";
+
+import { appendAuditRecord } from "../../reliability/audit.ts";
+import { mergePreferences } from "../merge.ts";
+import { brainDirs } from "../paths.ts";
+import { archivePage, executeRecompile, planRecompile } from "../recompile.ts";
+import { appendClaimEvent } from "../truth/store.ts";
+import type { HygienePlan } from "./plan.ts";
+import type { HygieneFinding } from "./types.ts";
+
+export interface HygieneApplyOptions {
+ readonly dryRun?: boolean;
+ readonly agent: string;
+ readonly now: Date;
+}
+
+export interface HygieneAppliedAction {
+ readonly finding_id: string;
+ readonly action: string;
+ readonly detail: string;
+}
+
+export interface HygieneApplyResult {
+ readonly dry_run: boolean;
+ /** Dry-run preview of what would execute. */
+ readonly planned: ReadonlyArray<HygieneAppliedAction>;
+ readonly applied: ReadonlyArray<HygieneAppliedAction>;
+ readonly errors: ReadonlyArray<{ finding_id: string; message: string }>;
+}
+
+function plannedAction(finding: HygieneFinding): HygieneAppliedAction {
+ return Object.freeze({
+ finding_id: finding.id,
+ action: finding.proposed_action,
+ detail: finding.targets.join(", "),
+ });
+}
+
+async function executeFinding(
+ vault: string,
+ finding: HygieneFinding,
+ opts: HygieneApplyOptions,
+): Promise<HygieneAppliedAction> {
+ switch (finding.proposed_action) {
+ case "merge": {
+ const [keep, drop] = finding.targets;
+ if (keep === undefined || drop === undefined) {
+ throw new Error("merge finding must carry exactly two targets");
+ }
+ const plan = mergePreferences(vault, keep, drop, {
+ now: opts.now,
+ agentName: opts.agent,
+ });
+ return Object.freeze({
+ finding_id: finding.id,
+ action: "merge",
+ detail: `kept ${plan.keep_id}, retired ${plan.drop_id}`,
+ });
+ }
+ case "supersede": {
+ const resolver = finding.evidence["resolver"] as { winner_value?: unknown } | undefined;
+ const winner = resolver !== undefined ? resolver.winner_value : undefined;
+ const slot = finding.targets[0] ?? "";
+ // Entities/aspects are normalized names (no '#'), so the first
+ // '#' is always the slot separator.
+ const separator = slot.indexOf("#");
+ if (typeof winner !== "string" || winner.length === 0 || separator <= 0) {
+ throw new Error("supersede finding lacks a resolver winner or a valid entity#aspect slot");
+ }
+ appendClaimEvent(vault, {
+ ts: opts.now.toISOString(),
+ agent: opts.agent,
+ entity: slot.slice(0, separator),
+ aspect: slot.slice(separator + 1),
+ value: winner,
+ source: "[[hygiene-resolver]]",
+ });
+ return Object.freeze({
+ finding_id: finding.id,
+ action: "supersede",
+ detail: `${slot} -> ${winner}`,
+ });
+ }
+ case "recompile": {
+ const page = finding.targets[0];
+ const plan = planRecompile(vault);
+ const scoped = Object.freeze({
+ entries: Object.freeze(plan.entries.filter((entry) => entry.page === page)),
+ });
+ const result = await executeRecompile(vault, scoped, {
+ agent: opts.agent,
+ now: opts.now,
+ });
+ if (result.errors.length > 0) throw new Error(result.errors[0]!.message);
+ return Object.freeze({
+ finding_id: finding.id,
+ action: "recompile",
+ detail: `rederived ${result.rederived.length}, archived ${result.archived.length}, manual ${result.manual.length}`,
+ });
+ }
+ case "archive":
+ case "forget": {
+ const page = finding.targets[0];
+ if (page === undefined) throw new Error("archive finding carries no target page");
+ const target = archivePage(vault, page, opts.now);
+ return Object.freeze({
+ finding_id: finding.id,
+ action: finding.proposed_action,
+ detail: `archived to ${target}`,
+ });
+ }
+ default:
+ throw new Error(`no executor for action '${finding.proposed_action}'`);
+ }
+}
+
+export async function applyHygienePlan(
+ vault: string,
+ plan: HygienePlan,
+ opts: HygieneApplyOptions,
+): Promise<HygieneApplyResult> {
+ const dryRun = opts.dryRun === true;
+ if (dryRun) {
+ return Object.freeze({
+ dry_run: true,
+ planned: Object.freeze(plan.selected.map(plannedAction)),
+ applied: Object.freeze([]),
+ errors: Object.freeze([]),
+ });
+ }
+
+ const applied: HygieneAppliedAction[] = [];
+ const errors: { finding_id: string; message: string }[] = [];
+ for (const finding of plan.selected) {
+ try {
+ applied.push(await executeFinding(vault, finding, opts));
+ } catch (error) {
+ errors.push({
+ finding_id: finding.id,
+ message: error instanceof Error ? error.message : "apply failed",
+ });
+ }
+ }
+
+ if (applied.length > 0 || errors.length > 0) {
+ appendAuditRecord(join(brainDirs(vault).log, "hygiene"), {
+ timestamp: opts.now.toISOString(),
+ actor: opts.agent,
+ action: "hygiene_apply",
+ target: "Brain",
+ ok: errors.length === 0,
+ details: {
+ applied: applied.length,
+ errors: errors.length,
+ actions: applied.map((action) => `${action.action}:${action.finding_id}`),
+ },
+ });
+ }
+
+ return Object.freeze({
+ dry_run: false,
+ planned: Object.freeze([]),
+ applied: Object.freeze(applied),
+ errors: Object.freeze(errors),
+ });
+}
diff --git a/src/core/brain/hygiene/detectors/conflicts.ts b/src/core/brain/hygiene/detectors/conflicts.ts
new file mode 100644
index 00000000..a2e2f99a
--- /dev/null
+++ b/src/core/brain/hygiene/detectors/conflicts.ts
@@ -0,0 +1,47 @@
+/**
+ * Conflicts detector (continuity-hygiene-freshness suite; kanban
+ * t_db375a60, detection side).
+ *
+ * Deterministic wrapper over the truth layer's temporal-structural
+ * conflict rule (`computeTruthStateWithConflicts`): two independent
+ * values for one `entity#aspect` slot inside the conflict window are
+ * CONTESTED. Detection here is always deterministic; resolution
+ * (supersede / merge / flag) happens later through the external
+ * resolver bridge or stays `review` for the operator.
+ */
+
+import { computeTruthStateWithConflicts } from "../../truth/conflicts.ts";
+import { readClaimEvents } from "../../truth/store.ts";
+import { hygieneFindingId } from "./id.ts";
+import type { HygieneFinding } from "../types.ts";
+
+export function detectConflicts(vault: string): ReadonlyArray<HygieneFinding> {
+ const events = readClaimEvents(vault).events;
+ if (events.length === 0) return Object.freeze([]);
+ const state = computeTruthStateWithConflicts(events);
+ return Object.freeze(
+ state.conflicts.map((conflict) => {
+ const slot = `${conflict.entity}#${conflict.aspect}`;
+ return Object.freeze({
+ id: hygieneFindingId("conflicts", [slot]),
+ detector: "conflicts" as const,
+ severity: "warning" as const,
+ title: `Contested values for ${slot} (${conflict.values.length} contenders)`,
+ targets: Object.freeze([slot]),
+ proposed_action: "review" as const,
+ evidence: Object.freeze({
+ kind: conflict.kind,
+ priority: conflict.priority,
+ detected_at: conflict.detectedAt,
+ values: conflict.values.map((value) => ({
+ value: value.value,
+ ts: value.ts,
+ agent: value.agent,
+ source: value.source,
+ assert_count: value.assertCount,
+ })),
+ }),
+ });
+ }),
+ );
+}
diff --git a/src/core/brain/hygiene/detectors/dedup.ts b/src/core/brain/hygiene/detectors/dedup.ts
new file mode 100644
index 00000000..ee7384ad
--- /dev/null
+++ b/src/core/brain/hygiene/detectors/dedup.ts
@@ -0,0 +1,202 @@
+/**
+ * Dedup detector (continuity-hygiene-freshness suite; kanban
+ * t_da3f138f).
+ *
+ * Near-duplicate memories surface as merge findings. Two layers:
+ *
+ * - Embedding similarity when vectors are available in the search
+ * index (cosine over stored chunk embeddings, threshold default
+ * 0.97) - see `embeddingDuplicatePairs`.
+ * - Deterministic lexical fallback otherwise: the shared
+ * `findMergeCandidates` jaccard detector over preference
+ * principles, clearly labeled `method: "lexical"` so a report
+ * never passes lexical similarity off as semantic.
+ *
+ * The detector only nominates pairs; merging happens through the
+ * hygiene apply plan (which routes to the existing merge machinery).
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { resolveSearchConfig } from "../../../search/index.ts";
+import { makeProvider, type EmbeddingProvider } from "../../../search/embeddings/provider.ts";
+import { findMergeCandidates } from "../../merge-candidates.ts";
+import { brainDirs } from "../../paths.ts";
+import { parsePreference } from "../../preference.ts";
+import { hygieneFindingId } from "./id.ts";
+import type { HygieneDetectorContext, HygieneFinding } from "../types.ts";
+
+/** Cosine-similarity threshold for the embedding layer (upstream default). */
+export const DEDUP_EMBEDDING_THRESHOLD = 0.97;
+/** Jaccard threshold for the lexical fallback - above merge-suggest level. */
+export const DEDUP_LEXICAL_THRESHOLD = 0.8;
+
+export interface DedupDetectorOptions {
+ readonly lexicalThreshold?: number;
+}
+
+/** Bound on how many preferences enter pairwise comparison. */
+const DEDUP_CANDIDATE_CAP = 200;
+
+export type DedupMethod = "embedding" | "lexical";
+
+export interface SemanticDedupOptions {
+ /**
+ * Embedding provider override. `undefined` resolves the vault's
+ * configured provider; `null` (or an unusable provider) falls back
+ * to the lexical layer.
+ */
+ readonly provider?: EmbeddingProvider | null;
+ readonly threshold?: number;
+ readonly lexicalThreshold?: number;
+}
+
+export interface SemanticDedupResult {
+ readonly method: DedupMethod;
+ readonly findings: ReadonlyArray<HygieneFinding>;
+}
+
+interface PrefCandidate {
+ readonly id: string;
+ readonly topic: string;
+ readonly scope: string | null;
+ readonly principle: string;
+}
+
+function listPreferenceCandidates(vault: string): PrefCandidate[] {
+ const dir = brainDirs(vault).preferences;
+ if (!existsSync(dir)) return [];
+ const out: PrefCandidate[] = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ if (!name.endsWith(".md")) continue;
+ try {
+ const pref = parsePreference(join(dir, name));
+ out.push({
+ id: pref.id,
+ topic: pref.topic,
+ scope: pref.scope ?? null,
+ principle: pref.principle,
+ });
+ } catch {
+ continue;
+ }
+ if (out.length >= DEDUP_CANDIDATE_CAP) break;
+ }
+ return out;
+}
+
+function cosine(a: ReadonlyArray<number>, b: ReadonlyArray<number>): number {
+ let dot = 0;
+ let normA = 0;
+ let normB = 0;
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
+ dot += a[i]! * b[i]!;
+ normA += a[i]! * a[i]!;
+ normB += b[i]! * b[i]!;
+ }
+ if (normA === 0 || normB === 0) return 0;
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
+}
+
+function resolveConfiguredProvider(vault: string): EmbeddingProvider | null {
+ try {
+ const provider = makeProvider(resolveSearchConfig({ vault }).semantic);
+ return provider.name === "null" ? null : provider;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Semantic dedup layer: embed every preference principle (bounded) and
+ * nominate pairs whose cosine similarity reaches the threshold -
+ * across topic buckets, which is exactly where the lexical layer is
+ * blind. Any provider problem falls back to the deterministic lexical
+ * layer, labeled as such.
+ */
+export async function detectSemanticDedup(
+ vault: string,
+ opts: SemanticDedupOptions = {},
+): Promise<SemanticDedupResult> {
+ const provider = opts.provider === undefined ? resolveConfiguredProvider(vault) : opts.provider;
+ const lexical = (): SemanticDedupResult =>
+ Object.freeze({
+ method: "lexical" as const,
+ findings: detectDedup(
+ vault,
+ { now: new Date(0) },
+ opts.lexicalThreshold !== undefined ? { lexicalThreshold: opts.lexicalThreshold } : {},
+ ),
+ });
+ if (provider === null || provider.name === "null") return lexical();
+
+ const candidates = listPreferenceCandidates(vault);
+ if (candidates.length < 2) return lexical();
+ const threshold = opts.threshold ?? DEDUP_EMBEDDING_THRESHOLD;
+
+ let vectors: number[][];
+ try {
+ vectors = await provider.embed(candidates.map((candidate) => candidate.principle));
+ } catch {
+ return lexical();
+ }
+ if (vectors.length !== candidates.length) return lexical();
+
+ const findings: HygieneFinding[] = [];
+ for (let i = 0; i < candidates.length; i++) {
+ for (let j = i + 1; j < candidates.length; j++) {
+ const similarity = cosine(vectors[i]!, vectors[j]!);
+ if (similarity < threshold) continue;
+ const a = candidates[i]!;
+ const b = candidates[j]!;
+ findings.push(
+ Object.freeze({
+ id: hygieneFindingId("dedup", [a.id, b.id]),
+ detector: "dedup" as const,
+ severity: "warning" as const,
+ title: `Near-duplicate preferences ${a.id} and ${b.id} (cosine ${similarity.toFixed(3)})`,
+ targets: Object.freeze([a.id, b.id].toSorted()),
+ proposed_action: "merge" as const,
+ evidence: Object.freeze({
+ method: "embedding",
+ model: provider.model,
+ cosine: Number(similarity.toFixed(4)),
+ principle_a: a.principle,
+ principle_b: b.principle,
+ }),
+ }),
+ );
+ }
+ }
+ return Object.freeze({ method: "embedding" as const, findings: Object.freeze(findings) });
+}
+
+export function detectDedup(
+ vault: string,
+ _ctx: HygieneDetectorContext,
+ opts: DedupDetectorOptions = {},
+): ReadonlyArray<HygieneFinding> {
+ const threshold = opts.lexicalThreshold ?? DEDUP_LEXICAL_THRESHOLD;
+ const candidates = findMergeCandidates(vault, { threshold, limit: 50 });
+ return Object.freeze(
+ candidates.map((pair) =>
+ Object.freeze({
+ id: hygieneFindingId("dedup", [pair.a, pair.b]),
+ detector: "dedup" as const,
+ severity: "warning" as const,
+ title: `Near-duplicate preferences ${pair.a} and ${pair.b} (jaccard ${pair.jaccard})`,
+ targets: Object.freeze([pair.a, pair.b]),
+ proposed_action: "merge" as const,
+ evidence: Object.freeze({
+ method: "lexical",
+ jaccard: pair.jaccard,
+ topic: pair.topic,
+ scope: pair.scope,
+ principle_a: pair.principle_a,
+ principle_b: pair.principle_b,
+ }),
+ }),
+ ),
+ );
+}
diff --git a/src/core/brain/hygiene/detectors/freshness.ts b/src/core/brain/hygiene/detectors/freshness.ts
new file mode 100644
index 00000000..ba517ecf
--- /dev/null
+++ b/src/core/brain/hygiene/detectors/freshness.ts
@@ -0,0 +1,59 @@
+/**
+ * Freshness detector (continuity-hygiene-freshness suite; kanban
+ * t_d9624ef6): wraps the source-freshness substrate as a hygiene
+ * detector. Stale pages propose `recompile` (the targeted-recompile
+ * executor picks them up); orphaned pages propose `review` - deleting
+ * a page because its sources vanished is an operator call.
+ */
+
+import { scanFreshness } from "../../freshness.ts";
+import { hygieneFindingId } from "./id.ts";
+import type { HygieneFinding } from "../types.ts";
+
+export function detectFreshness(vault: string): ReadonlyArray<HygieneFinding> {
+ const report = scanFreshness(vault);
+ const findings: HygieneFinding[] = [];
+ for (const stale of report.stale) {
+ findings.push(
+ Object.freeze({
+ id: hygieneFindingId("freshness", [stale.page]),
+ detector: "freshness" as const,
+ severity: "action" as const,
+ title: `Derived page is stale: ${stale.changed_sources.length} changed, ${stale.missing_sources.length} missing source(s)`,
+ targets: Object.freeze([stale.page]),
+ proposed_action: "recompile" as const,
+ evidence: Object.freeze({
+ changed_sources: stale.changed_sources,
+ missing_sources: stale.missing_sources,
+ }),
+ }),
+ );
+ }
+ for (const orphan of report.orphaned) {
+ findings.push(
+ Object.freeze({
+ id: hygieneFindingId("freshness", [orphan]),
+ detector: "freshness" as const,
+ severity: "warning" as const,
+ title: "Derived page is orphaned: every recorded source is gone",
+ targets: Object.freeze([orphan]),
+ proposed_action: "review" as const,
+ evidence: Object.freeze({}),
+ }),
+ );
+ }
+ for (const invalid of report.invalid_contract) {
+ findings.push(
+ Object.freeze({
+ id: hygieneFindingId("freshness", [invalid]),
+ detector: "freshness" as const,
+ severity: "info" as const,
+ title: "Source-freshness contract is malformed on this page",
+ targets: Object.freeze([invalid]),
+ proposed_action: "review" as const,
+ evidence: Object.freeze({}),
+ }),
+ );
+ }
+ return Object.freeze(findings);
+}
diff --git a/src/core/brain/hygiene/detectors/id.ts b/src/core/brain/hygiene/detectors/id.ts
new file mode 100644
index 00000000..bc25c286
--- /dev/null
+++ b/src/core/brain/hygiene/detectors/id.ts
@@ -0,0 +1,17 @@
+/**
+ * Deterministic hygiene finding ids: `<detector>:<sha256 prefix>` over
+ * the sorted target list, so the same finding keeps the same id across
+ * scans and can be selected into an apply plan by id.
+ */
+
+import { createHash } from "node:crypto";
+
+import type { HygieneDetectorId } from "../types.ts";
+
+export function hygieneFindingId(
+ detector: HygieneDetectorId,
+ targets: ReadonlyArray<string>,
+): string {
+ const digest = createHash("sha256").update(targets.toSorted().join("\0")).digest("hex");
+ return `${detector}:${digest.slice(0, 12)}`;
+}
diff --git a/src/core/brain/hygiene/detectors/usefulness.ts b/src/core/brain/hygiene/detectors/usefulness.ts
new file mode 100644
index 00000000..6c96db64
--- /dev/null
+++ b/src/core/brain/hygiene/detectors/usefulness.ts
@@ -0,0 +1,80 @@
+/**
+ * Usefulness detector (continuity-hygiene-freshness suite; kanban
+ * t_698db8f7).
+ *
+ * Low-usefulness candidates: preferences that have been around longer
+ * than the evidence window yet never appear in any recall-telemetry
+ * `top_artifacts` and carry zero applied evidence. The detector only
+ * nominates for review - forgetting is an operator decision executed
+ * through the apply plan.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { brainDirs } from "../../paths.ts";
+import { parsePreference } from "../../preference.ts";
+import { listRecallTelemetry } from "../../recall-telemetry.ts";
+import { hygieneFindingId } from "./id.ts";
+import type { HygieneDetectorContext, HygieneFinding } from "../types.ts";
+
+/** A preference younger than this many days is not judged. */
+export const USEFULNESS_MIN_AGE_DAYS = 45;
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function recalledArtifactIds(vault: string): Set<string> {
+ const ids = new Set<string>();
+ for (const record of listRecallTelemetry(vault)) {
+ const top = record.payload["top_artifacts"];
+ if (!Array.isArray(top)) continue;
+ for (const artifact of top) {
+ if (artifact !== null && typeof artifact === "object") {
+ const id = (artifact as { id?: unknown }).id;
+ if (typeof id === "string" && id.length > 0) ids.add(id);
+ }
+ }
+ }
+ return ids;
+}
+
+export function detectUsefulness(
+ vault: string,
+ ctx: HygieneDetectorContext,
+): ReadonlyArray<HygieneFinding> {
+ const dir = brainDirs(vault).preferences;
+ if (!existsSync(dir)) return Object.freeze([]);
+ const recalled = recalledArtifactIds(vault);
+ const cutoffMs = ctx.now.getTime() - USEFULNESS_MIN_AGE_DAYS * DAY_MS;
+ const findings: HygieneFinding[] = [];
+ for (const name of readdirSync(dir).toSorted()) {
+ if (!name.endsWith(".md")) continue;
+ let pref;
+ try {
+ pref = parsePreference(join(dir, name));
+ } catch {
+ continue; // malformed preferences belong to doctor, not hygiene
+ }
+ if (recalled.has(pref.id)) continue;
+ if (pref.applied_count > 0) continue;
+ const createdMs = Date.parse(pref.created_at);
+ if (!Number.isFinite(createdMs) || createdMs > cutoffMs) continue;
+ findings.push(
+ Object.freeze({
+ id: hygieneFindingId("usefulness", [pref.id]),
+ detector: "usefulness" as const,
+ severity: "info" as const,
+ title: `Preference ${pref.id} has no recall or applied evidence since creation`,
+ targets: Object.freeze([pref.id]),
+ proposed_action: "review" as const,
+ evidence: Object.freeze({
+ created_at: pref.created_at,
+ status: pref.status,
+ applied_count: pref.applied_count,
+ min_age_days: USEFULNESS_MIN_AGE_DAYS,
+ }),
+ }),
+ );
+ }
+ return Object.freeze(findings);
+}
diff --git a/src/core/brain/hygiene/plan.ts b/src/core/brain/hygiene/plan.ts
new file mode 100644
index 00000000..c38e64b4
--- /dev/null
+++ b/src/core/brain/hygiene/plan.ts
@@ -0,0 +1,55 @@
+/**
+ * Hygiene apply plan - explicit selection of scan findings
+ * (continuity-hygiene-freshness suite; kanban t_698db8f7).
+ *
+ * `apply` never acts on a raw scan: the operator (or a surface acting
+ * for them) selects finding ids out of a scan report, and `review`
+ * findings are structurally excluded - they have no automated
+ * remediation by definition.
+ */
+
+import type { HygieneFinding, HygieneScanReport } from "./types.ts";
+
+export interface HygienePlan {
+ /** Findings selected for execution (never `review`). */
+ readonly selected: ReadonlyArray<HygieneFinding>;
+ /** Selected ids that pointed at review-only findings. */
+ readonly excluded_review: ReadonlyArray<string>;
+ /** Selected ids that matched nothing in the report. */
+ readonly unknown_ids: ReadonlyArray<string>;
+}
+
+export interface BuildHygienePlanOptions {
+ /** Finding ids to execute; omitted selects every actionable finding. */
+ readonly ids?: ReadonlyArray<string>;
+}
+
+export function buildHygienePlan(
+ report: HygieneScanReport,
+ opts: BuildHygienePlanOptions = {},
+): HygienePlan {
+ const byId = new Map(report.findings.map((finding) => [finding.id, finding]));
+ const requested = opts.ids ?? report.findings.map((finding) => finding.id);
+
+ const selected: HygieneFinding[] = [];
+ const excludedReview: string[] = [];
+ const unknown: string[] = [];
+ for (const id of requested) {
+ const finding = byId.get(id);
+ if (finding === undefined) {
+ unknown.push(id);
+ continue;
+ }
+ if (finding.proposed_action === "review") {
+ excludedReview.push(id);
+ continue;
+ }
+ selected.push(finding);
+ }
+
+ return Object.freeze({
+ selected: Object.freeze(selected),
+ excluded_review: Object.freeze(excludedReview),
+ unknown_ids: Object.freeze(unknown),
+ });
+}
diff --git a/src/core/brain/hygiene/resolve-conflicts.ts b/src/core/brain/hygiene/resolve-conflicts.ts
new file mode 100644
index 00000000..0e901924
--- /dev/null
+++ b/src/core/brain/hygiene/resolve-conflicts.ts
@@ -0,0 +1,133 @@
+/**
+ * External conflict resolution
+ * (continuity-hygiene-freshness suite; kanban t_db375a60).
+ *
+ * The Brain core stays deterministic: conflict DETECTION is the truth
+ * layer's temporal-structural rule, and this module only consults an
+ * optional external resolver command - through the shared
+ * `runJsonCommandBridge` - for an advisory verdict per conflict
+ * finding. The contract is fail-open at every step: no resolver
+ * configured, resolver error, malformed output, unknown finding id,
+ * or an action outside the allowed vocabulary all leave the finding
+ * at `review` for the operator.
+ *
+ * Wire protocol: the resolver receives
+ * `{ "conflicts": [<conflict findings>] }` on stdin and answers
+ * `{ "verdicts": { "<finding-id>": { "action": "supersede" | "merge"
+ * | "flag", "winner_value"?, "rationale"? } } }` on stdout.
+ */
+
+import { runJsonCommandBridge } from "../../reliability/command-bridge.ts";
+import type { HygieneFinding, HygieneProposedAction } from "./types.ts";
+
+export interface ResolveConflictOptions {
+ /** External resolver command (`hygiene.resolver_cmd`). Absent = flag-for-review. */
+ readonly resolverCmd?: string;
+ readonly timeoutMs?: number;
+}
+
+interface ResolverVerdict {
+ readonly action: "supersede" | "merge" | "flag";
+ readonly winner_value?: string;
+ readonly rationale?: string;
+}
+
+function parseVerdict(raw: unknown): ResolverVerdict | null {
+ if (raw === null || typeof raw !== "object") return null;
+ const candidate = raw as { action?: unknown; winner_value?: unknown; rationale?: unknown };
+ if (
+ candidate.action !== "supersede" &&
+ candidate.action !== "merge" &&
+ candidate.action !== "flag"
+ ) {
+ return null;
+ }
+ return {
+ action: candidate.action,
+ ...(typeof candidate.winner_value === "string" ? { winner_value: candidate.winner_value } : {}),
+ ...(typeof candidate.rationale === "string" ? { rationale: candidate.rationale } : {}),
+ };
+}
+
+function withResolverEvidence(
+ finding: HygieneFinding,
+ action: HygieneProposedAction,
+ extra: Readonly<Record<string, unknown>>,
+): HygieneFinding {
+ return Object.freeze({
+ ...finding,
+ proposed_action: action,
+ evidence: Object.freeze({ ...finding.evidence, ...extra }),
+ });
+}
+
+/**
+ * Attach resolver verdicts to conflict findings. Non-conflict findings
+ * pass through by reference; conflicts without a usable verdict stay
+ * `review`. Never throws.
+ */
+export function resolveConflictFindings(
+ _vault: string,
+ findings: ReadonlyArray<HygieneFinding>,
+ opts: ResolveConflictOptions,
+): ReadonlyArray<HygieneFinding> {
+ const conflicts = findings.filter((finding) => finding.detector === "conflicts");
+ if (conflicts.length === 0 || opts.resolverCmd === undefined || opts.resolverCmd.trim() === "") {
+ return findings;
+ }
+
+ const result = runJsonCommandBridge(
+ opts.resolverCmd,
+ { conflicts },
+ {
+ label: "hygiene resolver",
+ ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),
+ },
+ );
+
+ if (result.status === "skipped") return findings;
+ if (result.status === "error") {
+ return Object.freeze(
+ findings.map((finding) =>
+ finding.detector === "conflicts"
+ ? withResolverEvidence(finding, "review", { resolver_error: result.detail })
+ : finding,
+ ),
+ );
+ }
+
+ const verdictsRaw =
+ result.output !== null && typeof result.output === "object"
+ ? ((result.output as { verdicts?: unknown }).verdicts ?? {})
+ : {};
+ const verdicts =
+ verdictsRaw !== null && typeof verdictsRaw === "object"
+ ? (verdictsRaw as Record<string, unknown>)
+ : {};
+
+ return Object.freeze(
+ findings.map((finding) => {
+ if (finding.detector !== "conflicts") return finding;
+ const verdict = parseVerdict(verdicts[finding.id]);
+ if (verdict === null || verdict.action === "flag") {
+ const flagEvidence =
+ verdict !== null
+ ? {
+ resolver: {
+ action: "flag",
+ ...(verdict.rationale ? { rationale: verdict.rationale } : {}),
+ },
+ }
+ : {};
+ return withResolverEvidence(finding, "review", flagEvidence);
+ }
+ return withResolverEvidence(finding, verdict.action, {
+ resolver: {
+ action: verdict.action,
+ ...(verdict.winner_value !== undefined ? { winner_value: verdict.winner_value } : {}),
+ ...(verdict.rationale !== undefined ? { rationale: verdict.rationale } : {}),
+ },
+ });
+ }),
+ );
+}
diff --git a/src/core/brain/hygiene/scan.ts b/src/core/brain/hygiene/scan.ts
new file mode 100644
index 00000000..80823a73
--- /dev/null
+++ b/src/core/brain/hygiene/scan.ts
@@ -0,0 +1,71 @@
+/**
+ * Hygiene scan - read-only composition over the detector registry
+ * (continuity-hygiene-freshness suite; kanban t_698db8f7).
+ *
+ * Runs the requested detectors (default: all), folds their findings
+ * into one frozen digest with per-detector counts, and converts a
+ * thrown detector into an `errors` entry instead of failing the scan.
+ * The scan never mutates the vault; remediation lives in `apply.ts`.
+ */
+
+import { detectConflicts } from "./detectors/conflicts.ts";
+import { detectDedup } from "./detectors/dedup.ts";
+import { detectFreshness } from "./detectors/freshness.ts";
+import { detectUsefulness } from "./detectors/usefulness.ts";
+import {
+ HYGIENE_DETECTOR_IDS,
+ type HygieneDetector,
+ type HygieneDetectorId,
+ type HygieneFinding,
+ type HygieneScanError,
+ type HygieneScanReport,
+} from "./types.ts";
+
+const DETECTORS: Readonly<Record<HygieneDetectorId, HygieneDetector>> = Object.freeze({
+ conflicts: (vault) => detectConflicts(vault),
+ dedup: (vault, ctx) => detectDedup(vault, ctx),
+ freshness: (vault) => detectFreshness(vault),
+ usefulness: (vault, ctx) => detectUsefulness(vault, ctx),
+});
+
+export interface RunHygieneScanOptions {
+ /** Detector subset to run; defaults to every registered detector. */
+ readonly detectors?: ReadonlyArray<HygieneDetectorId>;
+ /** Injected clock. */
+ readonly now: Date;
+}
+
+export function runHygieneScan(vault: string, opts: RunHygieneScanOptions): HygieneScanReport {
+ const requested =
+ opts.detectors !== undefined && opts.detectors.length > 0
+ ? HYGIENE_DETECTOR_IDS.filter((id) => opts.detectors!.includes(id))
+ : HYGIENE_DETECTOR_IDS;
+
+ const findings: HygieneFinding[] = [];
+ const errors: HygieneScanError[] = [];
+ const counts: Partial<Record<HygieneDetectorId, number>> = {};
+
+ for (const id of requested) {
+ try {
+ const detected = DETECTORS[id](vault, { now: opts.now });
+ counts[id] = detected.length;
+ findings.push(...detected);
+ } catch (error) {
+ counts[id] = 0;
+ errors.push(
+ Object.freeze({
+ detector: id,
+ message: error instanceof Error ? error.message : "detector failed",
+ }),
+ );
+ }
+ }
+
+ return Object.freeze({
+ generated_at: opts.now.toISOString(),
+ detectors_run: Object.freeze([...requested]),
+ findings: Object.freeze(findings),
+ counts: Object.freeze(counts),
+ errors: Object.freeze(errors),
+ });
+}
diff --git a/src/core/brain/hygiene/types.ts b/src/core/brain/hygiene/types.ts
new file mode 100644
index 00000000..02facfa6
--- /dev/null
+++ b/src/core/brain/hygiene/types.ts
@@ -0,0 +1,71 @@
+/**
+ * Hygiene findings pipeline - shared types
+ * (continuity-hygiene-freshness suite; kanban t_698db8f7).
+ *
+ * One detector contract for every hygiene concern: a pure function
+ * over the vault returning typed findings. `scan` composes detectors
+ * into a read-only digest; `apply` executes an explicit remediation
+ * plan built from finding ids. Detectors never mutate anything and
+ * never throw past the scan boundary.
+ */
+
+export const HYGIENE_DETECTOR_IDS = ["conflicts", "dedup", "freshness", "usefulness"] as const;
+
+export type HygieneDetectorId = (typeof HYGIENE_DETECTOR_IDS)[number];
+
+export type HygieneSeverity = "info" | "warning" | "action";
+
+/**
+ * Closed action vocabulary. `review` is the universal safe default -
+ * anything an automated remediation should not touch lands there.
+ */
+export type HygieneProposedAction =
+ | "merge"
+ | "supersede"
+ | "archive"
+ | "recompile"
+ | "forget"
+ | "review";
+
+export interface HygieneFinding {
+ /** Deterministic id: `<detector>:<sha256-prefix of targets>`. */
+ readonly id: string;
+ readonly detector: HygieneDetectorId;
+ readonly severity: HygieneSeverity;
+ /** One-line human-readable summary (English). */
+ readonly title: string;
+ /** What the finding is about: page paths, preference ids, `entity#aspect` slots. */
+ readonly targets: ReadonlyArray<string>;
+ readonly proposed_action: HygieneProposedAction;
+ /** Detector-specific supporting data, JSON-serializable. */
+ readonly evidence: Readonly<Record<string, unknown>>;
+}
+
+export interface HygieneDetectorContext {
+ /** Injected clock - detectors never read the wall clock themselves. */
+ readonly now: Date;
+}
+
+export type HygieneDetector = (
+ vault: string,
+ ctx: HygieneDetectorContext,
+) => ReadonlyArray<HygieneFinding>;
+
+export interface HygieneScanError {
+ readonly detector: HygieneDetectorId;
+ readonly message: string;
+}
+
+export interface HygieneScanReport {
+ readonly generated_at: string;
+ readonly detectors_run: ReadonlyArray<HygieneDetectorId>;
+ readonly findings: ReadonlyArray<HygieneFinding>;
+ readonly counts: Readonly<Partial<Record<HygieneDetectorId, number>>>;
+ readonly errors: ReadonlyArray<HygieneScanError>;
+}
+
+export function isHygieneDetectorId(value: unknown): value is HygieneDetectorId {
+ return (
+ typeof value === "string" && (HYGIENE_DETECTOR_IDS as ReadonlyArray<string>).includes(value)
+ );
+}
diff --git a/src/core/brain/lineage/crutch.ts b/src/core/brain/lineage/crutch.ts
new file mode 100644
index 00000000..c8a16d91
--- /dev/null
+++ b/src/core/brain/lineage/crutch.ts
@@ -0,0 +1,77 @@
+/**
+ * CRUTCH(t_1459706f) - interim session-lineage inference.
+ *
+ * The deployed Hermes collapses `parent_session_id` into `session_id`
+ * in its shell-hook payload (`_serialize_payload`) and exposes no
+ * lineage field; upstream PR NousResearch/hermes-agent#42940 adds the
+ * native field but has not merged. Until it ships, this module infers
+ * the parent of a brand-new session id from the lineage ledger.
+ *
+ * The inference is deliberately conservative - a false stitch (two
+ * unrelated conversations merged) is strictly worse than a missed
+ * stitch (status quo). A link happens only when ALL hold:
+ *
+ * 1. the new session has NO ledger history of its own (a session
+ * seen before without a link is a parallel session);
+ * 2. a predecessor exists in the SAME cwd;
+ * 3. the predecessor's LATEST event evidences a compression
+ * boundary (PostCompact / PreCompact / SessionStart:compact);
+ * 4. the predecessor's last activity falls within
+ * `CRUTCH_LINK_WINDOW_MS` before now.
+ *
+ * Time proximity alone NEVER links. Removal plan (kanban
+ * t_1459706f): once the upstream PR merges and the deployed Hermes
+ * emits `parent_session_id`, delete this file and every call site
+ * carrying the CRUTCH(t_1459706f) marker; the native payload path in
+ * `resolve.ts` already takes precedence.
+ */
+
+import {
+ CRUTCH_LINK_WINDOW_MS,
+ type LineageLedgerEntry,
+ type LineageLedgerState,
+} from "./ledger.ts";
+import type { SessionLineage } from "./types.ts";
+
+/**
+ * Infer lineage for `sessionId` from the ledger, or return `null`
+ * when no conservative link exists. CRUTCH(t_1459706f).
+ */
+export function resolveCrutchLineage(
+ sessionId: string,
+ cwd: string | undefined,
+ ledger: LineageLedgerState,
+ nowMs: number,
+): SessionLineage | null {
+ const own = ledger.get(sessionId);
+ // A previously persisted link (from an earlier crutch or payload
+ // resolution) is authoritative for the rest of the session.
+ if (own?.lineage !== undefined && own.lineage.source !== "flat") {
+ return own.lineage;
+ }
+ // Rule 1: known session without a link = parallel session, not a
+ // continuation. Never re-guess.
+ if (own !== undefined) return null;
+ if (cwd === undefined || cwd.length === 0) return null;
+
+ let predecessor: LineageLedgerEntry | null = null;
+ for (const entry of ledger.values()) {
+ if (entry.sessionId === sessionId) continue;
+ if (entry.cwd !== cwd) continue; // Rule 2
+ if (!entry.compressionEvidence) continue; // Rule 3
+ const age = nowMs - entry.lastSeenMs;
+ if (age < 0 || age > CRUTCH_LINK_WINDOW_MS) continue; // Rule 4
+ if (predecessor === null || entry.lastSeenMs > predecessor.lastSeenMs) {
+ predecessor = entry;
+ }
+ }
+ if (predecessor === null) return null;
+
+ const parentLineage = predecessor.lineage;
+ return Object.freeze({
+ rootId: parentLineage !== undefined ? parentLineage.rootId : predecessor.sessionId,
+ parentId: predecessor.sessionId,
+ depth: (parentLineage !== undefined ? parentLineage.depth : 0) + 1,
+ source: "crutch" as const,
+ });
+}
diff --git a/src/core/brain/lineage/ledger.ts b/src/core/brain/lineage/ledger.ts
new file mode 100644
index 00000000..15547f5b
--- /dev/null
+++ b/src/core/brain/lineage/ledger.ts
@@ -0,0 +1,215 @@
+/**
+ * Session-lineage ledger (continuity-hygiene-freshness suite).
+ *
+ * Append-only JSONL under `Brain/.state/` (dot-directory: excluded
+ * from vault walking and search indexing, like `.snapshots`). One line
+ * per lifecycle observation: session id, timestamp, cwd, event name,
+ * whether the event evidences a compression boundary, and the resolved
+ * lineage when the caller already knows it.
+ *
+ * The ledger exists for one consumer: the interim crutch resolution in
+ * `crutch.ts` (CRUTCH(t_1459706f)). Once the host emits native lineage
+ * fields the ledger keeps working as a cache of resolved links but is
+ * no longer load-bearing.
+ *
+ * Contract for capture callers: resolve lineage BEFORE recording the
+ * session's own observation - the crutch treats "this session already
+ * has ledger history without a link" as proof it is a parallel
+ * session, not a continuation.
+ *
+ * Everything here is fail-soft: a missing ledger reads as empty,
+ * corrupt lines are skipped, and the file is compacted in place
+ * (atomic rewrite) once it grows past the line cap.
+ */
+
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname, join, posix } from "node:path";
+
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";
+import type { SessionLineage } from "./types.ts";
+
+/** Crutch link window: a continuation must start this close to the
+ * predecessor's compression evidence. CRUTCH(t_1459706f). */
+export const CRUTCH_LINK_WINDOW_MS = 900_000;
+
+/** Compact the ledger once it holds more lines than this. */
+const MAX_LEDGER_LINES = 512;
+/** Sessions retained (most recent first) by a compaction rewrite. */
+const RETAIN_SESSIONS = 256;
+
+const STATE_DIR_REL = posix.join(BRAIN_ROOT_REL, ".state");
+const LEDGER_FILE = "session-lineage.jsonl";
+
+export interface LineageObservation {
+ readonly sessionId: string;
+ /** ISO-8601 timestamp of the observation (host clock, injected). */
+ readonly at: string;
+ readonly cwd?: string;
+ readonly event: string;
+ /** True when this event evidences a compression boundary. */
+ readonly compressionEvidence?: boolean;
+ /** Resolved lineage to persist alongside the observation. */
+ readonly lineage?: SessionLineage;
+}
+
+export interface LineageLedgerEntry {
+ readonly sessionId: string;
+ readonly firstSeenMs: number;
+ readonly lastSeenMs: number;
+ readonly cwd?: string;
+ readonly lastEvent: string;
+ /** Evidence flag of the LATEST observation (not sticky). */
+ readonly compressionEvidence: boolean;
+ /** Last persisted lineage for the session, if any. */
+ readonly lineage?: SessionLineage;
+}
+
+export type LineageLedgerState = ReadonlyMap<string, LineageLedgerEntry>;
+
+export function sessionLineageLedgerPath(vault: string): string {
+ return ensureInsideVault(join(vault, STATE_DIR_REL, LEDGER_FILE), vault);
+}
+
+interface LedgerLine {
+ readonly sid: string;
+ readonly at: string;
+ readonly cwd?: string;
+ readonly event: string;
+ readonly ce?: boolean;
+ readonly parent?: string | null;
+ readonly root?: string;
+ readonly depth?: number;
+ readonly src?: SessionLineage["source"];
+}
+
+function toLine(obs: LineageObservation): LedgerLine {
+ return {
+ sid: obs.sessionId,
+ at: obs.at,
+ ...(obs.cwd !== undefined ? { cwd: obs.cwd } : {}),
+ event: obs.event,
+ ...(obs.compressionEvidence === true ? { ce: true } : {}),
+ ...(obs.lineage !== undefined
+ ? {
+ parent: obs.lineage.parentId,
+ root: obs.lineage.rootId,
+ depth: obs.lineage.depth,
+ src: obs.lineage.source,
+ }
+ : {}),
+ };
+}
+
+function parseLines(raw: string): LedgerLine[] {
+ const out: LedgerLine[] = [];
+ for (const line of raw.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.length === 0) continue;
+ try {
+ const parsed = JSON.parse(trimmed) as unknown;
+ if (parsed === null || typeof parsed !== "object") continue;
+ const candidate = parsed as LedgerLine;
+ if (typeof candidate.sid !== "string" || typeof candidate.at !== "string") continue;
+ out.push(candidate);
+ } catch {
+ // Fail-soft: a corrupt line never poisons the ledger.
+ }
+ }
+ return out;
+}
+
+function buildState(lines: ReadonlyArray<LedgerLine>): Map<string, LineageLedgerEntry> {
+ const state = new Map<string, LineageLedgerEntry>();
+ for (const line of lines) {
+ const atMs = Date.parse(line.at);
+ if (!Number.isFinite(atMs)) continue;
+ const prev = state.get(line.sid);
+ const lineage: SessionLineage | undefined =
+ typeof line.root === "string" && line.src !== undefined
+ ? Object.freeze({
+ rootId: line.root,
+ parentId: line.parent ?? null,
+ depth: typeof line.depth === "number" ? line.depth : 0,
+ source: line.src,
+ })
+ : prev?.lineage;
+ state.set(line.sid, {
+ sessionId: line.sid,
+ firstSeenMs: prev === undefined ? atMs : Math.min(prev.firstSeenMs, atMs),
+ lastSeenMs: prev === undefined ? atMs : Math.max(prev.lastSeenMs, atMs),
+ ...(line.cwd !== undefined
+ ? { cwd: line.cwd }
+ : prev?.cwd !== undefined
+ ? { cwd: prev.cwd }
+ : {}),
+ lastEvent: line.event ?? prev?.lastEvent ?? "unknown",
+ compressionEvidence: line.ce === true,
+ ...(lineage !== undefined ? { lineage } : {}),
+ });
+ }
+ return state;
+}
+
+/** Read the ledger into per-session state. Missing file reads empty. */
+export function readLineageLedger(vault: string): LineageLedgerState {
+ const path = sessionLineageLedgerPath(vault);
+ if (!existsSync(path)) return new Map();
+ let raw: string;
+ try {
+ raw = readFileSync(path, "utf8");
+ } catch {
+ return new Map();
+ }
+ return buildState(parseLines(raw));
+}
+
+/**
+ * Append one observation; compact the file (atomic rewrite keeping the
+ * most recent sessions) once it crosses the line cap. Fail-soft: any
+ * filesystem error is swallowed - lineage is an enhancement, never a
+ * capture blocker.
+ */
+export function recordLineageObservation(vault: string, obs: LineageObservation): void {
+ try {
+ const path = sessionLineageLedgerPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ const serialized = `${JSON.stringify(toLine(obs))}\n`;
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
+ const lines = parseLines(existing);
+ if (lines.length + 1 > MAX_LEDGER_LINES) {
+ lines.push(toLine(obs));
+ const state = buildState(lines);
+ const retained = [...state.values()]
+ .toSorted((a, b) => b.lastSeenMs - a.lastSeenMs)
+ .slice(0, RETAIN_SESSIONS);
+ // One summary line per retained session, oldest first so a
+ // future append keeps chronological order readable.
+ retained.reverse();
+ const compacted = retained
+ .map((entry) =>
+ JSON.stringify({
+ sid: entry.sessionId,
+ at: new Date(entry.lastSeenMs).toISOString(),
+ ...(entry.cwd !== undefined ? { cwd: entry.cwd } : {}),
+ event: entry.lastEvent,
+ ...(entry.compressionEvidence ? { ce: true } : {}),
+ ...(entry.lineage !== undefined
+ ? {
+ parent: entry.lineage.parentId,
+ root: entry.lineage.rootId,
+ depth: entry.lineage.depth,
+ src: entry.lineage.source,
+ }
+ : {}),
+ }),
+ )
+ .join("\n");
+ atomicWriteFileSync(path, `${compacted}\n`);
+ return;
+ }
+ appendFileSync(path, serialized, "utf8");
+ } catch {
+ // Fail-soft by contract.
+ }
+}
diff --git a/src/core/brain/lineage/resolve.ts b/src/core/brain/lineage/resolve.ts
new file mode 100644
index 00000000..09c6e812
--- /dev/null
+++ b/src/core/brain/lineage/resolve.ts
@@ -0,0 +1,73 @@
+/**
+ * Session-lineage resolution (continuity-hygiene-freshness suite).
+ *
+ * Single resolution point for "which conversation does this session id
+ * belong to". Precedence: native payload fields, then the interim
+ * ledger crutch, then flat. See `types.ts` for the contract and
+ * `crutch.ts` for the conservative inference rules.
+ */
+
+import { resolveCrutchLineage } from "./crutch.ts";
+import type { LineageLedgerState } from "./ledger.ts";
+import type { LineageHints, SessionLineage } from "./types.ts";
+
+export interface ResolveLineageOptions {
+ /** Ledger state for the crutch path; omit to disable the crutch. */
+ readonly ledger?: LineageLedgerState;
+ /** Clock injected by the caller (epoch ms). Required for the crutch. */
+ readonly nowMs?: number;
+}
+
+function readId(value: string | null | undefined): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
+}
+
+/** Resolve the lineage of one session id. Never throws. */
+export function resolveSessionLineage(
+ hints: LineageHints,
+ opts: ResolveLineageOptions = {},
+): SessionLineage {
+ const sessionId = hints.sessionId;
+
+ // Native path: any genuine lineage field on the payload wins. A
+ // parent or root equal to the session itself carries no information
+ // (the deployed Hermes collapses parent into session_id exactly this
+ // way) and is ignored.
+ const parentRaw = readId(hints.parentSessionId);
+ const rootRaw = readId(hints.rootSessionId);
+ const parentId = parentRaw !== null && parentRaw !== sessionId ? parentRaw : null;
+ const rootFromPayload = rootRaw !== null && rootRaw !== sessionId ? rootRaw : null;
+ if (parentId !== null || rootFromPayload !== null) {
+ // A payload that names only its direct parent must not promote
+ // that parent to root blindly - in a chain A -> B -> C the parent
+ // B itself descends from A. When the ledger knows the parent's own
+ // lineage, inherit its root (and continue its depth count).
+ const parentLineage = parentId !== null ? opts.ledger?.get(parentId)?.lineage : undefined;
+ const inheritedRoot =
+ parentLineage !== undefined && parentLineage.source !== "flat" ? parentLineage.rootId : null;
+ const depthRaw = hints.compressionDepth;
+ const depth =
+ typeof depthRaw === "number" && Number.isInteger(depthRaw) && depthRaw >= 0
+ ? depthRaw
+ : parentId !== null
+ ? (parentLineage !== undefined && parentLineage.source !== "flat"
+ ? parentLineage.depth
+ : 0) + 1
+ : 0;
+ return Object.freeze({
+ rootId: rootFromPayload ?? inheritedRoot ?? parentId ?? sessionId,
+ parentId,
+ depth,
+ source: "payload" as const,
+ });
+ }
+
+ // Interim inference for hosts without native lineage fields.
+ // CRUTCH(t_1459706f).
+ if (opts.ledger !== undefined) {
+ const inferred = resolveCrutchLineage(sessionId, hints.cwd, opts.ledger, opts.nowMs ?? 0);
+ if (inferred !== null) return inferred;
+ }
+
+ return Object.freeze({ rootId: sessionId, parentId: null, depth: 0, source: "flat" as const });
+}
diff --git a/src/core/brain/lineage/types.ts b/src/core/brain/lineage/types.ts
new file mode 100644
index 00000000..8118ede2
--- /dev/null
+++ b/src/core/brain/lineage/types.ts
@@ -0,0 +1,54 @@
+/**
+ * Session-lineage kernel types (continuity-hygiene-freshness suite;
+ * kanban t_d08ccc5a / t_a94623ad).
+ *
+ * One logical conversation can span several runtime session ids when
+ * the host compresses context and rotates the id. The kernel resolves
+ * every session id to a lineage: the root id of the conversation, the
+ * immediate parent segment, and how many compression boundaries deep
+ * the segment sits. Three sources, in strict precedence order:
+ *
+ * - `payload`: the hook payload carried native lineage fields
+ * (`parent_session_id` et al. - upstream Hermes PR #42940).
+ * - `crutch`: the interim ledger-based inference for hosts that do
+ * not emit lineage yet. See `crutch.ts`, CRUTCH(t_1459706f).
+ * - `flat`: no lineage known; the session is its own root. This is
+ * byte-identical to the pre-lineage behavior and the fallback for
+ * every ambiguous case.
+ */
+
+export type SessionLineageSource = "payload" | "crutch" | "flat";
+
+export interface SessionLineage {
+ /** Root session id of the whole conversation (self when flat). */
+ readonly rootId: string;
+ /** Immediate predecessor segment, `null` for a root segment. */
+ readonly parentId: string | null;
+ /** Compression boundaries between this segment and the root. */
+ readonly depth: number;
+ readonly source: SessionLineageSource;
+}
+
+/**
+ * Lineage-relevant fields extracted from a hook payload. All optional
+ * except the session id; absent fields simply lower the resolution
+ * source down the precedence ladder.
+ */
+export interface LineageHints {
+ readonly sessionId: string;
+ readonly parentSessionId?: string | null;
+ readonly rootSessionId?: string | null;
+ readonly compressionDepth?: number | null;
+ /** Working directory the host reported for the session, if any. */
+ readonly cwd?: string;
+}
+
+/**
+ * True when a lifecycle event signals that a compression boundary was
+ * just crossed. Structural check only: event names and the
+ * SessionStart `source` discriminator, never message text.
+ */
+export function isCompressionEvidenceEvent(event: string, sessionStartSource?: string): boolean {
+ if (event === "PostCompact" || event === "PreCompact") return true;
+ return event === "SessionStart" && sessionStartSource === "compact";
+}
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index 65502e36..bffd83c1 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -24,9 +24,12 @@ import { parseBrainYaml, type ParsedBlock } from "./yaml-parse.ts";
import type {
BrainActiveConfig,
+ BrainAnticipatoryConfig,
BrainConfig,
BrainGuardrailConfig,
BrainHealthConfig,
+ BrainHygieneConfig,
+ BrainRecallConfig,
BrainLinkGraphConfig,
BrainNotesConfig,
BrainSessionsConfig,
@@ -1496,6 +1499,95 @@ export function validateBrainConfigDetailed(
}
}
+ // Optional `hygiene:` block (continuity-hygiene-freshness suite).
+ let hygiene: BrainHygieneConfig | undefined;
+ if ("hygiene" in obj) {
+ const raw = obj["hygiene"];
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
+ throw new BrainConfigError(
+ `block must be a map of keys; got ${describe(raw)}`,
+ "hygiene",
+ source,
+ );
+ }
+ const rawMap = raw as Record<string, unknown>;
+ const partial: { resolver_cmd?: string; dedup_threshold?: number } = {};
+ if ("resolver_cmd" in rawMap) {
+ const cmd = rawMap["resolver_cmd"];
+ if (typeof cmd !== "string" || cmd.trim() === "") {
+ throw new BrainConfigError(
+ `must be a non-empty string; got ${describe(cmd)}`,
+ "hygiene.resolver_cmd",
+ source,
+ );
+ }
+ partial.resolver_cmd = cmd;
+ }
+ if ("dedup_threshold" in rawMap) {
+ const threshold = rawMap["dedup_threshold"];
+ if (typeof threshold !== "number" || !(threshold > 0) || threshold > 1) {
+ throw new BrainConfigError(
+ `must be a number in (0, 1]; got ${describe(threshold)}`,
+ "hygiene.dedup_threshold",
+ source,
+ );
+ }
+ partial.dedup_threshold = threshold;
+ }
+ hygiene = Object.freeze(partial);
+ }
+
+ // Optional `anticipatory:` block (continuity-hygiene-freshness suite).
+ let anticipatory: BrainAnticipatoryConfig | undefined;
+ if ("anticipatory" in obj) {
+ const raw = obj["anticipatory"];
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
+ throw new BrainConfigError(
+ `block must be a map of keys; got ${describe(raw)}`,
+ "anticipatory",
+ source,
+ );
+ }
+ const rawMap = raw as Record<string, unknown>;
+ const partial: { ttl_seconds?: number; max_tokens?: number } = {};
+ if ("ttl_seconds" in rawMap) {
+ requirePositiveInteger("anticipatory.ttl_seconds", rawMap["ttl_seconds"], source);
+ partial.ttl_seconds = rawMap["ttl_seconds"] as number;
+ }
+ if ("max_tokens" in rawMap) {
+ requirePositiveInteger("anticipatory.max_tokens", rawMap["max_tokens"], source);
+ partial.max_tokens = rawMap["max_tokens"] as number;
+ }
+ anticipatory = Object.freeze(partial);
+ }
+
+ // Optional `recall:` block (continuity-hygiene-freshness suite).
+ let recall: BrainRecallConfig | undefined;
+ if ("recall" in obj) {
+ const raw = obj["recall"];
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
+ throw new BrainConfigError(
+ `block must be a map of keys; got ${describe(raw)}`,
+ "recall",
+ source,
+ );
+ }
+ const rawMap = raw as Record<string, unknown>;
+ const partial: { degradation?: "hard-cut" | "staged" } = {};
+ if ("degradation" in rawMap) {
+ const mode = rawMap["degradation"];
+ if (mode !== "hard-cut" && mode !== "staged") {
+ throw new BrainConfigError(
+ `must be 'hard-cut' or 'staged'; got ${describe(mode)}`,
+ "recall.degradation",
+ source,
+ );
+ }
+ partial.degradation = mode;
+ }
+ recall = Object.freeze(partial);
+ }
+
const config: BrainConfig = {
schema_version: schemaVersion,
primary_agent: primaryAgent,
@@ -1529,6 +1621,9 @@ export function validateBrainConfigDetailed(
...(sessions !== undefined ? { sessions } : {}),
...(health !== undefined ? { health } : {}),
...(schema !== undefined ? { schema } : {}),
+ ...(hygiene !== undefined ? { hygiene } : {}),
+ ...(anticipatory !== undefined ? { anticipatory } : {}),
+ ...(recall !== undefined ? { recall } : {}),
};
return { config, warnings };
diff --git a/src/core/brain/pre-compress-pack.ts b/src/core/brain/pre-compress-pack.ts
index ee80559e..e8bab053 100644
--- a/src/core/brain/pre-compress-pack.ts
+++ b/src/core/brain/pre-compress-pack.ts
@@ -20,7 +20,7 @@ import { join } from "node:path";
import { brainActivePath, brainDirs } from "./paths.ts";
import { parsePreference } from "./preference.ts";
-import { applyCharBudget } from "./recall-budget.ts";
+import { applyCharBudget, type CharBudgetDegradationMode } from "./recall-budget.ts";
import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
import { emitGatedTelemetry } from "./continuity/emit.ts";
import { emitRecallTelemetry, type RecallTelemetryOptions } from "./recall-telemetry.ts";
@@ -62,6 +62,12 @@ export interface PreCompressOptions {
readonly maxCharsPerMemory?: number;
/** Total character cap across the bundle; <= 0 / undefined disables. */
readonly maxTotalChars?: number;
+ /**
+ * Per-entry trim strategy (continuity-hygiene-freshness suite):
+ * `staged` degrades an over-budget entry at structural boundaries
+ * instead of cutting mid-sentence. Default keeps the hard cut.
+ */
+ readonly degradation?: CharBudgetDegradationMode;
/** Opt-in audit receipt for the final emitted addendum. */
readonly receipt?: ContextReceiptOptions;
/** Opt-in telemetry for recall coverage and gap diagnostics. */
@@ -146,6 +152,7 @@ export function buildPreCompressPack(vault: string, opts: PreCompressOptions): P
const budgeted = applyCharBudget(entries, {
maxCharsPerEntry: opts.maxCharsPerMemory,
maxTotalChars: opts.maxTotalChars,
+ ...(opts.degradation !== undefined ? { degradation: opts.degradation } : {}),
});
let activeText: string | null = null;
diff --git a/src/core/brain/recall-budget.ts b/src/core/brain/recall-budget.ts
index 34faf6f4..64eecaa4 100644
--- a/src/core/brain/recall-budget.ts
+++ b/src/core/brain/recall-budget.ts
@@ -16,13 +16,29 @@
* are measured in Unicode code points, so multi-byte scripts and astral
* characters are counted and truncated without splitting a surrogate
* pair. Pure and deterministic: no I/O, clock, or randomness.
+ *
+ * Per-entry trimming supports two strategies
+ * (continuity-hygiene-freshness suite): the historical hard cut
+ * (default, byte-identical) and an opt-in staged degradation ladder
+ * that prefers structural boundaries - sentence terminators, then
+ * whole leading lines - over cutting mid-sentence.
*/
+export type CharBudgetDegradationMode = "hard-cut" | "staged";
+export type CharBudgetDegradationStage = "sentence" | "lines" | "hard";
+
export interface CharBudgetOptions {
/** Max code points per entry; <= 0 or undefined disables per-entry trimming. */
readonly maxCharsPerEntry?: number;
/** Max cumulative code points across kept entries; <= 0 or undefined disables. */
readonly maxTotalChars?: number;
+ /**
+ * Per-entry trim strategy. `hard-cut` (default) keeps the historical
+ * mid-sentence cut byte-identical; `staged` walks the deterministic
+ * degradation ladder: sentence-boundary trim, then whole leading
+ * lines, then hard cut.
+ */
+ readonly degradation?: CharBudgetDegradationMode;
}
export interface BudgetedEntry<T> {
@@ -31,6 +47,8 @@ export interface BudgetedEntry<T> {
readonly text: string;
/** True when `text` was truncated by `maxCharsPerEntry`. */
readonly trimmed: boolean;
+ /** Ladder stage that produced the trim (staged mode only). */
+ readonly degradation?: CharBudgetDegradationStage;
}
export interface CharBudgetResult<T> {
@@ -45,6 +63,62 @@ function codePoints(s: string): string[] {
return [...s];
}
+/**
+ * Sentence-terminator code points across scripts. Structural
+ * punctuation only - Latin/Cyrillic terminators, ellipsis, CJK full
+ * stops, Arabic question mark and full stop, Devanagari danda - never
+ * language-specific wordlists.
+ */
+const SENTENCE_TERMINATORS = new Set([
+ ".",
+ "!",
+ "?",
+ "…", // horizontal ellipsis
+ "。", // CJK full stop
+ "!", // fullwidth exclamation
+ "?", // fullwidth question
+ "؟", // Arabic question mark
+ "۔", // Arabic full stop
+ "।", // Devanagari danda
+ "॥", // Devanagari double danda
+]);
+
+interface DegradedText {
+ readonly text: string;
+ readonly stage: CharBudgetDegradationStage;
+}
+
+/**
+ * Walk the degradation ladder for one over-budget entry: cut after the
+ * last sentence terminator inside the window, else keep whole leading
+ * lines that fit, else hard-cut. Pure and deterministic.
+ */
+function degradeEntry(cps: ReadonlyArray<string>, budget: number): DegradedText {
+ const window = cps.slice(0, budget);
+
+ // Stage 1: last sentence terminator inside the window.
+ for (let i = window.length - 1; i >= 0; i--) {
+ if (!SENTENCE_TERMINATORS.has(window[i]!)) continue;
+ const candidate = window
+ .slice(0, i + 1)
+ .join("")
+ .trimEnd();
+ if (candidate.length > 0) return { text: candidate, stage: "sentence" };
+ break;
+ }
+
+ // Stage 2: whole leading lines that fit the window.
+ const windowText = window.join("");
+ const lastBreak = windowText.lastIndexOf("\n");
+ if (lastBreak > 0) {
+ const candidate = windowText.slice(0, lastBreak).trimEnd();
+ if (candidate.length > 0) return { text: candidate, stage: "lines" };
+ }
+
+ // Stage 3: the historical hard cut.
+ return { text: windowText, stage: "hard" };
+}
+
/**
* Apply per-entry and total character caps to an ordered entry list.
* With no caps set this is an identity pass (every entry kept, untrimmed,
@@ -64,10 +138,17 @@ export function applyCharBudget<T>(
for (const { item, text } of entries) {
let outText = text;
let trimmed = false;
+ let stage: CharBudgetDegradationStage | undefined;
if (perEntry > 0) {
const cps = codePoints(text);
if (cps.length > perEntry) {
- outText = cps.slice(0, perEntry).join("");
+ if (opts.degradation === "staged") {
+ const degraded = degradeEntry(cps, perEntry);
+ outText = degraded.text;
+ stage = degraded.stage;
+ } else {
+ outText = cps.slice(0, perEntry).join("");
+ }
trimmed = true;
}
}
@@ -79,7 +160,12 @@ export function applyCharBudget<T>(
continue;
}
used += len;
- kept.push({ item, text: outText, trimmed });
+ kept.push({
+ item,
+ text: outText,
+ trimmed,
+ ...(stage !== undefined ? { degradation: stage } : {}),
+ });
}
return Object.freeze({
diff --git a/src/core/brain/recompile.ts b/src/core/brain/recompile.ts
new file mode 100644
index 00000000..e109bb90
--- /dev/null
+++ b/src/core/brain/recompile.ts
@@ -0,0 +1,219 @@
+/**
+ * Targeted recompile of stale derived pages
+ * (continuity-hygiene-freshness suite; kanban t_fe490119).
+ *
+ * Instead of a full re-ingestion, refresh exactly the pages whose
+ * recorded sources changed: the planner maps freshness findings to a
+ * typed plan, the executor re-derives through the page's ORIGINAL
+ * pipeline. Today's known pipeline is the handoff note (session
+ * transcript -> deterministic note); pages without a known pipeline
+ * stay `manual` and orphaned pages stage an archive cleanup into
+ * `Brain/.snapshots/` - moved, never deleted. Dry-run previews the
+ * whole plan with zero writes.
+ */
+
+import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs";
+import { basename, isAbsolute, join } from "node:path";
+
+import { appendAuditRecord } from "../reliability/audit.ts";
+import { scanFreshness } from "./freshness.ts";
+import { writeHandoffNote } from "./handoff.ts";
+import { brainDirs, BRAIN_SNAPSHOTS_REL } from "./paths.ts";
+import { detectAdapter } from "./sessions/registry.ts";
+import type { SessionTurn } from "./sessions/types.ts";
+import { isoDate } from "./time.ts";
+import { parseFrontmatter } from "../vault.ts";
+
+export type RecompileEntryKind = "rederive-handoff" | "cleanup" | "manual";
+
+export interface RecompileEntry {
+ readonly kind: RecompileEntryKind;
+ readonly page: string;
+ /** Transcript path for `rederive-handoff` entries. */
+ readonly transcript?: string;
+ readonly session_id?: string;
+ /** Why the page landed in this bucket. */
+ readonly reason: string;
+}
+
+export interface RecompilePlan {
+ readonly entries: ReadonlyArray<RecompileEntry>;
+}
+
+export interface ExecuteRecompileOptions {
+ readonly dryRun?: boolean;
+ readonly agent: string;
+ readonly now: Date;
+}
+
+export interface RecompileResult {
+ readonly dry_run: boolean;
+ readonly rederived: ReadonlyArray<string>;
+ readonly archived: ReadonlyArray<string>;
+ readonly manual: ReadonlyArray<string>;
+ readonly errors: ReadonlyArray<{ page: string; message: string }>;
+}
+
+function resolveSource(vault: string, source: string): string {
+ return isAbsolute(source) ? source : join(vault, source);
+}
+
+/**
+ * Build the recompile plan from the current freshness state. Read-only
+ * and side-effect free - this IS the dry-run preview.
+ */
+export function planRecompile(vault: string): RecompilePlan {
+ const freshness = scanFreshness(vault);
+ const entries: RecompileEntry[] = [];
+
+ for (const stale of freshness.stale) {
+ const [meta] = parseFrontmatter(stale.page);
+ const sessionId = typeof meta["session_id"] === "string" ? meta["session_id"] : null;
+ const sources = Array.isArray(meta["source_paths"]) ? (meta["source_paths"] as string[]) : [];
+ const transcript = sources.length === 1 ? resolveSource(vault, sources[0]!) : null;
+ if (sessionId !== null && transcript !== null && existsSync(transcript)) {
+ entries.push(
+ Object.freeze({
+ kind: "rederive-handoff" as const,
+ page: stale.page,
+ transcript,
+ session_id: sessionId,
+ reason: `changed source(s): ${[...stale.changed_sources, ...stale.missing_sources].join(", ")}`,
+ }),
+ );
+ continue;
+ }
+ entries.push(
+ Object.freeze({
+ kind: "manual" as const,
+ page: stale.page,
+ reason: "no known derivation pipeline for this page",
+ }),
+ );
+ }
+
+ for (const orphan of freshness.orphaned) {
+ entries.push(
+ Object.freeze({
+ kind: "cleanup" as const,
+ page: orphan,
+ reason: "every recorded source is gone",
+ }),
+ );
+ }
+
+ return Object.freeze({ entries: Object.freeze(entries) });
+}
+
+/**
+ * Trust model: transcript paths come from the derived page's own
+ * `source_paths` frontmatter, i.e. from inside the vault trust
+ * boundary (only the operator and their agents write vault pages).
+ * Transcripts legitimately live OUTSIDE the vault (host session
+ * directories), so an inside-vault check would break the feature; the
+ * adapter format detection below bounds what a pointed-at file can be
+ * parsed as.
+ */
+async function readTranscriptTurns(transcript: string): Promise<SessionTurn[] | null> {
+ const text = readFileSync(transcript, "utf8");
+ const nl = text.indexOf("\n");
+ const adapter = detectAdapter(nl < 0 ? text : text.slice(0, nl));
+ if (adapter === null) return null;
+ const turns: SessionTurn[] = [];
+ for await (const turn of adapter.iterate(transcript)) turns.push(turn);
+ return turns.length > 0 ? turns : null;
+}
+
+/**
+ * Move a vault page into a dated hygiene snapshot directory - the
+ * shared "archive, never delete" primitive for recompile cleanups and
+ * hygiene `archive` / `forget` actions.
+ */
+export function archivePage(vault: string, page: string, now: Date): string {
+ const dir = join(vault, BRAIN_SNAPSHOTS_REL, `hygiene-${isoDate(now)}`);
+ mkdirSync(dir, { recursive: true });
+ let target = join(dir, basename(page));
+ let suffix = 1;
+ while (existsSync(target)) {
+ target = join(dir, `${basename(page, ".md")}-${suffix}.md`);
+ suffix++;
+ }
+ renameSync(page, target);
+ return target;
+}
+
+/**
+ * Execute a recompile plan. Per-entry fail-soft: one broken page lands
+ * in `errors` and the rest still process. Every mutation is audited.
+ */
+export async function executeRecompile(
+ vault: string,
+ plan: RecompilePlan,
+ opts: ExecuteRecompileOptions,
+): Promise<RecompileResult> {
+ const dryRun = opts.dryRun === true;
+ const rederived: string[] = [];
+ const archived: string[] = [];
+ const manual: string[] = [];
+ const errors: { page: string; message: string }[] = [];
+
+ for (const entry of plan.entries) {
+ if (entry.kind === "manual") {
+ manual.push(entry.page);
+ continue;
+ }
+ if (dryRun) continue;
+ try {
+ if (entry.kind === "rederive-handoff") {
+ const turns = await readTranscriptTurns(entry.transcript!);
+ if (turns === null) {
+ errors.push({ page: entry.page, message: "transcript is no longer readable" });
+ continue;
+ }
+ writeHandoffNote(vault, {
+ sessionId: entry.session_id!,
+ agent: opts.agent,
+ now: opts.now,
+ turns,
+ sourcePaths: [entry.transcript!],
+ targetPath: entry.page,
+ });
+ rederived.push(entry.page);
+ } else {
+ archived.push(archivePage(vault, entry.page, opts.now));
+ }
+ } catch (error) {
+ errors.push({
+ page: entry.page,
+ message: error instanceof Error ? error.message : "recompile failed",
+ });
+ }
+ }
+
+ if (
+ !dryRun &&
+ (rederived.length > 0 || archived.length > 0 || manual.length > 0 || errors.length > 0)
+ ) {
+ appendAuditRecord(join(brainDirs(vault).log, "hygiene"), {
+ timestamp: opts.now.toISOString(),
+ actor: opts.agent,
+ action: "targeted_recompile",
+ target: "Brain",
+ ok: errors.length === 0,
+ details: {
+ rederived: rederived.length,
+ archived: archived.length,
+ manual: manual.length,
+ errors: errors.length,
+ },
+ });
+ }
+
+ return Object.freeze({
+ dry_run: dryRun,
+ rederived: Object.freeze(rederived),
+ archived: Object.freeze(archived),
+ manual: Object.freeze(manual),
+ errors: Object.freeze(errors),
+ });
+}
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index cc723a74..8adb94df 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -18,6 +18,10 @@ import { resolveSessionHandoff } from "../config.ts";
import { writeHandoffNote, type HandoffNoteResult } from "./handoff.ts";
import { detectAdapter } from "./sessions/registry.ts";
import type { SessionTurn } from "./sessions/types.ts";
+import { readLineageLedger, recordLineageObservation } from "./lineage/ledger.ts";
+import { resolveSessionLineage } from "./lineage/resolve.ts";
+import { isCompressionEvidenceEvent, type SessionLineage } from "./lineage/types.ts";
+import { refreshAnticipatoryCache } from "./anticipatory-cache.ts";
export interface CaptureSessionLifecycleOptions {
readonly agent: string;
@@ -44,6 +48,12 @@ export interface CaptureSessionLifecycleResult {
readonly focus_cleared?: boolean;
/** Path of the handoff note a SessionEnd event produced (gated). */
readonly handoff_path?: string;
+ /**
+ * Session lineage when the session is part of a compression chain
+ * (continuity-hygiene-freshness suite). Absent for flat sessions so
+ * the pre-lineage result shape stays byte-identical.
+ */
+ readonly lineage?: SessionLineage;
}
interface NormalizedPayload {
@@ -53,6 +63,12 @@ interface NormalizedPayload {
readonly promptText?: string;
readonly toolName?: string;
readonly toolInput?: unknown;
+ readonly cwd?: string;
+ readonly parentSessionId?: string;
+ readonly rootSessionId?: string;
+ readonly compressionDepth?: number;
+ /** SessionStart discriminator (`startup|resume|clear|compact`). */
+ readonly sessionStartSource?: string;
readonly malformed: number;
}
@@ -86,6 +102,48 @@ export async function captureSessionLifecycleEvent(
const decision = boundary.sessionDecision(normalized.sessionId, normalized.transcriptPath);
const mayWrite = decision === "capture";
+ // Session lineage (continuity-hygiene-freshness): resolve BEFORE
+ // recording this session's own ledger observation - the crutch
+ // treats prior unlinked history as proof of a parallel session.
+ // Read-only resolution runs for every session; the ledger only
+ // grows for captured, non-dry runs. Fail-soft throughout.
+ let lineage: SessionLineage | undefined;
+ if (normalized.sessionId !== undefined) {
+ try {
+ lineage = resolveSessionLineage(
+ {
+ sessionId: normalized.sessionId,
+ ...(normalized.parentSessionId !== undefined
+ ? { parentSessionId: normalized.parentSessionId }
+ : {}),
+ ...(normalized.rootSessionId !== undefined
+ ? { rootSessionId: normalized.rootSessionId }
+ : {}),
+ ...(normalized.compressionDepth !== undefined
+ ? { compressionDepth: normalized.compressionDepth }
+ : {}),
+ ...(normalized.cwd !== undefined ? { cwd: normalized.cwd } : {}),
+ },
+ { ledger: readLineageLedger(vault), nowMs: now.getTime() },
+ );
+ if (mayWrite && !opts.dryRun) {
+ recordLineageObservation(vault, {
+ sessionId: normalized.sessionId,
+ at: now.toISOString(),
+ ...(normalized.cwd !== undefined ? { cwd: normalized.cwd } : {}),
+ event: normalized.event,
+ ...(isCompressionEvidenceEvent(normalized.event, normalized.sessionStartSource)
+ ? { compressionEvidence: true }
+ : {}),
+ ...(lineage.source !== "flat" ? { lineage } : {}),
+ });
+ }
+ } catch {
+ lineage = undefined; // lineage is an enhancement, never a blocker
+ }
+ }
+ const chainLineage = lineage !== undefined && lineage.source !== "flat" ? lineage : undefined;
+
let promptText = normalized.promptText;
if (mayWrite && promptText !== undefined && boundary.suppressMessage(promptText)) {
counters.suppressed_messages++;
@@ -153,6 +211,27 @@ export async function captureSessionLifecycleEvent(
}
}
+ // Anticipatory context cache (continuity-hygiene-freshness,
+ // t_4cee9df5): piggyback on events that already fire - no daemon, no
+ // watcher. TTL debounce lives inside the refresh; suppressed prompt
+ // text never reaches the cache (promptText is already cleared above).
+ if (
+ mayWrite &&
+ !opts.dryRun &&
+ normalized.sessionId !== undefined &&
+ (normalized.event === "UserPromptSubmit" || normalized.event === "PostToolUse")
+ ) {
+ try {
+ refreshAnticipatoryCache(vault, {
+ sessionId: normalized.sessionId,
+ ...(promptText !== undefined ? { signalText: promptText } : {}),
+ now,
+ });
+ } catch {
+ // The cache is an enhancement, never a capture blocker.
+ }
+ }
+
let logPath: string | undefined;
if (mayWrite && !opts.dryRun) {
logPath = appendLifecycleLog(vault, normalized, opts.agent, now, counters);
@@ -169,6 +248,14 @@ export async function captureSessionLifecycleEvent(
...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),
dry_run: opts.dryRun === true,
boundary_decision: decision,
+ ...(chainLineage !== undefined
+ ? {
+ lineage_root: chainLineage.rootId,
+ ...(chainLineage.parentId !== null ? { lineage_parent: chainLineage.parentId } : {}),
+ lineage_depth: chainLineage.depth,
+ lineage_source: chainLineage.source,
+ }
+ : {}),
...counters,
},
});
@@ -188,10 +275,17 @@ export async function captureSessionLifecycleEvent(
...(logPath ? { log_path: logPath } : {}),
...(focusCleared ? { focus_cleared: true } : {}),
...(handoffPath !== undefined ? { handoff_path: handoffPath } : {}),
+ ...(chainLineage !== undefined ? { lineage: chainLineage } : {}),
};
}
-/** Read the recorded transcript via the session adapters and write a handoff note. */
+/**
+ * Read the recorded transcript via the session adapters and write a
+ * handoff note. Trust model: `transcript_path` is produced by the host
+ * runtime itself (Claude Code / Hermes hand their own transcript path
+ * to their own hook); it is not user-typed input, which is why no
+ * inside-vault check applies - transcripts live in host directories.
+ */
async function writeHandoffNoteFromTranscript(
vault: string,
normalized: NormalizedPayload,
@@ -212,6 +306,7 @@ async function writeHandoffNoteFromTranscript(
sessionId: normalized.sessionId ?? basename(path),
agent,
now,
+ sourcePaths: [path],
});
}
@@ -226,10 +321,26 @@ function normalizePayload(payload: unknown): NormalizedPayload {
"unknown";
const sessionId = readNonEmptyString(record["session_id"]);
const transcriptPath = readNonEmptyString(record["transcript_path"]);
+ const cwd = readNonEmptyString(record["cwd"]);
+ const parentSessionId = readNonEmptyString(record["parent_session_id"]);
+ const rootSessionId = readNonEmptyString(record["root_session_id"]);
+ const compressionDepthRaw = record["compression_depth"];
+ const compressionDepth =
+ typeof compressionDepthRaw === "number" &&
+ Number.isInteger(compressionDepthRaw) &&
+ compressionDepthRaw >= 0
+ ? compressionDepthRaw
+ : undefined;
+ const sessionStartSource = readNonEmptyString(record["source"]);
return {
event,
...(sessionId ? { sessionId } : {}),
...(transcriptPath ? { transcriptPath } : {}),
+ ...(cwd ? { cwd } : {}),
+ ...(parentSessionId ? { parentSessionId } : {}),
+ ...(rootSessionId ? { rootSessionId } : {}),
+ ...(compressionDepth !== undefined ? { compressionDepth } : {}),
+ ...(sessionStartSource ? { sessionStartSource } : {}),
...(extractPromptText(record) ? { promptText: extractPromptText(record)! } : {}),
...(readNonEmptyString(record["tool_name"])
? { toolName: readNonEmptyString(record["tool_name"])! }
diff --git a/src/core/brain/session-recall.ts b/src/core/brain/session-recall.ts
index 99ac1fb4..49fa5e64 100644
--- a/src/core/brain/session-recall.ts
+++ b/src/core/brain/session-recall.ts
@@ -2,6 +2,8 @@ import { createHash } from "node:crypto";
import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+import { readLineageLedger } from "./lineage/ledger.ts";
+import type { SessionLineage } from "./lineage/types.ts";
import type { SessionTurn } from "./sessions/types.ts";
export interface ImportSessionRecallInput {
@@ -9,6 +11,12 @@ export interface ImportSessionRecallInput {
readonly turns: ReadonlyArray<SessionTurn>;
readonly createdAt?: string;
readonly summaryGroupSize?: number;
+ /**
+ * Lineage of the imported segment (continuity-hygiene-freshness
+ * suite). Non-flat lineage is stamped onto every imported record so
+ * recall can stitch the conversation across compression boundaries.
+ */
+ readonly lineage?: SessionLineage;
}
export interface ImportSessionRecallResult {
@@ -42,11 +50,23 @@ export interface DescribeSessionRecallInput {
readonly sessionId: string;
}
+export interface SessionLineageSegment {
+ readonly session_id: string;
+ readonly parent_session_id: string | null;
+}
+
export interface DescribeSessionRecallResult {
readonly session_id: string;
readonly raw_turns: number;
readonly summary_nodes: number;
readonly depths: Readonly<Record<string, number>>;
+ /**
+ * Lineage fields, present only when the session is part of a
+ * multi-segment compression chain - flat sessions keep the exact
+ * pre-lineage result shape.
+ */
+ readonly lineage_root?: string;
+ readonly segments?: ReadonlyArray<SessionLineageSegment>;
}
export interface ExpandSessionRecallInput {
@@ -79,8 +99,10 @@ export function importSessionRecall(
input: ImportSessionRecallInput,
): ImportSessionRecallResult {
const createdAt = input.createdAt ?? new Date().toISOString();
+ const lineage =
+ input.lineage !== undefined && input.lineage.source !== "flat" ? input.lineage : undefined;
const rawTurns = input.turns.map((turn) =>
- importRawTurn(vault, input.sessionId, turn, createdAt),
+ importRawTurn(vault, input.sessionId, turn, createdAt, lineage),
);
const summaryNodes = [
...importSummaryDepth(
@@ -90,6 +112,7 @@ export function importSessionRecall(
1,
input.summaryGroupSize ?? DEFAULT_GROUP_SIZE,
createdAt,
+ lineage,
),
];
summaryNodes.push(
@@ -100,6 +123,7 @@ export function importSessionRecall(
2,
input.summaryGroupSize ?? DEFAULT_GROUP_SIZE,
createdAt,
+ lineage,
),
);
return Object.freeze({
@@ -141,9 +165,45 @@ export function describeSessionRecall(
raw_turns: rawTurns.length,
summary_nodes: summaries.length,
depths: Object.freeze(depths),
+ ...lineageDescription(vault, records, input.sessionId),
});
}
+/**
+ * Lineage fields for `describeSessionRecall`: present only when the
+ * conversation spans more than one segment. Segments are listed in
+ * chronological order of their first record, each with its immediate
+ * parent so the continuity edge between adjacent segments is explicit.
+ */
+function lineageDescription(
+ vault: string,
+ records: ReadonlyArray<ContinuityRecord>,
+ sessionId: string,
+): { lineage_root?: string; segments?: ReadonlyArray<SessionLineageSegment> } {
+ const links = lineageLinks(vault, records);
+ const rootId = transitiveRootOf(sessionId, links);
+ const seen = new Set<string>();
+ const segments: SessionLineageSegment[] = [];
+ for (const record of records) {
+ const sid = record.payload["session_id"];
+ if (typeof sid !== "string" || seen.has(sid)) continue;
+ seen.add(sid);
+ segments.push(
+ Object.freeze({ session_id: sid, parent_session_id: links.get(sid)?.parentId ?? null }),
+ );
+ }
+ // A root segment can exist without records of its own (the chain was
+ // linked before the root transcript was ever imported); it still
+ // anchors the conversation, so list it first.
+ if (!seen.has(rootId)) {
+ segments.unshift(
+ Object.freeze({ session_id: rootId, parent_session_id: links.get(rootId)?.parentId ?? null }),
+ );
+ }
+ if (segments.length < 2) return {};
+ return { lineage_root: rootId, segments: Object.freeze(segments) };
+}
+
export function expandSessionRecall(
vault: string,
input: ExpandSessionRecallInput,
@@ -168,11 +228,21 @@ export function expandSessionRecall(
});
}
+function lineagePayloadFields(lineage: SessionLineage | undefined): Record<string, unknown> {
+ if (lineage === undefined) return {};
+ return {
+ root_session_id: lineage.rootId,
+ ...(lineage.parentId !== null ? { parent_session_id: lineage.parentId } : {}),
+ compression_depth: lineage.depth,
+ };
+}
+
function importRawTurn(
vault: string,
sessionId: string,
turn: SessionTurn,
createdAt: string,
+ lineage: SessionLineage | undefined,
): ContinuityRecord {
const text = turn.text ?? "";
const textHash = hash(text);
@@ -191,6 +261,7 @@ function importRawTurn(
text,
text_hash: textHash,
dedupe_key: dedupeKey,
+ ...lineagePayloadFields(lineage),
},
});
}
@@ -202,6 +273,7 @@ function importSummaryDepth(
depth: number,
groupSize: number,
createdAt: string,
+ lineage: SessionLineage | undefined,
): ContinuityRecord[] {
if (sources.length === 0) return [];
const nodes: ContinuityRecord[] = [];
@@ -237,6 +309,7 @@ function importSummaryDepth(
source_turn_ids: sourceTurnIds,
text_hash: hash(summary),
dedupe_key: dedupeKey,
+ ...lineagePayloadFields(lineage),
},
}),
);
@@ -245,13 +318,87 @@ function importSummaryDepth(
}
function sessionRecallRecords(vault: string, sessionId?: string): ContinuityRecord[] {
- return listContinuityRecords(vault)
- .filter(
- (record) =>
- (record.kind === "session_turn" || record.kind === "session_summary_node") &&
- (sessionId === undefined || record.payload["session_id"] === sessionId),
- )
- .sort((left, right) => compareRecords(left, right));
+ const records = listContinuityRecords(vault).filter(
+ (record) => record.kind === "session_turn" || record.kind === "session_summary_node",
+ );
+ let scoped = records;
+ if (sessionId !== undefined) {
+ const scope = lineageScope(vault, records, sessionId);
+ scoped = records.filter((record) => scope.has(String(record.payload["session_id"] ?? "")));
+ }
+ return scoped.sort((left, right) => compareRecords(left, right));
+}
+
+interface LineageLink {
+ readonly rootId: string;
+ readonly parentId: string | null;
+}
+
+/**
+ * Per-session lineage links visible to recall: stamped record payloads
+ * first, then persisted ledger links for captured-but-unimported
+ * segments. Flat sessions never appear in the map.
+ */
+function lineageLinks(
+ vault: string,
+ records: ReadonlyArray<ContinuityRecord>,
+): Map<string, LineageLink> {
+ const links = new Map<string, LineageLink>();
+ for (const record of records) {
+ const sid = record.payload["session_id"];
+ const root = record.payload["root_session_id"];
+ if (typeof sid !== "string" || typeof root !== "string" || links.has(sid)) continue;
+ const parent = record.payload["parent_session_id"];
+ links.set(sid, { rootId: root, parentId: typeof parent === "string" ? parent : null });
+ }
+ try {
+ for (const [sid, entry] of readLineageLedger(vault)) {
+ if (links.has(sid)) continue;
+ if (entry.lineage === undefined || entry.lineage.source === "flat") continue;
+ links.set(sid, { rootId: entry.lineage.rootId, parentId: entry.lineage.parentId });
+ }
+ } catch {
+ // Fail-soft: recall works from record payloads alone.
+ }
+ return links;
+}
+
+/**
+ * Transitive root of one session id: follow recorded roots and parents
+ * until a fixpoint, so a chain whose segments each recorded only their
+ * direct predecessor (A -> B -> C with per-segment links) still
+ * resolves every segment to the SAME root. Cycle-guarded.
+ */
+function transitiveRootOf(sessionId: string, links: ReadonlyMap<string, LineageLink>): string {
+ let current = sessionId;
+ const seen = new Set<string>([current]);
+ for (;;) {
+ const link = links.get(current);
+ const next = link === undefined ? null : link.rootId !== current ? link.rootId : link.parentId;
+ if (next === null || seen.has(next)) return current;
+ seen.add(next);
+ current = next;
+ }
+}
+
+/**
+ * Every session id belonging to the same conversation as `sessionId`:
+ * the lineage root, all segments resolving to that root (transitively),
+ * and the id itself. A flat session resolves to just itself, keeping
+ * pre-lineage recall byte-identical.
+ */
+function lineageScope(
+ vault: string,
+ records: ReadonlyArray<ContinuityRecord>,
+ sessionId: string,
+): Set<string> {
+ const links = lineageLinks(vault, records);
+ const rootId = transitiveRootOf(sessionId, links);
+ const scope = new Set<string>([sessionId, rootId]);
+ for (const sid of links.keys()) {
+ if (transitiveRootOf(sid, links) === rootId) scope.add(sid);
+ }
+ return scope;
}
function hitFor(
diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.ts
index 2c1f60f5..e0075feb 100644
--- a/src/core/brain/sessions/import.ts
+++ b/src/core/brain/sessions/import.ts
@@ -44,6 +44,9 @@ import {
import { validateBrainFeedbackInput } from "./validate-feedback.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "../capture-boundary.ts";
import { extractFacts, routeExtractedFacts } from "../fact-extract.ts";
+import { readLineageLedger } from "../lineage/ledger.ts";
+import { resolveSessionLineage } from "../lineage/resolve.ts";
+import type { SessionLineage } from "../lineage/types.ts";
export interface ImportSessionOptions {
/** Agent identity stamped on signals when the turn has no own agent. */
@@ -73,6 +76,12 @@ export interface ImportSessionOptions {
readonly recall?: boolean;
readonly recallSessionId?: string;
readonly recallSummaryGroupSize?: number;
+ /**
+ * Lineage of the imported segment (continuity-hygiene-freshness
+ * suite). When omitted, a link persisted in the lineage ledger for
+ * the recall session id is used; flat sessions import unchanged.
+ */
+ readonly recallLineage?: SessionLineage;
/** Optional ingest scope label stamped into imported signal notes. */
readonly ingestScope?: string;
/** Optional role filter for write-side extraction. */
@@ -345,13 +354,20 @@ export async function importSession(
let recallSummaryNodes = 0;
if (opts.recall === true && opts.dryRun !== true && recallTurns.length > 0) {
try {
+ const recallSessionId = opts.recallSessionId ?? basename(absPath);
+ // Persisted-link resolution only: without a clock the crutch
+ // never infers a new link, so an unknown session imports flat.
+ const lineage =
+ opts.recallLineage ??
+ resolveSessionLineage({ sessionId: recallSessionId }, { ledger: readLineageLedger(vault) });
const recalled = importSessionRecall(vault, {
- sessionId: opts.recallSessionId ?? basename(absPath),
+ sessionId: recallSessionId,
turns: recallTurns,
createdAt: isoSecond(now),
...(opts.recallSummaryGroupSize !== undefined
? { summaryGroupSize: opts.recallSummaryGroupSize }
: {}),
+ ...(lineage.source !== "flat" ? { lineage } : {}),
});
recallTurnsImported = recalled.rawTurns.length;
recallSummaryNodes = recalled.summaryNodes.length;
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index 049015f6..274ee432 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -1047,6 +1047,48 @@ export interface BrainConfig {
* consumers resolve built-ins through `resolveSchemaVocabulary`.
*/
readonly schema?: BrainSchemaConfig;
+ /**
+ * Optional `hygiene:` block (continuity-hygiene-freshness suite).
+ * Tunes the hygiene pipeline: the external conflict-resolver command
+ * (operator-configured only - never accepted from a tool argument)
+ * and the semantic dedup threshold. Absent: no resolver, default
+ * threshold.
+ */
+ readonly hygiene?: BrainHygieneConfig;
+ /**
+ * Optional `anticipatory:` block (continuity-hygiene-freshness
+ * suite). Tunes the anticipatory context cache refreshed by
+ * lifecycle hooks. Absent: built-in TTL and budget defaults.
+ */
+ readonly anticipatory?: BrainAnticipatoryConfig;
+ /**
+ * Optional `recall:` block (continuity-hygiene-freshness suite).
+ * Selects the per-entry budget trim strategy for context-pack and
+ * pre-compress. Absent: the historical hard cut.
+ */
+ readonly recall?: BrainRecallConfig;
+}
+
+/** Optional `hygiene:` block (continuity-hygiene-freshness suite). */
+export interface BrainHygieneConfig {
+ /** External conflict-resolver command (JSON stdin/stdout, fail-open). */
+ readonly resolver_cmd?: string;
+ /** Cosine threshold for semantic dedup, in (0, 1]. Default 0.97. */
+ readonly dedup_threshold?: number;
+}
+
+/** Optional `anticipatory:` block (continuity-hygiene-freshness suite). */
+export interface BrainAnticipatoryConfig {
+ /** Cache freshness/debounce window in seconds. Default 120. */
+ readonly ttl_seconds?: number;
+ /** Token budget of the cached context pack. Default 2000. */
+ readonly max_tokens?: number;
+}
+
+/** Optional `recall:` block (continuity-hygiene-freshness suite). */
+export interface BrainRecallConfig {
+ /** Per-entry trim strategy: historical hard cut or the staged ladder. */
+ readonly degradation?: "hard-cut" | "staged";
}
/**
diff --git a/src/core/reliability/command-bridge.ts b/src/core/reliability/command-bridge.ts
new file mode 100644
index 00000000..19c080b0
--- /dev/null
+++ b/src/core/reliability/command-bridge.ts
@@ -0,0 +1,62 @@
+/**
+ * Shared external-command JSON bridge (continuity-hygiene-freshness
+ * suite).
+ *
+ * The Brain core stays deterministic: no LLM (or any other external
+ * judgment) ever runs inside the harness. When a feature wants an
+ * external opinion - the bench judge, the hygiene conflict resolver -
+ * it goes through this one boundary: a configured shell command
+ * receives the question as JSON on stdin and answers with JSON on
+ * stdout. The bridge is advisory and fail-open by contract: an absent
+ * command skips, and every failure mode (non-zero exit, signal kill,
+ * timeout, malformed JSON) reports `error` instead of throwing, so a
+ * broken bridge can never take down the deterministic path around it.
+ */
+
+import { spawnSync } from "node:child_process";
+
+export interface JsonCommandBridgeOptions {
+ /** Kill the command after this many milliseconds (default 60s). */
+ readonly timeoutMs?: number;
+ /** Noun used in error details, e.g. "judge command" (default "command"). */
+ readonly label?: string;
+}
+
+export type JsonCommandBridgeResult =
+ | { readonly status: "skipped" }
+ | { readonly status: "ran"; readonly output: unknown }
+ | { readonly status: "error"; readonly detail: string };
+
+const DEFAULT_TIMEOUT_MS = 60_000;
+
+/**
+ * Run `cmd` through `sh -c` with `input` serialized as JSON on stdin
+ * and parse its stdout as JSON. Never throws.
+ */
+export function runJsonCommandBridge(
+ cmd: string | undefined,
+ input: unknown,
+ opts: JsonCommandBridgeOptions = {},
+): JsonCommandBridgeResult {
+ if (cmd === undefined || cmd.trim() === "") return Object.freeze({ status: "skipped" });
+ const label = opts.label ?? "command";
+ try {
+ const proc = spawnSync("sh", ["-c", cmd], {
+ input: JSON.stringify(input),
+ encoding: "utf8",
+ timeout: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
+ });
+ if (proc.status !== 0) {
+ return Object.freeze({
+ status: "error",
+ detail: `${label} exited ${proc.status ?? "by signal"}`,
+ });
+ }
+ return Object.freeze({ status: "ran", output: JSON.parse(proc.stdout) as unknown });
+ } catch (error) {
+ return Object.freeze({
+ status: "error",
+ detail: error instanceof Error ? error.message : `${label} failed`,
+ });
+ }
+}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 4351d11a..3241dd4f 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -25,6 +25,7 @@ import { RECALL_TOOLS } from "./brain/recall-tools.ts";
import { WORKSPACE_TOOLS } from "./brain/workspace-tools.ts";
import { PROCEDURE_TOOLS } from "./brain/procedure-tools.ts";
import { LANDSCAPE_TOOLS } from "./brain/landscape-tools.ts";
+import { HYGIENE_TOOLS } from "./brain/hygiene-tools.ts";
import type { ToolDefinition } from "./tools.ts";
export { vaultRelativeSafe } from "./brain/shared.ts";
@@ -45,4 +46,5 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
...WORKSPACE_TOOLS,
...PROCEDURE_TOOLS,
...LANDSCAPE_TOOLS,
+ ...HYGIENE_TOOLS,
]);
diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.ts
new file mode 100644
index 00000000..2acbe9ab
--- /dev/null
+++ b/src/mcp/brain/hygiene-tools.ts
@@ -0,0 +1,196 @@
+/**
+ * Hygiene surface: scan / apply / refresh over the findings pipeline
+ * (continuity-hygiene-freshness suite; kanban t_698db8f7, t_da3f138f,
+ * t_db375a60, t_d9624ef6, t_fe490119).
+ *
+ * One tool, three modes:
+ * - `scan` (default): read-only digest of detector findings, with
+ * resolver verdicts attached when the operator configured
+ * `hygiene.resolver_cmd` in `_brain.yaml`;
+ * - `apply`: execute an explicit plan selected by finding ids -
+ * ids are REQUIRED, a bare apply never runs everything blindly;
+ * - `refresh`: the targeted-recompile path for stale derived pages
+ * (`dry_run` previews with zero writes).
+ *
+ * The resolver command comes exclusively from operator config - it is
+ * never accepted as a tool argument, so an MCP caller cannot make this
+ * server execute an arbitrary command.
+ */
+
+import { resolveAgentName } from "../../core/config.ts";
+import { loadBrainConfig } from "../../core/brain/policy.ts";
+import { applyHygienePlan } from "../../core/brain/hygiene/apply.ts";
+import { buildHygienePlan } from "../../core/brain/hygiene/plan.ts";
+import { resolveConflictFindings } from "../../core/brain/hygiene/resolve-conflicts.ts";
+import { runHygieneScan } from "../../core/brain/hygiene/scan.ts";
+import {
+ isHygieneDetectorId,
+ type HygieneDetectorId,
+ type HygieneFinding,
+ type HygieneScanReport,
+} from "../../core/brain/hygiene/types.ts";
+import { executeRecompile, planRecompile } from "../../core/brain/recompile.ts";
+import { coerceBool } from "../coerce.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { vaultRelativeSafe } from "./shared.ts";
+
+function coerceStringArray(args: Record<string, unknown>, key: string): string[] | undefined {
+ const raw = args[key];
+ if (raw === undefined) return undefined;
+ if (!Array.isArray(raw) || !raw.every((value) => typeof value === "string")) {
+ throw new MCPError(INVALID_PARAMS, `'${key}' must be an array of strings`);
+ }
+ return raw;
+}
+
+function resolverCmdFromConfig(vault: string): string | undefined {
+ try {
+ return loadBrainConfig(vault).hygiene?.resolver_cmd;
+ } catch {
+ return undefined; // a broken config never blocks a read-only scan
+ }
+}
+
+function scanWithResolver(
+ vault: string,
+ detectors: HygieneDetectorId[] | undefined,
+ now: Date,
+): HygieneScanReport {
+ const report = runHygieneScan(vault, {
+ ...(detectors !== undefined && detectors.length > 0 ? { detectors } : {}),
+ now,
+ });
+ const resolverCmd = resolverCmdFromConfig(vault);
+ if (resolverCmd === undefined) return report;
+ return Object.freeze({
+ ...report,
+ findings: resolveConflictFindings(vault, report.findings, { resolverCmd }),
+ });
+}
+
+function findingView(vault: string, finding: HygieneFinding): Record<string, unknown> {
+ return {
+ id: finding.id,
+ detector: finding.detector,
+ severity: finding.severity,
+ title: finding.title,
+ targets: finding.targets.map((target) =>
+ target.startsWith("/") ? vaultRelativeSafe(vault, target) : target,
+ ),
+ proposed_action: finding.proposed_action,
+ evidence: finding.evidence,
+ };
+}
+
+async function toolBrainHygiene(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const mode = args["mode"] ?? "scan";
+ if (mode !== "scan" && mode !== "apply" && mode !== "refresh") {
+ throw new MCPError(INVALID_PARAMS, "'mode' must be one of: scan, apply, refresh");
+ }
+ const now = new Date();
+ const dryRun = coerceBool(args, "dry_run") === true;
+
+ if (mode === "refresh") {
+ const plan = planRecompile(ctx.vault);
+ const result = await executeRecompile(ctx.vault, plan, {
+ dryRun,
+ agent: resolveAgentName(ctx.configPath ?? undefined),
+ now,
+ });
+ return {
+ mode,
+ dry_run: result.dry_run,
+ plan: plan.entries.map((entry) => ({
+ kind: entry.kind,
+ page: vaultRelativeSafe(ctx.vault, entry.page),
+ reason: entry.reason,
+ })),
+ rederived: result.rederived.map((page) => vaultRelativeSafe(ctx.vault, page)),
+ archived: result.archived.map((page) => vaultRelativeSafe(ctx.vault, page)),
+ manual: result.manual.map((page) => vaultRelativeSafe(ctx.vault, page)),
+ errors: result.errors,
+ };
+ }
+
+ const detectorsRaw = coerceStringArray(args, "detectors");
+ const detectors = detectorsRaw?.filter(isHygieneDetectorId);
+ if (detectorsRaw !== undefined && detectors!.length !== detectorsRaw.length) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "'detectors' entries must be: conflicts, dedup, freshness, usefulness",
+ );
+ }
+ const report = scanWithResolver(ctx.vault, detectors, now);
+
+ if (mode === "scan") {
+ return {
+ mode,
+ generated_at: report.generated_at,
+ detectors_run: report.detectors_run,
+ counts: report.counts,
+ findings: report.findings.map((finding) => findingView(ctx.vault, finding)),
+ errors: report.errors,
+ };
+ }
+
+ const ids = coerceStringArray(args, "ids");
+ if (ids === undefined || ids.length === 0) {
+ throw new MCPError(INVALID_PARAMS, "apply requires explicit finding 'ids' from a prior scan");
+ }
+ const plan = buildHygienePlan(report, { ids });
+ const result = await applyHygienePlan(ctx.vault, plan, {
+ dryRun,
+ agent: resolveAgentName(ctx.configPath ?? undefined),
+ now,
+ });
+ return {
+ mode,
+ dry_run: result.dry_run,
+ selected: plan.selected.map((finding) => finding.id),
+ excluded_review: plan.excluded_review,
+ unknown_ids: plan.unknown_ids,
+ planned: result.planned,
+ applied: result.applied,
+ errors: result.errors,
+ };
+}
+
+export const HYGIENE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_hygiene",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description:
+ "Memory hygiene pipeline. `scan`: read-only digest of contested truth slots, near-duplicate preferences, stale/orphaned pages, low-usefulness candidates. `apply`: execute selected finding ids (review findings never execute). `refresh`: targeted recompile of stale pages with dry-run.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ mode: {
+ type: "string",
+ enum: ["scan", "apply", "refresh"],
+ description: "Pipeline stage. Default `scan` (read-only).",
+ },
+ detectors: {
+ type: "array",
+ items: { type: "string", enum: ["conflicts", "dedup", "freshness", "usefulness"] },
+ description: "Detector subset for scan/apply. Default: all detectors.",
+ },
+ ids: {
+ type: "array",
+ items: { type: "string" },
+ description: "Finding ids to execute (apply mode; required there).",
+ },
+ dry_run: {
+ type: "boolean",
+ description: "Preview apply/refresh with zero writes.",
+ },
+ },
+ additionalProperties: false,
+ },
+ handler: toolBrainHygiene,
+ },
+]);
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index 52ade060..d3f819c3 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -12,6 +12,11 @@ import { resolveSearchFocusContextPack } from "../../core/config.ts";
import { resolveSearchConfig } from "../../core/search/index.ts";
import { readActiveSessionFocus } from "../../core/search/session-focus.ts";
import { packContext } from "../../core/brain/context-pack.ts";
+import {
+ readAnticipatoryContext,
+ refreshAnticipatoryCache,
+} from "../../core/brain/anticipatory-cache.ts";
+import { loadBrainConfig } from "../../core/brain/policy.ts";
import { buildPreCompressPack } from "../../core/brain/pre-compress-pack.ts";
import {
getContextReceipt,
@@ -103,6 +108,9 @@ async function toolBrainContextPack(
: {}),
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ ...(configuredDegradation(ctx.vault) !== undefined
+ ? { degradation: configuredDegradation(ctx.vault)! }
+ : {}),
...(telemetry !== undefined ? { telemetry } : {}),
...(attentionFlowIds.length > 0 ? { attentionFlowIds } : {}),
});
@@ -283,6 +291,9 @@ async function toolBrainPreCompressPack(
topK,
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
+ ...(configuredDegradation(ctx.vault) !== undefined
+ ? { degradation: configuredDegradation(ctx.vault)! }
+ : {}),
...(receipt !== undefined ? { receipt } : {}),
...(telemetry !== undefined ? { telemetry } : {}),
});
@@ -331,6 +342,64 @@ async function toolBrainPreCompactExtract(
// ----- session recall DAG --------------------------------------------------
+/** Operator-configured trim strategy (`recall.degradation` in `_brain.yaml`). */
+function configuredDegradation(vault: string): "staged" | undefined {
+ try {
+ return loadBrainConfig(vault).recall?.degradation === "staged" ? "staged" : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+async function toolBrainAnticipatoryContext(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const sessionId = coerceStr(args, "session_id");
+ if (sessionId === null || sessionId === undefined || sessionId.trim() === "") {
+ throw new MCPError(INVALID_PARAMS, "'session_id' is required");
+ }
+ let ttlSeconds: number | undefined;
+ let maxTokens: number | undefined;
+ try {
+ const anticipatory = loadBrainConfig(ctx.vault).anticipatory;
+ ttlSeconds = anticipatory?.ttl_seconds;
+ maxTokens = anticipatory?.max_tokens;
+ } catch {
+ // defaults apply; a broken config never blocks a read
+ }
+ const now = new Date();
+ if (coerceBool(args, "refresh") === true) {
+ const signal = coerceStr(args, "signal_text");
+ refreshAnticipatoryCache(ctx.vault, {
+ sessionId,
+ ...(typeof signal === "string" && signal.trim() !== "" ? { signalText: signal } : {}),
+ now,
+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
+ });
+ }
+ const result = readAnticipatoryContext(ctx.vault, {
+ sessionId,
+ now,
+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
+ ...(maxTokens !== undefined ? { maxTokens } : {}),
+ });
+ return {
+ cache_state: result.cache_state,
+ root_session_id: result.root_session_id,
+ ...(result.generated_at !== undefined ? { generated_at: result.generated_at } : {}),
+ items: result.context.items.map((item) => ({
+ id: item.id,
+ tier: item.tier,
+ tokens: item.tokens,
+ principle: item.principle,
+ body: item.body,
+ })),
+ session_hits: result.context.session_hits,
+ };
+}
+
export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_context_pack",
@@ -589,4 +658,30 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
handler: toolBrainPreCompactExtract,
},
+ {
+ name: "brain_anticipatory_context",
+ previewBudget: MCP_PREVIEW_BUDGET,
+ description:
+ "Turn-specific context bundle kept warm by lifecycle hooks: the active context pack plus session-recall hits, keyed by the session's lineage root. Returns the warm cache inside the TTL or a live fallback, reporting `cache_state`. `refresh: true` forces a refresh first.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: {
+ type: "string",
+ description: "Session id (any segment of a compression chain resolves to its root).",
+ },
+ refresh: {
+ type: "boolean",
+ description: "Refresh the cache before reading (TTL debounce still applies).",
+ },
+ signal_text: {
+ type: "string",
+ description: "Latest prompt/signal text steering the refreshed bundle.",
+ },
+ },
+ required: ["session_id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainAnticipatoryContext,
+ },
]);
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index 1e8fb4df..ffa1cd65 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -111,6 +111,43 @@ describe("importSession", () => {
);
});
+ test("recall import stamps explicit lineage and stitches with the parent segment", async () => {
+ const res = await importSession(tmp, CLAUDE, {
+ agent: "test",
+ recall: true,
+ recallSessionId: "import-child",
+ recallLineage: {
+ rootId: "import-root",
+ parentId: "import-root",
+ depth: 1,
+ source: "payload",
+ },
+ });
+ expect(res.recall_turns_imported).toBeGreaterThan(0);
+ // Recall over the ROOT id reaches the child-segment turns.
+ const described = describeSessionRecall(tmp, { sessionId: "import-root" });
+ expect(described.raw_turns).toBe(res.recall_turns_imported);
+ expect(described.lineage_root).toBe("import-root");
+ });
+
+ test("recall import resolves persisted ledger lineage when no explicit lineage is given", async () => {
+ const { recordLineageObservation } = await import("../../src/core/brain/lineage/ledger.ts");
+ recordLineageObservation(tmp, {
+ sessionId: "ledger-child",
+ at: "2026-06-10T09:00:00Z",
+ event: "SessionStart",
+ lineage: { rootId: "ledger-root", parentId: "ledger-root", depth: 1, source: "crutch" },
+ });
+ const res = await importSession(tmp, CLAUDE, {
+ agent: "test",
+ recall: true,
+ recallSessionId: "ledger-child",
+ });
+ expect(res.recall_turns_imported).toBeGreaterThan(0);
+ const described = describeSessionRecall(tmp, { sessionId: "ledger-root" });
+ expect(described.raw_turns).toBe(res.recall_turns_imported);
+ });
+
test("supports filtered write mode by role", async () => {
const res = await importSession(tmp, CLAUDE, {
agent: "test",
diff --git a/tests/core/brain/anticipatory-cache.test.ts b/tests/core/brain/anticipatory-cache.test.ts
new file mode 100644
index 00000000..747e7c39
--- /dev/null
+++ b/tests/core/brain/anticipatory-cache.test.ts
@@ -0,0 +1,181 @@
+/**
+ * Anticipatory Brain context cache
+ * (continuity-hygiene-freshness suite, Task 6; kanban t_4cee9df5).
+ *
+ * The cache keeps a small, inspectable, turn-specific context pack
+ * warm while an agent works: refreshed from existing hook events (no
+ * daemon, no watcher), debounced by TTL with an injected clock, written
+ * atomically, keyed by the lineage root. Reads return the warm cache
+ * or fall back to a live pack, always reporting `cache_state`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { captureSessionLifecycleEvent } from "../../../src/core/brain/session-lifecycle.ts";
+import { recordLineageObservation } from "../../../src/core/brain/lineage/ledger.ts";
+import {
+ anticipatoryCachePath,
+ readAnticipatoryContext,
+ refreshAnticipatoryCache,
+} from "../../../src/core/brain/anticipatory-cache.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-anticipatory-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const T0 = new Date("2026-06-10T12:00:00Z");
+
+describe("refreshAnticipatoryCache", () => {
+ test("writes a cache keyed by the lineage root", () => {
+ recordLineageObservation(vault, {
+ sessionId: "child-1",
+ at: T0.toISOString(),
+ event: "SessionStart",
+ lineage: { rootId: "root-1", parentId: "root-1", depth: 1, source: "payload" },
+ });
+ const result = refreshAnticipatoryCache(vault, {
+ sessionId: "child-1",
+ signalText: "debugging the indexer",
+ now: T0,
+ });
+ expect(result.refreshed).toBe(true);
+ expect(result.rootSessionId).toBe("root-1");
+ const raw = JSON.parse(readFileSync(anticipatoryCachePath(vault, "root-1"), "utf8")) as {
+ schema: string;
+ root_session_id: string;
+ };
+ expect(raw.schema).toBe("o2b.anticipatory.v1");
+ expect(raw.root_session_id).toBe("root-1");
+ });
+
+ test("debounces by TTL with the injected clock", () => {
+ const first = refreshAnticipatoryCache(vault, { sessionId: "s-1", now: T0 });
+ expect(first.refreshed).toBe(true);
+ const second = refreshAnticipatoryCache(vault, {
+ sessionId: "s-1",
+ now: new Date(T0.getTime() + 30_000),
+ ttlSeconds: 120,
+ });
+ expect(second.refreshed).toBe(false);
+ const third = refreshAnticipatoryCache(vault, {
+ sessionId: "s-1",
+ now: new Date(T0.getTime() + 121_000),
+ ttlSeconds: 120,
+ });
+ expect(third.refreshed).toBe(true);
+ });
+
+ test("distinct roots that sanitize identically never share a cache file", () => {
+ const pathA = anticipatoryCachePath(vault, "a/b");
+ const pathB = anticipatoryCachePath(vault, "a:b");
+ expect(pathA).not.toBe(pathB);
+ const longA = anticipatoryCachePath(vault, "x".repeat(150) + "A");
+ const longB = anticipatoryCachePath(vault, "x".repeat(150) + "B");
+ expect(longA).not.toBe(longB);
+ });
+
+ test("a token-budget change bypasses the TTL debounce and is never served warm", () => {
+ refreshAnticipatoryCache(vault, { sessionId: "s-budget", now: T0, maxTokens: 2000 });
+ const rebuilt = refreshAnticipatoryCache(vault, {
+ sessionId: "s-budget",
+ now: new Date(T0.getTime() + 5_000),
+ maxTokens: 500,
+ });
+ expect(rebuilt.refreshed).toBe(true);
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-budget",
+ now: new Date(T0.getTime() + 10_000),
+ maxTokens: 4000,
+ });
+ expect(read.cache_state).not.toBe("warm");
+ });
+
+ test("sanitizes hostile session ids into safe cache filenames", () => {
+ const result = refreshAnticipatoryCache(vault, { sessionId: "../../etc/passwd", now: T0 });
+ expect(result.refreshed).toBe(true);
+ const path = anticipatoryCachePath(vault, "../../etc/passwd");
+ expect(path).toContain(join("Brain", ".state", "anticipatory"));
+ expect(path.includes("..")).toBe(false);
+ });
+});
+
+describe("readAnticipatoryContext", () => {
+ test("returns the warm cache inside the TTL", () => {
+ refreshAnticipatoryCache(vault, { sessionId: "s-2", signalText: "warm topic", now: T0 });
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-2",
+ now: new Date(T0.getTime() + 10_000),
+ ttlSeconds: 120,
+ });
+ expect(read.cache_state).toBe("warm");
+ expect(read.generated_at).toBe(T0.toISOString());
+ expect(Array.isArray(read.context.items)).toBe(true);
+ });
+
+ test("falls back to a live pack on miss", () => {
+ const read = readAnticipatoryContext(vault, { sessionId: "never-cached", now: T0 });
+ expect(read.cache_state).toBe("miss");
+ expect(Array.isArray(read.context.items)).toBe(true);
+ });
+
+ test("falls back to a live pack when the cache is stale", () => {
+ refreshAnticipatoryCache(vault, { sessionId: "s-3", now: T0 });
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-3",
+ now: new Date(T0.getTime() + 10 * 60_000),
+ ttlSeconds: 120,
+ });
+ expect(read.cache_state).toBe("stale");
+ });
+
+ test("treats a corrupt cache file as a miss instead of throwing", () => {
+ const path = anticipatoryCachePath(vault, "s-4");
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "not-json", "utf8");
+ const read = readAnticipatoryContext(vault, { sessionId: "s-4", now: T0 });
+ expect(read.cache_state).toBe("miss");
+ });
+});
+
+describe("hook integration", () => {
+ test("a UserPromptSubmit lifecycle event warms the cache fail-soft", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "hook-1",
+ cwd: "/work",
+ prompt: "plain prompt with no markers",
+ },
+ { agent: "tester", now: T0 },
+ );
+ const read = readAnticipatoryContext(vault, { sessionId: "hook-1", now: T0 });
+ expect(read.cache_state).toBe("warm");
+ });
+
+ test("dry runs never write the cache", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "hook-2",
+ cwd: "/work",
+ prompt: "plain prompt",
+ },
+ { agent: "tester", now: T0, dryRun: true },
+ );
+ const read = readAnticipatoryContext(vault, { sessionId: "hook-2", now: T0 });
+ expect(read.cache_state).toBe("miss");
+ });
+});
diff --git a/tests/core/brain/freshness.test.ts b/tests/core/brain/freshness.test.ts
new file mode 100644
index 00000000..31fbedf6
--- /dev/null
+++ b/tests/core/brain/freshness.test.ts
@@ -0,0 +1,168 @@
+/**
+ * Source-freshness substrate
+ * (continuity-hygiene-freshness suite, Task 7; kanban t_d9624ef6).
+ *
+ * Derived pages declare their sources in frontmatter (`source_paths` +
+ * parallel `source_hashes`, recorded at derivation). Freshness is
+ * computed on demand - no background jobs: `stale` when any recorded
+ * source changed, `orphaned` when every source is gone, `fresh`
+ * otherwise. Pages without the contract are skipped silently.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import {
+ checkPageFreshness,
+ computeSourceStamp,
+ formatSourceStampFrontmatter,
+ scanFreshness,
+} from "../../../src/core/brain/freshness.ts";
+import { writeHandoffNote } from "../../../src/core/brain/handoff.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-freshness-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeSource(rel: string, content: string): string {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+ return path;
+}
+
+function writeDerivedPage(rel: string, sourceRels: ReadonlyArray<string>): string {
+ const stamp = computeSourceStamp(vault, sourceRels);
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(
+ path,
+ `---\n${formatSourceStampFrontmatter(stamp)}\n---\n\nDerived content.\n`,
+ "utf8",
+ );
+ return path;
+}
+
+describe("computeSourceStamp", () => {
+ test("records vault-relative paths with sha256 hashes", () => {
+ writeSource("notes/source-a.md", "alpha");
+ const stamp = computeSourceStamp(vault, ["notes/source-a.md"]);
+ expect(stamp.source_paths).toEqual(["notes/source-a.md"]);
+ expect(stamp.source_hashes[0]).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("missing sources stamp an empty-hash marker instead of throwing", () => {
+ const stamp = computeSourceStamp(vault, ["notes/never-existed.md"]);
+ expect(stamp.source_hashes[0]).toBe("missing");
+ });
+});
+
+describe("checkPageFreshness", () => {
+ test("fresh while sources are unchanged", () => {
+ writeSource("notes/src.md", "alpha");
+ const page = writeDerivedPage("Brain/derived/page.md", ["notes/src.md"]);
+ expect(checkPageFreshness(vault, page)?.status).toBe("fresh");
+ });
+
+ test("stale once a source changes", () => {
+ writeSource("notes/src.md", "alpha");
+ const page = writeDerivedPage("Brain/derived/page.md", ["notes/src.md"]);
+ writeSource("notes/src.md", "alpha CHANGED");
+ const freshness = checkPageFreshness(vault, page);
+ expect(freshness?.status).toBe("stale");
+ expect(freshness?.changed_sources).toEqual(["notes/src.md"]);
+ });
+
+ test("orphaned once every source is gone", () => {
+ writeSource("notes/src.md", "alpha");
+ const page = writeDerivedPage("Brain/derived/page.md", ["notes/src.md"]);
+ rmSync(join(vault, "notes/src.md"));
+ expect(checkPageFreshness(vault, page)?.status).toBe("orphaned");
+ });
+
+ test("one missing source among living ones is stale, not orphaned", () => {
+ writeSource("notes/a.md", "alpha");
+ writeSource("notes/b.md", "beta");
+ const page = writeDerivedPage("Brain/derived/page.md", ["notes/a.md", "notes/b.md"]);
+ rmSync(join(vault, "notes/b.md"));
+ const freshness = checkPageFreshness(vault, page);
+ expect(freshness?.status).toBe("stale");
+ expect(freshness?.missing_sources).toEqual(["notes/b.md"]);
+ });
+
+ test("an unreadable source is stale, never orphaned", () => {
+ const src = writeSource("notes/locked.md", "alpha");
+ const page = writeDerivedPage("Brain/derived/page.md", ["notes/locked.md"]);
+ const { chmodSync } = require("node:fs") as typeof import("node:fs");
+ chmodSync(src, 0o000);
+ try {
+ const freshness = checkPageFreshness(vault, page);
+ expect(freshness?.status).toBe("stale");
+ expect(freshness?.unreadable_sources).toEqual(["notes/locked.md"]);
+ expect(freshness?.missing_sources).toEqual([]);
+ } finally {
+ chmodSync(src, 0o644);
+ }
+ });
+
+ test("returns null for a page without the contract", () => {
+ const page = writeSource("Brain/plain.md", "---\ntitle: x\n---\nNo sources here.");
+ expect(checkPageFreshness(vault, page)).toBeNull();
+ });
+});
+
+describe("scanFreshness", () => {
+ test("classifies all contract pages and skips the rest silently", () => {
+ writeSource("notes/live.md", "alpha");
+ writeSource("notes/edited.md", "beta");
+ writeDerivedPage("Brain/derived/fresh-page.md", ["notes/live.md"]);
+ writeDerivedPage("Brain/derived/stale-page.md", ["notes/edited.md"]);
+ writeDerivedPage("Brain/derived/orphan-page.md", ["notes/gone.md"]);
+ writeSource("notes/edited.md", "beta CHANGED");
+ writeSource("Brain/no-contract.md", "plain page");
+
+ const report = scanFreshness(vault);
+ expect(report.with_contract).toBe(3);
+ expect(report.fresh).toBe(1);
+ expect(report.stale.map((s) => s.page.endsWith("stale-page.md"))).toEqual([true]);
+ expect(report.orphaned.map((o) => o.endsWith("orphan-page.md"))).toEqual([true]);
+ });
+
+ test("a malformed contract is reported, not thrown", () => {
+ const page = join(vault, "Brain/bad.md");
+ writeFileSync(
+ page,
+ "---\nsource_paths: [a.md, b.md]\nsource_hashes: [deadbeef]\n---\nbody",
+ "utf8",
+ );
+ const report = scanFreshness(vault);
+ expect(report.invalid_contract.map((p) => p.endsWith("bad.md"))).toEqual([true]);
+ });
+});
+
+describe("handoff notes carry the contract", () => {
+ test("writeHandoffNote stamps source_paths and source_hashes when given a transcript", () => {
+ const transcript = writeSource("transcripts/session.jsonl", '{"turn":1}\n');
+ const result = writeHandoffNote(vault, {
+ sessionId: "sess-1",
+ agent: "tester",
+ now: new Date("2026-06-10T12:00:00Z"),
+ turns: [
+ { turnId: "t1", role: "user", text: "do the thing", timestamp: "2026-06-10T11:00:00Z" },
+ ],
+ sourcePaths: [transcript],
+ });
+ expect(result.content).toContain("source_paths:");
+ expect(result.content).toContain("source_hashes:");
+ expect(checkPageFreshness(vault, result.path)?.status).toBe("fresh");
+ });
+});
diff --git a/tests/core/brain/hygiene-apply.test.ts b/tests/core/brain/hygiene-apply.test.ts
new file mode 100644
index 00000000..d600aa77
--- /dev/null
+++ b/tests/core/brain/hygiene-apply.test.ts
@@ -0,0 +1,150 @@
+/**
+ * Hygiene apply: explicit plan execution with audit
+ * (continuity-hygiene-freshness suite, Task 11; kanban t_698db8f7).
+ *
+ * Apply consumes a plan built from scan finding ids; review findings
+ * are structurally excluded, dry-run previews with zero writes, merge
+ * routes to the preference merge machinery, supersede appends the
+ * resolver-chosen claim, archive moves pages under Brain/.snapshots
+ * (never deletes).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { appendClaimEvent, readTruthState } from "../../../src/core/brain/truth/store.ts";
+import { runHygieneScan } from "../../../src/core/brain/hygiene/scan.ts";
+import { buildHygienePlan } from "../../../src/core/brain/hygiene/plan.ts";
+import { applyHygienePlan } from "../../../src/core/brain/hygiene/apply.ts";
+import { resolveConflictFindings } from "../../../src/core/brain/hygiene/resolve-conflicts.ts";
+import type { HygieneFinding } from "../../../src/core/brain/hygiene/types.ts";
+
+let vault: string;
+
+const NOW = new Date("2026-06-10T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hygiene-apply-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, topic: string, principle: string): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ [
+ "---",
+ "kind: brain-preference",
+ `id: pref-${slug}`,
+ "tags: [brain, brain/preference]",
+ `topic: ${topic}`,
+ "_status: confirmed",
+ `principle: ${principle}`,
+ "created_at: 2026-01-01T00:00:00Z",
+ "unconfirmed_until: 2026-01-15T00:00:00Z",
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+}
+
+describe("buildHygienePlan", () => {
+ test("review findings are structurally excluded", () => {
+ writePref("solo", "lonely-topic", "a principle that nobody recalled");
+ const report = runHygieneScan(vault, { detectors: ["usefulness"], now: NOW });
+ const reviewId = report.findings[0]!.id;
+ const plan = buildHygienePlan(report, { ids: [reviewId, "nope:000000000000"] });
+ expect(plan.selected).toHaveLength(0);
+ expect(plan.excluded_review).toEqual([reviewId]);
+ expect(plan.unknown_ids).toEqual(["nope:000000000000"]);
+ });
+});
+
+describe("applyHygienePlan", () => {
+ test("dry-run previews routed actions with zero writes", async () => {
+ writePref("dup-a", "same-topic", "collect metrics before optimizing the code");
+ writePref("dup-b", "same-topic", "collect metrics before optimizing the code base");
+ const report = runHygieneScan(vault, { detectors: ["dedup"], now: NOW });
+ const plan = buildHygienePlan(report);
+ expect(plan.selected.length).toBeGreaterThan(0);
+ const result = await applyHygienePlan(vault, plan, { dryRun: true, agent: "tester", now: NOW });
+ expect(result.dry_run).toBe(true);
+ expect(result.planned[0]?.action).toBe("merge");
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-dup-b.md"))).toBe(true);
+ expect(readdirSync(join(vault, "Brain", "retired"))).toHaveLength(0);
+ });
+
+ test("merge keeps the first target and retires the second", async () => {
+ writePref("dup-a", "same-topic", "collect metrics before optimizing the code");
+ writePref("dup-b", "same-topic", "collect metrics before optimizing the code base");
+ const report = runHygieneScan(vault, { detectors: ["dedup"], now: NOW });
+ const plan = buildHygienePlan(report);
+ const result = await applyHygienePlan(vault, plan, { agent: "tester", now: NOW });
+ expect(result.errors).toHaveLength(0);
+ expect(result.applied[0]?.action).toBe("merge");
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-dup-a.md"))).toBe(true);
+ expect(existsSync(join(vault, "Brain", "preferences", "pref-dup-b.md"))).toBe(false);
+ expect(readdirSync(join(vault, "Brain", "retired")).some((n) => n.includes("dup-b"))).toBe(
+ true,
+ );
+ });
+
+ test("supersede appends the resolver-chosen claim as current truth", async () => {
+ appendClaimEvent(vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "agent-a",
+ entity: "acme",
+ aspect: "hq",
+ value: "Berlin",
+ source: "[[note-a]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-05T10:00:00Z",
+ agent: "agent-b",
+ entity: "acme",
+ aspect: "hq",
+ value: "Lisbon",
+ source: "[[note-b]]",
+ });
+ const report = runHygieneScan(vault, { detectors: ["conflicts"], now: NOW });
+ const withVerdicts = resolveConflictFindings(vault, report.findings, {
+ resolverCmd: `printf '{"verdicts": {"${report.findings[0]!.id}": {"action": "supersede", "winner_value": "Lisbon", "rationale": "later independent source"}}}'`,
+ });
+ const plan = buildHygienePlan({ ...report, findings: withVerdicts });
+ const result = await applyHygienePlan(vault, plan, { agent: "hygiene", now: NOW });
+ expect(result.errors).toHaveLength(0);
+ expect(result.applied[0]?.action).toBe("supersede");
+ const state = readTruthState(vault);
+ const slot = state?.slots.find((s) => s.entity === "acme" && s.aspect === "hq");
+ expect(slot?.current.value).toBe("Lisbon");
+ expect(slot?.current.source).toBe("[[hygiene-resolver]]");
+ });
+
+ test("archive moves the page under Brain/.snapshots and records the destination", async () => {
+ const page = join(vault, "Brain", "old-page.md");
+ writeFileSync(page, "---\ntitle: old\n---\nbody", "utf8");
+ const finding: HygieneFinding = {
+ id: "freshness:manualtest1",
+ detector: "freshness",
+ severity: "warning",
+ title: "operator chose to archive",
+ targets: [page],
+ proposed_action: "archive",
+ evidence: {},
+ };
+ const result = await applyHygienePlan(
+ vault,
+ { selected: [finding], excluded_review: [], unknown_ids: [] },
+ { agent: "tester", now: NOW },
+ );
+ expect(result.applied[0]?.detail).toContain(".snapshots");
+ expect(existsSync(page)).toBe(false);
+ });
+});
diff --git a/tests/core/brain/hygiene-dedup.test.ts b/tests/core/brain/hygiene-dedup.test.ts
new file mode 100644
index 00000000..72b56de4
--- /dev/null
+++ b/tests/core/brain/hygiene-dedup.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Semantic dedup detector layer
+ * (continuity-hygiene-freshness suite, Task 9; kanban t_da3f138f).
+ *
+ * Embedding cosine similarity above the threshold (default 0.97)
+ * nominates near-duplicate preferences for merge, across topic
+ * buckets. When no usable embedding provider exists (or it fails),
+ * the detector falls back to the deterministic lexical layer and the
+ * report says so - lexical similarity is never passed off as
+ * semantic.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import type { EmbeddingProvider } from "../../../src/core/search/embeddings/provider.ts";
+import { detectSemanticDedup } from "../../../src/core/brain/hygiene/detectors/dedup.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hygiene-dedup-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, topic: string, principle: string): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ [
+ "---",
+ "kind: brain-preference",
+ `id: pref-${slug}`,
+ "tags: [brain, brain/preference]",
+ `topic: ${topic}`,
+ "_status: confirmed",
+ `principle: ${principle}`,
+ "created_at: 2026-01-01T00:00:00Z",
+ "unconfirmed_until: 2026-01-15T00:00:00Z",
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+}
+
+function fixedVectorProvider(vectors: Readonly<Record<string, number[]>>): EmbeddingProvider {
+ return {
+ name: "fixed",
+ model: "fixed-test",
+ dimension: 3,
+ embed: (texts) => Promise.resolve(texts.map((text) => vectors[text] ?? [0, 0, 1])),
+ ping: () => Promise.resolve({ ok: true as const, dimension: 3 }),
+ };
+}
+
+describe("detectSemanticDedup", () => {
+ test("reports embedding pairs above the threshold across topic buckets", async () => {
+ writePref("a", "writing-style", "Never use exclamation marks in docs");
+ writePref("b", "doc-tone", "Do not use exclamation marks in documentation");
+ writePref("c", "git", "Always rebase before merge");
+ const provider = fixedVectorProvider({
+ "Never use exclamation marks in docs": [1, 0, 0],
+ "Do not use exclamation marks in documentation": [0.999, 0.0447, 0],
+ "Always rebase before merge": [0, 1, 0],
+ });
+ const result = await detectSemanticDedup(vault, { provider });
+ expect(result.method).toBe("embedding");
+ expect(result.findings).toHaveLength(1);
+ const finding = result.findings[0]!;
+ expect(finding.targets).toEqual(["pref-a", "pref-b"]);
+ expect(finding.proposed_action).toBe("merge");
+ expect(finding.evidence["method"]).toBe("embedding");
+ expect(finding.evidence["model"]).toBe("fixed-test");
+ });
+
+ test("falls back to the lexical layer when the provider fails", async () => {
+ writePref("x", "same-topic", "Collect the metrics before optimizing the code");
+ writePref("y", "same-topic", "Collect the metrics before optimizing the code base");
+ const broken: EmbeddingProvider = {
+ name: "broken",
+ model: "broken",
+ dimension: 3,
+ embed: () => Promise.reject(new Error("provider down")),
+ ping: () => Promise.resolve({ ok: false as const, reason: "down" }),
+ };
+ const result = await detectSemanticDedup(vault, { provider: broken });
+ expect(result.method).toBe("lexical");
+ expect(result.findings.length).toBeGreaterThan(0);
+ expect(result.findings[0]?.evidence["method"]).toBe("lexical");
+ });
+
+ test("falls back to lexical when no provider is usable", async () => {
+ const result = await detectSemanticDedup(vault, { provider: null });
+ expect(result.method).toBe("lexical");
+ expect(result.findings).toHaveLength(0);
+ });
+});
diff --git a/tests/core/brain/hygiene-resolve.test.ts b/tests/core/brain/hygiene-resolve.test.ts
new file mode 100644
index 00000000..57008369
--- /dev/null
+++ b/tests/core/brain/hygiene-resolve.test.ts
@@ -0,0 +1,117 @@
+/**
+ * External conflict resolution over the command bridge
+ * (continuity-hygiene-freshness suite, Task 10; kanban t_db375a60).
+ *
+ * Detection stays deterministic; resolution consults an optional
+ * external resolver command (JSON stdin/stdout, fail-open). Without a
+ * resolver - or on any resolver failure or invalid verdict - every
+ * conflict stays `review`. A valid `supersede` / `merge` verdict
+ * upgrades the finding and records the resolver evidence.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";
+import { runHygieneScan } from "../../../src/core/brain/hygiene/scan.ts";
+import { resolveConflictFindings } from "../../../src/core/brain/hygiene/resolve-conflicts.ts";
+
+let vault: string;
+
+const NOW = new Date("2026-06-10T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hygiene-resolve-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ appendClaimEvent(vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "agent-a",
+ entity: "acme",
+ aspect: "hq",
+ value: "Berlin",
+ source: "[[note-a]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-05T10:00:00Z",
+ agent: "agent-b",
+ entity: "acme",
+ aspect: "hq",
+ value: "Lisbon",
+ source: "[[note-b]]",
+ });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function conflictFindings() {
+ return runHygieneScan(vault, { detectors: ["conflicts"], now: NOW }).findings;
+}
+
+/** Write a resolver script answering every conflict with one action. */
+function resolverCmd(action: string): string {
+ const script = join(vault, "resolver.ts");
+ writeFileSync(
+ script,
+ [
+ "const input = await new Response(Bun.stdin.stream()).json();",
+ "const verdicts: Record<string, unknown> = {};",
+ "for (const conflict of input.conflicts) {",
+ ` verdicts[conflict.id] = { action: ${JSON.stringify(action)}, winner_value: conflict.evidence.values.at(-1).value, rationale: "latest independent assertion" };`,
+ "}",
+ "console.log(JSON.stringify({ verdicts }));",
+ ].join("\n"),
+ "utf8",
+ );
+ return `bun ${script}`;
+}
+
+describe("resolveConflictFindings", () => {
+ test("without a resolver every conflict stays review", () => {
+ const findings = conflictFindings();
+ const resolved = resolveConflictFindings(vault, findings, {});
+ expect(resolved[0]?.proposed_action).toBe("review");
+ expect(resolved[0]?.evidence["resolver"]).toBeUndefined();
+ });
+
+ test("a supersede verdict upgrades the finding and records evidence", () => {
+ const findings = conflictFindings();
+ const resolved = resolveConflictFindings(vault, findings, {
+ resolverCmd: resolverCmd("supersede"),
+ });
+ expect(resolved).toHaveLength(1);
+ const finding = resolved[0]!;
+ expect(finding.proposed_action).toBe("supersede");
+ const resolver = finding.evidence["resolver"] as Record<string, unknown>;
+ expect(resolver["action"]).toBe("supersede");
+ expect(resolver["winner_value"]).toBe("Lisbon");
+ expect(resolver["rationale"]).toBe("latest independent assertion");
+ });
+
+ test("an invalid verdict action falls back to review", () => {
+ const findings = conflictFindings();
+ const resolved = resolveConflictFindings(vault, findings, {
+ resolverCmd: resolverCmd("delete-everything"),
+ });
+ expect(resolved[0]?.proposed_action).toBe("review");
+ });
+
+ test("a failing resolver is fail-open: review plus the error recorded", () => {
+ const findings = conflictFindings();
+ const resolved = resolveConflictFindings(vault, findings, { resolverCmd: "exit 7" });
+ expect(resolved[0]?.proposed_action).toBe("review");
+ expect(String(resolved[0]?.evidence["resolver_error"])).toContain("exited 7");
+ });
+
+ test("non-conflict findings pass through untouched", () => {
+ const findings = conflictFindings();
+ const foreign = { ...findings[0]!, detector: "dedup" as const };
+ const resolved = resolveConflictFindings(vault, [foreign], {
+ resolverCmd: resolverCmd("supersede"),
+ });
+ expect(resolved[0]).toBe(foreign);
+ });
+});
diff --git a/tests/core/brain/hygiene-scan.test.ts b/tests/core/brain/hygiene-scan.test.ts
new file mode 100644
index 00000000..e31383c7
--- /dev/null
+++ b/tests/core/brain/hygiene-scan.test.ts
@@ -0,0 +1,157 @@
+/**
+ * Hygiene kernel: scan over pure detectors
+ * (continuity-hygiene-freshness suite, Task 8; kanban t_698db8f7 /
+ * t_db375a60 detection side).
+ *
+ * `runHygieneScan` is read-only composition: each detector returns
+ * typed findings, the scan folds them into one frozen digest, and a
+ * broken detector lands in `errors` instead of failing the run.
+ * Detectors here: `conflicts` (truth-layer value conflicts),
+ * `usefulness` (preferences with no recall evidence), `freshness`
+ * (stale -> recompile, orphaned -> review).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { appendClaimEvent } from "../../../src/core/brain/truth/store.ts";
+import { emitRecallTelemetry } from "../../../src/core/brain/recall-telemetry.ts";
+import {
+ computeSourceStamp,
+ formatSourceStampFrontmatter,
+} from "../../../src/core/brain/freshness.ts";
+import { runHygieneScan } from "../../../src/core/brain/hygiene/scan.ts";
+
+let vault: string;
+
+const NOW = new Date("2026-06-10T12:00:00Z");
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hygiene-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, createdAt: string): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ [
+ "---",
+ "kind: brain-preference",
+ `id: pref-${slug}`,
+ "tags: [brain, brain/preference]",
+ `topic: ${slug}`,
+ "_status: confirmed",
+ `principle: principle for ${slug}`,
+ `created_at: ${createdAt}`,
+ `unconfirmed_until: ${createdAt}`,
+ "---",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+}
+
+describe("conflicts detector", () => {
+ test("surfaces a contested truth slot as a review finding", () => {
+ appendClaimEvent(vault, {
+ ts: "2026-06-01T10:00:00Z",
+ agent: "agent-a",
+ entity: "ACME Corp",
+ aspect: "headquarters",
+ value: "Berlin",
+ source: "[[note-a]]",
+ });
+ appendClaimEvent(vault, {
+ ts: "2026-06-05T10:00:00Z",
+ agent: "agent-b",
+ entity: "ACME Corp",
+ aspect: "headquarters",
+ value: "Lisbon",
+ source: "[[note-b]]",
+ });
+ const report = runHygieneScan(vault, { detectors: ["conflicts"], now: NOW });
+ expect(report.findings).toHaveLength(1);
+ const finding = report.findings[0]!;
+ expect(finding.detector).toBe("conflicts");
+ expect(finding.proposed_action).toBe("review");
+ expect(finding.targets[0]).toBe("acme corp#headquarters");
+ expect(report.counts.conflicts).toBe(1);
+ });
+
+ test("no conflicts means no findings", () => {
+ const report = runHygieneScan(vault, { detectors: ["conflicts"], now: NOW });
+ expect(report.findings).toHaveLength(0);
+ });
+});
+
+describe("usefulness detector", () => {
+ test("flags old preferences with zero recall evidence, skips recalled ones", () => {
+ writePref("never-recalled", "2026-01-01T00:00:00Z");
+ writePref("recalled", "2026-01-01T00:00:00Z");
+ writePref("too-young", "2026-06-01T00:00:00Z");
+ emitRecallTelemetry(vault, {
+ host: "test",
+ mode: "context_pack",
+ status: "ok",
+ durationMs: 5,
+ resultCount: 1,
+ topArtifacts: [{ id: "pref-recalled" }],
+ });
+ const report = runHygieneScan(vault, { detectors: ["usefulness"], now: NOW });
+ expect(report.findings).toHaveLength(1);
+ const finding = report.findings[0]!;
+ expect(finding.detector).toBe("usefulness");
+ expect(finding.targets).toEqual(["pref-never-recalled"]);
+ expect(finding.proposed_action).toBe("review");
+ });
+});
+
+describe("freshness detector", () => {
+ test("maps stale pages to recompile and orphaned pages to review", () => {
+ writeFileSync(join(vault, "notes-src.md"), "alpha", "utf8");
+ const staleStamp = computeSourceStamp(vault, ["notes-src.md"]);
+ mkdirSync(join(vault, "Brain", "derived"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "derived", "stale.md"),
+ `---\n${formatSourceStampFrontmatter(staleStamp)}\n---\nbody`,
+ "utf8",
+ );
+ const orphanStamp = computeSourceStamp(vault, ["gone-src.md"]);
+ writeFileSync(
+ join(vault, "Brain", "derived", "orphan.md"),
+ `---\n${formatSourceStampFrontmatter(orphanStamp)}\n---\nbody`,
+ "utf8",
+ );
+ writeFileSync(join(vault, "notes-src.md"), "alpha CHANGED", "utf8");
+
+ const report = runHygieneScan(vault, { detectors: ["freshness"], now: NOW });
+ const byAction = new Map(report.findings.map((f) => [f.proposed_action, f]));
+ expect(byAction.get("recompile")?.targets[0]?.endsWith("stale.md")).toBe(true);
+ expect(byAction.get("review")?.targets[0]?.endsWith("orphan.md")).toBe(true);
+ });
+});
+
+describe("scan composition", () => {
+ test("runs every requested detector, freezes the digest, reports counts", () => {
+ const report = runHygieneScan(vault, { now: NOW });
+ expect(report.detectors_run).toEqual(["conflicts", "dedup", "freshness", "usefulness"]);
+ expect(Object.isFrozen(report)).toBe(true);
+ expect(Object.isFrozen(report.findings)).toBe(true);
+ expect(report.errors).toHaveLength(0);
+ expect(report.generated_at).toBe(NOW.toISOString());
+ });
+
+ test("finding ids are deterministic across runs", () => {
+ writePref("never-recalled", "2026-01-01T00:00:00Z");
+ const first = runHygieneScan(vault, { detectors: ["usefulness"], now: NOW });
+ const second = runHygieneScan(vault, { detectors: ["usefulness"], now: NOW });
+ expect(first.findings[0]?.id).toBe(second.findings[0]?.id);
+ });
+});
diff --git a/tests/core/brain/lineage.test.ts b/tests/core/brain/lineage.test.ts
new file mode 100644
index 00000000..88cc0221
--- /dev/null
+++ b/tests/core/brain/lineage.test.ts
@@ -0,0 +1,250 @@
+/**
+ * Unit tests for the session-lineage kernel
+ * (continuity-hygiene-freshness suite, Task 2; kanban t_d08ccc5a /
+ * t_a94623ad).
+ *
+ * Resolution order pinned here: native payload fields win; the interim
+ * Hermes crutch (CRUTCH(t_1459706f)) links only on compression evidence
+ * + same cwd + bounded window; everything else is flat. A false stitch
+ * is worse than a missed stitch, so every ambiguous case resolves flat.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { tmpdir } from "node:os";
+
+import {
+ CRUTCH_LINK_WINDOW_MS,
+ readLineageLedger,
+ recordLineageObservation,
+ sessionLineageLedgerPath,
+} from "../../../src/core/brain/lineage/ledger.ts";
+import { resolveSessionLineage } from "../../../src/core/brain/lineage/resolve.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-lineage-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const T0 = Date.parse("2026-06-10T08:00:00Z");
+
+describe("resolveSessionLineage — native payload path", () => {
+ test("uses payload lineage fields when present", () => {
+ const lineage = resolveSessionLineage({
+ sessionId: "s-child",
+ parentSessionId: "s-parent",
+ rootSessionId: "s-root",
+ compressionDepth: 2,
+ });
+ expect(lineage).toEqual({
+ rootId: "s-root",
+ parentId: "s-parent",
+ depth: 2,
+ source: "payload",
+ });
+ });
+
+ test("defaults root to parent and depth to 1 when only parent_session_id arrives", () => {
+ const lineage = resolveSessionLineage({ sessionId: "s-child", parentSessionId: "s-parent" });
+ expect(lineage).toEqual({
+ rootId: "s-parent",
+ parentId: "s-parent",
+ depth: 1,
+ source: "payload",
+ });
+ });
+
+ test("a parent-only payload inherits the parent's root from the ledger (A -> B -> C)", () => {
+ recordLineageObservation(tmp, {
+ sessionId: "s-b",
+ at: new Date(T0).toISOString(),
+ event: "SessionStart",
+ lineage: { rootId: "s-a", parentId: "s-a", depth: 1, source: "payload" },
+ });
+ const lineage = resolveSessionLineage(
+ { sessionId: "s-c", parentSessionId: "s-b" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 1_000 },
+ );
+ expect(lineage).toEqual({ rootId: "s-a", parentId: "s-b", depth: 2, source: "payload" });
+ });
+
+ test("ignores a parent equal to the session itself (flat)", () => {
+ const lineage = resolveSessionLineage({ sessionId: "s-1", parentSessionId: "s-1" });
+ expect(lineage.source).toBe("flat");
+ expect(lineage.rootId).toBe("s-1");
+ });
+});
+
+describe("resolveSessionLineage — flat fallback", () => {
+ test("no payload fields and no ledger resolves flat", () => {
+ const lineage = resolveSessionLineage({ sessionId: "s-1" });
+ expect(lineage).toEqual({ rootId: "s-1", parentId: null, depth: 0, source: "flat" });
+ });
+});
+
+describe("lineage ledger — observations", () => {
+ test("read of a missing ledger returns an empty state", () => {
+ const state = readLineageLedger(tmp);
+ expect(state.size).toBe(0);
+ });
+
+ test("records observations and reads them back last-wins", () => {
+ recordLineageObservation(tmp, {
+ sessionId: "s-1",
+ at: new Date(T0).toISOString(),
+ cwd: "/work",
+ event: "UserPromptSubmit",
+ });
+ recordLineageObservation(tmp, {
+ sessionId: "s-1",
+ at: new Date(T0 + 60_000).toISOString(),
+ cwd: "/work",
+ event: "PostCompact",
+ compressionEvidence: true,
+ });
+ const state = readLineageLedger(tmp);
+ const entry = state.get("s-1");
+ expect(entry?.lastSeenMs).toBe(T0 + 60_000);
+ expect(entry?.cwd).toBe("/work");
+ expect(entry?.compressionEvidence).toBe(true);
+ });
+
+ test("skips corrupt ledger lines instead of throwing", () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(path, "not-json\n{\n", "utf8");
+ recordLineageObservation(tmp, {
+ sessionId: "s-1",
+ at: new Date(T0).toISOString(),
+ event: "Stop",
+ });
+ const state = readLineageLedger(tmp);
+ expect(state.size).toBe(1);
+ });
+});
+
+describe("resolveSessionLineage — crutch path (CRUTCH(t_1459706f))", () => {
+ function seedPredecessor(opts: { evidence: boolean; cwd?: string; endMs?: number }): void {
+ recordLineageObservation(tmp, {
+ sessionId: "s-old",
+ at: new Date(opts.endMs ?? T0).toISOString(),
+ cwd: opts.cwd ?? "/work",
+ event: opts.evidence ? "PostCompact" : "Stop",
+ ...(opts.evidence ? { compressionEvidence: true } : {}),
+ });
+ }
+
+ test("links a new session to a compression-evidenced predecessor in the same cwd", () => {
+ seedPredecessor({ evidence: true });
+ const lineage = resolveSessionLineage(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000 },
+ );
+ expect(lineage).toEqual({ rootId: "s-old", parentId: "s-old", depth: 1, source: "crutch" });
+ });
+
+ test("does not link without compression evidence", () => {
+ seedPredecessor({ evidence: false });
+ const lineage = resolveSessionLineage(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000 },
+ );
+ expect(lineage.source).toBe("flat");
+ });
+
+ test("does not link across different cwds", () => {
+ seedPredecessor({ evidence: true, cwd: "/elsewhere" });
+ const lineage = resolveSessionLineage(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000 },
+ );
+ expect(lineage.source).toBe("flat");
+ });
+
+ test("does not link outside the bounded window", () => {
+ seedPredecessor({ evidence: true });
+ const lineage = resolveSessionLineage(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + CRUTCH_LINK_WINDOW_MS + 1 },
+ );
+ expect(lineage.source).toBe("flat");
+ });
+
+ test("does not link when the session already has its own ledger history", () => {
+ seedPredecessor({ evidence: true });
+ // s-new was already active before the predecessor's compaction -
+ // it is a parallel session, not a continuation.
+ recordLineageObservation(tmp, {
+ sessionId: "s-new",
+ at: new Date(T0 - 120_000).toISOString(),
+ cwd: "/work",
+ event: "UserPromptSubmit",
+ });
+ const lineage = resolveSessionLineage(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000 },
+ );
+ expect(lineage.source).toBe("flat");
+ });
+
+ test("persisted crutch links are reused and chain depth across two compactions", () => {
+ seedPredecessor({ evidence: true });
+ const first = resolveSessionLineage(
+ { sessionId: "s-mid", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 10_000 },
+ );
+ expect(first.source).toBe("crutch");
+ recordLineageObservation(tmp, {
+ sessionId: "s-mid",
+ at: new Date(T0 + 10_000).toISOString(),
+ cwd: "/work",
+ event: "SessionStart",
+ lineage: first,
+ });
+ recordLineageObservation(tmp, {
+ sessionId: "s-mid",
+ at: new Date(T0 + 20_000).toISOString(),
+ cwd: "/work",
+ event: "PostCompact",
+ compressionEvidence: true,
+ });
+ const second = resolveSessionLineage(
+ { sessionId: "s-tip", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 40_000 },
+ );
+ expect(second).toEqual({ rootId: "s-old", parentId: "s-mid", depth: 2, source: "crutch" });
+
+ // A later event for s-mid resolves from its persisted link, not flat.
+ const replay = resolveSessionLineage(
+ { sessionId: "s-mid", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 60_000 },
+ );
+ expect(replay).toEqual({ rootId: "s-old", parentId: "s-old", depth: 1, source: "crutch" });
+ });
+});
+
+describe("lineage ledger — pruning", () => {
+ test("rewrites the ledger keeping the most recent sessions once over capacity", () => {
+ for (let i = 0; i < 600; i++) {
+ recordLineageObservation(tmp, {
+ sessionId: `s-${i}`,
+ at: new Date(T0 + i * 1_000).toISOString(),
+ event: "Stop",
+ });
+ }
+ const state = readLineageLedger(tmp);
+ expect(state.size).toBeLessThanOrEqual(512);
+ expect(state.has("s-599")).toBe(true);
+ expect(state.has("s-0")).toBe(false);
+ const raw = readFileSync(sessionLineageLedgerPath(tmp), "utf8");
+ expect(raw.split("\n").filter((line) => line.trim().length > 0).length).toBeLessThanOrEqual(
+ 512,
+ );
+ });
+});
diff --git a/tests/core/brain/recall-budget.ladder.test.ts b/tests/core/brain/recall-budget.ladder.test.ts
new file mode 100644
index 00000000..b4a2c478
--- /dev/null
+++ b/tests/core/brain/recall-budget.ladder.test.ts
@@ -0,0 +1,92 @@
+/**
+ * Staged degradation ladder for over-budget recall entries
+ * (continuity-hygiene-freshness suite, Task 5; kanban t_05f5dc12).
+ *
+ * Default behavior stays the hard code-point cut (pinned by
+ * recall-budget.test.ts). Opting into `degradation: "staged"` walks a
+ * deterministic ladder instead of cutting mid-sentence:
+ * 1. trim at the last sentence terminator inside the budget;
+ * 2. keep whole leading lines that fit;
+ * 3. hard cut as the last resort.
+ * Boundaries are structural (terminator punctuation across scripts,
+ * line breaks) - never language-specific wordlists.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { applyCharBudget } from "../../../src/core/brain/recall-budget.ts";
+
+describe("applyCharBudget — staged degradation", () => {
+ test("default mode stays a hard cut with no degradation report", () => {
+ const result = applyCharBudget([{ item: "a", text: "one two. three four" }], {
+ maxCharsPerEntry: 10,
+ });
+ expect(result.kept[0]?.text).toBe("one two. t");
+ expect(result.kept[0]?.trimmed).toBe(true);
+ expect("degradation" in (result.kept[0] ?? {})).toBe(false);
+ });
+
+ test("stage 1: trims at the last sentence terminator inside the budget", () => {
+ const result = applyCharBudget(
+ [{ item: "a", text: "First sentence. Second sentence! Third sentence is long." }],
+ { maxCharsPerEntry: 40, degradation: "staged" },
+ );
+ expect(result.kept[0]?.text).toBe("First sentence. Second sentence!");
+ expect(result.kept[0]?.trimmed).toBe(true);
+ expect(result.kept[0]?.degradation).toBe("sentence");
+ });
+
+ test("stage 1 works with CJK terminators", () => {
+ const result = applyCharBudget(
+ [{ item: "a", text: "第一句话。第二句话。第三句话很长很长很长" }],
+ {
+ maxCharsPerEntry: 10,
+ degradation: "staged",
+ },
+ );
+ expect(result.kept[0]?.text).toBe("第一句话。第二句话。");
+ expect(result.kept[0]?.degradation).toBe("sentence");
+ });
+
+ test("stage 2: keeps whole leading lines when no sentence boundary fits", () => {
+ const text = "- bullet one\n- bullet two\n- bullet three is much longer than the budget";
+ const result = applyCharBudget([{ item: "a", text }], {
+ maxCharsPerEntry: 30,
+ degradation: "staged",
+ });
+ expect(result.kept[0]?.text).toBe("- bullet one\n- bullet two");
+ expect(result.kept[0]?.degradation).toBe("lines");
+ });
+
+ test("stage 3: hard cut when no structural boundary exists in the window", () => {
+ const result = applyCharBudget([{ item: "a", text: "x".repeat(100) }], {
+ maxCharsPerEntry: 10,
+ degradation: "staged",
+ });
+ expect(result.kept[0]?.text).toBe("x".repeat(10));
+ expect(result.kept[0]?.degradation).toBe("hard");
+ });
+
+ test("entries inside the budget stay untouched and unreported", () => {
+ const result = applyCharBudget([{ item: "a", text: "short. text" }], {
+ maxCharsPerEntry: 100,
+ degradation: "staged",
+ });
+ expect(result.kept[0]?.text).toBe("short. text");
+ expect(result.kept[0]?.trimmed).toBe(false);
+ expect("degradation" in (result.kept[0] ?? {})).toBe(false);
+ });
+
+ test("total-chars accounting charges the degraded text, not the original", () => {
+ const result = applyCharBudget(
+ [
+ { item: "a", text: "First sentence. Tail that will be dropped" },
+ { item: "b", text: "Second entry" },
+ ],
+ { maxCharsPerEntry: 20, maxTotalChars: 30, degradation: "staged" },
+ );
+ expect(result.kept[0]?.text).toBe("First sentence.");
+ expect(result.kept[1]?.text).toBe("Second entry");
+ expect(result.totalChars).toBe("First sentence.".length + "Second entry".length);
+ });
+});
diff --git a/tests/core/brain/recompile.test.ts b/tests/core/brain/recompile.test.ts
new file mode 100644
index 00000000..69facd66
--- /dev/null
+++ b/tests/core/brain/recompile.test.ts
@@ -0,0 +1,137 @@
+/**
+ * Targeted recompile of stale derived pages
+ * (continuity-hygiene-freshness suite, Task 12; kanban t_fe490119).
+ *
+ * The planner walks freshness findings and produces a typed plan:
+ * stale handoff notes re-derive from their recorded transcript onto
+ * the SAME page path, orphaned pages stage an archive cleanup,
+ * anything without a known derivation pipeline is `manual`. Dry-run
+ * previews the full plan with zero writes. Unrelated pages are never
+ * touched.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { checkPageFreshness } from "../../../src/core/brain/freshness.ts";
+import { writeHandoffNote } from "../../../src/core/brain/handoff.ts";
+import { executeRecompile, planRecompile } from "../../../src/core/brain/recompile.ts";
+
+let vault: string;
+
+const NOW = new Date("2026-06-10T12:00:00Z");
+
+/** A minimal Claude-format transcript the session adapters can read. */
+function writeTranscript(path: string, text: string): void {
+ writeFileSync(
+ path,
+ [
+ '{"type":"queue-operation","timestamp":"2026-06-10T10:00:00.000Z","sessionId":"recompile-sess"}',
+ `{"parentUuid":null,"sessionId":"recompile-sess","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":${JSON.stringify(text)}},"uuid":"u1","timestamp":"2026-06-10T10:00:01.000Z"}`,
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-recompile-"));
+ mkdirSync(join(vault, "Brain", "handoffs"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function seedStaleHandoff(): { page: string; transcript: string } {
+ const transcript = join(vault, "session.jsonl");
+ writeTranscript(transcript, "implemented the original feature");
+ const note = writeHandoffNote(vault, {
+ sessionId: "recompile-sess",
+ agent: "tester",
+ now: new Date("2026-06-09T12:00:00Z"),
+ turns: [
+ {
+ turnId: "t1",
+ role: "user",
+ text: "implemented the original feature",
+ timestamp: "2026-06-10T10:00:01Z",
+ },
+ ],
+ sourcePaths: [transcript],
+ });
+ // The transcript changes after derivation -> the note goes stale.
+ writeTranscript(transcript, "implemented the UPDATED feature with new scope");
+ return { page: note.path, transcript };
+}
+
+describe("planRecompile", () => {
+ test("maps stale handoff notes to rederive and orphans to cleanup", () => {
+ const { page } = seedStaleHandoff();
+ const orphan = join(vault, "Brain", "orphan.md");
+ writeFileSync(
+ orphan,
+ '---\nsource_paths: ["gone.md"]\nsource_hashes: ["deadbeef"]\n---\nbody',
+ "utf8",
+ );
+ const plan = planRecompile(vault);
+ const byKind = new Map(plan.entries.map((entry) => [entry.kind, entry]));
+ expect(byKind.get("rederive-handoff")?.page).toBe(page);
+ expect(byKind.get("cleanup")?.page).toBe(orphan);
+ expect(plan.entries).toHaveLength(2);
+ });
+
+ test("a stale page without a known pipeline plans as manual", () => {
+ const source = join(vault, "data.txt");
+ writeFileSync(source, "v1", "utf8");
+ const page = join(vault, "Brain", "derived.md");
+ const { computeSourceStamp, formatSourceStampFrontmatter } =
+ require("../../../src/core/brain/freshness.ts") as typeof import("../../../src/core/brain/freshness.ts");
+ writeFileSync(
+ page,
+ `---\n${formatSourceStampFrontmatter(computeSourceStamp(vault, ["data.txt"]))}\n---\nbody`,
+ "utf8",
+ );
+ writeFileSync(source, "v2", "utf8");
+ const plan = planRecompile(vault);
+ expect(plan.entries[0]?.kind).toBe("manual");
+ });
+});
+
+describe("executeRecompile", () => {
+ test("dry-run previews and writes nothing", async () => {
+ const { page } = seedStaleHandoff();
+ const before = readFileSync(page, "utf8");
+ const plan = planRecompile(vault);
+ const result = await executeRecompile(vault, plan, { dryRun: true, agent: "tester", now: NOW });
+ expect(result.dry_run).toBe(true);
+ expect(result.rederived).toHaveLength(0);
+ expect(readFileSync(page, "utf8")).toBe(before);
+ });
+
+ test("re-derives a stale handoff note in place and makes it fresh again", async () => {
+ const { page } = seedStaleHandoff();
+ const plan = planRecompile(vault);
+ const result = await executeRecompile(vault, plan, { agent: "tester", now: NOW });
+ expect(result.rederived).toEqual([page]);
+ expect(readFileSync(page, "utf8")).toContain("UPDATED feature");
+ expect(checkPageFreshness(vault, page)?.status).toBe("fresh");
+ });
+
+ test("cleanup archives the orphaned page out of its live location", async () => {
+ const orphan = join(vault, "Brain", "orphan.md");
+ writeFileSync(
+ orphan,
+ '---\nsource_paths: ["gone.md"]\nsource_hashes: ["deadbeef"]\n---\nbody',
+ "utf8",
+ );
+ const plan = planRecompile(vault);
+ const result = await executeRecompile(vault, plan, { agent: "tester", now: NOW });
+ expect(result.archived).toHaveLength(1);
+ expect(existsSync(orphan)).toBe(false);
+ expect(existsSync(result.archived[0]!)).toBe(true);
+ expect(result.archived[0]).toContain(".snapshots");
+ });
+});
diff --git a/tests/core/brain/session-lifecycle.lineage.test.ts b/tests/core/brain/session-lifecycle.lineage.test.ts
new file mode 100644
index 00000000..041da5a0
--- /dev/null
+++ b/tests/core/brain/session-lifecycle.lineage.test.ts
@@ -0,0 +1,137 @@
+/**
+ * Lineage plumbing through lifecycle capture
+ * (continuity-hygiene-freshness suite, Task 3; kanban t_d08ccc5a).
+ *
+ * The hook payload boundary now carries optional native lineage fields
+ * (upstream Hermes PR #42940); capture resolves them through the
+ * lineage kernel, feeds the crutch ledger, and stamps non-flat lineage
+ * into its result. Flat sessions stay byte-identical to the
+ * pre-lineage behavior: no lineage key anywhere.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { captureSessionLifecycleEvent } from "../../../src/core/brain/session-lifecycle.ts";
+import {
+ readLineageLedger,
+ sessionLineageLedgerPath,
+} from "../../../src/core/brain/lineage/ledger.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-lifecycle-lineage-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("captureSessionLifecycleEvent — native lineage payload", () => {
+ test("resolves payload lineage fields and stamps them on the result", async () => {
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "seg-2",
+ parent_session_id: "seg-1",
+ root_session_id: "seg-1",
+ compression_depth: 1,
+ cwd: "/work",
+ prompt: "hello",
+ },
+ { agent: "tester", now: new Date("2026-06-10T09:00:00Z") },
+ );
+ expect(result.lineage).toEqual({
+ rootId: "seg-1",
+ parentId: "seg-1",
+ depth: 1,
+ source: "payload",
+ });
+ const entry = readLineageLedger(vault).get("seg-2");
+ expect(entry?.lineage?.rootId).toBe("seg-1");
+ });
+
+ test("flat payload carries no lineage key and records a plain observation", async () => {
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "solo-1",
+ cwd: "/work",
+ prompt: "hello",
+ },
+ { agent: "tester", now: new Date("2026-06-10T09:00:00Z") },
+ );
+ expect("lineage" in result).toBe(false);
+ const entry = readLineageLedger(vault).get("solo-1");
+ expect(entry).toBeDefined();
+ expect(entry?.lineage).toBeUndefined();
+ });
+});
+
+describe("captureSessionLifecycleEvent — crutch flow (CRUTCH(t_1459706f))", () => {
+ test("stitches a new session that follows a compression boundary in the same cwd", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "old-1", cwd: "/work", prompt: "hi" },
+ { agent: "tester", now: new Date("2026-06-10T09:00:00Z") },
+ );
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "PostCompact", session_id: "old-1", cwd: "/work" },
+ { agent: "tester", now: new Date("2026-06-10T09:10:00Z") },
+ );
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "new-1", cwd: "/work", prompt: "go" },
+ { agent: "tester", now: new Date("2026-06-10T09:11:00Z") },
+ );
+ expect(result.lineage).toEqual({
+ rootId: "old-1",
+ parentId: "old-1",
+ depth: 1,
+ source: "crutch",
+ });
+ });
+
+ test("SessionStart with source compact counts as compression evidence", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "SessionStart", session_id: "old-2", cwd: "/work", source: "compact" },
+ { agent: "tester", now: new Date("2026-06-10T09:00:00Z") },
+ );
+ const entry = readLineageLedger(vault).get("old-2");
+ expect(entry?.compressionEvidence).toBe(true);
+ });
+
+ test("does not stitch across cwds", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "PostCompact", session_id: "old-3", cwd: "/a" },
+ { agent: "tester", now: new Date("2026-06-10T09:00:00Z") },
+ );
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "new-3", cwd: "/b", prompt: "go" },
+ { agent: "tester", now: new Date("2026-06-10T09:01:00Z") },
+ );
+ expect("lineage" in result).toBe(false);
+ });
+});
+
+describe("captureSessionLifecycleEvent — ledger write gating", () => {
+ test("dry runs never write the ledger", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "dry-1", cwd: "/work", prompt: "x" },
+ { agent: "tester", now: new Date("2026-06-10T09:00:00Z"), dryRun: true },
+ );
+ expect(existsSync(sessionLineageLedgerPath(vault))).toBe(false);
+ });
+});
diff --git a/tests/core/brain/session-recall.lineage.test.ts b/tests/core/brain/session-recall.lineage.test.ts
new file mode 100644
index 00000000..312ebc46
--- /dev/null
+++ b/tests/core/brain/session-recall.lineage.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Compression-aware session recall keyed on the lineage root
+ * (continuity-hygiene-freshness suite, Task 4; kanban t_a94623ad).
+ *
+ * A conversation that the host split across a compression boundary is
+ * one lineage: search / describe over ANY segment id must return the
+ * stitched conversation, and describe must expose the segment chain.
+ * Never-compacted sessions stay byte-identical to the flat behavior.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ describeSessionRecall,
+ importSessionRecall,
+ searchSessionRecall,
+} from "../../../src/core/brain/session-recall.ts";
+import type { SessionTurn } from "../../../src/core/brain/sessions/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-recall-lineage-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function turn(
+ turnId: string,
+ role: SessionTurn["role"],
+ text: string,
+ second: number,
+): SessionTurn {
+ return {
+ turnId,
+ role,
+ text,
+ timestamp: `2026-06-10T10:00:${String(second).padStart(2, "0")}.000Z`,
+ };
+}
+
+function importSegments(): void {
+ importSessionRecall(vault, {
+ sessionId: "root-seg",
+ turns: [
+ turn("t1", "user", "alpha question before compaction", 1),
+ turn("t2", "assistant", "alpha answer before compaction", 2),
+ ],
+ createdAt: "2026-06-10T10:00:10Z",
+ });
+ importSessionRecall(vault, {
+ sessionId: "child-seg",
+ turns: [
+ turn("t3", "user", "beta question after compaction", 21),
+ turn("t4", "assistant", "beta answer after compaction", 22),
+ ],
+ createdAt: "2026-06-10T10:01:10Z",
+ lineage: { rootId: "root-seg", parentId: "root-seg", depth: 1, source: "payload" },
+ });
+}
+
+describe("lineage stamping on imported records", () => {
+ test("non-flat lineage lands on turn and summary payloads", () => {
+ importSegments();
+ const hits = searchSessionRecall(vault, { query: "beta question", sessionId: "child-seg" });
+ expect(hits.hits.length).toBeGreaterThan(0);
+ const described = describeSessionRecall(vault, { sessionId: "child-seg" });
+ expect(described.lineage_root).toBe("root-seg");
+ });
+});
+
+describe("stitched recall across the compression boundary", () => {
+ test("search via the child id finds turns from the root segment", () => {
+ importSegments();
+ const hits = searchSessionRecall(vault, { query: "alpha question", sessionId: "child-seg" });
+ expect(hits.hits.length).toBeGreaterThan(0);
+ });
+
+ test("search via the root id finds turns from the child segment", () => {
+ importSegments();
+ const hits = searchSessionRecall(vault, { query: "beta answer", sessionId: "root-seg" });
+ expect(hits.hits.length).toBeGreaterThan(0);
+ });
+
+ test("describe over any segment counts the whole lineage and lists segments", () => {
+ importSegments();
+ const fromChild = describeSessionRecall(vault, { sessionId: "child-seg" });
+ const fromRoot = describeSessionRecall(vault, { sessionId: "root-seg" });
+ expect(fromChild.raw_turns).toBe(4);
+ expect(fromRoot.raw_turns).toBe(4);
+ expect(fromRoot.lineage_root).toBe("root-seg");
+ expect(fromChild.segments).toEqual([
+ { session_id: "root-seg", parent_session_id: null },
+ { session_id: "child-seg", parent_session_id: "root-seg" },
+ ]);
+ });
+});
+
+describe("deep chains stitch transitively", () => {
+ test("three segments with per-segment parent links resolve to one conversation", () => {
+ importSessionRecall(vault, {
+ sessionId: "seg-a",
+ turns: [turn("t1", "user", "first segment text", 1)],
+ createdAt: "2026-06-10T10:00:10Z",
+ });
+ importSessionRecall(vault, {
+ sessionId: "seg-b",
+ turns: [turn("t2", "user", "second segment text", 11)],
+ createdAt: "2026-06-10T10:01:10Z",
+ lineage: { rootId: "seg-a", parentId: "seg-a", depth: 1, source: "payload" },
+ });
+ // seg-c recorded only its direct parent (parent promoted to root
+ // by an older writer) - the scope must still reach seg-a.
+ importSessionRecall(vault, {
+ sessionId: "seg-c",
+ turns: [turn("t3", "user", "third segment text", 21)],
+ createdAt: "2026-06-10T10:02:10Z",
+ lineage: { rootId: "seg-b", parentId: "seg-b", depth: 2, source: "payload" },
+ });
+ const fromTip = describeSessionRecall(vault, { sessionId: "seg-c" });
+ expect(fromTip.raw_turns).toBe(3);
+ expect(fromTip.lineage_root).toBe("seg-a");
+ const hits = searchSessionRecall(vault, { query: "first segment", sessionId: "seg-c" });
+ expect(hits.hits.length).toBeGreaterThan(0);
+ const fromRoot = describeSessionRecall(vault, { sessionId: "seg-a" });
+ expect(fromRoot.raw_turns).toBe(3);
+ });
+});
+
+describe("flat sessions regress nothing", () => {
+ test("a never-compacted session keeps the exact flat result shape", () => {
+ importSessionRecall(vault, {
+ sessionId: "solo",
+ turns: [turn("t1", "user", "gamma standalone", 1)],
+ createdAt: "2026-06-10T10:00:10Z",
+ });
+ const described = describeSessionRecall(vault, { sessionId: "solo" });
+ expect(described).toEqual({
+ session_id: "solo",
+ raw_turns: 1,
+ summary_nodes: 1,
+ depths: { "1": 1 },
+ });
+ expect("lineage_root" in described).toBe(false);
+ expect("segments" in described).toBe(false);
+ const foreign = searchSessionRecall(vault, { query: "gamma", sessionId: "other" });
+ expect(foreign.hits).toHaveLength(0);
+ });
+});
diff --git a/tests/core/command-bridge.test.ts b/tests/core/command-bridge.test.ts
new file mode 100644
index 00000000..584156b0
--- /dev/null
+++ b/tests/core/command-bridge.test.ts
@@ -0,0 +1,56 @@
+/**
+ * Unit tests for the shared external-command JSON bridge
+ * (continuity-hygiene-freshness suite, Task 1).
+ *
+ * The bridge is the single sanctioned boundary for consulting an
+ * external command with JSON on stdin and reading JSON from stdout.
+ * Contract pinned here: skipped on absent command, ran with parsed
+ * output on success, error (never throw) on non-zero exit, malformed
+ * JSON, signal kill, or timeout - the fail-open semantics
+ * `src/core/bench/judge.ts` shipped with.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { runJsonCommandBridge } from "../../src/core/reliability/command-bridge.ts";
+
+describe("runJsonCommandBridge", () => {
+ test("skips when the command is undefined or blank", () => {
+ expect(runJsonCommandBridge(undefined, { a: 1 })).toEqual({ status: "skipped" });
+ expect(runJsonCommandBridge("", { a: 1 })).toEqual({ status: "skipped" });
+ expect(runJsonCommandBridge(" ", { a: 1 })).toEqual({ status: "skipped" });
+ });
+
+ test("runs the command, passes input JSON on stdin, parses stdout JSON", () => {
+ const result = runJsonCommandBridge("cat", { questions: [1, 2] });
+ expect(result.status).toBe("ran");
+ if (result.status === "ran") {
+ expect(result.output).toEqual({ questions: [1, 2] });
+ }
+ });
+
+ test("reports error with exit status on non-zero exit", () => {
+ const result = runJsonCommandBridge("exit 3", {});
+ expect(result).toEqual({ status: "error", detail: "command exited 3" });
+ });
+
+ test("labels error details when a label is supplied", () => {
+ const result = runJsonCommandBridge("exit 2", {}, { label: "judge command" });
+ expect(result).toEqual({ status: "error", detail: "judge command exited 2" });
+ });
+
+ test("reports error on malformed stdout JSON instead of throwing", () => {
+ const result = runJsonCommandBridge("echo not-json", {});
+ expect(result.status).toBe("error");
+ });
+
+ test("reports error on timeout instead of hanging or throwing", () => {
+ const result = runJsonCommandBridge("sleep 5", {}, { timeoutMs: 100 });
+ expect(result.status).toBe("error");
+ });
+
+ test("result objects are frozen", () => {
+ const result = runJsonCommandBridge("cat", {});
+ expect(Object.isFrozen(result)).toBe(true);
+ });
+});
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index 0dce6103..540acd0a 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -6,6 +6,9 @@
* future registry change) is provably name-set-preserving. A failure
* here means the public surface changed - that requires a deliberate
* major/minor release decision, not a refactor.
+ *
+ * Deliberate surface changes so far: v1.3.0 added `brain_hygiene` and
+ * `brain_anticipatory_context` (continuity-hygiene-freshness suite).
*/
import { describe, expect, test } from "bun:test";
@@ -16,6 +19,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_agent_diff",
"brain_agent_query",
"brain_analytics",
+ "brain_anticipatory_context",
"brain_apply_evidence",
"brain_audit",
"brain_backlinks",
@@ -35,6 +39,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_feedback",
"brain_foresight",
"brain_health",
+ "brain_hygiene",
"brain_idea_discovery",
"brain_intent_review",
"brain_intention",
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index cbc01500..df3460dd 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -198,6 +198,7 @@ describe("tool listing", () => {
"brain_agent_diff",
"brain_doctor",
"brain_health",
+ "brain_hygiene",
"brain_mcp_landscape",
// Canonical entity registry read surface (Memory Integrity Suite).
"brain_entity",
@@ -230,6 +231,7 @@ describe("tool listing", () => {
// names above stay registered as deprecated aliases.
"brain_brief",
"brain_analytics",
+ "brain_anticipatory_context",
// Search (added in v0.10.0; recall gate added in v0.27.0).
"brain_recall_feedback",
"brain_recall_gate",
@@ -520,7 +522,9 @@ describe("stdio loop", () => {
// (Entity Truth & Self-Improving Dream Suite) = 61.
// + brain_labels / brain_tiers / brain_secrets / brain_maintenance
// (Write-Time Integrity & Governance Suite) = 65.
- expect(list.result.tools.length).toBe(69);
+ // + brain_hygiene / brain_anticipatory_context
+ // (continuity-hygiene-freshness suite, v1.3.0) = 71.
+ expect(list.result.tools.length).toBe(71);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index 295a552e..b7f6fc34 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -138,5 +138,5 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
method: "tools/list",
params: {},
})) as { result: { tools: Array<{ name: string }> } };
- expect(list.result.tools.length).toBe(69);
+ expect(list.result.tools.length).toBe(71);
});