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(brain): session-boundary capture durability and post-compaction pinned-anchor survival audit (v1.19.0) (#112)

Sol Aitkenbb5f3201ae23
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 5bd02774..5aa3a562 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.18.1",
+ "version": "1.19.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 f4651ee5..77ce35bd 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.18.1",
+ "version": "1.19.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 3e430918..abeb458a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,62 @@ 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.19.0] - 2026-06-24
+
+Session-boundary capture durability and a post-compaction survival
+audit for pinned context. Three durability gaps at session boundaries
+are closed, and each new behaviour is off by default or otherwise
+byte-identical until opted in. The kernel still calls no LLM.
+
+### Added
+
+- **Post-compaction pinned-anchor survival audit and selective
+ re-assertion (`t_post_compact_audit`).** A deterministic, LLM-free
+ audit symmetric to the existing pre-compaction capture
+ (`extractPreCompactRecords`). After a Hermes context-compaction demotes
+ a pinned anchor's text into the background summary block, nothing
+ previously verified the anchor still lived in the ACTIVE region or
+ re-surfaced it. `detectCompaction` scans the conversation for Hermes
+ compressor handoff markers (Unicode SUMMARY_PREFIX, ASCII fallback, and
+ legacy `[CONTEXT SUMMARY]:`; overridable per-host) and splits summary
+ versus active. A per-session summary-body hash
+ (`sessionId:summaryHash` dedupe key on a new `post_compact_audit`
+ continuity record) ensures only a genuinely new compaction triggers an
+ audit, so re-running each turn cannot churn the prompt cache.
+ Locale-agnostic keyword probes (length-based, no stopword list)
+ classify each pinned and static anchor as survived, drifted, or absent;
+ only drifted anchors (present in the summary, gone from active) are
+ re-asserted via `appendPinnedContext`, so survivors cost zero tokens.
+ Fail-open throughout (every recoverable error lands in `errors`, never
+ thrown), with a bounded drift log. Surfaced as the `o2b brain
+ post-compact-audit` CLI verb and gated by `post_compact_survival_audit`
+ (default OFF, env/config), with `--force` for diagnostics; unchanged
+ installs stay byte-identical.
+
+### Changed
+
+- **Interrupted sessions are captured instead of dropped
+ (`t_interrupted_capture`).** Since Hermes PRs #50004/#50003/#50312, a
+ SIGHUP/SIGTERM/force-quit/restart-drain now flushes the in-flight
+ transcript and fires `on_session_end(interrupted=True)`. Previously
+ Open Second Brain swallowed the `interrupted` flag into `_kwargs` and
+ these sessions left no memory trace. `session-lifecycle.ts` now threads
+ an absent-by-default `interrupted` flag through `NormalizedPayload`; on
+ an interrupted `SessionEnd` it consumes the persisted pre-restart
+ transcript via the session adapters and runs its user turns through the
+ same marker/fact extraction as a live prompt. Double-counting on resume
+ is prevented by the existing content-keyed dedupe seams (signal
+ `dedup_hash` and the fact dedup index). `interrupted` and
+ `transcript_consumed` are recorded honestly in the audit record/result;
+ an unreadable transcript surfaces `transcript_consumed: false` rather
+ than coercing to a clean close. The Hermes `provider.py` surfaces the
+ `interrupted` kwarg from `on_session_end` onto the flush payload
+ (absent by default, so a clean close is byte-identical) and makes no
+ capture decision. The `pre-compact-extract` path and the
+ `brain_pre_compact_extract` MCP schema accept an optional `interrupted`
+ flag recorded on the continuity record so an interrupted capture is
+ marked honestly. Fail-soft throughout.
+
## [1.18.1] - 2026-06-24
### Fixed
@@ -5962,6 +6018,8 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.19.0]: https://github.com/itechmeat/open-second-brain/compare/v1.18.1...v1.19.0
+[1.18.1]: https://github.com/itechmeat/open-second-brain/compare/v1.18.0...v1.18.1
[1.18.0]: https://github.com/itechmeat/open-second-brain/compare/v1.17.0...v1.18.0
[1.17.0]: https://github.com/itechmeat/open-second-brain/compare/v1.16.0...v1.17.0
[1.16.0]: https://github.com/itechmeat/open-second-brain/compare/v1.15.0...v1.16.0
diff --git a/README.md b/README.md
index 675403f6..c79006b7 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm
## What is new
-Open Second Brain 1.17.0 widens the CodeGraph and MCP surfaces without changing any default behavior. The deterministic link extractor now resolves CommonMark reference-style Markdown links into real graph edges, a standalone MCP console entry mirrors the existing launcher and injects the mcp subcommand, an optional streamable HTTP MCP transport adds constant-time API-key auth for remote hosts, and search indexing gains an explicit offline backend that processes a keyless corpus to completion and never calls an LLM. Every change is strictly additive: the kernel still calls no LLM, and existing flows are byte-identical when the new options are unused.
+Open Second Brain 1.19.0 closes two session-boundary durability gaps that silently lost or distorted memory, and it adds a deterministic post-compaction survival audit for pinned context. When the host runtime reports an interrupted shutdown, the agent now honours the flag, consumes the persisted pre-restart transcript, and runs its turns through the same extraction as a live prompt, so a SIGHUP or force-quit no longer leaves the conversation without a memory trace. A new LLM-free post-compaction audit detects when a pinned anchor has drifted into a context summary and selectively re-asserts only the drifted anchors, keeping the long-conversation memory the pinned store was built to protect. Both behaviours are off by default and byte-identical when unused, and the kernel still calls no LLM.
## Why
diff --git a/docs/brainstorm/session-lifecycle-capture-durability/cli-output/claude.md b/docs/brainstorm/session-lifecycle-capture-durability/cli-output/claude.md
new file mode 100644
index 00000000..c1db3884
--- /dev/null
+++ b/docs/brainstorm/session-lifecycle-capture-durability/cli-output/claude.md
@@ -0,0 +1,33 @@
+### Variant 1: TS-core authority, dumb provider
+- **Approach:** Keep `provider.py` a pure pass-through: surface the `interrupted` kwarg as an explicit field on the bridge payload and forward both the `messages` list and the `session-transcript.jsonl` path, but make no capture decisions in Python. All new behaviour — interrupted-end reconciliation, resume de-dup, and the post-compaction survival audit — lands as new/extended modules under `src/core/brain` (a new `post-compact-audit.ts` mirroring `pre-compact-extract.ts`, plus `interrupted` handling inside `session-lifecycle.ts`). One CLI verb gains the flag; the deterministic core owns all logic and all dedupe.
+- **Trade-offs:**
+ - Pro: Single deterministic, unit-testable locus; honours "core is LLM-free" and keeps the Python shim trivial and fail-soft by construction.
+ - Pro: Survival audit sits naturally beside the symmetric `extractPreCompactRecords`, sharing the continuity store and `[KIND, sessionId, contentHash]` key.
+ - Con: Widens the bridge payload contract and pushes interrupted-transcript bytes across the boundary even when the flag is absent (mitigated by an off-by-default field).
+ - Con: Larger TS surface to land in one PR; three concerns touch the same lifecycle file.
+- **Complexity:** medium
+- **Risk:** low
+
+### Variant 2: Minimal seam-reuse, three independent diffs
+- **Approach:** Treat the three tasks as three small additive diffs against existing seams, introducing no new abstraction. `interrupted` becomes an optional `NormalizedPayload` field consumed by the existing SessionEnd branch, reusing `resolveSessionLineage` for resume detection and the existing dedupe key to suppress re-capture; the `/exit` task is a verification-plus-deletion of the local poll workaround in `provider.py`; the survival audit is a new post-compaction CLI verb that reuses `pre-compress-pack.ts` read primitives and `readPinnedContext` plus the bounded drift log. Each ships behind its own absent-by-default field/flag.
+- **Trade-offs:**
+ - Pro: Smallest possible diff per task; byte-identical when flags/fields absent, matching repo conventions exactly.
+ - Pro: Maximally reuses named existing substrates (dedupe key, lineage, symmetric pre-compact pass) the grounding calls out, lowering double-count and regression risk.
+ - Pro: Each task is independently reviewable and revertible within the shared branch.
+ - Con: No unifying model means interrupted-end, clean-end, and audit paths stay three parallel code paths — some duplicated idempotency reasoning.
+ - Con: The honest-surfacing of an un-honourable `interrupted` flag is handled ad hoc per path rather than centrally.
+- **Complexity:** small
+- **Risk:** low
+
+### Variant 3: Unified continuity-event pipeline with idempotency ledger
+- **Approach:** Introduce a single `SessionContinuityEvent` abstraction that normalizes interrupted-end, clean-end, and post-compaction-survival into one typed event flowing through one capture pipeline backed by an explicit append-only idempotency ledger (superseding the per-call dedupe key). Both `provider.py` hooks and a new post-compact verb emit into this pipeline; the ledger guarantees no double-count across interrupt→resume and no duplicate continuity records, and records un-honoured `interrupted` flags as honest ledger entries.
+- **Trade-offs:**
+ - Pro: One place to reason about idempotency, honesty surfacing, and fail-soft behaviour across all three tasks; strongest future extensibility.
+ - Pro: Cleanest conceptual model — interrupted capture and audit re-assertion become uniform events.
+ - Con: Largest blast radius; replacing the proven `[KIND, sessionId, contentHash]` dedupe with a new ledger risks regressions in already-shipped capture paths and breaks "additive where possible."
+ - Con: Hard to keep byte-identical for unchanged installs when a core store is replaced; heavier review and migration burden in a single release.
+- **Complexity:** large
+- **Risk:** high
+
+### Recommended: Variant 2
+The release scope explicitly catalogues the substrates each task needs — the `[KIND, sessionId, contentHash]` dedupe key, resume-aware `resolveSessionLineage`, and the symmetric `extractPreCompactRecords` pass — so the lowest-risk path is three tight additive diffs that reuse them, fully honouring off-by-default/byte-identical, fail-soft, and KISS. It avoids both Variant 3's risky core-store replacement and Variant 1's premature TS consolidation, while leaving Variant 1's `post-compact-audit.ts` placement available as a later refactor if the parallel paths prove worth unifying.
diff --git a/docs/brainstorm/session-lifecycle-capture-durability/cli-output/prompt.md b/docs/brainstorm/session-lifecycle-capture-durability/cli-output/prompt.md
new file mode 100644
index 00000000..21b1194f
--- /dev/null
+++ b/docs/brainstorm/session-lifecycle-capture-durability/cli-output/prompt.md
@@ -0,0 +1,116 @@
+# Consultation: Open Second Brain — Session Lifecycle Capture Durability
+
+You are a senior backend architect. Produce exactly **3 distinct architectural
+variants** for shipping the release below, then exactly one
+**"Recommended: Variant N"** line with rationale. Output ONLY the three variant
+sections and the recommendation. No code. No prose outside those sections.
+
+## Project
+
+- **Name:** Open Second Brain (repo `open-second-brain`, local slug `o2b`)
+- **Language/runtime:** TypeScript (strict), runs on **Bun**. ESM (`"type": "module"`).
+- **Tests:** `bash scripts/test`. The provider shim is plain Python (no Hermes needed in CI).
+- **Nature:** An Obsidian-native memory layer for the Hermes Agent. Memory is plain Markdown under `Brain/` in the vault. The core is **deterministic / LLM-free** by design.
+- **Conventions:** SOLID / KISS / DRY. No misleading fallbacks. No hardcoding. All strings and docs in English; the design must be abstract and multi-language-capable, never locale-coupled. New behaviour must be **off by default or byte-identical** when unused. Hooks must be **fail-soft** (a capture path can never break an agent turn). Every change is **additive** where possible.
+
+## Release scope (three tasks shipping together on one branch)
+
+### t_c181f92b — Capture interrupted sessions: on_session_end(interrupted=True) + persisted transcript (#50004/#50003/#50312)
+
+Hermes PRs #50004 (CLI), #50003 (TUI), #50312 (gateway drain-timeout) — all merged — now flush the in-flight transcript on SIGHUP/SIGTERM/force-quit/restart-drain and fire `on_session_end` with `interrupted=True`. Previously these sessions were silently dropped from memory capture. Ensure the OSB session-lifecycle / session-summary path handles the `interrupted` flag and consumes the now-available pre-restart transcript, so interrupted conversations are captured (not lost) and **not double-counted on resume**. Refs: `src/core/brain/session-lifecycle.ts`, `session-summary.ts`; `plugins/hermes/provider.py`.
+
+### t_3b8fe3a1 — Verify memory on_session_end fires on /exit now native (#49315); drop any workaround
+
+Hermes #49315 (merged) restored the memory-provider `on_session_end` hook on CLI `/exit` (the god-file Phase 4 refactor had bound the atexit `_active_agent_ref` to the mixin module, not `cli.py`, so `on_session_end` never ran). Confirm OSB's provider end-of-session capture now fires on `/exit` and **remove any local workaround/poll** that compensated for the missing hook. Refs: `plugins/hermes/provider.py`, `_base.py`.
+
+### t_12c8b256 — [upstream:hermes-memlock] Post-compaction pinned-anchor survival audit and selective re-assertion
+
+Detect a Hermes context-compaction event, audit which pinned anchors / standing instructions actually survived in the ACTIVE (non-summary) region of the conversation, and re-assert only the drifted ones as a reminder block. MemLock's `pre_llm_call` hook scans `conversation_history` for the compressor's `SUMMARY_PREFIX` literal, hashes the summary body to detect a NEW compaction, then runs keyword probes (optionally windowed-embedding) for each anchor scoped to the non-summary region — an anchor whose probes hit only inside the summary block counts as drifted. Drifted anchors get rehydrated; survivors cost zero tokens. Deterministic, no LLM in the loop; fail-open; bounded drift log. Refs: `src/core/brain/pinned.ts` (`readPinnedContext`/`writePinnedContext`/`appendPinnedContext`, `MAX_PINNED_CONTEXT_LEN = 20_000`), `src/core/brain/pre-compact-extract.ts` (`extractPreCompactRecords` — the SYMMETRIC pre-compaction capture pass that already exists), `src/core/brain/context-presets.ts`, `src/core/brain/active-budget.ts`. There is currently NO post-compaction survival check anywhere in `src/core/brain`.
+
+## Current architecture (grounding — do NOT re-derive)
+
+### Python provider — `plugins/hermes/provider.py` (386 lines)
+
+`OpenSecondBrainMemoryProvider` is a thin orchestrator over a `BrainBridge` to the TS core.
+
+- Hook contract (verified): `on_session_end(self, messages: list, **_kwargs: Any)` and `on_pre_compress(self, messages, **_kwargs)`. `interrupted=True` now arrives via `_kwargs` — currently swallowed into `_kwargs` and ignored.
+- `sync_turn(user, assistant, *, session_id, messages)` buffers the turn off the hot path on a **daemon thread**: `_append_turn` appends `(user, assistant)` to `self._buffer` (under `self._lock`) AND calls `_persist_turn` which appends a durable `session-transcript.jsonl` line under `hermes_home/open-second-brain/`.
+- `on_session_end` and `on_pre_compress` both call `_drain_captures()` (join outstanding daemon threads, timeout=5s) then `_flush_buffer()` which joins buffered turns into one text blob and calls the `brain_pre_compact_extract` bridge tool with `{session_id, turn_start, turn_end, text}`.
+- `shutdown()` does the same drain+flush then `self._bridge.stop()`.
+- All bridge calls go through `_safe_call` (try/except → `None`); hooks must never raise into Hermes.
+- `_base.py` ships a fallback `MemoryProvider` no-op ABC so the module imports and unit-tests without a Hermes install.
+
+### TS lifecycle capture — `src/core/brain/session-lifecycle.ts` (512 lines)
+
+`captureSessionLifecycleEvent(vault, payload, opts)` is the single entry point, invoked by the CLI verb `o2b brain session-hook` (`src/cli/brain/verbs/session-hook.ts`) which reads the host hook payload from stdin.
+
+Flow: normalize payload → build capture boundary → session-decision (`capture`/`stateless`/`ignored`) → resolve session lineage → capture markers → route extracted facts → tool feedback replay → session-scoped focus cleanup on `SessionEnd` → handoff note on `SessionEnd` (gated by `session_handoff` config, reads transcript via session adapters) → anticipatory cache refresh → append lifecycle log → append audit record → return counters.
+
+`NormalizedPayload` carries: `event` (`SessionStart`/`UserPromptSubmit`/`PostToolUse`/`SessionEnd`), `sessionId`, `parentSessionId`, `rootSessionId`, `compressionDepth`, `cwd`, `transcriptPath`, `promptText`, `toolName`, `sessionStartSource` (`startup|resume|clear|compact`). The event discriminator at `NormalizedPayload` comment: "SessionStart discriminator (`startup|resume|clear|compact`)."
+
+### TS continuity records
+
+- `pre-compact-extract.ts` — `extractPreCompactRecords`: pulls decisions/rules out BEFORE compaction, stores a `pre_compact_extract` continuity record (kind `pre_compact_extract`), dedupes by content hash. This is the PRE-compaction capture pass that t_12c8b256's audit is the symmetric complement to.
+- `session-summary.ts` — `appendSessionSummary`/`getSessionSummary`: dedupes by `[KIND, sessionId, contentHash]` dedupe key; `listSessionSummaries`.
+- `pinned.ts` — `readPinnedContext`/`writePinnedContext`/`appendPinnedContext`/`clearPinnedContext`, `applyPinnedOperations` (atomic batch), budget enforcement via `assertWithinPinnedBudget` (`MAX_PINNED_CONTEXT_LEN = 20_000`).
+- A shared continuity store: `listContinuityRecords(vault, { kind, since })`, `ContinuityRecord`/`ContinuitySourceRef`.
+
+### Key codegraph facts
+
+- A `pre_llm_call` / pre-compression hook seam already exists conceptually (`on_pre_compress` + the `pre-compress-pack.ts` read-only bundle). The compressor's `SUMMARY_PREFIX` literal and a post-compaction survival audit do NOT exist anywhere.
+- Resume-aware lineage: `resolveSessionLineage` + `recordLineageObservation` + `isCompressionEvidenceEvent` already exist — a resume after an interrupt is already detectable as a lineage child.
+- The capture boundary already dedupes sessions and suppresses repeated message text; double-counting protection has an existing substrate.
+
+## Constraints & invariants (must hold for every variant)
+
+1. The TS core stays deterministic / no-LLM. t_12c8b256's keyword-probe audit must not sneak in an LLM call (embedding probe is optional and off by default if proposed).
+2. Hooks are fail-soft: an interrupted-session flush or a drift audit failure must never break an agent turn or block session close.
+3. New behaviour is off-by-default or byte-identical when the flags/fields are absent (so unchanged installs see no diff).
+4. No misleading fallback: an interrupted flag that cannot be honoured must be surfaced honestly (e.g. in the audit record), not silently coerced to a clean SessionEnd.
+5. No double-counting: an interrupted session resumed later must not re-capture turns already captured by the pre-interrupt flush, and must not create duplicate session-summary / pre-compact-extract continuity records (reuse the existing `[KIND, sessionId, contentHash]` dedupe key).
+6. The interrupted path must consume the now-available pre-restart transcript (the `messages` list Hermes hands to `on_session_end`, plus the persisted `session-transcript.jsonl`).
+7. English-only strings; locale-agnostic.
+
+## Git log (last 20, newest first)
+
+```
+c5e30b8 fix: cross-vault chain-stop reads the max normalized score (v1.18.1) (#111)
+33b4fba feat: recall precision, coverage, and provenance hardening (v1.18.0) (#110)
+254b580 feat: codegraph link-graph depth and MCP exposure (v1.17.0) (#108)
+da2e3cc feat: memory subsystem alignment - honest pinned budgets, atomic batch writes, on_memory_write host bridge (v1.16.0) (#107)
+4db7862 fix(hermes): pass --repo so bridge skill discovery resolves repoRoot (#103) (#106)
+0a4b6da feat: calendar obligations, agenda synthesis, OKF portability, Obsidian Bases and steelman synthesis (v1.15.0) (#105)
+f8b4abf feat(brain): add feedback default scope and vault write containment (#104)
+20ea7ef feat: per-handoff LLM generation tracing and prompt-prefix stability metric (#102)
+9c1d48f feat: CodeGraph and MCP operational readability (v1.12.0) (#101)
+c2c3ff4 feat: Session Knowledge Synthesis Suite (v1.11.0) (#100)
+56dd3dd fix(hermes): bridge EOF - byte streams, stderr drain, retry loop (#92)
+35b824e feat: Recall & Working-Memory Quality Suite (v1.10.0) (#99)
+929d54c feat: Brain Portability & Interop Suite (v1.9.0) (#98)
+7cdbfc0 feat: Indexer Durability & Resilience Suite (v1.7.0) (#97)
+8b679fe feat: Knowledge Provenance Suite (v1.7.0) (#96)
+6e59a42 feat: Vault Integrity & Trust Suite (v1.6.0) (#95)
+70d95c6 chore(release): bump version to 1.5.0 (#94)
+e4df212 feat: Search & Recall Quality Suite (v1.10.0) (#93)
+2e74afe feat: native Grok Build CLI integration - bundled plugin, hooks, session import (v1.4.0) (#91)
+3e7e233 fix(hermes): serialize handle_tool_call result to a string (v1.3.1) (#90)
+```
+
+## Output format (STRICT)
+
+### Variant 1: <short name>
+- **Approach:** 2-3 sentences.
+- **Trade-offs:** bullet list (Pro/Con).
+- **Complexity:** small | medium | large
+- **Risk:** low | medium | high
+
+### Variant 2: <short name>
+(same shape)
+
+### Variant 3: <short name>
+(same shape)
+
+### Recommended: Variant N
+2-3 sentence rationale.
+
+Nothing else. No code. No preamble. No closing summary.
diff --git a/docs/brainstorm/session-lifecycle-capture-durability/design.md b/docs/brainstorm/session-lifecycle-capture-durability/design.md
new file mode 100644
index 00000000..605b1109
--- /dev/null
+++ b/docs/brainstorm/session-lifecycle-capture-durability/design.md
@@ -0,0 +1,232 @@
+# Session Lifecycle Capture Durability — not losing or distorting memory at session boundaries
+
+**Status:** implementation-ready
+**Author:** product-tech-lead (via Phase 0 brainstorm)
+**Audience:** implementation
+**Branch:** `feat/session-lifecycle-capture-durability`
+
+## Problem statement
+
+Open Second Brain captures memory at session boundaries — when the agent's
+host runtime (Hermes CLI/TUI/gateway) fires `on_session_end` and
+`on_pre_compress`. Three real durability gaps exist at exactly those
+boundaries:
+
+1. **Interrupted sessions were silently dropped.** Before Hermes PRs
+ #50004/#50003/#50312 (now merged), a SIGHUP/SIGTERM/force-quit/restart-drain
+ never flushed the in-flight transcript and never fired `on_session_end`.
+ The conversation that was interrupted mid-way left no memory trace. Now that
+ Hermes flushes the transcript and fires `on_session_end(interrupted=True)`,
+ OSB must (a) honour the flag, (b) consume the now-available pre-restart
+ transcript, and (c) avoid double-counting turns when the same session is
+ resumed later. Today OSB swallows `interrupted` into `_kwargs` and ignores it.
+
+2. **End-of-session capture silently did not fire on `/exit`.** Hermes #49315
+ (merged) restored the memory-provider `on_session_end` hook on CLI `/exit`
+ (a Phase 4 god-file refactor had rebound the atexit `_active_agent_ref` to
+ the wrong module, so the hook never ran). OSB may carry a local
+ workaround/poll that compensated for the missing hook; that workaround must
+ be verified-unnecessary and removed, otherwise it is dead/misleading code.
+
+3. **No post-compaction survival check for pinned anchors.** OSB owns the
+ pinned-context store (`pinned.ts`) and a PRE-compaction capture pass
+ (`pre-compact-extract.ts` that pulls decisions/rules out before compaction).
+ It has no symmetric POST-compaction survival audit: nothing verifies a
+ pinned fact still lives in the ACTIVE (non-summary) region after Hermes
+ summarizes the conversation, and nothing re-asserts the ones that drifted
+ into the summary. This is the exact long-conversation failure mode pinned
+ context exists to fight.
+
+These three share one substrate (`provider.py`, `session-lifecycle.ts`,
+`pinned.ts`, `pre-compact-extract.ts`, the continuity store) and fold into one
+release: "do not lose and do not distort memory at session boundaries."
+
+## Grounding: what already exists (do NOT rebuild)
+
+- The hook contract already hands `messages` to `on_session_end`; `interrupted`
+ arrives as a kwarg. The Python provider is a thin orchestrator — deterministic
+ logic belongs in the TS core, not Python.
+- `sync_turn` already persists every turn durably to
+ `hermes_home/open-second-brain/session-transcript.jsonl` (`_persist_turn`),
+ so an interrupted session's turns are recoverable from disk independent of
+ the in-memory `messages` list.
+- The capture boundary in `session-lifecycle.ts` already dedupes sessions and
+ suppresses repeated message text; double-counting protection has a substrate.
+- `resolveSessionLineage` + `recordLineageObservation` +
+ `isCompressionEvidenceEvent` already exist — a resume after an interrupt is
+ already detectable as a lineage child.
+- The continuity store's generic `recordId()` is content-derived over
+ `kind + createdAt + sourceRefs + payload`; `extractPreCompactRecords` also
+ carries an explicit payload-level `dedupe_key` built from
+ `sessionId + turnStart + turnEnd + type + contentHash`. Reuse those existing
+ idempotency seams instead of inventing a new ledger.
+- `extractPreCompactRecords` (kind `pre_compact_extract`) is the symmetric
+ pre-compaction pass that this release's survival audit complements.
+- `on_pre_compress` already exists as a seam; `pre-compress-pack.ts` is a
+ read-only bundle that the host runtime injects before compression.
+- All bridge calls go through `_safe_call` (fail-soft: hooks never raise into
+ Hermes).
+
+## Scope
+
+- **t_c181f92b — interrupted-session capture.** Surface `interrupted` from the
+ Python `on_session_end` kwarg as an explicit, absent-by-default field on the
+ host hook payload; thread it into `NormalizedPayload`. On an interrupted
+ `SessionEnd`, consume the pre-restart transcript (the `messages` list and/or
+ the persisted `session-transcript.jsonl`) so the in-flight turns reach the
+ same extraction as a clean close. Record the interrupted status honestly in
+ the audit record. Suppress double-counting on resume by reusing the existing
+ capture-boundary dedupe, signal `dedup_hash`, and continuity payload-level
+ `dedupe_key` conventions scoped to the same `sessionId`/turn range. Fail-soft throughout.
+- **t_3b8fe3a1 — verify `/exit` hook, drop workaround.** Confirm the provider's
+ `on_session_end` capture now fires on CLI `/exit` against the merged #49315,
+ and remove any local workaround/poll that compensated for the missing hook
+ (none was found by static grep across `plugins/hermes/` and `src/`, so this is
+ primarily a verification + a guard against regressions). The work product is a
+ regression test asserting end-of-session capture runs on the `/exit` path, plus
+ deletion of any dead compensating code discovered during verification.
+- **t_12c8b256 — post-compaction pinned-anchor survival audit.** A
+ deterministic, no-LLM audit that detects a Hermes compaction event (scans the
+ conversation for Hermes compressor handoff prefixes (`SUMMARY_PREFIX`, ASCII
+ fallback, and legacy `[CONTEXT SUMMARY]:`), hashes the summary body to detect
+ a NEW compaction vs. one already audited), then for each pinned
+ anchor runs a keyword probe scoped to the ACTIVE (non-summary) region. An
+ anchor whose probes hit only inside the summary block counts as drifted and is
+ re-asserted as a reminder block via the existing pinned store; survivors cost
+ zero tokens. Optional windowed-embedding probe is off by default. Fail-open;
+ bounded drift log. Sits as a new module symmetric to `pre-compact-extract.ts`.
+
+## Out of scope
+
+- **No replacement of existing lifecycle/continuity idempotency seams**
+ with a new ledger. Reuse capture-boundary suppression, signal `dedup_hash`,
+ continuity `recordId()`, and existing payload-level `dedupe_key` patterns; a
+ new append-only ledger would risk regressions in already-shipped capture paths
+ and violates
+ "additive where possible." (The honest slice of Variant 3, rejected.)
+- **No new `SessionContinuityEvent` abstraction / unified pipeline.** Three
+ parallel additive code paths are lower-risk than a core-store refactor for a
+ single release. Unification is available as a later refactor if the parallel
+ paths prove worth merging.
+- **No preemptive / every-turn blanket re-injection.** Re-injection is a repair
+ action (on-drift), not a per-turn injection — keeps prompt-cache stable.
+- **No embedding index built eagerly.** The optional embedding probe, if ever
+ added, stays behind a flag and off by default; the audit defaults to keyword
+ probes only.
+- **No changes to the host runtime's own compaction or transcript-flush
+ behavior.** OSB consumes what Hermes emits; it does not alter Hermes.
+- **No locale-specific keyword tables.** Anchor keywords/probes are derived from
+ the pinned content itself, locale-agnostic.
+
+## Chosen approach
+
+**Variant 2 — Minimal seam-reuse, three independent additive diffs.** Each task
+is a small diff against an existing seam, gated by an absent-by-default field or
+flag, so unchanged installs are byte-identical.
+
+- t_c181f92b: an optional `interrupted` boolean on the hook payload →
+ `NormalizedPayload`, consumed by the existing `SessionEnd` branch. Resume
+ detection reuses `resolveSessionLineage`; de-dup reuses capture-boundary
+ suppression, signal `dedup_hash`, and existing continuity payload-level
+ `dedupe_key` conventions rather than a new ledger.
+- t_3b8fe3a1: verification + deletion of any local workaround in `provider.py`;
+ a regression test for the `/exit` path.
+- t_12c8b256: a new post-compaction audit module reusing
+ `extractPreCompactRecords`-shaped continuity records and `readPinnedContext`,
+ with a bounded drift log, behind an absent-by-default config flag.
+
+This is the lowest-risk path because the release scope itself catalogues the
+exact substrates each task needs, and the repo conventions explicitly require
+additive / byte-identical-when-unused behaviour. It avoids both Variant 1's
+premature TS consolidation (which pushes transcript bytes across the bridge even
+when the flag is absent) and Variant 3's risky core-store replacement.
+
+## Design decisions
+
+1. **Python stays dumb.** `provider.py` only surfaces the `interrupted` kwarg
+ onto the payload and forwards the transcript path; no capture decisions in
+ Python. Deterministic logic, dedupe, and audit live in the TS core. This
+ honours the "core is LLM-free and unit-testable" invariant and keeps the
+ shim fail-soft by construction.
+2. **`interrupted` is absent-by-default.** The payload field is optional; when
+ Hermes does not set it, behaviour is byte-identical to today. No field is
+ invented when the host does not emit it.
+3. **Double-counting is prevented by existing idempotency seams, not by a
+ new ledger.** A resumed session shares the original `sessionId`; turns
+ captured by the pre-interrupt flush are suppressed on re-capture via
+ capture-boundary message suppression, signal `dedup_hash`, and the same
+ payload-level `dedupe_key` pattern already used by `pre_compact_extract`
+ (`sessionId + turnStart + turnEnd + type + contentHash`). No new
+ idempotency store.
+4. **Honest surfacing of an un-honourable interrupted flag.** If the
+ interrupted flag is present but the transcript cannot be consumed (empty
+ `messages`, unreadable transcript path), the audit record records
+ `interrupted: true` with a `transcript_consumed: false` detail rather than
+ silently coercing to a clean `SessionEnd`. No misleading fallback.
+5. **Survival audit is the symmetric complement to `extractPreCompactRecords`.**
+ It reuses the continuity store and the same `pre_compact_extract`-shaped
+ record (a new `post_compact_audit` kind where the lifecycle differs), a
+ Hermes compaction-prefix scan (`SUMMARY_PREFIX`, ASCII fallback, and legacy
+ prefix) + summary-body hash to detect a NEW compaction, and a keyword probe
+ over the non-summary region. Re-injection is on-drift only.
+6. **Deterministic, fail-open audit.** The survival audit never calls an LLM;
+ the optional embedding probe is off by default. A probe or re-injection
+ failure must never break a turn (fail-open), and the drift log is bounded.
+7. **English-only, locale-agnostic.** Probe keywords are derived from the
+ pinned anchor text itself; no hardcoded locale word lists.
+
+## File changes (planned surface)
+
+**t_c181f92b**
+- `plugins/hermes/provider.py` — surface `interrupted` from the `on_session_end`
+ kwarg onto the hook payload; forward the transcript path. (Thin adapter only.)
+- `src/core/brain/session-lifecycle.ts` — add optional `interrupted` to
+ `NormalizedPayload`; in the `SessionEnd` branch, when `interrupted` is true,
+ consume the pre-restart transcript and record it honestly; reuse existing
+ lineage + dedupe for resume de-dup.
+- `src/cli/brain/verbs/session-hook.ts` — pass the field through (payload is
+ already read-from-stdin verbatim; only typed access changes).
+- Focused tests under `tests/`.
+
+**t_3b8fe3a1**
+- `plugins/hermes/provider.py` — delete any workaround/poll discovered during
+ verification (static grep found none; verification will confirm at runtime).
+- A regression test asserting end-of-session capture fires on the `/exit` path.
+- `plugins/hermes/_base.py` — only if the fallback ABC needs the field threaded
+ (likely no change; `_kwargs` already absorbs it).
+
+**t_12c8b256**
+- `src/core/brain/post-compact-audit.ts` (new) — compaction detection
+ (Hermes compaction-prefix scan + summary-body hash), keyword-probe survival audit scoped
+ to the non-summary region, selective re-assertion via `readPinnedContext`/
+ `appendPinnedContext`, bounded drift log.
+- `src/core/brain/pinned.ts` — expose any read helper the audit needs (reuse
+ existing `readPinnedContext`); no budget change.
+- A CLI verb / host hook entry that runs the audit post-compaction, behind an
+ absent-by-default config flag (`post_compact_survival_audit`).
+- Focused tests under `tests/`.
+
+## Risks
+
+- **Double-counting on a real interrupt→resume cycle.** Mitigated by reusing
+ capture-boundary suppression, signal `dedup_hash`, and payload-level
+ continuity `dedupe_key` patterns scoped to `sessionId`/turn range, plus an
+ explicit test that resumes an interrupted session and asserts zero duplicate
+ records and zero re-captured turns. Risk: low.
+- **Transcript-consumption correctness under partial flush.** The pre-restart
+ transcript may be partially flushed. Mitigated by treating the persisted
+ `session-transcript.jsonl` as the source of truth (already durable) and
+ recording `transcript_consumed` honestly when only a partial read is possible.
+ Risk: low.
+- **Compaction-detection false positives.** A Hermes compaction-prefix literal
+ appearing in user text could masquerade as a compaction boundary. Mitigated by hashing
+ the summary body and comparing against a per-session audited-compaction set, so
+ only a genuinely NEW compaction triggers an audit. Risk: low-medium.
+- **Survival-audit keyword-probe drift (recall/precision).** Keyword probes may
+ miss a drifted anchor that was rephrased. Mitigated by fail-open behaviour
+ (a missed re-assertion is a soft loss, not a turn-breaker) and the optional
+ off-by-default embedding probe for users who want higher recall. Risk: low.
+- **`/exit` verification flakiness.** The verification is runtime-dependent on
+ the merged #49315; CI cannot run a live Hermes. Mitigated by a unit-level
+ regression test that drives the provider hook directly, plus a static
+ confirmation that no workaround code remains. Risk: low.
diff --git a/docs/brainstorm/session-lifecycle-capture-durability/plan.md b/docs/brainstorm/session-lifecycle-capture-durability/plan.md
new file mode 100644
index 00000000..d9399498
--- /dev/null
+++ b/docs/brainstorm/session-lifecycle-capture-durability/plan.md
@@ -0,0 +1,161 @@
+# Session Lifecycle Capture Durability — implementation plan
+
+Branch: `feat/session-lifecycle-capture-durability`
+
+Overall release scope (ships together in this single release):
+
+- `t_c181f92b` — Capture interrupted sessions: `on_session_end(interrupted=True)` + persisted transcript (#50004/#50003/#50312).
+- `t_3b8fe3a1` — Verify memory `on_session_end` fires on `/exit` now native (#49315); drop any workaround.
+- `t_12c8b256` — Post-compaction pinned-anchor survival audit and selective re-assertion.
+
+Combined design: `docs/brainstorm/session-lifecycle-capture-durability/design.md`.
+Full variant audit: `docs/brainstorm/session-lifecycle-capture-durability/variants.md`.
+
+Drive these cards **one at a time** on the shared branch. Each worker MUST
+`git log` and `git status` before editing, build on the commits previously-driven
+in-scope cards already landed, and must not duplicate or conflict with sibling
+tasks. Follow each section under TDD (write the failing test first).
+
+Recommended drive order: `t_c181f92b` first (lands the `interrupted` field that
+the other two reason about), then `t_3b8fe3a1` (verification, smallest), then
+`t_12c8b256` (the new audit module, largest, builds on the pinned/continuity
+substrate the first two also touch).
+
+## t_c181f92b — Capture interrupted sessions: on_session_end(interrupted=True) + persisted transcript
+
+### Files
+
+- `plugins/hermes/provider.py`
+- `src/core/brain/session-lifecycle.ts`
+- `src/cli/brain/verbs/session-hook.ts` (typed access only; payload is read verbatim from stdin)
+- Focused tests under `tests/`
+
+### Plan
+
+1. Add an optional `interrupted?: boolean` field to `NormalizedPayload`
+ (`session-lifecycle.ts`), normalized from the host hook payload. Absent by
+ default — when the host does not emit it, behaviour is byte-identical.
+2. In `provider.py`, surface the `interrupted` kwarg from `on_session_end`
+ (`**_kwargs`) onto the hook payload the provider emits, and forward the
+ transcript path (`session-transcript.jsonl`). Python makes no capture decision.
+3. In the `SessionEnd` branch of `captureSessionLifecycleEvent`, when
+ `interrupted === true`: consume the pre-restart transcript (the `messages`
+ list and/or the persisted `session-transcript.jsonl`) so in-flight turns
+ reach marker/fact/handoff extraction like a clean close.
+4. Reuse `resolveSessionLineage` to recognize a resume as a lineage child of the
+ interrupted session; reuse the existing capture-boundary dedupe, signal `dedup_hash`, and
+ continuity payload-level `dedupe_key` conventions (scoped to the same
+ `sessionId`/turn range) so turns already captured by the pre-interrupt flush
+ are not re-captured on resume.
+5. Record the interrupted status honestly in the audit record: `interrupted:
+ true` plus `transcript_consumed: true|false`. If the transcript cannot be
+ consumed, surface `transcript_consumed: false` — never coerce to a clean
+ `SessionEnd`.
+6. Keep it fail-soft: a transcript read or extraction failure must never raise
+ into Hermes.
+
+### Acceptance (passing test)
+
+- A test drives `captureSessionLifecycleEvent` with an `interrupted: true`
+ `SessionEnd` payload carrying a transcript, and asserts:
+ - the in-flight turns from the transcript are captured (markers/facts reach
+ storage);
+ - the audit record carries `interrupted: true` and `transcript_consumed: true`;
+ - resuming the same `sessionId` does NOT create duplicate continuity records
+ (same existing dedupe seams / payload-level `dedupe_key` pattern) and does
+ not re-capture turns already captured by the interrupted close.
+- A second test asserts an absent `interrupted` field leaves the clean-close
+ path byte-identical (no audit `interrupted` key, existing tests unchanged).
+
+### Depends on
+
+- No in-scope card dependency. Land first; `t_3b8fe3a1` and `t_12c8b256` reason
+ about the same field/substrate.
+
+## t_3b8fe3a1 — Verify memory on_session_end fires on /exit now native (#49315); drop any workaround
+
+### Files
+
+- `plugins/hermes/provider.py` (delete any workaround/poll found at verification time)
+- `plugins/hermes/_base.py` (only if the fallback ABC needs threading; likely no change)
+- A regression test under `tests/`
+
+### Plan
+
+1. Confirm against merged Hermes #49315 that the provider's `on_session_end`
+ now fires on CLI `/exit`. Static grep across `plugins/hermes/` and `src/`
+ found no `atexit`/`poll`/workaround compensating for the missing hook —
+ confirm at runtime that none exists and none is needed.
+2. If a workaround/poll IS discovered during verification, delete it (it is now
+ dead/misleading code that duplicates the native hook). Update any comment
+ that referenced the missing hook.
+3. Add a regression test that drives the provider's `on_session_end` hook
+ directly (unit-level, no live Hermes required) and asserts the drain+flush
+ capture path runs — guarding against a future regression of the `/exit`
+ binding.
+
+### Acceptance (passing test)
+
+- A test constructs `OpenSecondBrainMemoryProvider` with a fake bridge, calls
+ `on_session_end(messages=[...])`, and asserts the buffered turns are flushed
+ to the bridge (`brain_pre_compact_extract` called) and the capture threads are
+ drained — proving end-of-session capture runs on the path `/exit` now drives.
+- `grep -rni "atexit\|poll\|workaround\|missing hook" plugins/hermes/` returns
+ no compensating workaround code (or, if one is found and removed, the test
+ passes without it).
+
+### Depends on
+
+- Ideally after `t_c181f92b` (shares the `on_session_end` surface), but no hard
+ dependency — can land in either order on the shared branch.
+
+## t_12c8b256 — [upstream:hermes-memlock] Post-compaction pinned-anchor survival audit and selective re-assertion
+
+### Files
+
+- `src/core/brain/post-compact-audit.ts` (new)
+- `src/core/brain/pinned.ts` (expose read helper if needed; reuse `readPinnedContext`; no budget change)
+- A CLI verb / host hook entry under `src/cli/brain/verbs/` for the post-compaction audit
+- `src/core/config.ts` (add absent-by-default `post_compact_survival_audit` key) if config-gated
+- Focused tests under `tests/`
+
+### Plan
+
+1. Create `post-compact-audit.ts` symmetric to `pre-compact-extract.ts`. It is
+ deterministic and LLM-free. Reuse the continuity store (`ContinuityRecord`,
+ `listContinuityRecords`) and `readPinnedContext`.
+2. Compaction detection: scan the conversation for Hermes compressor handoff prefixes
+ (`SUMMARY_PREFIX`, ASCII fallback, and legacy `[CONTEXT SUMMARY]:`); hash the
+ summary body; compare against a per-session audited-compaction set (a
+ `post_compact_audit` continuity record carrying a payload-level dedupe key
+ derived from `sessionId + summaryHash`) so only a genuinely NEW compaction
+ triggers an audit.
+3. Survival audit: for each pinned anchor, run a keyword probe (derived from the
+ anchor text, locale-agnostic) scoped to the ACTIVE (non-summary) region. An
+ anchor whose probes hit only inside the summary block counts as drifted.
+4. Selective re-assertion: re-inject only drifted anchors as a reminder block via
+ `appendPinnedContext` (or a dedicated re-assertion entry). Survivors cost zero
+ tokens. Re-injection is on-drift only, never a blanket per-turn injection.
+5. Optional windowed-embedding probe: off by default (config flag
+ `post_compact_survival_audit_embedding`); keyword probes are the default.
+6. Fail-open: any probe or re-injection failure is logged to a bounded drift log
+ and must never break a turn. Wire the audit behind an absent-by-default config
+ flag (`post_compact_survival_audit`) so unchanged installs are byte-identical.
+
+### Acceptance (passing test)
+
+- A test seeds pinned anchors, feeds a conversation containing a Hermes
+ compaction-prefix block with one anchor demoted into the summary and one still
+ in the active region, runs the audit, and asserts:
+ - the drifted anchor is re-asserted (a re-assertion record / reminder block is
+ written);
+ - the surviving anchor is NOT re-injected (zero tokens spent);
+ - a second audit of the SAME summary (same hash) does not re-run the audit
+ (idempotent via the per-session audited-compaction key);
+ - a malformed/empty conversation does not raise (fail-open) and produces a
+ bounded drift-log entry.
+
+### Depends on
+
+- After `t_c181f92b` (shared `session-lifecycle.ts` / continuity substrate). No
+ dependency on `t_3b8fe3a1`. Reuse `pinned.ts` and the continuity store as-is.
diff --git a/docs/brainstorm/session-lifecycle-capture-durability/variants.md b/docs/brainstorm/session-lifecycle-capture-durability/variants.md
new file mode 100644
index 00000000..47239fd9
--- /dev/null
+++ b/docs/brainstorm/session-lifecycle-capture-durability/variants.md
@@ -0,0 +1,68 @@
+# Session Lifecycle Capture Durability — variant audit trail
+
+Primary consultant: Claude Code (`claude -p --model claude-opus-4-8`), output
+captured verbatim in `cli-output/claude.md`. Fallback not invoked — the primary
+returned three parseable variants and a recommendation (exit code 0).
+
+Below: the consultant's variants verbatim, then the orchestrator's final
+decision and rationale.
+
+---
+
+## Consultant variants (verbatim)
+
+### Variant 1: TS-core authority, dumb provider
+- **Approach:** Keep `provider.py` a pure pass-through: surface the `interrupted` kwarg as an explicit field on the bridge payload and forward both the `messages` list and the `session-transcript.jsonl` path, but make no capture decisions in Python. All new behaviour — interrupted-end reconciliation, resume de-dup, and the post-compaction survival audit — lands as new/extended modules under `src/core/brain` (a new `post-compact-audit.ts` mirroring `pre-compact-extract.ts`, plus `interrupted` handling inside `session-lifecycle.ts`). One CLI verb gains the flag; the deterministic core owns all logic and all dedupe.
+- **Trade-offs:**
+ - Pro: Single deterministic, unit-testable locus; honours "core is LLM-free" and keeps the Python shim trivial and fail-soft by construction.
+ - Pro: Survival audit sits naturally beside the symmetric `extractPreCompactRecords`, sharing the continuity store and `[KIND, sessionId, contentHash]` key.
+ - Con: Widens the bridge payload contract and pushes interrupted-transcript bytes across the boundary even when the flag is absent (mitigated by an off-by-default field).
+ - Con: Larger TS surface to land in one PR; three concerns touch the same lifecycle file.
+- **Complexity:** medium
+- **Risk:** low
+
+### Variant 2: Minimal seam-reuse, three independent diffs
+- **Approach:** Treat the three tasks as three small additive diffs against existing seams, introducing no new abstraction. `interrupted` becomes an optional `NormalizedPayload` field consumed by the existing SessionEnd branch, reusing `resolveSessionLineage` for resume detection and the existing dedupe key to suppress re-capture; the `/exit` task is a verification-plus-deletion of the local poll workaround in `provider.py`; the survival audit is a new post-compaction CLI verb that reuses `pre-compress-pack.ts` read primitives and `readPinnedContext` plus the bounded drift log. Each ships behind its own absent-by-default field/flag.
+- **Trade-offs:**
+ - Pro: Smallest possible diff per task; byte-identical when flags/fields absent, matching repo conventions exactly.
+ - Pro: Maximally reuses named existing substrates (dedupe key, lineage, symmetric pre-compact pass) the grounding calls out, lowering double-count and regression risk.
+ - Pro: Each task is independently reviewable and revertible within the shared branch.
+ - Con: No unifying model means interrupted-end, clean-end, and audit paths stay three parallel code paths — some duplicated idempotency reasoning.
+ - Con: The honest-surfacing of an un-honourable `interrupted` flag is handled ad hoc per path rather than centrally.
+- **Complexity:** small
+- **Risk:** low
+
+### Variant 3: Unified continuity-event pipeline with idempotency ledger
+- **Approach:** Introduce a single `SessionContinuityEvent` abstraction that normalizes interrupted-end, clean-end, and post-compaction-survival into one typed event flowing through one capture pipeline backed by an explicit append-only idempotency ledger (superseding the per-call dedupe key). Both `provider.py` hooks and a new post-compact verb emit into this pipeline; the ledger guarantees no double-count across interrupt→resume and no duplicate continuity records, and records un-honoured `interrupted` flags as honest ledger entries.
+- **Trade-offs:**
+ - Pro: One place to reason about idempotency, honesty surfacing, and fail-soft behaviour across all three tasks; strongest future extensibility.
+ - Pro: Cleanest conceptual model — interrupted capture and audit re-assertion become uniform events.
+ - Con: Largest blast radius; replacing the proven `[KIND, sessionId, contentHash]` dedupe with a new ledger risks regressions in already-shipped capture paths and breaks "additive where possible."
+ - Con: Hard to keep byte-identical for unchanged installs when a core store is replaced; heavier review and migration burden in a single release.
+- **Complexity:** large
+- **Risk:** high
+
+### Consultant's recommendation: Variant 2
+
+---
+
+## Final decision: Variant 2 (agree with the recommendation)
+
+**Variant 2 — Minimal seam-reuse, three independent additive diffs.**
+
+Rationale: the release scope itself catalogues the exact substrates each task
+needs — the `[KIND, sessionId, contentHash]` continuity dedupe key, the
+resume-aware `resolveSessionLineage`, and the symmetric `extractPreCompactRecords`
+pass — so the lowest-risk path is three tight additive diffs that reuse them.
+This directly honours the repo's explicit conventions: new behaviour must be
+off-by-default or byte-identical when unused, hooks must be fail-soft, and
+additive-where-possible. Variant 3's core-store replacement (a new idempotency
+ledger superseding the proven dedupe key) risks regressions in already-shipped
+capture paths and breaks byte-identity for unchanged installs — too high a price
+for a single release. Variant 1's TS consolidation is sound but prematurely
+pushes transcript bytes across the bridge boundary even when the `interrupted`
+flag is absent; Variant 2 keeps the field absent-by-default and the Python shim
+truly dumb. The one acknowledged cost of Variant 2 (three parallel code paths
+with some duplicated idempotency reasoning) is acceptable because each path is
+small and independently revertible, and unification remains available as a later
+refactor if the parallel paths prove worth merging.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index b9ad118a..2432de07 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -72,6 +72,7 @@ o2b brain recall-telemetry List/summarise opt-in recall telemetry continuity
o2b brain generation-reports Record/list/summarise opt-in inbound LLM generation traces (prompt hash + token counts only; kernel never calls an LLM)
o2b brain context-presets Show/suggest/diff read-only context budget presets (since v0.29.0)
o2b brain pre-compact-extract Extract decision/commitment/outcome/rule/open-question continuity records from bounded text (since v0.29.0)
+o2b brain post-compact-audit Audit pinned-anchor survival after a compaction and re-assert drifted anchors (gated by post_compact_survival_audit)
o2b brain session-grep Search imported session recall raw turns and summary nodes (since v0.29.0)
o2b brain session-describe Count raw turns and deterministic summary depths for one session recall DAG (since v0.29.0)
o2b brain session-expand Expand a session recall node to immediate sources and paginated raw turn content (since v0.29.0)
@@ -115,6 +116,7 @@ o2b brain recall-telemetry list|summary [--mode search|context_pack|pre_compr
o2b brain generation-reports record <write_session|context_pack|dream_stage> --ref <id> --agent <name> --prompt <text> [--enable] [--provider <p>] [--model <m>] [--finish-reason <r>] [--latency-ms <n>] [--input-tokens <n>] [--output-tokens <n>] [--cached-tokens <n>] [--total-tokens <n>] [--scope <s>] [--source <id[=path]>...] [--created-at <iso>] [--json]; list|summary [--handoff <kind>] [--agent <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--json]; show <report-id> [--json] - record is gated (default off) by --enable or generation_trace_enabled; stores prompt_hash + counts only
o2b brain context-presets show [tight-context|long-context] --json; suggest --model <name> --context-window <tokens> --json; diff <preset-id> [current-value flags] [--override <path>...] --json
o2b brain pre-compact-extract --session-id <id> --turn-start <id> --turn-end <id> --text <bounded-text> [--host <name>] [--max-chars <n>] [--json]
+o2b brain post-compact-audit [--session-id <id>] [--no-reassert] [--force] [--vault <path>] [--json] - reads { session_id, messages } JSON from stdin; gated off by default (post_compact_survival_audit), --force overrides
o2b brain import-session <path> --recall [--recall-session-id <id>] [--recall-summary-group-size <n>] [--json]
o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--json]
o2b brain session-describe --session-id <id> [--json]
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 2567122d..67a32970 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.18.1",
+ "version": "1.19.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index fb1b46c8..832b81e7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.18.1",
+ "version": "1.19.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 b23076db..7850318e 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.18.1"
+version: "1.19.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 aed7b770..8497fddb 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.18.1",
+ "version": "1.19.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/_schemas.py b/plugins/hermes/_schemas.py
index beb4c725..db468a70 100644
--- a/plugins/hermes/_schemas.py
+++ b/plugins/hermes/_schemas.py
@@ -437,7 +437,14 @@ STATIC_TOOL_SCHEMAS: tuple[dict[str, Any], ...] = (
'minimum': 1,
'description': 'Optional maximum input '
'characters to scan before '
- 'extracting.'}},
+ 'extracting.'},
+ 'interrupted': {'type': 'boolean',
+ 'description': 'When true, mark the extracted '
+ 'records as flushed by an '
+ 'interrupted close '
+ '(SIGHUP/SIGTERM/force-quit/'
+ 'restart-drain). Absent by '
+ 'default.'}},
'required': ['session_id', 'turn_start', 'turn_end', 'text'],
'additionalProperties': False}},
)
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index b23076db..7850318e 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.18.1"
+version: "1.19.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/hermes/provider.py b/plugins/hermes/provider.py
index 9d0b3333..6fc05280 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -251,10 +251,19 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
self._drain_captures()
self._flush_buffer()
- def on_session_end(self, messages: list, **_kwargs: Any) -> None:
- """Flush any remaining buffered turns at session close."""
+ def on_session_end(self, messages: list, *, interrupted: bool = False, **_kwargs: Any) -> None:
+ """Flush any remaining buffered turns at session close.
+
+ Hermes now fires this hook on an interrupted close too
+ (SIGHUP/SIGTERM/force-quit/restart-drain, #50004/#50003/#50312),
+ passing ``interrupted=True`` alongside the flushed in-flight transcript.
+ Surfacing the flag onto the flush payload lets the TS core record an
+ interrupted capture honestly; the flush itself already drains the same
+ buffered turns whether the close was clean or interrupted, so no turn is
+ lost. Python makes no capture decision - it only forwards the flag.
+ """
self._drain_captures()
- self._flush_buffer()
+ self._flush_buffer(interrupted=bool(interrupted))
def on_memory_write(
self,
@@ -359,23 +368,27 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
except OSError:
pass
- def _flush_buffer(self) -> None:
- """Hand buffered turns to deterministic extraction, then clear the buffer."""
+ def _flush_buffer(self, interrupted: bool = False) -> None:
+ """Hand buffered turns to deterministic extraction, then clear the buffer.
+
+ ``interrupted`` is forwarded to the extractor only when set, so a clean
+ close emits a byte-identical payload (the field is absent by default).
+ """
with self._lock:
turns = list(self._buffer)
self._buffer.clear()
if not turns:
return
text = "\n\n".join(f"User: {u}\nAssistant: {a}" for u, a in turns)
- self._safe_call(
- "brain_pre_compact_extract",
- {
- "session_id": self._session_id or "hermes",
- "turn_start": 0,
- "turn_end": len(turns),
- "text": text,
- },
- )
+ args: dict[str, Any] = {
+ "session_id": self._session_id or "hermes",
+ "turn_start": 0,
+ "turn_end": len(turns),
+ "text": text,
+ }
+ if interrupted:
+ args["interrupted"] = True
+ self._safe_call("brain_pre_compact_extract", args)
def _drain_captures(self) -> None:
"""Join outstanding capture threads so a turn buffered just before a
diff --git a/pyproject.toml b/pyproject.toml
index 64f03181..a6072803 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.18.1"
+version = "1.19.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 59ffb396..77f6f62d 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -101,6 +101,7 @@ import {
cmdBrainEventTrace,
cmdBrainContextPresets,
cmdBrainPreCompactExtract,
+ cmdBrainPostCompactAudit,
cmdBrainRecallTelemetry,
cmdBrainGenerationReports,
cmdBrainSkillProposals,
@@ -330,6 +331,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainContextPresets(rest);
case "pre-compact-extract":
return await cmdBrainPreCompactExtract(rest);
+ case "post-compact-audit":
+ return await cmdBrainPostCompactAudit(rest);
case "recall-telemetry":
return await cmdBrainRecallTelemetry(rest);
case "generation-reports":
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 2e83df3a..31283354 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -84,6 +84,7 @@ Brain verbs (observing memory):
event-trace Show context traces attached to logged events by correlation id
context-presets Show/suggest/diff read-only context budget presets
pre-compact-extract Extract typed continuity records from bounded text
+ post-compact-audit Audit pinned-anchor survival after a compaction; re-assert drifted anchors
recall-telemetry List/summarize opt-in recall telemetry records
generation-reports Record/list/summarize opt-in LLM generation traces
skill-proposals Learn/list/review deterministic skill proposals
@@ -580,6 +581,9 @@ export const VERB_HELP: Record<string, string> = {
"pre-compact-extract":
"usage: o2b brain pre-compact-extract --vault <path> --session-id <id> --turn-start <id> --turn-end <id> --text <text> [--host <name>] [--max-chars <n>] [--json]\n" +
"Extract Decision/Commitment/Outcome/Rule/Open question lines into idempotent continuity records.\n",
+ "post-compact-audit":
+ "usage: o2b brain post-compact-audit [--session-id <id>] [--no-reassert] [--force] [--vault <path>] [--json]\n" +
+ "Reads a { session_id, messages } JSON document from stdin. Detects a Hermes compaction, audits which pinned anchors survived in the active (non-summary) region, and re-asserts only the drifted ones. Gated by post_compact_survival_audit (default off); --force overrides the gate.\n",
"recall-telemetry":
"usage: o2b brain recall-telemetry list [--mode search|context_pack|pre_compress] [--status ok|empty|error|timeout] [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--vault <path>] [--json]\n" +
" o2b brain recall-telemetry summary [same filters] [--vault <path>] [--json]\n" +
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index 89ce2920..1bc20fd4 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -85,6 +85,7 @@ export { cmdBrainContextReceipts } from "./context-receipts.ts";
export { cmdBrainEventTrace } from "./event-trace.ts";
export { cmdBrainContextPresets } from "./context-presets.ts";
export { cmdBrainPreCompactExtract } from "./pre-compact-extract.ts";
+export { cmdBrainPostCompactAudit } from "./post-compact-audit.ts";
export { cmdBrainRecallTelemetry } from "./recall-telemetry.ts";
export { cmdBrainGenerationReports } from "./generation-reports.ts";
export { cmdBrainSkillProposals } from "./skill-proposals.ts";
diff --git a/src/cli/brain/verbs/post-compact-audit.ts b/src/cli/brain/verbs/post-compact-audit.ts
new file mode 100644
index 00000000..c3ad531a
--- /dev/null
+++ b/src/cli/brain/verbs/post-compact-audit.ts
@@ -0,0 +1,118 @@
+import { defaultConfigPath, resolvePostCompactSurvivalAudit } from "../../../core/config.ts";
+import {
+ auditPostCompaction,
+ type ConversationMessage,
+} from "../../../core/brain/post-compact-audit.ts";
+import { readHookInput } from "../../../../hooks/lib/stdin.ts";
+import { CliError, okJson, parse, resolveBrainVault } from "../helpers.ts";
+import { inspect } from "node:util";
+
+/**
+ * Post-compaction pinned-anchor survival audit entry. Reads the
+ * post-compaction conversation (a `{ session_id, messages }` JSON
+ * document) from stdin — the shape a host hook hands a context-event
+ * hook — detects the Hermes compaction, and re-asserts only the drifted
+ * anchors.
+ *
+ * Gated by `post_compact_survival_audit` (default OFF): when the operator
+ * has not opted in, the verb is a no-op that reports `enabled: false` and
+ * touches nothing, so unchanged installs stay byte-identical. `--force`
+ * runs the audit regardless of the gate (for diagnostics).
+ */
+export async function cmdBrainPostCompactAudit(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ json: { type: "boolean" },
+ vault: { type: "string" },
+ "session-id": { type: "string" },
+ "no-reassert": { type: "boolean" },
+ force: { type: "boolean" },
+ });
+ const config = defaultConfigPath();
+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);
+
+ const enabled = resolvePostCompactSurvivalAudit(config);
+ const forced = flags["force"] === true;
+ if (!enabled && !forced) {
+ writeOutput(
+ { enabled: false, forced: false, compaction_detected: false },
+ flags["json"] === true,
+ );
+ return 0;
+ }
+
+ let payload: unknown;
+ try {
+ payload = await readHookInput();
+ } catch (err) {
+ throw new CliError(
+ `brain post-compact-audit: failed to read stdin: ${(err as Error).message ?? err}`,
+ );
+ }
+
+ const sessionId = stringOptional(flags["session-id"]) ?? readSessionId(payload) ?? undefined;
+ if (sessionId === undefined) {
+ throw new CliError(
+ "brain post-compact-audit: --session-id or a payload session_id is required",
+ );
+ }
+ const messages = readMessages(payload);
+
+ const result = auditPostCompaction(vault, {
+ sessionId,
+ messages,
+ ...(flags["no-reassert"] === true ? { reassert: false } : {}),
+ });
+
+ writeOutput(
+ {
+ enabled,
+ forced,
+ compaction_detected: result.compactionDetected,
+ already_audited: result.alreadyAudited,
+ summary_hash: result.summaryHash,
+ drifted: result.drifted,
+ survived: result.survived,
+ absent: result.absent,
+ reasserted: result.reasserted,
+ ...(result.reminderBlock !== null ? { reminder_block: result.reminderBlock } : {}),
+ errors: result.errors,
+ },
+ flags["json"] === true,
+ );
+ return 0;
+}
+
+function readSessionId(payload: unknown): string | undefined {
+ if (payload === null || typeof payload !== "object") return undefined;
+ const value = (payload as { session_id?: unknown }).session_id;
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
+}
+
+function readMessages(payload: unknown): ReadonlyArray<ConversationMessage> {
+ if (payload === null || typeof payload !== "object") return [];
+ const raw = (payload as { messages?: unknown }).messages;
+ if (!Array.isArray(raw)) return [];
+ const messages: ConversationMessage[] = [];
+ for (const item of raw) {
+ if (item === null || typeof item !== "object") continue;
+ const content = (item as { content?: unknown }).content;
+ if (typeof content !== "string") continue;
+ const role = (item as { role?: unknown }).role;
+ messages.push(typeof role === "string" ? { role, content } : { content });
+ }
+ return messages;
+}
+
+function stringOptional(value: string | boolean | string[] | undefined): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+function writeOutput(value: Record<string, unknown>, json: boolean): void {
+ if (json) {
+ okJson(value);
+ return;
+ }
+ process.stdout.write(inspect(value, { colors: false, depth: null }) + "\n");
+}
diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.ts
index 17a96ecf..bb99c4ca 100644
--- a/src/core/brain/continuity/types.ts
+++ b/src/core/brain/continuity/types.ts
@@ -14,6 +14,7 @@ export type ContinuityRecordKind =
| "recall_telemetry"
| "gate_telemetry"
| "pre_compact_extract"
+ | "post_compact_audit"
| "session_turn"
| "session_summary_node"
| "session_summary_digest"
diff --git a/src/core/brain/post-compact-audit.ts b/src/core/brain/post-compact-audit.ts
new file mode 100644
index 00000000..47b96fd2
--- /dev/null
+++ b/src/core/brain/post-compact-audit.ts
@@ -0,0 +1,448 @@
+import { createHash } from "node:crypto";
+
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+import { sanitizePreCompactText } from "./pre-compact-extract.ts";
+import { appendPinnedContext, readPinnedContext } from "./pinned.ts";
+
+/**
+ * Post-compaction pinned-anchor survival audit — the symmetric POST
+ * complement to {@link extractPreCompactRecords} (which captures
+ * decisions/rules BEFORE a Hermes context-compaction). After Hermes
+ * summarizes a long conversation, a pinned anchor's text can be demoted
+ * into the (background) summary block while the ACTIVE region carries on
+ * without it. This module detects the compaction event, audits which
+ * anchors still live in the active region, and re-asserts ONLY the ones
+ * that drifted — survivors cost zero tokens.
+ *
+ * Deterministic and LLM-free: detection is a literal marker scan plus a
+ * summary-body hash; the survival probe is keyword-only (an optional
+ * windowed-embedding probe is a documented future extension gated behind
+ * `post_compact_survival_audit_embedding`, off by default — NOT built
+ * here). Fail-open throughout: a malformed conversation, an unreadable
+ * pinned store, or an over-budget re-assertion is recorded in the bounded
+ * audit record and never thrown into the caller's turn.
+ */
+
+/**
+ * Hermes compressor handoff markers. The summary block a compaction
+ * emits is prefixed by one of these. Defaults mirror the design's
+ * enumerated set: the Unicode `SUMMARY_PREFIX`, its ASCII fallback, and
+ * the legacy `[CONTEXT SUMMARY]:`. A host that emits a different literal
+ * passes its own via {@link PostCompactAuditInput.summaryMarkers}; the
+ * defaults stay in place when it does not.
+ */
+export const DEFAULT_SUMMARY_MARKERS: ReadonlyArray<string> = Object.freeze([
+ "⟦CONTEXT-SUMMARY⟧",
+ "[[CONTEXT-SUMMARY]]",
+ "[CONTEXT SUMMARY]:",
+]);
+
+/** Header of the on-drift re-assertion block written to the pinned store. */
+export const REASSERT_HEADER = "## Re-asserted standing context (post-compaction";
+
+const DEFAULT_PRESENCE_RATIO = 0.5;
+const DEFAULT_MAX_ANCHORS = 200;
+const DEFAULT_MAX_DRIFT_LOG = 50;
+const MAX_PROBES_PER_ANCHOR = 8;
+const ANCHOR_LOG_MAX_CHARS = 400;
+
+export type AnchorStatus = "survived" | "drifted" | "absent";
+export type AnchorSource = "pinned" | "static";
+
+export interface ConversationMessage {
+ readonly role?: string;
+ readonly content: string;
+}
+
+export interface PostCompactAuditInput {
+ readonly sessionId: string;
+ /**
+ * The post-compaction conversation, in order. The summary block is the
+ * LAST message whose content opens with a known marker; every message
+ * after it is the ACTIVE (non-summary) region.
+ */
+ readonly messages: ReadonlyArray<ConversationMessage>;
+ /**
+ * Static standing-instruction anchors (e.g. config, reseeded each
+ * session start). Audited alongside the dynamic pins read from the
+ * pinned store. Absent by default.
+ */
+ readonly staticAnchors?: ReadonlyArray<string>;
+ /** Override the compaction markers; defaults to {@link DEFAULT_SUMMARY_MARKERS}. */
+ readonly summaryMarkers?: ReadonlyArray<string>;
+ /**
+ * Fraction of an anchor's keyword probes that must hit a region for the
+ * anchor to count as present there. Default 0.5 (at least one probe is
+ * always required).
+ */
+ readonly presenceRatio?: number;
+ /**
+ * When false, compute the audit + reminder block but do NOT write the
+ * re-assertion into the pinned store (dry-run). Default true.
+ */
+ readonly reassert?: boolean;
+ /** Bounded cap on anchors recorded in the audit drift log. Default 50. */
+ readonly maxDriftLog?: number;
+ readonly createdAt?: string;
+}
+
+export interface AnchorVerdict {
+ readonly anchor: string;
+ readonly status: AnchorStatus;
+ readonly source: AnchorSource;
+ readonly probes: ReadonlyArray<string>;
+}
+
+export interface PostCompactAuditResult {
+ readonly compactionDetected: boolean;
+ /** True when this exact summary (by hash) was already audited for the session. */
+ readonly alreadyAudited: boolean;
+ readonly summaryHash: string | null;
+ readonly anchors: ReadonlyArray<AnchorVerdict>;
+ readonly drifted: ReadonlyArray<string>;
+ readonly survived: number;
+ readonly absent: number;
+ /** True when an on-drift reminder block was written to the pinned store. */
+ readonly reasserted: boolean;
+ /** The on-drift repair text (the reminder block), or null when nothing drifted. */
+ readonly reminderBlock: string | null;
+ /** The bounded `post_compact_audit` continuity record, or null when nothing was recorded. */
+ readonly record: ContinuityRecord | null;
+ readonly errors: ReadonlyArray<string>;
+}
+
+interface CompactionSplit {
+ readonly summaryBody: string;
+ readonly summaryRegion: string;
+ readonly activeRegion: string;
+}
+
+interface Anchor {
+ readonly text: string;
+ readonly source: AnchorSource;
+ readonly probes: ReadonlyArray<string>;
+}
+
+/**
+ * Audit pinned-anchor survival after a Hermes compaction. Never throws:
+ * every recoverable failure lands in the returned `errors` array, so a
+ * caller can wire this into a per-turn hook without a try/catch.
+ */
+export function auditPostCompaction(
+ vault: string,
+ input: PostCompactAuditInput,
+): PostCompactAuditResult {
+ const errors: string[] = [];
+ try {
+ return runAudit(vault, input, errors);
+ } catch (error) {
+ errors.push(error instanceof Error ? error.message : String(error));
+ return emptyResult(false, false, null, errors);
+ }
+}
+
+function runAudit(
+ vault: string,
+ input: PostCompactAuditInput,
+ errors: string[],
+): PostCompactAuditResult {
+ const markers =
+ input.summaryMarkers && input.summaryMarkers.length > 0
+ ? input.summaryMarkers
+ : DEFAULT_SUMMARY_MARKERS;
+ const split = detectCompaction(input.messages, markers);
+ if (split === null) {
+ return emptyResult(false, false, null, errors);
+ }
+
+ const summaryHash = hash(split.summaryBody);
+ const dedupeKey = `${input.sessionId}:${summaryHash}`;
+ if (findExistingAudit(vault, dedupeKey) !== null) {
+ // The same compaction was already audited for this session. Re-running
+ // every turn would re-inject drifted anchors repeatedly and churn the
+ // prompt cache; skip as a no-op.
+ return emptyResult(true, true, summaryHash, errors);
+ }
+
+ const ratio = clampRatio(input.presenceRatio);
+ const anchors = collectAnchors(vault, input.staticAnchors, errors);
+ const verdicts: AnchorVerdict[] = [];
+ for (const anchor of anchors) {
+ let status: AnchorStatus;
+ try {
+ const inActive = regionContainsAnchor(split.activeRegion, anchor.probes, ratio);
+ const inSummary = regionContainsAnchor(split.summaryRegion, anchor.probes, ratio);
+ status = inActive ? "survived" : inSummary ? "drifted" : "absent";
+ } catch (error) {
+ // A single un-probeable anchor never aborts the audit.
+ errors.push(error instanceof Error ? error.message : String(error));
+ continue;
+ }
+ verdicts.push({ anchor: anchor.text, status, source: anchor.source, probes: anchor.probes });
+ }
+
+ const drifted = verdicts.filter((v) => v.status === "drifted").map((v) => v.anchor);
+ const survived = verdicts.filter((v) => v.status === "survived").length;
+ const absent = verdicts.filter((v) => v.status === "absent").length;
+ const reminderBlock = drifted.length > 0 ? buildReminderBlock(drifted, summaryHash) : null;
+
+ let reasserted = false;
+ if (reminderBlock !== null && input.reassert !== false) {
+ reasserted = reassertReminder(vault, reminderBlock, errors);
+ }
+
+ const record = recordAudit(vault, {
+ sessionId: input.sessionId,
+ summaryHash,
+ dedupeKey,
+ anchorsTotal: verdicts.length,
+ survived,
+ drifted,
+ absent,
+ reasserted,
+ createdAt: input.createdAt,
+ maxDriftLog: input.maxDriftLog ?? DEFAULT_MAX_DRIFT_LOG,
+ errors,
+ });
+
+ return Object.freeze({
+ compactionDetected: true,
+ alreadyAudited: false,
+ summaryHash,
+ anchors: Object.freeze(verdicts),
+ drifted: Object.freeze(drifted),
+ survived,
+ absent,
+ reasserted,
+ reminderBlock,
+ record,
+ errors: Object.freeze([...errors]),
+ });
+}
+
+/**
+ * Locate the most recent compaction summary in the conversation. The
+ * summary is the LAST message whose content opens with a marker; the
+ * active region is every message after it, the summary region everything
+ * up to and including it. Returns null when no marker is present.
+ */
+export function detectCompaction(
+ messages: ReadonlyArray<ConversationMessage>,
+ markers: ReadonlyArray<string> = DEFAULT_SUMMARY_MARKERS,
+): CompactionSplit | null {
+ if (!Array.isArray(messages) || messages.length === 0) return null;
+ let summaryIndex = -1;
+ let summaryBody = "";
+ for (let index = 0; index < messages.length; index += 1) {
+ const content = messages[index]?.content;
+ if (typeof content !== "string") continue;
+ const marker = markers.find((m) => content.trimStart().startsWith(m));
+ if (marker !== undefined) {
+ summaryIndex = index;
+ summaryBody = content.trimStart().slice(marker.length).trim();
+ }
+ }
+ if (summaryIndex === -1) return null;
+
+ const contentAt = (index: number): string =>
+ typeof messages[index]?.content === "string" ? (messages[index]!.content as string) : "";
+ const summaryRegion = messages
+ .slice(0, summaryIndex + 1)
+ .map((_, offset) => contentAt(offset))
+ .join("\n");
+ const activeRegion = messages
+ .slice(summaryIndex + 1)
+ .map((_, offset) => contentAt(summaryIndex + 1 + offset))
+ .join("\n");
+ return { summaryBody, summaryRegion, activeRegion };
+}
+
+/**
+ * Derive locale-agnostic keyword probes from an anchor's own text. No
+ * hardcoded stopword lists: distinctiveness is approximated purely by
+ * token length, so the probe set is the same regardless of language.
+ */
+export function deriveProbes(anchorText: string): string[] {
+ const tokens = anchorText.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
+ let probes = tokens.filter((t) => t.length >= 4);
+ if (probes.length === 0) probes = tokens.filter((t) => t.length >= 2);
+ return [...new Set(probes)]
+ .toSorted((a, b) => b.length - a.length || a.localeCompare(b))
+ .slice(0, MAX_PROBES_PER_ANCHOR);
+}
+
+function regionContainsAnchor(
+ region: string,
+ probes: ReadonlyArray<string>,
+ ratio: number,
+): boolean {
+ if (probes.length === 0) return false;
+ const lower = region.toLowerCase();
+ const matched = probes.filter((p) => lower.includes(p)).length;
+ if (matched === 0) return false;
+ return matched / probes.length >= ratio;
+}
+
+function collectAnchors(
+ vault: string,
+ staticAnchors: ReadonlyArray<string> | undefined,
+ errors: string[],
+): Anchor[] {
+ const anchors: Anchor[] = [];
+ const seen = new Set<string>();
+ const push = (text: string, source: AnchorSource): void => {
+ const clean = sanitizePreCompactText(text.trim());
+ if (clean.length === 0) return;
+ const key = clean.toLowerCase();
+ if (seen.has(key)) return;
+ const probes = deriveProbes(clean);
+ if (probes.length === 0) return; // un-probeable line (punctuation/separator only)
+ seen.add(key);
+ anchors.push({ text: clean, source, probes });
+ };
+
+ let pinnedContent = "";
+ try {
+ pinnedContent = readPinnedContext(vault).content;
+ } catch (error) {
+ errors.push(error instanceof Error ? error.message : String(error));
+ }
+ for (const line of pinnedContent.split(/\r?\n/)) {
+ if (anchors.length >= DEFAULT_MAX_ANCHORS) break;
+ const stripped = stripAnchorLine(line);
+ if (stripped !== null) push(stripped, "pinned");
+ }
+ for (const raw of staticAnchors ?? []) {
+ if (anchors.length >= DEFAULT_MAX_ANCHORS) break;
+ if (typeof raw === "string") push(raw, "static");
+ }
+ return anchors;
+}
+
+/**
+ * Normalise one pinned line into an anchor, or null when it carries no
+ * standing instruction (blank, heading, or rule separator). Leading list
+ * markers are stripped so `- Always X` and `Always X` audit identically.
+ */
+function stripAnchorLine(line: string): string | null {
+ const trimmed = line.trim();
+ if (trimmed.length === 0) return null;
+ if (/^#{1,6}\s/.test(trimmed)) return null; // markdown heading
+ if (/^([-*_])\1{2,}$/.test(trimmed.replace(/\s+/g, ""))) return null; // --- *** ___ rule
+ return trimmed.replace(/^(?:[-*+]\s+|\d+[.)]\s+)/, "").trim();
+}
+
+function buildReminderBlock(drifted: ReadonlyArray<string>, summaryHash: string): string {
+ const header = `${REASSERT_HEADER} ${summaryHash.slice(0, 8)})`;
+ return [header, ...drifted.map((a) => `- ${a}`)].join("\n");
+}
+
+/**
+ * Append the reminder block to the pinned store, fail-open. Idempotent
+ * against the per-compaction header (so a retried turn does not duplicate
+ * the block) and bounded by the pinned budget (an over-budget append is
+ * recorded, not thrown).
+ */
+function reassertReminder(vault: string, reminderBlock: string, errors: string[]): boolean {
+ try {
+ const header = reminderBlock.split("\n")[0] ?? "";
+ if (header.length > 0 && readPinnedContext(vault).content.includes(header)) {
+ return false; // already re-asserted for this compaction
+ }
+ appendPinnedContext(vault, reminderBlock);
+ return true;
+ } catch (error) {
+ errors.push(error instanceof Error ? error.message : String(error));
+ return false;
+ }
+}
+
+interface RecordAuditInput {
+ readonly sessionId: string;
+ readonly summaryHash: string;
+ readonly dedupeKey: string;
+ readonly anchorsTotal: number;
+ readonly survived: number;
+ readonly drifted: ReadonlyArray<string>;
+ readonly absent: number;
+ readonly reasserted: boolean;
+ readonly createdAt?: string;
+ readonly maxDriftLog: number;
+ readonly errors: ReadonlyArray<string>;
+}
+
+function recordAudit(vault: string, input: RecordAuditInput): ContinuityRecord | null {
+ try {
+ const boundedDrift = input.drifted
+ .slice(0, Math.max(0, input.maxDriftLog))
+ .map((text) => sanitizePreCompactText(text).slice(0, ANCHOR_LOG_MAX_CHARS));
+ return appendContinuityRecord(vault, {
+ kind: "post_compact_audit",
+ createdAt: input.createdAt ?? new Date().toISOString(),
+ sourceRefs: auditSourceRefs(input.sessionId),
+ payload: {
+ session_id: input.sessionId,
+ summary_hash: input.summaryHash,
+ dedupe_key: input.dedupeKey,
+ anchors_total: input.anchorsTotal,
+ survived: input.survived,
+ drifted_count: input.drifted.length,
+ absent: input.absent,
+ drifted: boundedDrift,
+ drift_log_truncated: input.drifted.length > boundedDrift.length,
+ reasserted: input.reasserted,
+ ...(input.errors.length > 0 ? { errors: input.errors.slice(0, 10) } : {}),
+ },
+ });
+ } catch (error) {
+ // Recording the audit must never break the turn. A failure here means
+ // no idempotency record exists, so the next turn re-audits — a soft
+ // loss, not a turn-breaker.
+ (input.errors as string[]).push(error instanceof Error ? error.message : String(error));
+ return null;
+ }
+}
+
+function auditSourceRefs(sessionId: string): ReadonlyArray<ContinuitySourceRef> {
+ return Object.freeze([Object.freeze({ type: "session", id: sessionId })]);
+}
+
+function findExistingAudit(vault: string, dedupeKey: string): ContinuityRecord | null {
+ return (
+ listContinuityRecords(vault, { kind: "post_compact_audit" }).find(
+ (record) => record.payload["dedupe_key"] === dedupeKey,
+ ) ?? null
+ );
+}
+
+function clampRatio(ratio: number | undefined): number {
+ if (typeof ratio !== "number" || !Number.isFinite(ratio)) return DEFAULT_PRESENCE_RATIO;
+ if (ratio <= 0) return DEFAULT_PRESENCE_RATIO;
+ return Math.min(1, ratio);
+}
+
+function emptyResult(
+ compactionDetected: boolean,
+ alreadyAudited: boolean,
+ summaryHash: string | null,
+ errors: string[],
+): PostCompactAuditResult {
+ return Object.freeze({
+ compactionDetected,
+ alreadyAudited,
+ summaryHash,
+ anchors: Object.freeze([]),
+ drifted: Object.freeze([]),
+ survived: 0,
+ absent: 0,
+ reasserted: false,
+ reminderBlock: null,
+ record: null,
+ errors: Object.freeze([...errors]),
+ });
+}
+
+function hash(value: string): string {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
diff --git a/src/core/brain/pre-compact-extract.ts b/src/core/brain/pre-compact-extract.ts
index dce1dc84..ef91540c 100644
--- a/src/core/brain/pre-compact-extract.ts
+++ b/src/core/brain/pre-compact-extract.ts
@@ -18,6 +18,13 @@ export interface PreCompactExtractInput {
readonly host?: string;
readonly createdAt?: string;
readonly maxChars?: number;
+ /**
+ * True when this segment was flushed by an interrupted close
+ * (SIGHUP/SIGTERM/force-quit/restart-drain). Recorded on the continuity
+ * record so an interrupted capture is honestly distinguishable from a clean
+ * one. Absent by default - omitted records stay byte-identical (t_c181f92b).
+ */
+ readonly interrupted?: boolean;
}
export interface PreCompactExtractResult {
@@ -83,6 +90,7 @@ export function extractPreCompactRecords(
turn_end: input.turnEnd,
turn_range: `${input.turnStart}..${input.turnEnd}`,
...(host !== undefined && host.length > 0 ? { host } : {}),
+ ...(input.interrupted === true ? { interrupted: true } : {}),
content_hash: contentHash,
dedupe_key: dedupeKey,
truncated_input: boundedText.length < input.text.length,
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index 8adb94df..d7217881 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -44,6 +44,18 @@ export interface CaptureSessionLifecycleResult {
readonly facts_deduped: number;
readonly audit_path: string;
readonly log_path?: string;
+ /**
+ * True when the host marked this SessionEnd as interrupted
+ * (SIGHUP/SIGTERM/force-quit/restart-drain). Absent for a clean close so
+ * the pre-interrupt result shape stays byte-identical (t_c181f92b).
+ */
+ readonly interrupted?: boolean;
+ /**
+ * Whether the pre-restart transcript could be consumed on an interrupted
+ * close. Absent unless `interrupted` is set; `false` when the transcript
+ * was missing/unreadable/empty rather than silently coerced to a clean close.
+ */
+ readonly transcript_consumed?: boolean;
/** True when a SessionEnd event cleared that session's bound focus. */
readonly focus_cleared?: boolean;
/** Path of the handoff note a SessionEnd event produced (gated). */
@@ -69,6 +81,12 @@ interface NormalizedPayload {
readonly compressionDepth?: number;
/** SessionStart discriminator (`startup|resume|clear|compact`). */
readonly sessionStartSource?: string;
+ /**
+ * Host flag: this SessionEnd was an interrupted close
+ * (SIGHUP/SIGTERM/force-quit/restart-drain). Absent by default; only
+ * `true` is honoured so an omitted field is byte-identical (t_c181f92b).
+ */
+ readonly interrupted?: boolean;
readonly malformed: number;
}
@@ -191,6 +209,55 @@ export async function captureSessionLifecycleEvent(
}
}
+ // Interrupted-session capture (t_c181f92b): when the host flushes an
+ // in-flight transcript on SIGHUP/SIGTERM/force-quit/restart-drain and fires
+ // SessionEnd with interrupted=true, the in-flight user turns may never have
+ // reached per-turn capture. Consume the persisted pre-restart transcript so
+ // those turns reach the SAME marker/fact extraction as a live prompt. Only
+ // user-authored turns are extracted (matching the fact-extract carve-out -
+ // bare assistant output is never auto-captured). Double-counting on resume
+ // is prevented by the existing content-keyed dedupe seams (signal
+ // dedup_hash + fact dedup index), so re-reading the same turns on a later
+ // close suppresses them. Honest: when the transcript cannot be consumed,
+ // transcript_consumed is recorded false rather than coerced to a clean
+ // close. Fail-soft - a bad transcript never blocks lifecycle capture.
+ let transcriptConsumed: boolean | undefined;
+ if (
+ normalized.event === "SessionEnd" &&
+ normalized.interrupted === true &&
+ mayWrite &&
+ !opts.dryRun
+ ) {
+ transcriptConsumed = false;
+ if (normalized.transcriptPath !== undefined) {
+ try {
+ const turns = await readTranscriptTurns(normalized.transcriptPath);
+ for (const turn of turns) {
+ if (turn.role !== "user" || turn.text === undefined) continue;
+ if (boundary.suppressMessage(turn.text)) {
+ counters.suppressed_messages++;
+ continue;
+ }
+ captureMarkers(vault, normalized, turn.text, opts, now, ensureDedup(), counters);
+ const routed = routeExtractedFacts(vault, {
+ facts: extractFacts(turn.text),
+ agent: opts.agent,
+ now,
+ sessionRef: sessionReference(normalized),
+ dedup: ensureDedup(),
+ });
+ counters.facts_extracted += routed.created;
+ counters.facts_deduped += routed.deduped;
+ }
+ transcriptConsumed = turns.length > 0;
+ } catch {
+ // A malformed/unreadable transcript is surfaced honestly (false),
+ // never raised into the host.
+ transcriptConsumed = false;
+ }
+ }
+ }
+
// Handoff note on SessionEnd (Agent Surface Suite, t_28afa4d2):
// gated by the session_handoff config key (default off) and the
// capture boundary; reads the recorded transcript through the
@@ -248,6 +315,8 @@ export async function captureSessionLifecycleEvent(
...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),
dry_run: opts.dryRun === true,
boundary_decision: decision,
+ ...(normalized.interrupted === true ? { interrupted: true } : {}),
+ ...(transcriptConsumed !== undefined ? { transcript_consumed: transcriptConsumed } : {}),
...(chainLineage !== undefined
? {
lineage_root: chainLineage.rootId,
@@ -273,6 +342,8 @@ export async function captureSessionLifecycleEvent(
facts_deduped: counters.facts_deduped,
audit_path: auditPath,
...(logPath ? { log_path: logPath } : {}),
+ ...(normalized.interrupted === true ? { interrupted: true } : {}),
+ ...(transcriptConsumed !== undefined ? { transcript_consumed: transcriptConsumed } : {}),
...(focusCleared ? { focus_cleared: true } : {}),
...(handoffPath !== undefined ? { handoff_path: handoffPath } : {}),
...(chainLineage !== undefined ? { lineage: chainLineage } : {}),
@@ -293,13 +364,7 @@ async function writeHandoffNoteFromTranscript(
now: Date,
): Promise<HandoffNoteResult | null> {
const path = normalized.transcriptPath!;
- if (!existsSync(path)) return null;
- const text = readFileSync(path, "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(path)) turns.push(turn);
+ const turns = await readTranscriptTurns(path);
if (turns.length === 0) return null;
return writeHandoffNote(vault, {
turns,
@@ -310,6 +375,28 @@ async function writeHandoffNoteFromTranscript(
});
}
+/**
+ * Read a recorded transcript through the session adapters. Returns an empty
+ * array (never throws) when the path is missing, unrecognised, or empty - the
+ * callers treat "no turns" as "nothing to consume". Trust model matches
+ * {@link writeHandoffNoteFromTranscript}: the path is host-produced, not
+ * user-typed, so no inside-vault check applies.
+ */
+async function readTranscriptTurns(path: string): Promise<SessionTurn[]> {
+ try {
+ if (!existsSync(path)) return [];
+ const text = readFileSync(path, "utf8");
+ const nl = text.indexOf("\n");
+ const adapter = detectAdapter(nl < 0 ? text : text.slice(0, nl));
+ if (adapter === null) return [];
+ const turns: SessionTurn[] = [];
+ for await (const turn of adapter.iterate(path)) turns.push(turn);
+ return turns;
+ } catch {
+ return [];
+ }
+}
+
function normalizePayload(payload: unknown): NormalizedPayload {
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
return { event: "unknown", malformed: 1 };
@@ -341,6 +428,7 @@ function normalizePayload(payload: unknown): NormalizedPayload {
...(rootSessionId ? { rootSessionId } : {}),
...(compressionDepth !== undefined ? { compressionDepth } : {}),
...(sessionStartSource ? { sessionStartSource } : {}),
+ ...(record["interrupted"] === true ? { interrupted: true } : {}),
...(extractPromptText(record) ? { promptText: extractPromptText(record)! } : {}),
...(readNonEmptyString(record["tool_name"])
? { toolName: readNonEmptyString(record["tool_name"])! }
diff --git a/src/core/config.ts b/src/core/config.ts
index 694fc6df..5505794c 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -305,6 +305,19 @@ export function resolveSearchFocusContextPack(configPath?: string): boolean {
return raw === "true" || raw === "1";
}
+/**
+ * Post-compaction pinned-anchor survival audit gate
+ * (session-lifecycle-capture-durability, t_12c8b256). Default OFF: the
+ * `o2b brain post-compact-audit` entry is a no-op unless
+ * `post_compact_survival_audit: "true"`, so unchanged installs run no
+ * post-compaction re-assertion and stay byte-identical.
+ */
+export function resolvePostCompactSurvivalAudit(configPath?: string): boolean {
+ const env = process.env["OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT"]?.trim();
+ const raw = env || discoverConfig(configPath).data["post_compact_survival_audit"]?.trim();
+ return raw === "true" || raw === "1";
+}
+
/**
* SessionEnd handoff-note gate (Agent Surface Suite, t_28afa4d2).
* Default OFF: lifecycle capture writes no handoff note unless
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index 2a3a1a41..6b5442bd 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -376,6 +376,7 @@ async function toolBrainPreCompactExtract(
? { host: optionalStringArg("brain_pre_compact_extract", args, "host") }
: {}),
...(maxChars !== undefined ? { maxChars } : {}),
+ ...(coerceBool(args, "interrupted") === true ? { interrupted: true } : {}),
});
return { count: result.records.length, ...result };
}
@@ -732,6 +733,11 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
minimum: 1,
description: "Optional maximum input characters to scan before extracting.",
},
+ interrupted: {
+ type: "boolean",
+ description:
+ "When true, mark the extracted records as flushed by an interrupted close (SIGHUP/SIGTERM/force-quit/restart-drain). Absent by default.",
+ },
},
required: ["session_id", "turn_start", "turn_end", "text"],
additionalProperties: false,
diff --git a/tests/cli/brain-post-compact-audit.test.ts b/tests/cli/brain-post-compact-audit.test.ts
new file mode 100644
index 00000000..bcc56a1a
--- /dev/null
+++ b/tests/cli/brain-post-compact-audit.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writePinnedContext, readPinnedContext } from "../../src/core/brain/pinned.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-cli-post-compact-audit-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const PAYLOAD = JSON.stringify({
+ session_id: "session-cli",
+ messages: [
+ { role: "system", content: "[CONTEXT SUMMARY]: Operator set a deployment freeze window." },
+ { role: "user", content: "Telemetry stays opt-in for every preset." },
+ ],
+});
+
+test("default off: post-compact-audit is a no-op without the gate", async () => {
+ writePinnedContext(vault, "- Maintain the deployment freeze window.");
+ const result = await runCli(["brain", "post-compact-audit", "--vault", vault, "--json"], {
+ stdin: PAYLOAD,
+ env: { OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT: "" },
+ });
+ expect(result.returncode).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.enabled).toBe(false);
+ expect(body.forced).toBe(false);
+ expect(body.compaction_detected).toBe(false);
+ expect(readPinnedContext(vault).content).not.toContain("Re-asserted standing context");
+});
+
+test("gated on: re-asserts the drifted anchor from stdin", async () => {
+ writePinnedContext(vault, "- Maintain the deployment freeze window.");
+ const result = await runCli(["brain", "post-compact-audit", "--vault", vault, "--json"], {
+ stdin: PAYLOAD,
+ env: { OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT: "true" },
+ });
+ expect(result.returncode).toBe(0);
+ expect(result.stderr).toBe("");
+ const body = JSON.parse(result.stdout);
+ expect(body.enabled).toBe(true);
+ expect(body.compaction_detected).toBe(true);
+ expect(body.drifted).toEqual(["Maintain the deployment freeze window."]);
+ expect(body.reasserted).toBe(true);
+ expect(readPinnedContext(vault).content).toContain("Re-asserted standing context");
+});
+
+test("--force runs the audit even when the gate is off", async () => {
+ writePinnedContext(vault, "- Maintain the deployment freeze window.");
+ const result = await runCli(
+ ["brain", "post-compact-audit", "--vault", vault, "--force", "--json"],
+ { stdin: PAYLOAD, env: { OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT: "" } },
+ );
+ expect(result.returncode).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.compaction_detected).toBe(true);
+ expect(body.reasserted).toBe(true);
+ expect(body.enabled).toBe(false);
+ expect(body.forced).toBe(true);
+});
diff --git a/tests/core/brain/post-compact-audit.test.ts b/tests/core/brain/post-compact-audit.test.ts
new file mode 100644
index 00000000..03b7b580
--- /dev/null
+++ b/tests/core/brain/post-compact-audit.test.ts
@@ -0,0 +1,169 @@
+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 { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
+import {
+ auditPostCompaction,
+ deriveProbes,
+ detectCompaction,
+ REASSERT_HEADER,
+} from "../../../src/core/brain/post-compact-audit.ts";
+import { readPinnedContext, writePinnedContext } from "../../../src/core/brain/pinned.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-post-compact-audit-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+// A conversation where the "deployment freeze" anchor was demoted into the
+// compaction summary, while the "telemetry opt-in" anchor is still alive in
+// the active region.
+function driftedConversation() {
+ return [
+ {
+ role: "system",
+ content:
+ "[CONTEXT SUMMARY]: Earlier the operator imposed a deployment freeze " +
+ "window over the holidays and we discussed staffing.",
+ },
+ { role: "user", content: "Remember telemetry stays opt-in for every preset." },
+ { role: "assistant", content: "Understood — telemetry remains opt-in across presets." },
+ ];
+}
+
+describe("detectCompaction", () => {
+ test("splits the summary block from the active region", () => {
+ const split = detectCompaction(driftedConversation());
+ expect(split).not.toBeNull();
+ expect(split!.summaryBody).toContain("deployment freeze");
+ expect(split!.activeRegion).toContain("telemetry");
+ expect(split!.activeRegion).not.toContain("deployment freeze");
+ });
+
+ test("returns null with no compaction marker", () => {
+ expect(detectCompaction([{ content: "just a normal turn" }])).toBeNull();
+ expect(detectCompaction([])).toBeNull();
+ });
+
+ test("matches the Unicode and ASCII fallback markers", () => {
+ expect(detectCompaction([{ content: "⟦CONTEXT-SUMMARY⟧ folded" }])).not.toBeNull();
+ expect(detectCompaction([{ content: "[[CONTEXT-SUMMARY]] folded" }])).not.toBeNull();
+ });
+});
+
+describe("deriveProbes", () => {
+ test("derives locale-agnostic length-based probes, no stopword list", () => {
+ expect(deriveProbes("Keep telemetry opt-in for presets")).toContain("telemetry");
+ expect(deriveProbes("Keep telemetry opt-in for presets")).toContain("presets");
+ // Non-English text still yields probes (no English-only filtering).
+ expect(deriveProbes("conserver la télémétrie activée").length).toBeGreaterThan(0);
+ });
+});
+
+describe("auditPostCompaction", () => {
+ test("re-asserts the drifted anchor and leaves the survivor untouched", () => {
+ writePinnedContext(
+ vault,
+ ["- Maintain the deployment freeze window.", "- Keep telemetry opt-in for presets."].join(
+ "\n",
+ ),
+ );
+
+ const result = auditPostCompaction(vault, {
+ sessionId: "session-a",
+ messages: driftedConversation(),
+ createdAt: "2026-06-24T12:00:00.000Z",
+ });
+
+ expect(result.compactionDetected).toBe(true);
+ expect(result.alreadyAudited).toBe(false);
+ expect(result.drifted).toHaveLength(1);
+ expect(result.drifted[0]).toContain("deployment freeze");
+ expect(result.survived).toBe(1);
+ expect(result.reasserted).toBe(true);
+ expect(result.reminderBlock).toContain("deployment freeze");
+ // The survivor is NOT in the reminder block — survivors cost zero tokens.
+ expect(result.reminderBlock).not.toContain("telemetry");
+
+ const pinned = readPinnedContext(vault).content;
+ expect(pinned).toContain(REASSERT_HEADER);
+ expect(pinned).toContain("Maintain the deployment freeze window.");
+ });
+
+ test("records a post_compact_audit continuity record idempotently per summary", () => {
+ writePinnedContext(vault, "- Maintain the deployment freeze window.");
+ const input = {
+ sessionId: "session-b",
+ messages: driftedConversation(),
+ createdAt: "2026-06-24T12:00:00.000Z",
+ };
+
+ const first = auditPostCompaction(vault, input);
+ expect(first.record).not.toBeNull();
+ expect(first.alreadyAudited).toBe(false);
+
+ const second = auditPostCompaction(vault, input);
+ expect(second.alreadyAudited).toBe(true);
+ expect(second.reasserted).toBe(false);
+ expect(second.record).toBeNull();
+
+ expect(listContinuityRecords(vault, { kind: "post_compact_audit" })).toHaveLength(1);
+ });
+
+ test("does not re-assert when reassert is false (dry run)", () => {
+ writePinnedContext(vault, "- Maintain the deployment freeze window.");
+ const result = auditPostCompaction(vault, {
+ sessionId: "session-dry",
+ messages: driftedConversation(),
+ reassert: false,
+ createdAt: "2026-06-24T12:00:00.000Z",
+ });
+ expect(result.drifted).toHaveLength(1);
+ expect(result.reminderBlock).not.toBeNull();
+ expect(result.reasserted).toBe(false);
+ expect(readPinnedContext(vault).content).not.toContain(REASSERT_HEADER);
+ });
+
+ test("no compaction marker is a zero-cost no-op", () => {
+ writePinnedContext(vault, "- Maintain the deployment freeze window.");
+ const result = auditPostCompaction(vault, {
+ sessionId: "session-none",
+ messages: [{ content: "no summary here" }],
+ });
+ expect(result.compactionDetected).toBe(false);
+ expect(result.reasserted).toBe(false);
+ expect(result.record).toBeNull();
+ expect(listContinuityRecords(vault, { kind: "post_compact_audit" })).toHaveLength(0);
+ });
+
+ test("fail-open on a malformed conversation, still bounded", () => {
+ const result = auditPostCompaction(vault, {
+ sessionId: "session-bad",
+ messages: undefined as unknown as never,
+ });
+ expect(result.compactionDetected).toBe(false);
+ expect(result.errors).toEqual([]);
+ expect(result.reasserted).toBe(false);
+ expect(result.record).toBeNull();
+ });
+
+ test("audits static anchors alongside dynamic pins", () => {
+ // No pinned content; the drifted anchor is supplied as a static
+ // (config-reseeded) anchor.
+ const result = auditPostCompaction(vault, {
+ sessionId: "session-static",
+ staticAnchors: ["Maintain the deployment freeze window."],
+ messages: driftedConversation(),
+ createdAt: "2026-06-24T12:00:00.000Z",
+ });
+ expect(result.drifted).toHaveLength(1);
+ expect(result.anchors[0]!.source).toBe("static");
+ });
+});
diff --git a/tests/core/brain/pre-compact-extract.test.ts b/tests/core/brain/pre-compact-extract.test.ts
index 3d5ffbd0..51ec18d9 100644
--- a/tests/core/brain/pre-compact-extract.test.ts
+++ b/tests/core/brain/pre-compact-extract.test.ts
@@ -51,6 +51,27 @@ describe("pre-compact extraction", () => {
expect(result.records[5]!.payload["text"]).toContain("[base64]");
});
+ test("records the interrupted flag only when set, byte-identical otherwise", () => {
+ const clean = extractPreCompactRecords(vault, {
+ createdAt: "2026-05-20T17:00:00.000Z",
+ sessionId: "session-clean",
+ turnStart: "turn-1",
+ turnEnd: "turn-1",
+ text: "Decision: Clean close keeps the payload unchanged.",
+ });
+ expect("interrupted" in clean.records[0]!.payload).toBe(false);
+
+ const interrupted = extractPreCompactRecords(vault, {
+ createdAt: "2026-05-20T17:00:00.000Z",
+ sessionId: "session-interrupted",
+ turnStart: "turn-1",
+ turnEnd: "turn-1",
+ text: "Decision: An interrupted flush is recorded honestly.",
+ interrupted: true,
+ });
+ expect(interrupted.records[0]!.payload["interrupted"]).toBe(true);
+ });
+
test("is idempotent by session, turn range, type, and content hash", () => {
const input = {
createdAt: "2026-05-20T17:00:00.000Z",
diff --git a/tests/core/brain/session-lifecycle.interrupted.test.ts b/tests/core/brain/session-lifecycle.interrupted.test.ts
new file mode 100644
index 00000000..30568282
--- /dev/null
+++ b/tests/core/brain/session-lifecycle.interrupted.test.ts
@@ -0,0 +1,172 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readdirSync, readFileSync, writeFileSync, 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";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-session-lifecycle-interrupted-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+/** Write a minimal Claude-format transcript the session adapters can parse. */
+function writeClaudeTranscript(sessionId: string, userTexts: ReadonlyArray<string>): string {
+ const path = join(vault, `${sessionId}.jsonl`);
+ const lines = userTexts.map((text, i) =>
+ JSON.stringify({
+ parentUuid: i === 0 ? null : `u-${i - 1}`,
+ sessionId,
+ entrypoint: "cli",
+ type: "user",
+ uuid: `u-${i}`,
+ timestamp: "2026-06-20T10:00:00Z",
+ message: { role: "user", content: text },
+ }),
+ );
+ // An assistant turn whose text carries a marker must NOT be auto-extracted.
+ lines.push(
+ JSON.stringify({
+ parentUuid: `u-${userTexts.length - 1}`,
+ sessionId,
+ entrypoint: "cli",
+ type: "assistant",
+ uuid: "a-0",
+ timestamp: "2026-06-20T10:00:01Z",
+ message: {
+ role: "assistant",
+ content: [
+ {
+ type: "text",
+ text: '@osb feedback negative topic=assistant-noise principle="should not be captured"',
+ },
+ ],
+ },
+ }),
+ );
+ writeFileSync(path, lines.join("\n") + "\n", "utf8");
+ return path;
+}
+
+function readAuditDetails(auditPath: string): Record<string, unknown> {
+ const lines = readFileSync(auditPath, "utf8").trim().split("\n").filter(Boolean);
+ const last = JSON.parse(lines[lines.length - 1]!);
+ return last.details as Record<string, unknown>;
+}
+
+describe("captureSessionLifecycleEvent interrupted close", () => {
+ test("consumes the pre-restart transcript and records interrupted honestly", async () => {
+ const sessionId = "session-interrupted";
+ const transcriptPath = writeClaudeTranscript(sessionId, [
+ '@osb feedback positive topic=interrupted-capture principle="capture in-flight turns"',
+ ]);
+
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "SessionEnd",
+ session_id: sessionId,
+ transcript_path: transcriptPath,
+ interrupted: true,
+ },
+ { agent: "tester", now: new Date("2026-06-20T10:05:00Z") },
+ );
+
+ expect(result.event).toBe("SessionEnd");
+ expect(result.interrupted).toBe(true);
+ expect(result.transcript_consumed).toBe(true);
+ // The in-flight user marker reached storage.
+ expect(result.signals_created).toBe(1);
+
+ const signalFiles = readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md"));
+ expect(signalFiles).toHaveLength(1);
+ expect(readFileSync(join(vault, "Brain", "inbox", signalFiles[0]!), "utf8")).toContain(
+ "interrupted-capture",
+ );
+
+ // Audit honesty.
+ const details = readAuditDetails(result.audit_path);
+ expect(details["interrupted"]).toBe(true);
+ expect(details["transcript_consumed"]).toBe(true);
+ });
+
+ test("resuming the same session does not re-capture turns already captured", async () => {
+ const sessionId = "session-resume";
+ const transcriptPath = writeClaudeTranscript(sessionId, [
+ '@osb feedback positive topic=resume-dedup principle="no double counting on resume"',
+ ]);
+
+ const first = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "SessionEnd",
+ session_id: sessionId,
+ transcript_path: transcriptPath,
+ interrupted: true,
+ },
+ { agent: "tester", now: new Date("2026-06-20T10:05:00Z") },
+ );
+ expect(first.signals_created).toBe(1);
+
+ // Resume: the same transcript turns are re-read on the next interrupted
+ // close. The content-keyed dedupe seam must suppress them all.
+ const second = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "SessionEnd",
+ session_id: sessionId,
+ transcript_path: transcriptPath,
+ interrupted: true,
+ },
+ { agent: "tester", now: new Date("2026-06-20T10:10:00Z") },
+ );
+ expect(second.signals_created).toBe(0);
+ expect(second.signals_deduped).toBe(1);
+ expect(second.transcript_consumed).toBe(true);
+
+ const signalFiles = readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.endsWith(".md"));
+ expect(signalFiles).toHaveLength(1);
+ });
+
+ test("an unreadable transcript records interrupted with transcript_consumed false", async () => {
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "SessionEnd",
+ session_id: "session-no-transcript",
+ transcript_path: join(vault, "does-not-exist.jsonl"),
+ interrupted: true,
+ },
+ { agent: "tester", now: new Date("2026-06-20T10:15:00Z") },
+ );
+
+ expect(result.interrupted).toBe(true);
+ expect(result.transcript_consumed).toBe(false);
+ expect(result.signals_created).toBe(0);
+ const details = readAuditDetails(result.audit_path);
+ expect(details["interrupted"]).toBe(true);
+ expect(details["transcript_consumed"]).toBe(false);
+ });
+
+ test("a clean close (absent interrupted) stays byte-identical", async () => {
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "SessionEnd", session_id: "session-clean" },
+ { agent: "tester", now: new Date("2026-06-20T10:20:00Z") },
+ );
+
+ expect(result.event).toBe("SessionEnd");
+ expect(result.interrupted).toBeUndefined();
+ expect(result.transcript_consumed).toBeUndefined();
+ const details = readAuditDetails(result.audit_path);
+ expect("interrupted" in details).toBe(false);
+ expect("transcript_consumed" in details).toBe(false);
+ });
+});
diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.ts
index f7b96e3b..bdb070c4 100644
--- a/tests/helpers/run-cli.ts
+++ b/tests/helpers/run-cli.ts
@@ -40,6 +40,7 @@ const RUNTIME_OVERRIDABLE_ENV = [
"OPEN_SECOND_BRAIN_WIKI_LINK_FORMAT",
"OPEN_SECOND_BRAIN_RECALL_GATE_TELEMETRY",
"OPEN_SECOND_BRAIN_BENCH_JUDGE_CMD",
+ "OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT",
] as const;
export async function runCli(
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 3cbd49d6..9bf171d1 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -483,6 +483,47 @@ class ProviderLifecycleTests(unittest.TestCase):
len([1 for n, _ in bridge.calls if n == "brain_pre_compact_extract"]), 1
)
+ def test_on_session_end_clean_close_omits_interrupted_flag(self):
+ bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ provider.sync_turn("u1", "a1", session_id="sess-1")
+ provider._drain_captures()
+ provider.on_session_end([])
+ extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
+ self.assertEqual(len(extract_calls), 1)
+ # A clean close is byte-identical: no interrupted field on the payload.
+ self.assertNotIn("interrupted", extract_calls[0])
+
+ def test_on_session_end_surfaces_interrupted_onto_flush_payload(self):
+ bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ provider.sync_turn("u1", "a1", session_id="sess-1")
+ provider._drain_captures()
+ provider.on_session_end([], interrupted=True)
+ extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
+ self.assertEqual(len(extract_calls), 1)
+ # The interrupted close is recorded honestly on the flushed segment.
+ self.assertIs(extract_calls[0].get("interrupted"), True)
+
+ def test_on_session_end_drains_and_flushes_the_exit_path(self):
+ # Regression for Hermes #49315: the god-file Phase 4 refactor bound the
+ # atexit _active_agent_ref to the mixin module instead of cli.py, so
+ # on_session_end never fired on CLI /exit and end-of-session capture was
+ # silently lost. The hook is native again; this guards the path /exit now
+ # drives by calling on_session_end WITHOUT a prior manual _drain_captures()
+ # — the hook must self-drain the in-flight sync_turn thread and flush.
+ bridge = FakeBrainBridge(results={"brain_pre_compact_extract": {"structuredContent": {}}})
+ provider = self._init(bridge, hermes_home="/tmp/hh")
+ provider.sync_turn("u1", "a1", session_id="sess-1")
+ # No _drain_captures() here: end-of-session capture must work end to end.
+ provider.on_session_end([])
+ extract_calls = [a for n, a in bridge.calls if n == "brain_pre_compact_extract"]
+ self.assertEqual(len(extract_calls), 1)
+ self.assertIn("u1", extract_calls[0]["text"])
+ self.assertIn("a1", extract_calls[0]["text"])
+ # The capture threads were joined: drain ran inside the hook.
+ self.assertEqual(provider._sync_threads, [])
+
def test_on_memory_write_forwards_to_host_bridge_tool(self):
bridge = FakeBrainBridge(
results={"brain_memory_bridge": {"structuredContent": {"recorded": True}}}