Skip to content

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

TypeScript

feat: continuity promote - the host-memory readback path for mirrored host memory writes (v1.94.0) (#278)

Serg Eroshe61a7ff1d7dbc
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index da433b5d..f49101b5 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.93.0",
+ "version": "1.94.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 7ac8a732..4b55a9e3 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.93.0",
+ "version": "1.94.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a437d8c..234df34d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,14 @@ 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.94.0] - 2026-10-26
+
+Open Second Brain 1.94.0 gives the continuity ledger its intended readback path. The Hermes provider's native memory writes have been mirrored into the ledger as durable, attributable records for some time, but the ledger was write-only for recall purposes: a fact the host wrote could be exported for audit and never recalled by the memory system itself. The new `o2b brain continuity promote` verb turns those records into ordinary preference pages, dry-run by default and sealed by an approval digest on apply, so a mirrored fact becomes recallable only through a review that says exactly what will land. The ledger itself stays write-only audit substrate, and the full-fidelity export keeps its job.
+
+### Added
+
+- **Mirrored host memory writes become recallable through an explicit, reviewable promotion verb.** The Hermes provider's native memory writes are mirrored by the `on_memory_write` bridge into the continuity ledger as `host_memory_write` records (`Brain/log/continuity/<YYYY-MM>[.<deviceId>].jsonl`), and until now the only readback was the full-fidelity `brain continuity export`, because the ledger is write-only to the rest of the memory system: the search index admits only Markdown pages, the session grep keeps only session kinds, and the context pack reads the preferences and retired lanes only. `o2b brain continuity promote` (the documented answer to GitHub issue #277) renders each `host_memory_write` record as a preference page under `Brain/preferences/pref-hostmem-<record-id12>.md`, deterministic per record id, so the mirrored fact becomes ordinarily recallable - page search finds it, and the context pack and its confirm flow treat it like any imported host memory. The verb is dry-run by default: it prints the plan - create, update, recreate, skip-unchanged or conflict per record, skips named with reasons, private records dropped and counted, redacted records promoted in masked form and counted - plus a plan digest. A malformed ledger row (a non-canonical createdAt or record id) skips by name and never aborts the run, records with identical content promote once and their later duplicates skip by name, and every record is re-scanned at promotion time under the export door's strict redaction grade - vendor tokens, bare high-entropy tokens, URL credentials - so the masked text is what lands and a credential a host wrote into its memory cannot reach the search index or the context pack through promote. `--apply` writes: an `--approval-digest <hex>` mismatch refuses with nothing written and no snapshot, mirroring the approval semantics of `o2b brain import-claude-memory`; a matching digest takes a snapshot, writes the pages atomically, records the promotion manifest (`Brain/.imports/host-memory-promotions.json`, rewritten only when something was actually applied) and appends a log event, while an interactive apply without a digest lands the current plan and a non-interactive apply must carry the digest; a corrupt promotion manifest is reported by the dry run (`manifest_corrupt: true` under `--json`) and refuses every apply until the operator reconciles the file, and a conflict - a `pref-hostmem-*` page the promotion manifest does not record, left behind by another writer or by a lost manifest, not an edit to a landed page, which is kept and plans skip-unchanged - throws after the safe writes land and exits 2. Pages land under the trial window (`dream.unconfirmed_window_days`): promoted pages start unconfirmed and are confirmed like any other preference, so a poisoned host write never becomes a live rule just by being promoted. `--month YYYY-MM` narrows the source window to one ledger month. No supersession is inferred: a `replace` record promotes as its own page beside the one it superseded, because the ledger never says which record replaced which, and reconciling the pair is the confirm flow's job. The ledger itself stays write-only audit substrate, and the division of labor between the two verbs stays clean: `brain continuity export` answers "what happened", promote answers "make it recallable".
+
## [1.93.0] - 2026-10-23
Open Second Brain 1.93.0 closes the gap between what a configuration promises and what the model, the filesystem and the package manager actually do. The chunker now charges a long whitespace-free run such as a URL at a conservative token rate and splits it across chunks, so the declared budget bounds what the embedding model really receives. Retirement provenance lands in the log shard the device actually writes, so a fresh retirement no longer reads as a broken link. The decision model tries providers in a configured order with automatic fallback inside the existing budgets, and per-model enforce thresholds move out of the source tree into the installation, keyed by the model id the server reports and kept for every model ever tuned. The launchers repair a checkout that a Codex marketplace add or upgrade strips, so the documented install path starts the CLI. The release also closes all twenty-seven findings of the previous release's external review, among them two paths that let marker-private content leave the vault, a quadratic regex on the synchronous write path, a hold rule that withheld fitting chunks from embedding, and a ranking rule that let one entity match outrank higher-scoring results.
@@ -8742,6 +8750,8 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.94.0]: https://github.com/itechmeat/open-second-brain/compare/v1.93.0...v1.94.0
+[1.93.0]: https://github.com/itechmeat/open-second-brain/compare/v1.92.0...v1.93.0
[1.92.0]: https://github.com/itechmeat/open-second-brain/compare/v1.91.0...v1.92.0
[1.91.0]: https://github.com/itechmeat/open-second-brain/compare/v1.90.0...v1.91.0
[1.90.0]: https://github.com/itechmeat/open-second-brain/compare/v1.89.0...v1.90.0
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 73fae6bb..876742c5 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -575,6 +575,7 @@ Trigger generation, brief delivery, and gate telemetry are pull-based or config-
```text
o2b brain continuity export --format atof|atif [--session <id>] [--month YYYY-MM] [--out <dir>] [--json] - read-only trajectory export of the continuity store; private records dropped, redacted text stays masked
+ promote [--month YYYY-MM] [--apply] [--approval-digest <hex>] [--json] - render the host_memory_write continuity records the Hermes bridge mirrors into the ledger as preference pages under Brain/preferences/pref-hostmem-<record-id12>.md, deterministic per record id, so a mirrored fact becomes ordinarily recallable - page search finds it and the context pack and its confirm flow treat it like any imported host memory; dry-run by default, printing the per-record plan (create / update / recreate / skip-unchanged / conflict, skips named with reasons, private records dropped and counted, redacted records promoted masked and counted) plus a plan digest; a malformed ledger row (non-canonical createdAt or record id) skips by name and never aborts the run, and records with identical content promote once, later duplicates skipped by name; every record is re-scanned at promotion time under the export door's strict redaction grade (vendor tokens, bare high-entropy tokens, URL credentials) and the masked text is what lands, so a credential a host wrote into its memory cannot reach the search index or the context pack through promote; --apply lands exactly the approved plan or nothing - a mismatched digest refuses with nothing written and no snapshot, a matching digest takes a snapshot, writes the pages atomically, records the promotion manifest Brain/.imports/host-memory-promotions.json (rewritten only when something was actually applied) and appends a log event, an interactive apply without a digest lands the current plan while a non-interactive one must carry the digest, a corrupt manifest is reported by the dry run (manifest_corrupt: true under --json) and refused by apply until the operator reconciles the file, and a conflict (a pref-hostmem-* page the promotion manifest does not record - another writer created the page or the manifest was lost; an edit to a landed page is not a conflict, the row plans skip-unchanged and the edit is kept) exits 2 after the safe writes land; pages land unconfirmed under the trial window (dream.unconfirmed_window_days) and are confirmed like any other preference; the ledger stays write-only audit substrate - export remains the full-fidelity audit path and promote is the explicit, reviewable readback (since v1.94.0)
o2b brain bench memory --fixture <name|path> [--suite <name>] [--sample-seed <value>] [--sample-cap <n>] [--resume <run-id>] [--runs-dir <dir>] [--json] - memory quality benchmark over a disposable fixture vault; quality, latency, and context cost reported separately; checkpoint/resume by run id; exit 1 on any failed question. Suites (since v1.82.0): longmemeval (strict recall_all@5 over the LongMemEval dataset shape; committed sample fixture, full dataset operator-supplied, judge glue over bench_judge_cmd) and surfacing-replay (replays a recorded prompt corpus through the shipped decision core and scores know_to_ask / false_fire). Sampling (since v1.83.0): --sample-seed plus --sample-cap run a seeded, question-type-proportional subset of the dataset instead of the whole fixture; longmemeval is the only suite that declares the capability
```
diff --git a/install/hermes.md b/install/hermes.md
index fc847af3..1aed9b9c 100644
--- a/install/hermes.md
+++ b/install/hermes.md
@@ -213,6 +213,32 @@ registration line indicates a version older than 1.0.1.
> state and `o2b doctor` for the full readiness suite - together they
> cover the same ground.
+## 6. Recall what Hermes wrote
+
+Hermes built-in memory writes are mirrored into the Open Second Brain
+continuity ledger, and `o2b brain continuity promote` is what makes
+those mirrored facts recallable: each becomes an ordinary preference
+page under `Brain/preferences/`, so page search finds it and the
+context pack and its confirm flow treat it like any imported host
+memory. Promote does not restore Hermes built-in memory - the ledger
+stays the durable copy, and `o2b brain continuity export` remains the
+full-fidelity audit path.
+
+Promote is dry-run by default and writes nothing. Run it, read the
+per-record plan, then apply with the approval digest it prints:
+
+```bash
+o2b brain continuity promote --vault /path/to/vault
+o2b brain continuity promote --vault /path/to/vault --apply \
+ --approval-digest <digest-from-the-dry-run>
+```
+
+`--apply` lands exactly the plan the digest seals or nothing at all; a
+non-interactive apply must carry the digest. Promoted pages land
+unconfirmed and stay under the trial window
+(`dream.unconfirmed_window_days`) until the confirm flow accepts them,
+like any other preference.
+
## Update
```bash
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 5e554bae..82f99d5e 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.93.0",
+ "version": "1.94.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 4e6eed70..05dfe93b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.93.0",
+ "version": "1.94.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 3aaa6dce..498c9b49 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.93.0"
+version: "1.94.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 4bf1ae35..341cdf20 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.93.0",
+ "version": "1.94.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 3aaa6dce..498c9b49 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.93.0"
+version: "1.94.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index b8ee3731..c8c05ae3 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
# `hermes_agent.memory_providers` group, not a CLI script.
[project]
name = "open-second-brain"
-version = "1.93.0"
+version = "1.94.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.ts
index 1f7c0f76..8e65c2ed 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -187,7 +187,7 @@ Brain verbs (observing memory):
extract-signals Mine taste signals from an imported session's user turns (two-phase, needs-llm-step)
design-note One-shot design note grounded in tensions, decisions and truth records
ideas Ranked next-direction candidates from open loops (--triggers to enqueue)
- continuity Export continuity records as ATOF/ATIF trajectories (read-only)
+ continuity Export ATOF/ATIF trajectories, rank records by usage decay, promote host memory writes (export and rank are read-only; promote is dry-run by default)
payload Externalized session payloads: get (paged), list, gc (dry-run by default)
bench Memory quality benchmark over a disposable fixture vault
git Git history as project memory: ingest, status, find, mine
@@ -1428,9 +1428,22 @@ export const VERB_HELP: Record<string, string> = {
"and aging inbox signals. --triggers enqueues the ranked ideas.\n",
continuity:
"usage: o2b brain continuity export --format atof|atif [--session <id>] [--month YYYY-MM] [--out <dir>] [--json]\n" +
+ " o2b brain continuity rank [--kind <kind>] [--limit N] [--all] [--json]\n" +
+ " o2b brain continuity promote [--month YYYY-MM] [--apply] [--approval-digest <hex>] [--json]\n" +
"Read-only trajectory export of the continuity store. atof renders one\n" +
"JSONL event stream; atif renders one trajectory document per session.\n" +
- "Records flagged private are dropped; redacted text stays masked.\n",
+ "Records flagged private are dropped; redacted text stays masked.\n" +
+ "rank lists working-memory continuity records by usage-driven decay\n" +
+ "weight (freshest and most-recalled first; default kind\n" +
+ "pre_compact_extract, --kind narrows, --all ranks every kind).\n" +
+ "promote renders host_memory_write records as unconfirmed preference\n" +
+ "pages under Brain/preferences/pref-hostmem-<record-id12>.md, dry-run\n" +
+ "by default: the per-record plan, named skips and a plan digest print,\n" +
+ "and --apply lands exactly that plan - non-interactively it must carry\n" +
+ "the dry run's --approval-digest. Every record is re-scanned under the\n" +
+ "export door's strict redaction grade and the masked text is what\n" +
+ "lands. The ledger stays write-only audit substrate; export remains\n" +
+ "the full-fidelity audit path.\n",
payload:
"usage: o2b brain payload get <osb-payload://sha256> [--offset N] [--limit N] [--json]\n" +
" o2b brain payload list [--json]\n" +
diff --git a/src/cli/brain/verbs/continuity.ts b/src/cli/brain/verbs/continuity.ts
index d767346b..51478a1c 100644
--- a/src/cli/brain/verbs/continuity.ts
+++ b/src/cli/brain/verbs/continuity.ts
@@ -17,12 +17,25 @@
* export verb redacted them. Write-time coverage also says nothing about
* a record already on disk or appended by another writer: the read model
* never re-scans. Scanning what this verb actually READ answers both.
+ *
+ * The third subcommand, `promote` (issue #277), is the one that writes:
+ * it re-renders `host_memory_write` records as unconfirmed preference
+ * pages through the read-model, dry-run by default, sealed with an
+ * approval digest an apply must carry back.
*/
import { mkdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
+import type { PlannedFile } from "../../../core/brain/claude-memory-plan.ts";
import { loadNormalizedContinuityRecords } from "../../../core/brain/continuity/read-model.ts";
+import { promoteHostMemory } from "../../../core/brain/continuity/promote-host-memory.ts";
+import {
+ PromoteConflictsError,
+ PromoteManifestCorruptError,
+ type PromoteConflictsPartialProgress,
+ type PromoteHostMemoryResult,
+} from "../../../core/brain/continuity/promote-host-memory.ts";
import {
deriveUsageSignals,
rankByUsageDecay,
@@ -44,12 +57,14 @@ const CLI_VERSION: string = OPEN_SECOND_BRAIN_VERSION;
const USAGE =
"usage: o2b brain continuity export --format atof|atif [--session <id>] [--month YYYY-MM] [--out <dir>] [--json]\n" +
- " o2b brain continuity rank [--kind <kind>] [--limit N] [--json]";
+ " o2b brain continuity rank [--kind <kind>] [--limit N] [--json]\n" +
+ " o2b brain continuity promote [--month YYYY-MM] [--apply] [--approval-digest <hex>] [--json]";
export async function cmdBrainContinuity(argv: string[]): Promise<number> {
const subcommand = argv[0];
if (subcommand === "export") return exportContinuity(argv.slice(1));
if (subcommand === "rank") return rankContinuity(argv.slice(1));
+ if (subcommand === "promote") return promoteContinuity(argv.slice(1));
return fail(USAGE);
}
@@ -210,3 +225,244 @@ function previewText(payload: Readonly<Record<string, unknown>>): string {
function safeName(value: string): string {
return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120);
}
+
+/**
+ * `o2b brain continuity promote`: re-render `host_memory_write` records
+ * as unconfirmed preference pages (issue #277). Dry-run by default - it
+ * plans, seals the plan and prints the digest, and writes nothing.
+ * `--apply` lands the plan; non-interactively it must carry the dry
+ * run's digest via `--approval-digest`, exactly as import-claude-memory
+ * does, so what lands is what was reviewed.
+ */
+function promoteContinuity(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ month: { type: "string" },
+ apply: { type: "boolean" },
+ "approval-digest": { type: "string" },
+ json: { type: "boolean" },
+ });
+ const month = typeof flags["month"] === "string" ? flags["month"].trim() : undefined;
+ if (month !== undefined && !/^\d{4}-\d{2}$/.test(month)) {
+ return usageError("brain continuity promote: --month must look like YYYY-MM");
+ }
+ const mode = flags["apply"] === true ? "apply" : "dry-run";
+ const approvalDigest =
+ typeof flags["approval-digest"] === "string" ? flags["approval-digest"].trim() : undefined;
+ // A dry run COMPUTES a digest; it cannot consume one. Refuse the
+ // pairing by name instead of silently dropping the value.
+ if (mode !== "apply" && approvalDigest !== undefined) {
+ return usageError(
+ "brain continuity promote: --approval-digest applies to --apply; " +
+ "a dry run computes a digest, it does not consume one",
+ );
+ }
+ if (mode === "apply" && approvalDigest === undefined && !process.stdin.isTTY) {
+ return usageError(
+ "brain continuity promote: --apply requires --approval-digest in non-interactive " +
+ "mode (run the default dry run first, then apply with the digest it prints)",
+ );
+ }
+
+ const vault = brainVerbContext(flags).vault;
+ const asJson = flags["json"] === true;
+ try {
+ const res = promoteHostMemory({
+ vault,
+ mode,
+ ...(month !== undefined ? { month } : {}),
+ ...(approvalDigest !== undefined ? { approvalDigest } : {}),
+ });
+ if (asJson) process.stdout.write(`${renderPromoteJson(month, res)}\n`);
+ else if (mode === "dry-run") printPromotePlan(res);
+ else {
+ printPromoteApply(
+ res.applied,
+ res.skipped,
+ res.skippedUnchanged,
+ res.snapshotRunId,
+ res.redactedCount,
+ res.privateCount,
+ res.total,
+ res.conflicts,
+ );
+ }
+ if (res.manifestCorrupt) printManifestCorruptWarning();
+ return 0;
+ } catch (err) {
+ if (err instanceof PromoteConflictsError) {
+ // The safe writes already landed; report the applied progress, then
+ // the conflicts, and exit 2.
+ const partial = err.partial;
+ if (asJson && partial !== null) {
+ process.stdout.write(`${renderPromotePartialJson(month, partial, err.conflicts)}\n`);
+ } else {
+ if (partial !== null) {
+ printPromoteApply(
+ partial.applied,
+ partial.skipped,
+ partial.skippedUnchanged,
+ partial.snapshotRunId,
+ partial.redactedCount,
+ partial.privateCount,
+ partial.total,
+ err.conflicts,
+ );
+ }
+ process.stderr.write("conflicts:\n");
+ for (const c of err.conflicts) {
+ process.stderr.write(
+ ` ${c.prefId} already exists in Brain but is not in ` +
+ `Brain/.imports/host-memory-promotions.json (${c.basename})\n`,
+ );
+ }
+ }
+ return 2;
+ }
+ if (err instanceof PromoteManifestCorruptError) {
+ return fail(`brain continuity promote: ${(err as Error).message}`);
+ }
+ return fail(`brain continuity promote: ${(err as Error).message}`);
+ }
+}
+
+function renderPromoteJson(month: string | undefined, res: PromoteHostMemoryResult): string {
+ return renderPromoteEnvelope({
+ mode: res.mode,
+ month,
+ total: res.total,
+ plans: res.plans,
+ applied: res.applied,
+ skipped: res.skipped,
+ skippedUnchanged: res.skippedUnchanged,
+ conflicts: res.conflicts,
+ redactedCount: res.redactedCount,
+ privateCount: res.privateCount,
+ manifestCorrupt: res.manifestCorrupt,
+ digest: res.digest,
+ snapshotRunId: res.snapshotRunId,
+ });
+}
+
+/**
+ * The one JSON envelope every promote exit spells: the same key set on
+ * the dry run, the clean apply and the conflict path, with `conflicts`
+ * always present (empty when none) and `plans` carrying the full plan
+ * even when the run stopped at exit 2 - a consumer keying on `plans`
+ * must not read zero rows off a partial run, and one keying on
+ * `conflicts` must not meet the key only on that path.
+ */
+function renderPromoteEnvelope(parts: {
+ mode: string;
+ month: string | undefined;
+ total: number;
+ plans: ReadonlyArray<PlannedFile>;
+ applied: ReadonlyArray<PlannedFile>;
+ skipped: ReadonlyArray<{ id: string; reason: string }>;
+ skippedUnchanged: ReadonlyArray<PlannedFile>;
+ conflicts: ReadonlyArray<PlannedFile>;
+ redactedCount: number;
+ privateCount: number;
+ manifestCorrupt: boolean;
+ digest: string;
+ snapshotRunId: string | null;
+}): string {
+ return JSON.stringify(
+ {
+ mode: parts.mode,
+ month: parts.month ?? null,
+ total: parts.total,
+ counts: {
+ plans: parts.plans.length,
+ applied: parts.applied.length,
+ skipped: parts.skipped.length,
+ skipped_unchanged: parts.skippedUnchanged.length,
+ conflicts: parts.conflicts.length,
+ private_dropped: parts.privateCount,
+ redacted: parts.redactedCount,
+ },
+ manifest_corrupt: parts.manifestCorrupt,
+ digest: parts.digest,
+ snapshot: parts.snapshotRunId,
+ plans: parts.plans.map((p) => ({ id: p.basename, pref_id: p.prefId, action: p.action })),
+ skipped: parts.skipped.map((s) => ({ id: s.id, reason: s.reason })),
+ applied: parts.applied.map((p) => ({ id: p.basename, pref_id: p.prefId, action: p.action })),
+ conflicts: parts.conflicts.map((p) => ({
+ id: p.basename,
+ pref_id: p.prefId,
+ action: p.action,
+ })),
+ },
+ null,
+ 2,
+ );
+}
+
+function renderPromotePartialJson(
+ month: string | undefined,
+ partial: PromoteConflictsPartialProgress,
+ conflicts: PromoteConflictsError["conflicts"],
+): string {
+ return renderPromoteEnvelope({
+ mode: "apply",
+ month,
+ total: partial.total,
+ plans: partial.plans,
+ applied: partial.applied,
+ skipped: partial.skipped,
+ skippedUnchanged: partial.skippedUnchanged,
+ conflicts,
+ redactedCount: partial.redactedCount,
+ privateCount: partial.privateCount,
+ manifestCorrupt: partial.manifestCorrupt,
+ digest: partial.digest,
+ snapshotRunId: partial.snapshotRunId,
+ });
+}
+
+function printManifestCorruptWarning(): void {
+ process.stderr.write(
+ "warning: Brain/.imports/host-memory-promotions.json could not be read as the " +
+ "manifest shape - this plan was computed against an empty history and --apply " +
+ "refuses until the file is reconciled\n",
+ );
+}
+
+function printPromotePlan(res: PromoteHostMemoryResult): void {
+ process.stdout.write(
+ `promote plan: ${res.plans.length} actionable, ${res.skipped.length} skipped\n`,
+ );
+ if (res.privateCount > 0 || res.redactedCount > 0) {
+ process.stdout.write(
+ ` saw ${res.total} record(s): ${res.privateCount} private dropped, ` +
+ `${res.redactedCount} redacted (masked text promoted)\n`,
+ );
+ }
+ process.stdout.write(`approval-digest: ${res.digest}\n`);
+ for (const p of res.plans) process.stdout.write(` ${p.action} ${p.prefId} (${p.basename})\n`);
+ for (const s of res.skipped) process.stdout.write(` SKIP ${s.id}: ${s.reason}\n`);
+}
+
+function printPromoteApply(
+ applied: ReadonlyArray<{ prefId: string }>,
+ skipped: ReadonlyArray<{ id: string; reason: string }>,
+ skippedUnchanged: ReadonlyArray<unknown>,
+ snapshotRunId: string | null,
+ redactedCount: number,
+ privateCount: number,
+ total: number,
+ conflicts: ReadonlyArray<unknown>,
+): void {
+ process.stdout.write(
+ `applied: ${applied.length}; unchanged: ${skippedUnchanged.length}; skipped: ${skipped.length}\n`,
+ );
+ if (privateCount > 0 || redactedCount > 0) {
+ process.stdout.write(
+ ` saw ${total} record(s): ${privateCount} private dropped, ` +
+ `${redactedCount} redacted (masked text promoted)\n`,
+ );
+ }
+ if (snapshotRunId) process.stdout.write(`snapshot: ${snapshotRunId}\n`);
+ for (const s of skipped) process.stdout.write(` SKIP ${s.id}: ${s.reason}\n`);
+ if (conflicts.length > 0) process.stdout.write(`conflicts: ${conflicts.length}\n`);
+}
diff --git a/src/core/brain/claude-memory-render.ts b/src/core/brain/claude-memory-render.ts
index fe7ca720..f1f66b4d 100644
--- a/src/core/brain/claude-memory-render.ts
+++ b/src/core/brain/claude-memory-render.ts
@@ -16,6 +16,27 @@ export interface RenderMemoryInput {
readonly bodySha256: string;
/** Owner token for the rendered page; omitted renders no `owner:`. */
readonly owner?: string | undefined;
+ /**
+ * First line of the rendered Origin section. Defaults to the Claude
+ * Code MEMORY label, byte-identical to the pre-field output; a caller
+ * that renders from a different substrate (the continuity ledger's
+ * host-memory promotion) passes its own so the page never claims a
+ * source it did not come from.
+ */
+ readonly originLabel?: string;
+ /**
+ * The name the page's IDENTITY derives from (the `id:` frontmatter and
+ * the `topic` tag, both slugified). Defaults to `name`, byte-identical
+ * to the import, where the display name and the identity are the same
+ * string. A caller whose target filename is keyed by something other
+ * than the display name - the continuity ledger's host-memory
+ * promotion, whose pages are named after the record id so the target
+ * never moves - passes its stable identity here and keeps its display
+ * text in `name`; a mismatched `id:` and basename would otherwise send
+ * every id-keyed lookup (evidence appends, confirmation) to a page
+ * that does not exist.
+ */
+ readonly identityName?: string;
}
/**
@@ -53,7 +74,7 @@ function isoDay(iso: string): string {
}
export function renderPreferenceFromMemory(input: RenderMemoryInput): string {
- const slug = slugifyMemoryName(input.name);
+ const slug = slugifyMemoryName(input.identityName ?? input.name);
if (!slug) {
// Punctuation-only / whitespace-only names produce an empty slug,
// which would yield the bare `pref-` id and a blank `topic:` field.
@@ -110,7 +131,7 @@ export function renderPreferenceFromMemory(input: RenderMemoryInput): string {
"",
"## Origin",
"",
- "Imported from Claude Code MEMORY:",
+ input.originLabel ?? "Imported from Claude Code MEMORY:",
`\`${input.memoryPath}\``,
`on ${isoDay(input.importedAt)}.`,
"",
diff --git a/src/core/brain/continuity/promote-host-memory.ts b/src/core/brain/continuity/promote-host-memory.ts
new file mode 100644
index 00000000..09591c55
--- /dev/null
+++ b/src/core/brain/continuity/promote-host-memory.ts
@@ -0,0 +1,645 @@
+/**
+ * `o2b brain continuity promote` - the host-memory readback path
+ * (issue #277).
+ *
+ * `host_memory_write` records land in the continuity ledger as a durable,
+ * write-only substrate: nothing read them back for recall. The search
+ * index admits only `.md`, the brain grep surface keeps session kinds,
+ * and the context pack reads preferences and retired pages. This module
+ * is the explicit, reviewable readback: it re-renders ledger rows as
+ * unconfirmed preference pages under the same trial window every
+ * first-party unconfirmed write observes, so a mirrored host fact becomes
+ * recallable like any other preference and the dream pass reviews it like
+ * any other candidate.
+ *
+ * The direction of authority is one-way and stated plainly: the ledger
+ * stays the durable substrate and is never rewritten or pruned by a
+ * promotion; the pages are a derived mirror whose provenance names the
+ * shard and the record each was rendered from. `brain continuity export`
+ * remains the full-fidelity audit path - it hands the same rows out
+ * whole, where a promotion lands only their rendered projection.
+ *
+ * No supersession is inferred: the bridge never says which record
+ * replaced which, so a `replace` action promotes as its own page beside
+ * the one it superseded, and reconciling the two is the confirm/retire
+ * flow's job, not this verb's guess.
+ *
+ * The module walks the same plan/seal/apply machinery as the Claude
+ * memory import: `planAction` for
+ * CREATE/UPDATE/RECREATE/SKIP_UNCHANGED/CONFLICT, a sealed approval
+ * digest so an apply lands exactly the plan an operator reviewed, a
+ * snapshot before the first write, and the evidence-preserving merge on
+ * UPDATE (shared from `import-claude-memory.ts`).
+ *
+ * Two doors onto the store, deliberately (provenance-at-the-boundary):
+ * the read-model supplies the promotion payload under the masking policy
+ * - `private` records are dropped and never reach a page - while the raw
+ * store door counts what the policy dropped, so the report states how
+ * many records it did not see instead of silently shortening the run.
+ */
+
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { resolveAgentName } from "../../config.ts";
+import { EGRESS_REDACTION_OPTIONS } from "../../egress/guard.ts";
+import { redactStructured } from "../../redactor.ts";
+import { digestVerifies, sealWithDigest, sha256Hex } from "../../integrity/digest.ts";
+import { loadBrainConfig } from "../policy.ts";
+import { DEFAULT_BRAIN_CONFIG } from "../policy/defaults.ts";
+import { mergePreservingEvidence } from "../import-claude-memory.ts";
+import {
+ loadPromotionsManifest,
+ savePromotionsManifest,
+ type HostMemoryPromotionEntry,
+} from "../host-memory-promotions.ts";
+import { appendLogEvent } from "../log.ts";
+import { BRAIN_PREFERENCES_REL, preferencePath, retiredPath, vaultRelative } from "../paths.ts";
+import { planAction, type PlannedFile } from "../claude-memory-plan.ts";
+import { renderPreferenceFromMemory, slugifyMemoryName } from "../claude-memory-render.ts";
+import { resolvedOwnerFor } from "../preference.ts";
+import { createSnapshot } from "../snapshot.ts";
+import { TagSyntaxError } from "../tag-syntax.ts";
+import { isoSecond } from "../time.ts";
+import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "../types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
+import { HOST_MEMORY_WRITE_KIND } from "../host-memory-write.ts";
+import { loadNormalizedContinuityRecords } from "./read-model.ts";
+import { continuityLogPath, isCanonicalUtcTimestamp, listContinuityRecords } from "./store.ts";
+
+export interface PromoteHostMemoryOpts {
+ readonly vault: string;
+ readonly mode: "dry-run" | "apply";
+ /** Restrict the readback to one UTC month (`YYYY-MM`), as the export verb spells it. */
+ readonly month?: string;
+ /**
+ * The plan digest a dry run computed and an operator approved (the CLI
+ * plumbing is `--approval-digest`). Absent, apply behaves exactly as it
+ * did before approval digests existed - the interactive path's escape
+ * hatch. Present, it is checked against the freshly computed plan
+ * BEFORE the snapshot or any write, and a mismatch is a
+ * {@link PromoteApprovalDigestError} that leaves the vault untouched.
+ */
+ readonly approvalDigest?: string;
+ readonly now?: Date;
+}
+
+export interface PromoteHostMemoryResult {
+ readonly mode: "dry-run" | "apply";
+ /** Raw `host_memory_write` rows the window holds, private rows included. */
+ readonly total: number;
+ readonly plans: ReadonlyArray<PlannedFile>;
+ readonly skipped: ReadonlyArray<{ id: string; reason: string }>;
+ readonly conflicts: ReadonlyArray<PlannedFile>;
+ readonly applied: ReadonlyArray<PlannedFile>;
+ readonly skippedUnchanged: ReadonlyArray<PlannedFile>;
+ /** Records that land in masked form: write-time redaction or the strict re-scan. */
+ readonly redactedCount: number;
+ /** Records the read-model dropped as private, counted through the store door. */
+ readonly privateCount: number;
+ /**
+ * True when the promotion sidecar exists but could not be read as the
+ * manifest shape: the plan was computed against an empty history, every
+ * landed page will show as CONFLICT, and an apply refuses until the
+ * operator reconciles the file.
+ */
+ readonly manifestCorrupt: boolean;
+ readonly snapshotRunId: string | null;
+ readonly localDate: string;
+ /**
+ * The seal of the promotion plan: sha256 of the plans, skips, conflicts
+ * and unchanged rows - each plan row bound to the sha256 of its source
+ * record's content and of its rendered body, clock fields normalized
+ * out of the latter (see {@link SEAL_RENDER_CLOCK}) - via the integrity
+ * module's `sealWithDigest`. Wall-clock fields (`localDate`, the
+ * promotion timestamps) are deliberately OUTSIDE the sealed body, so a
+ * dry run and a later apply of the same content seal identically and an
+ * approval binds the plan, never the moment it was printed.
+ */
+ readonly digest: string;
+}
+
+/**
+ * A plan row's content binding, sealed alongside the row: the sha256 of
+ * the source record's content and the sha256 of the RENDERED preference
+ * body the row would land, rendered under a fixed clock so the seal stays
+ * wall-clock-free.
+ */
+interface PromotedRowSeal {
+ readonly content_sha256: string;
+ readonly body_sha256: string;
+}
+
+/**
+ * The fixed clock the seal's render runs under. The rendered body embeds
+ * the run's clock (`created_at`, `unconfirmed_until`, `_imported_at`, the
+ * prose day); sealed as-written, a dry run and its later apply would seal
+ * differently on every tick and the approval could never carry. Re-
+ * rendered with both clock inputs pinned to this constant, the same
+ * content produces the same seal body whenever it is planned - while a
+ * source record whose content changed between the two runs still changes
+ * the rendered body, which is the binding the approval exists for.
+ */
+const SEAL_RENDER_CLOCK = "1970-01-01T00:00:00Z";
+
+/**
+ * The body an approval covers: what will land, what will not, and what
+ * refuses. The one spelling of "the plan", shared by the dry run that
+ * seals it and the apply that re-checks it. Each plan row carries its
+ * content binding ({@link PromotedRowSeal}) so a record whose content
+ * changed after the approved dry run no longer verifies, even when its
+ * plan action would come out the same.
+ */
+function planApprovalBody(parts: {
+ plans: ReadonlyArray<PlannedFile>;
+ skipped: ReadonlyArray<{ id: string; reason: string }>;
+ conflicts: ReadonlyArray<PlannedFile>;
+ skippedUnchanged: ReadonlyArray<PlannedFile>;
+ seals: ReadonlyMap<string, PromotedRowSeal>;
+}): Record<string, unknown> {
+ return {
+ conflicts: parts.conflicts,
+ plans: parts.plans.map((plan) => {
+ const seal = parts.seals.get(plan.basename);
+ return {
+ id: plan.basename,
+ pref_id: plan.prefId,
+ action: plan.action,
+ content_sha256: seal?.content_sha256 ?? null,
+ body_sha256: seal?.body_sha256 ?? null,
+ };
+ }),
+ skipped: parts.skipped,
+ skipped_unchanged: parts.skippedUnchanged,
+ };
+}
+
+/**
+ * The apply-time refusal when the plan an operator approved no longer
+ * matches the plan this run computed. Nothing has been written and no
+ * snapshot has been taken; the remedy is a fresh dry run, whose digest
+ * is what the next apply must carry.
+ */
+export class PromoteApprovalDigestError extends Error {
+ /** The digest the caller asked to apply against. */
+ readonly approvalDigest: string;
+ /** The digest of the plan this run just computed. */
+ readonly planDigest: string;
+
+ constructor(approvalDigest: string, planDigest: string) {
+ super(
+ `approval digest mismatch: the plan changed since the approved dry run ` +
+ `(approved ${approvalDigest}, current plan ${planDigest}); nothing was written and ` +
+ "no snapshot was taken. Re-run `o2b brain continuity promote` (the default is the " +
+ "dry run) to review the current plan, then apply with its digest.",
+ );
+ this.name = "PromoteApprovalDigestError";
+ this.approvalDigest = approvalDigest;
+ this.planDigest = planDigest;
+ }
+}
+
+/**
+ * The apply-time refusal while the promotion sidecar is unreadable. Every
+ * landed page would plan CONFLICT against the empty history and a save
+ * would flatten whatever was still recoverable; the remedy is operator
+ * reconciliation of the file, not a write over it.
+ */
+export class PromoteManifestCorruptError extends Error {
+ constructor() {
+ super(
+ "the promotion manifest Brain/.imports/host-memory-promotions.json exists but could " +
+ "not be read as the manifest shape, so the promotion history is unavailable and the " +
+ "apply refuses. Inspect and reconcile the file (every promoted page names its record " +
+ "id in the Origin section), or remove it to rebuild the history from scratch - a " +
+ "rebuild plans CONFLICT for every landed page, which is the review that keeps another " +
+ "writer's page from being overwritten.",
+ );
+ this.name = "PromoteManifestCorruptError";
+ }
+}
+
+export interface PromoteConflictsPartialProgress {
+ readonly total: number;
+ readonly plans: ReadonlyArray<PlannedFile>;
+ readonly applied: ReadonlyArray<PlannedFile>;
+ readonly skipped: ReadonlyArray<{ id: string; reason: string }>;
+ readonly skippedUnchanged: ReadonlyArray<PlannedFile>;
+ readonly redactedCount: number;
+ readonly privateCount: number;
+ readonly manifestCorrupt: boolean;
+ readonly snapshotRunId: string | null;
+ readonly localDate: string;
+ readonly digest: string;
+}
+
+export class PromoteConflictsError extends Error {
+ readonly conflicts: ReadonlyArray<PlannedFile>;
+ readonly partial: PromoteConflictsPartialProgress | null;
+ constructor(
+ conflicts: ReadonlyArray<PlannedFile>,
+ partial: PromoteConflictsPartialProgress | null = null,
+ ) {
+ super(`promote-host-memory: ${conflicts.length} conflict(s)`);
+ this.conflicts = conflicts;
+ this.partial = partial;
+ }
+}
+
+/** Longest head of a record id kept in a target slug. */
+const SLUG_REF_CHARS = 12;
+
+/**
+ * The stable short ref a record contributes to its target slug: the tail
+ * of the id, lowercased. The TAIL, not the head the way a filename slug
+ * is cut - a continuity id spells `ctn_<timestamp digits>_<content hash>`,
+ * so its first twelve characters are the UTC day plus the `ctn_` prefix
+ * and every record written on one day would slug-collide onto a single
+ * preference page, planning CONFLICT for each promotion after the first.
+ * The hash tail is content-derived and unique per record in practice.
+ */
+function slugRef(recordId: string): string {
+ return recordId.slice(-SLUG_REF_CHARS).toLowerCase();
+}
+
+/** Longest head of a line kept in a rendered name or description. */
+function headLine(line: string, maxChars: number): string {
+ return line.length > maxChars ? line.slice(0, maxChars) : line;
+}
+
+/**
+ * The provenance string a promoted page carries for its source: the
+ * month shard's vault-relative path, in the non-sharded spelling. The
+ * record may physically sit in a per-device `<month>.<deviceId>.jsonl`
+ * file, but the store merges every shard of the month and the page
+ * provenance stays stable across devices by naming the month, not this
+ * device's file.
+ */
+function ledgerShardRef(vault: string, createdAt: string): string {
+ return vaultRelative(continuityLogPath(vault, createdAt.slice(0, 7), ""), vault);
+}
+
+export function promoteHostMemory(opts: PromoteHostMemoryOpts): PromoteHostMemoryResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // dry-run form writes nothing, so it stays a read and is not gated -
+ // guarding a preview would refuse the very inspection an operator
+ // runs to decide whether the resolved vault is the intended one.
+ if (opts.mode === "apply") assertVaultIdentityForWrite(opts.vault);
+ const now = opts.now ?? new Date();
+ const promotedAt = isoSecond(now);
+ const localDate = promotedAt.slice(0, 10);
+ // Every promotion lands under trial, on the same source as every
+ // first-party unconfirmed write (`dream.unconfirmed_window_days`),
+ // read fail-soft: host memory is agent-writable from conversation
+ // content, so a poisoned entry must not become a live rule on landing.
+ const unconfirmedUntil = isoSecond(addDays(now, unconfirmedWindowDays(opts.vault)));
+ // The same window spelling the export verb builds for --month.
+ const window =
+ opts.month !== undefined
+ ? { since: `${opts.month}-01`, until: `${opts.month}-31T23:59:59.999Z` }
+ : {};
+
+ const records = loadNormalizedContinuityRecords(opts.vault, {
+ kind: HOST_MEMORY_WRITE_KIND,
+ ...window,
+ });
+ const rawRows = listContinuityRecords(opts.vault, {
+ kind: HOST_MEMORY_WRITE_KIND,
+ ...window,
+ });
+ const privateCount = rawRows.filter((record) => record.private === true).length;
+
+ const manifest = loadPromotionsManifest(opts.vault);
+ const newPromotions: Record<string, HostMemoryPromotionEntry> = { ...manifest.promotions };
+
+ const plans: PlannedFile[] = [];
+ const skipped: Array<{ id: string; reason: string }> = [];
+ const filesToWrite: Array<{ plan: PlannedFile; body: string; sha256: string; slug: string }> = [];
+ // The content binding per plan row, keyed by the row's record id: the
+ // record content's sha256 and the rendered body's sha256 (clock fields
+ // normalized out). Every plan row is pushed immediately after its
+ // render, so every row the seal below reads has an entry here.
+ const rowSeals = new Map<string, PromotedRowSeal>();
+ // Target slugs already claimed this run, so two records whose ids
+ // share a hash tail cannot plan onto one page where the second
+ // atomic write would silently overwrite the first.
+ const seenTargets = new Map<string, string>();
+ // Content shas already spoken for - by the sidecar (a landed page) or
+ // by a row planned earlier this run. The record id hashes createdAt
+ // (store.ts recordId), so the same memory text written in three
+ // sessions is three records; only the first may become a page, or the
+ // context pack fills with duplicates that each run their own trial.
+ const seenContentSha = new Map<string, string>();
+ for (const [id, entry] of Object.entries(manifest.promotions)) {
+ seenContentSha.set(entry.sha256, id);
+ }
+ let redactedCount = 0;
+
+ for (const record of records) {
+ // Fail-soft per row, the way the read model is: a hand-edited or
+ // foreign-written ledger row must never block every promotion. The
+ // canonical checks also pin the slug story - the filename, the
+ // retired-page guard and the frontmatter identity all derive from
+ // the id tail, and a tail that slugifies differently than it reads
+ // would land a page whose `id:` does not answer for it.
+ if (!isCanonicalUtcTimestamp(record.createdAt)) {
+ skipped.push({ id: record.id, reason: "non-canonical createdAt" });
+ continue;
+ }
+ if (!/^ctn_\d{14}_[0-9a-f]{16}$/.test(record.id)) {
+ skipped.push({ id: record.id, reason: "non-canonical record id" });
+ continue;
+ }
+ const content = record.payload["content"];
+ if (typeof content !== "string") {
+ skipped.push({ id: record.id, reason: "content is not text" });
+ continue;
+ }
+ if (content.trim().length === 0) {
+ skipped.push({ id: record.id, reason: "empty content" });
+ continue;
+ }
+ // The strict re-scan (issue #277 review H1): the ledger redacts at
+ // write time under the loose defaults, so a vendor key, a bare
+ // high-entropy token or a user:pass@host URL can sit in a row whose
+ // `redacted` flag is false, and the read model never re-scans. A
+ // promotion moves the text into the indexed corpus, where the export
+ // door's own header documents what would happen to it. The MASKED
+ // text is what lands - the fact stays recallable, the credential
+ // does not leave the shape the write-time scan left or the scan
+ // produces here.
+ const scanned = redactStructured(content, EGRESS_REDACTION_OPTIONS);
+ const safeContent = scanned.value;
+ if (typeof safeContent !== "string" || safeContent.trim().length === 0) {
+ skipped.push({ id: record.id, reason: "content is empty after redaction" });
+ continue;
+ }
+ const masked = scanned.redacted;
+ if (masked || record.redacted === true) redactedCount += 1;
+ const contentSha256 = sha256Hex(safeContent);
+ const sameAs = seenContentSha.get(contentSha256);
+ if (sameAs !== undefined && sameAs !== record.id) {
+ skipped.push({ id: record.id, reason: `same content as record ${sameAs}` });
+ continue;
+ }
+ seenContentSha.set(contentSha256, record.id);
+ const ref = slugRef(record.id);
+ // Defence in depth over the canonical-id check above: the slug the
+ // renderer derives from `identityName` must be the slug every
+ // consumer (filename, retired guard, manifest) computes, whatever
+ // the tail contains.
+ const slug = slugifyMemoryName(`hostmem-${ref}`);
+ if (slug.length <= "hostmem-".length) {
+ skipped.push({ id: record.id, reason: "record id produces no slug" });
+ continue;
+ }
+ const prefId = `pref-${slug}`;
+ const seenBy = seenTargets.get(slug);
+ if (seenBy !== undefined) {
+ skipped.push({
+ id: record.id,
+ reason: `target ${prefId} is already claimed by record ${seenBy}`,
+ });
+ continue;
+ }
+ const prefFile = preferencePath(opts.vault, slug);
+ if (existsSync(retiredPath(opts.vault, slug))) {
+ // A deliberately retired page must not resurrect through a
+ // re-run of the promotion: the retirement outlives the record.
+ skipped.push({
+ id: record.id,
+ reason: `a retired copy exists (${vaultRelative(retiredPath(opts.vault, slug), opts.vault)}); restore or delete it first`,
+ });
+ continue;
+ }
+ seenTargets.set(slug, record.id);
+ // The page's identity (`id:` frontmatter, `topic` tag, and the
+ // filename) is the stable record-derived slug; the memory's own
+ // first line is display text, carried by the `principle` field -
+ // not the identity, which would move with every rewording.
+ const firstLine =
+ safeContent
+ .split("\n")
+ .map((line) => line.trim())
+ .find((line) => line.length > 0) ?? "";
+ const memoryPath = ledgerShardRef(opts.vault, record.createdAt);
+ const renderInput = {
+ name: headLine(firstLine, 60) || `Host memory ${ref}`,
+ identityName: slug,
+ description: headLine(firstLine, 100),
+ body: safeContent,
+ memoryPath,
+ importedAt: promotedAt,
+ unconfirmedUntil,
+ bodySha256: contentSha256,
+ owner: resolvedOwnerFor(opts.vault, prefFile, undefined, undefined),
+ originLabel: `Promoted from host memory write \`${record.id}\` in the continuity ledger:`,
+ };
+ // Render BEFORE any plan row exists. A render that refuses THIS
+ // record - a purely numeric first line fails the one shared tag rule -
+ // is a per-record data problem: it lands a named skip row (record and
+ // rule both named) and the promotion continues.
+ let body: string;
+ try {
+ body = renderPreferenceFromMemory(renderInput);
+ } catch (err) {
+ if (!(err instanceof TagSyntaxError)) throw err;
+ skipped.push({ id: record.id, reason: err.message });
+ continue;
+ }
+ rowSeals.set(record.id, {
+ content_sha256: contentSha256,
+ // The seal's render of the SAME record under a fixed clock: the
+ // approval covers the content, never the moment.
+ body_sha256: sha256Hex(
+ renderPreferenceFromMemory({
+ ...renderInput,
+ importedAt: SEAL_RENDER_CLOCK,
+ unconfirmedUntil: SEAL_RENDER_CLOCK,
+ }),
+ ),
+ });
+ const manifestEntry = manifest.promotions[record.id];
+ const plan = planAction({
+ basename: record.id,
+ prefId,
+ sha256: contentSha256,
+ inManifest: manifestEntry ? { sha256: manifestEntry.sha256 } : null,
+ prefExists: existsSync(prefFile),
+ });
+ plans.push(plan);
+ if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {
+ filesToWrite.push({ plan, body, sha256: contentSha256, slug });
+ }
+ }
+
+ const conflicts = plans.filter((p) => p.action === "CONFLICT");
+ const skippedUnchanged = plans.filter((p) => p.action === "SKIP_UNCHANGED");
+
+ // Seal the promotion plan. The apply below re-checks the operator's
+ // approval against THIS seal before the snapshot or any write, so what
+ // lands is what was approved or nothing is.
+ const approvalBody = planApprovalBody({
+ plans,
+ skipped,
+ conflicts,
+ skippedUnchanged,
+ seals: rowSeals,
+ });
+ const planDigest = sealWithDigest(approvalBody).digest;
+
+ if (opts.mode === "dry-run") {
+ return {
+ mode: "dry-run",
+ total: rawRows.length,
+ plans,
+ skipped,
+ conflicts,
+ applied: [],
+ skippedUnchanged,
+ redactedCount,
+ privateCount,
+ manifestCorrupt: manifest.corrupt,
+ snapshotRunId: null,
+ localDate,
+ digest: planDigest,
+ };
+ }
+
+ // The approved plan is checked against the one just computed BEFORE
+ // the snapshot/write loop. Drift between dry run and apply is the case
+ // this exists for: a ledger that moved in between must be re-reviewed,
+ // never written over.
+ if (opts.approvalDigest !== undefined && !digestVerifies(approvalBody, opts.approvalDigest)) {
+ throw new PromoteApprovalDigestError(opts.approvalDigest, planDigest);
+ }
+
+ // A corrupt sidecar means the plan was computed against an empty
+ // history: every landed page would show CONFLICT and a save would
+ // flatten a file that was mostly recoverable. Refuse before the
+ // snapshot; reconciliation is the operator's move.
+ if (manifest.corrupt) {
+ throw new PromoteManifestCorruptError();
+ }
+
+ // Process the non-conflict records first; throw `PromoteConflictsError`
+ // at the end if any CONFLICT was detected, so the applied side of the
+ // run still landed. The caller (CLI) uses the thrown error to exit 2.
+ let snapshotRunId: string | null = null;
+ if (filesToWrite.length > 0) {
+ // The run-id prefix and the recorded reason are one constant, so the
+ // archive's filename can never disagree with its stamped provenance.
+ const runId = `${BRAIN_SNAPSHOT_REASON.promoteHostMemory}-${promotedAt.replace(/:/g, "-")}`;
+ createSnapshot(opts.vault, runId, {
+ reason: BRAIN_SNAPSHOT_REASON.promoteHostMemory,
+ now,
+ });
+ snapshotRunId = runId;
+ }
+
+ const applied: PlannedFile[] = [];
+ if (filesToWrite.length > 0) {
+ mkdirSync(join(opts.vault, BRAIN_PREFERENCES_REL), { recursive: true });
+ }
+ for (const { plan, body: freshBody, sha256, slug } of filesToWrite) {
+ const prefFile = preferencePath(opts.vault, slug);
+ let finalBody = freshBody;
+ if (plan.action === "UPDATE") {
+ // Preserve evidence fields by merging frontmatter.
+ finalBody = mergePreservingEvidence(readFileSync(prefFile, "utf8"), freshBody);
+ }
+ atomicWriteFileSync(prefFile, finalBody);
+ newPromotions[plan.basename] = { pref_id: plan.prefId, sha256, promoted_at: promotedAt };
+ applied.push(plan);
+ }
+
+ // The manifest is persisted only when something was applied: a
+ // conflict-only run would otherwise rewrite the file (a corrupt one to
+ // the empty set) without landing a page. The log event still records a
+ // conflict-only run, so the no-op bloat concern is about the sidecar,
+ // not the ledger.
+ if (applied.length > 0) {
+ savePromotionsManifest(opts.vault, { version: 1, promotions: newPromotions });
+ }
+ const didSomething = applied.length > 0 || conflicts.length > 0;
+ if (didSomething) {
+ const counts = {
+ created: plans.filter((p) => p.action === "CREATE").length,
+ updated: plans.filter((p) => p.action === "UPDATE").length,
+ recreated: plans.filter((p) => p.action === "RECREATE").length,
+ skipped_unchanged: skippedUnchanged.length,
+ skipped: skipped.length,
+ conflicts: conflicts.length,
+ };
+ appendLogEvent(opts.vault, {
+ timestamp: promotedAt,
+ eventType: BRAIN_LOG_EVENT_KIND.promoteHostMemory,
+ body: {
+ created: String(counts.created),
+ updated: String(counts.updated),
+ recreated: String(counts.recreated),
+ skipped_unchanged: String(counts.skipped_unchanged),
+ skipped: String(counts.skipped),
+ conflicts: String(counts.conflicts),
+ private_dropped: String(privateCount),
+ redacted: String(redactedCount),
+ snapshot: snapshotRunId ?? "none",
+ agent: resolveAgentName(),
+ },
+ });
+ }
+
+ if (conflicts.length > 0) {
+ // Throw AFTER landing the safe writes so partial progress is
+ // preserved. The error carries the conflict list and the run's
+ // progress; the CLI prints them and exits 2.
+ throw new PromoteConflictsError(conflicts, {
+ total: rawRows.length,
+ plans,
+ applied,
+ skipped,
+ skippedUnchanged,
+ redactedCount,
+ privateCount,
+ manifestCorrupt: manifest.corrupt,
+ snapshotRunId,
+ localDate,
+ digest: planDigest,
+ });
+ }
+
+ return {
+ mode: "apply",
+ total: rawRows.length,
+ plans,
+ skipped,
+ conflicts,
+ applied,
+ skippedUnchanged,
+ redactedCount,
+ privateCount,
+ manifestCorrupt: manifest.corrupt,
+ snapshotRunId,
+ localDate,
+ digest: planDigest,
+ };
+}
+
+function addDays(date: Date, days: number): Date {
+ return new Date(date.getTime() + days * 24 * 60 * 60 * 1000);
+}
+
+/**
+ * The trial window a promotion grants, in days. Same source as every
+ * first-party unconfirmed write (`dream.unconfirmed_window_days`), read
+ * fail-soft for the same reason the import's is: a vault with no
+ * readable `_brain.yaml` still gets the shipped default, not a live rule.
+ */
+function unconfirmedWindowDays(vault: string): number {
+ try {
+ return loadBrainConfig(vault).dream.unconfirmed_window_days;
+ } catch {
+ return DEFAULT_BRAIN_CONFIG.dream.unconfirmed_window_days;
+ }
+}
diff --git a/src/core/brain/host-memory-promotions.ts b/src/core/brain/host-memory-promotions.ts
new file mode 100644
index 00000000..92a06e0d
--- /dev/null
+++ b/src/core/brain/host-memory-promotions.ts
@@ -0,0 +1,84 @@
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+
+export interface HostMemoryPromotionEntry {
+ readonly pref_id: string;
+ readonly sha256: string;
+ readonly promoted_at: string;
+}
+
+export interface HostMemoryPromotionsManifest {
+ readonly version: 1;
+ readonly promotions: Readonly<Record<string, HostMemoryPromotionEntry>>;
+}
+
+/**
+ * What a load observed about the sidecar. `corrupt` is true when the file
+ * exists but could not be read as the manifest shape - truncated mid-run,
+ * hand-edited to a non-object, an array where the map belongs. The load
+ * still hands back the empty shape (the promotion planner needs SOMETHING
+ * to plan against), but the flag rides along so a dry run can say the
+ * plan was computed blind and an apply can refuse rather than save the
+ * empty set over a file that was mostly recoverable.
+ */
+export interface LoadedPromotionsManifest extends HostMemoryPromotionsManifest {
+ readonly corrupt: boolean;
+}
+
+function manifestPath(vault: string): string {
+ return join(vault, BRAIN_ROOT_REL, ".imports", "host-memory-promotions.json");
+}
+
+/**
+ * Load the promotion-history sidecar for continuity host-memory writes.
+ * Treats a missing file as "empty manifest" - first-time promotions rely
+ * on this. Type-validates the parsed `promotions` field defensively: a
+ * malformed file (hand-edited to non-object, truncated, etc.) returns the
+ * empty shape rather than propagating an unknown blob into the rest of
+ * the promotion pipeline, with `corrupt` set so the verb can surface the
+ * state instead of silently planning against a history it lost.
+ *
+ * Structure mirrors `claude-memory-manifest.ts` (the import-history
+ * sidecar) deliberately: both sidecars answer "which source rows already
+ * landed as which preference, under which content hash", so a promotion
+ * plans CREATE/UPDATE/RECREATE/SKIP_UNCHANGED/CONFLICT with the same
+ * semantics an import plans them. The manifest KEY is the continuity
+ * record id, which - unlike a memory file basename - is unique per row
+ * by construction.
+ */
+export function loadPromotionsManifest(vault: string): LoadedPromotionsManifest {
+ const p = manifestPath(vault);
+ if (!existsSync(p)) return { version: 1, promotions: {}, corrupt: false };
+ let raw: unknown;
+ try {
+ raw = JSON.parse(readFileSync(p, "utf8"));
+ } catch {
+ return { version: 1, promotions: {}, corrupt: true };
+ }
+ if (
+ raw === null ||
+ typeof raw !== "object" ||
+ typeof (raw as { promotions?: unknown }).promotions !== "object" ||
+ (raw as { promotions?: unknown }).promotions === null ||
+ Array.isArray((raw as { promotions?: unknown }).promotions)
+ ) {
+ return { version: 1, promotions: {}, corrupt: true };
+ }
+ return {
+ version: 1,
+ promotions: (raw as { promotions: Record<string, HostMemoryPromotionEntry> }).promotions,
+ corrupt: false,
+ };
+}
+
+export function savePromotionsManifest(vault: string, m: HostMemoryPromotionsManifest): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const p = manifestPath(vault);
+ mkdirSync(dirname(p), { recursive: true });
+ atomicWriteFileSync(p, JSON.stringify(m, null, 2) + "\n");
+}
diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.ts
index 56d07a64..9c079aa7 100644
--- a/src/core/brain/import-claude-memory.ts
+++ b/src/core/brain/import-claude-memory.ts
@@ -153,8 +153,13 @@ export class ApprovalDigestError extends Error {
*
* Fields preserved: _applied_count, _violated_count, _evidenced_by,
* _last_evidence_at, _confirmed_at, unconfirmed_until, pinned, scope.
+ *
+ * Exported rather than copied because the continuity host-memory promotion
+ * renders through the same preference shape and must preserve the same
+ * evidence fields on UPDATE; a second copy of this decision is how the
+ * two UPDATE paths drift.
*/
-function mergePreservingEvidence(existingBody: string, freshBody: string): string {
+export function mergePreservingEvidence(existingBody: string, freshBody: string): string {
const PRESERVED = [
"_applied_count",
"_violated_count",
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index dab2cf30..4f9e281f 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -252,6 +252,14 @@ export const BRAIN_LOG_EVENT_KIND = {
* entries, plus conflict and snapshot information.
*/
importClaudeMemory: "import-claude-memory",
+ /**
+ * `promote-host-memory` — operator promoted continuity host_memory_write
+ * records via `o2b brain continuity promote --apply` (issue #277). One
+ * log block per promotion run; payload carries counters for created,
+ * updated, recreated, and skipped records, plus conflict, privacy-drop
+ * and redaction counts, and snapshot information.
+ */
+ promoteHostMemory: "promote-host-memory",
/**
* `note` (§32B, v0.10.8) — one narrative-milestone line written by
* the `brain_note` MCP tool. Payload carries `text` (one-line
@@ -689,6 +697,12 @@ export const BRAIN_SNAPSHOT_REASON = Object.freeze({
upgrade: "upgrade",
/** Pre-write point taken before Claude Code memory is imported. */
importClaudeMemory: "import-claude-memory",
+ /**
+ * Pre-write point taken before continuity host_memory_write records are
+ * promoted into preference pages (issue #277). Kebab-case like its
+ * siblings because the value doubles as the archive's filename prefix.
+ */
+ promoteHostMemory: "promote-host-memory",
/** Pre-deletion point taken before a source's derived material is removed. */
deleteBySource: "delete-by-source",
/** Pre-prune point taken before malformed entity notes are deleted. */
diff --git a/src/core/egress/guard.ts b/src/core/egress/guard.ts
index e57cbc66..644e53db 100644
--- a/src/core/egress/guard.ts
+++ b/src/core/egress/guard.ts
@@ -137,8 +137,13 @@ export type EgressVerdict<T> = EgressReleased<T> | EgressRefused;
* The redaction policy for every path that writes outside the vault. One
* constant, because six paths with six policies is the drift this unit
* exists to remove.
+ *
+ * Exported for the one in-vault writer that needs the same grade without
+ * an egress site: the continuity promotion re-scans ledger text before it
+ * becomes an indexed page, and a second policy spelled next to this one
+ * would drift exactly the way the shared constant exists to prevent.
*/
-const EGRESS_REDACTION_OPTIONS: RedactRawOutputOptions = Object.freeze({
+export const EGRESS_REDACTION_OPTIONS: RedactRawOutputOptions = Object.freeze({
redactTokens: true,
redactUrlCredentials: true,
});
diff --git a/tests/cli/brain-continuity-promote.test.ts b/tests/cli/brain-continuity-promote.test.ts
new file mode 100644
index 00000000..bb9b20a0
--- /dev/null
+++ b/tests/cli/brain-continuity-promote.test.ts
@@ -0,0 +1,212 @@
+/**
+ * `o2b brain continuity promote` (issue #277): dry-run-first readback of
+ * continuity `host_memory_write` records into unconfirmed preference
+ * pages, sealed with an approval digest an apply must carry back.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { recordHostMemoryWrite } from "../../src/core/brain/host-memory-write.ts";
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-continuity-promote-cli-"));
+ vault = join(tmp, "vault");
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);
+ bootstrapBrain(vault, { configPath });
+ recordHostMemoryWrite(vault, {
+ action: "add",
+ target: "user",
+ content: "User prefers dark mode",
+ createdAt: "2026-06-20T10:00:00Z",
+ });
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+function writeHostMemory(v: string, content: string, createdAt: string) {
+ recordHostMemoryWrite(v, { action: "add", target: "user", content, createdAt });
+}
+
+const PROMOTE = ["brain", "continuity", "promote"];
+
+describe("o2b brain continuity promote", () => {
+ test("dry-run default leaves the vault untouched and prints plan plus digest", async () => {
+ const out = await runCli([...PROMOTE], { env: env() });
+ expect(out.returncode).toBe(0);
+ expect(out.stdout).toContain("promote plan: 1 actionable, 0 skipped");
+ expect(out.stdout).toContain("CREATE pref-hostmem-");
+ expect(out.stdout).toContain("approval-digest: ");
+ // The preferences directory exists from bootstrap; no promote page
+ // may be inside it, and no sidecar or snapshot may exist either.
+ expect(
+ readdirSync(join(vault, "Brain", "preferences")).filter((name) =>
+ name.startsWith("pref-hostmem-"),
+ ),
+ ).toEqual([]);
+ expect(existsSync(join(vault, "Brain", ".imports", "host-memory-promotions.json"))).toBe(false);
+ expect(
+ readdirSync(join(vault, "Brain", ".snapshots")).filter((name) =>
+ name.startsWith("promote-host-memory-"),
+ ),
+ ).toEqual([]);
+ });
+
+ test("--apply with the dry run's digest writes the page and prints the snapshot", async () => {
+ const dry = await runCli([...PROMOTE, "--json"], { env: env() });
+ const digest = (JSON.parse(dry.stdout) as { digest: string }).digest;
+
+ const out = await runCli([...PROMOTE, "--apply", "--approval-digest", digest], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(0);
+ expect(out.stdout).toContain("applied: 1");
+ expect(out.stdout).toContain("snapshot: promote-host-memory-");
+ const prefs = join(vault, "Brain", "preferences");
+ expect(readdirSync(prefs).some((name) => name.startsWith("pref-hostmem-"))).toBe(true);
+ });
+
+ test("--json prints one stable envelope", async () => {
+ const out = await runCli([...PROMOTE, "--json"], { env: env() });
+ expect(out.returncode).toBe(0);
+ const parsed = JSON.parse(out.stdout) as Record<string, unknown>;
+ expect(Object.keys(parsed).toSorted()).toEqual(
+ [
+ "applied",
+ "conflicts",
+ "counts",
+ "digest",
+ "manifest_corrupt",
+ "mode",
+ "month",
+ "plans",
+ "skipped",
+ "snapshot",
+ "total",
+ ].toSorted(),
+ );
+ expect(parsed["mode"]).toBe("dry-run");
+ expect(parsed["month"]).toBeNull();
+ expect(parsed["total"]).toBe(1);
+ expect(parsed["snapshot"]).toBeNull();
+ expect(Object.keys(parsed["counts"] as Record<string, unknown>).toSorted()).toEqual(
+ [
+ "applied",
+ "conflicts",
+ "plans",
+ "private_dropped",
+ "redacted",
+ "skipped",
+ "skipped_unchanged",
+ ].toSorted(),
+ );
+ const plans = parsed["plans"] as Array<Record<string, unknown>>;
+ expect(plans).toHaveLength(1);
+ expect(Object.keys(plans[0]!).toSorted()).toEqual(["action", "id", "pref_id"]);
+ expect(plans[0]!["action"]).toBe("CREATE");
+ });
+
+ test("a bad --month fails with the usage message", async () => {
+ const out = await runCli([...PROMOTE, "--month", "June"], { env: env() });
+ expect(out.returncode).toBe(2);
+ expect(out.stderr).toContain("--month must look like YYYY-MM");
+ });
+
+ test("--approval-digest paired with a dry run is refused", async () => {
+ const out = await runCli([...PROMOTE, "--approval-digest", "deadbeef"], { env: env() });
+ expect(out.returncode).toBe(2);
+ expect(out.stderr).toContain("a dry run computes a digest, it does not consume one");
+ });
+
+ test("non-interactive --apply without a digest is refused", async () => {
+ // A subprocess with a piped stdin, NOT the in-process form: the
+ // guard reads process.stdin.isTTY, which in-process is inherited
+ // from the runner and turns this test into a pass-on-CI /
+ // fail-in-a-terminal flip (review M8).
+ const out = await runCli([...PROMOTE, "--apply"], { env: env(), stdin: "" });
+ expect(out.returncode).toBe(2);
+ expect(out.stderr).toContain("--apply requires --approval-digest in non-interactive");
+ // The refusal wrote nothing.
+ expect(
+ readdirSync(join(vault, "Brain", "preferences")).filter((name) =>
+ name.startsWith("pref-hostmem-"),
+ ),
+ ).toEqual([]);
+ });
+
+ test("the exit-2 conflict path spells the same envelope, plans included (review M7)", async () => {
+ // Land a page, then drop the sidecar: the next run plans CONFLICT
+ // for the orphaned page, and the conflict apply exits 2 after the
+ // safe writes land.
+ const dry = await runCli([...PROMOTE, "--json"], { env: env() });
+ const digest = (JSON.parse(dry.stdout) as { digest: string }).digest;
+ await runCli([...PROMOTE, "--apply", "--approval-digest", digest], { env: env() });
+ rmSync(join(vault, "Brain", ".imports", "host-memory-promotions.json"));
+ writeHostMemory(vault, "A second fact", "2026-06-21T10:00:00Z");
+
+ const dry2 = await runCli([...PROMOTE, "--json"], { env: env() });
+ const dry2Parsed = JSON.parse(dry2.stdout) as {
+ plans: Array<Record<string, unknown>>;
+ conflicts: Array<Record<string, unknown>>;
+ };
+ expect(dry2Parsed.plans).toHaveLength(2);
+ expect(dry2Parsed.conflicts).toHaveLength(1);
+ expect(dry2Parsed.plans.some((p) => p["action"] === "CONFLICT")).toBe(true);
+
+ const digest2 = (JSON.parse(dry2.stdout) as { digest: string }).digest;
+ // The snapshot run-id embeds the second; two applies inside one
+ // second collide on the archive name and the second refuses. The
+ // CLI surface cannot pin a clock the way the core tests do, so the
+ // run boundary is the test's clock.
+ await new Promise((resolve) => setTimeout(resolve, 1100));
+ const out = await runCli([...PROMOTE, "--apply", "--json", "--approval-digest", digest2], {
+ env: env(),
+ });
+ expect(out.returncode).toBe(2);
+ const parsed = JSON.parse(out.stdout) as {
+ mode: string;
+ plans: Array<Record<string, unknown>>;
+ conflicts: Array<Record<string, unknown>>;
+ counts: Record<string, unknown>;
+ };
+ expect(Object.keys(parsed).toSorted()).toEqual(
+ [
+ "applied",
+ "conflicts",
+ "counts",
+ "digest",
+ "manifest_corrupt",
+ "mode",
+ "month",
+ "plans",
+ "skipped",
+ "snapshot",
+ "total",
+ ].toSorted(),
+ );
+ // The consumer keying on `plans` sees the conflict row, not zero.
+ expect(parsed.plans).toHaveLength(2);
+ expect(parsed.conflicts).toHaveLength(1);
+ expect(parsed.counts["applied"]).toBe(1);
+ });
+
+ test("an unknown subcommand fails with the USAGE block", async () => {
+ const out = await runCli(["brain", "continuity", "replay"], { env: env() });
+ expect(out.returncode).not.toBe(0);
+ expect(out.stderr).toContain("usage: o2b brain continuity export");
+ expect(out.stderr).toContain("o2b brain continuity promote");
+ });
+});
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index d45ae4b2..dfd04f53 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -1516,8 +1516,15 @@ const DIRECT_WRITE_ROWS = 85;
* page's `visibility:` line through the same helper on its apply arm - a
* dry-run-by-default repair pass over existing pages, writing no page of
* its own.
+ *
+ * 130 -> 132, from the host-memory readback wave and nothing else: the
+ * continuity promote verb (`src/core/brain/continuity/promote-host-memory.ts`)
+ * lands its rendered preference pages through the shared atomic writer,
+ * and its manifest sidecar (`src/core/brain/host-memory-promotions.ts`)
+ * commits `Brain/.imports/host-memory-promotions.json` through the same
+ * helper - both under the apply arm only, the dry run writes nothing.
*/
-const SHARED_HELPER_ROWS = 130;
+const SHARED_HELPER_ROWS = 132;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1680,8 +1687,12 @@ const UNSTAMPED_DIRECT_ROWS = 84;
* rewrite existing pages through the shared atomic writer, and neither
* stamps an origin channel - one writes a class the writer derives, the
* other a visibility token the page's own informal marker declares.
+ * 126 -> 128 is the same wave as the shared-helper pin above: the
+ * continuity promote verb and its promotion manifest both commit through
+ * the shared atomic writer, and a ledger readback stamps no origin
+ * channel - the pages it lands are vault pages, not channel records.
*/
-const UNSTAMPED_SHARED_ROWS = 126;
+const UNSTAMPED_SHARED_ROWS = 128;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 4bf9b323..34654a87 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -83,6 +83,8 @@ describe("BRAIN_* const enums", () => {
"upgrade",
// §3 import-claude-memory (agent-discipline-tail)
"import-claude-memory",
+ // host-memory readback (issue #277) promotion-run audit
+ "promote-host-memory",
// §32B (v0.10.8) brain_note narrative milestones
"note",
// Brain lifecycle suite (v0.21.0) reconcile-phase open questions
diff --git a/tests/core/brain/continuity/promote-host-memory.test.ts b/tests/core/brain/continuity/promote-host-memory.test.ts
new file mode 100644
index 00000000..ef20623e
--- /dev/null
+++ b/tests/core/brain/continuity/promote-host-memory.test.ts
@@ -0,0 +1,521 @@
+/**
+ * `promoteHostMemory` - the host-memory readback path (issue #277):
+ * continuity `host_memory_write` records re-rendered as unconfirmed
+ * preference pages, dry-run first, sealed with an approval digest.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { appendContinuityRecord } from "../../../../src/core/brain/continuity/store.ts";
+import {
+ PromoteApprovalDigestError,
+ PromoteConflictsError,
+ PromoteManifestCorruptError,
+ promoteHostMemory,
+} from "../../../../src/core/brain/continuity/promote-host-memory.ts";
+import { REDACTION_PLACEHOLDER, redactStructured } from "../../../../src/core/redactor.ts";
+import { loadPromotionsManifest } from "../../../../src/core/brain/host-memory-promotions.ts";
+import {
+ HOST_MEMORY_WRITE_KIND,
+ recordHostMemoryWrite,
+} from "../../../../src/core/brain/host-memory-write.ts";
+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
+import { brainConfigPath, preferencePath, retiredPath } from "../../../../src/core/brain/paths.ts";
+import { loadBrainConfig } from "../../../../src/core/brain/policy.ts";
+import { resolvedOwnerFor } from "../../../../src/core/brain/preference.ts";
+import { isoSecond } from "../../../../src/core/brain/time.ts";
+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { sha256Hex } from "../../../../src/core/integrity/digest.ts";
+import {
+ FAKE_PROVIDER_KEY,
+ FAKE_VENDOR_KEY,
+ fakeCredential,
+} from "../../../helpers/fake-credentials.ts";
+
+let vault: string;
+let savedEnv: Record<string, string | undefined>;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-promote-host-memory-"));
+ bootstrapBrain(vault);
+ savedEnv = { VAULT_AGENT_NAME: process.env["VAULT_AGENT_NAME"] };
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ for (const [key, value] of Object.entries(savedEnv)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+});
+
+const NOW = new Date("2026-07-01T12:00:00Z");
+const promotionsJson = () => join(vault, "Brain", ".imports", "host-memory-promotions.json");
+
+/** A private-page fixture body: the text lives only inside the private region. */
+const PRIVATE_BODY = "quiet retirement plan";
+
+function hostRef(recordId: string): string {
+ return `hostmem-${recordId.slice(-12).toLowerCase()}`;
+}
+
+/** Snapshot archives this feature has taken, by run-id prefix. */
+function promoteSnapshots(): string[] {
+ return readdirSync(join(vault, "Brain", ".snapshots"))
+ .filter((name) => name.startsWith("promote-host-memory-"))
+ .toSorted();
+}
+
+function writeHostMemory(content: string, createdAt = "2026-06-20T10:00:00Z") {
+ return recordHostMemoryWrite(vault, { action: "add", target: "user", content, createdAt });
+}
+
+/**
+ * Seed a ledger row with an exact id, bypassing the store's content-hash
+ * dedup - the only way to pin a slug-tail collision fixture.
+ */
+function writeRawHostRecord(id: string, content: string, createdAt = "2026-06-20T10:00:00Z") {
+ const dir = join(vault, "Brain", "log", "continuity");
+ mkdirSync(dir, { recursive: true });
+ const row = {
+ schema: "o2b.continuity.v1",
+ id,
+ kind: "host_memory_write",
+ createdAt,
+ sourceRefs: [],
+ payload: { action: "add", target: "user", content },
+ private: false,
+ redacted: false,
+ };
+ writeFileSync(join(dir, "2026-06.jsonl"), `${JSON.stringify(row)}\n`, { flag: "a" });
+}
+
+function writeRawHostRecordWithCreatedAt(id: string, content: string, createdAt: string) {
+ writeRawHostRecord(id, content, createdAt);
+}
+
+function promotionOf(recordId: string) {
+ return loadPromotionsManifest(vault).promotions[recordId];
+}
+
+describe("promoteHostMemory", () => {
+ test("dry-run plans and writes nothing", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+
+ expect(res.mode).toBe("dry-run");
+ expect(res.total).toBe(1);
+ expect(res.plans.map((p) => p.action)).toEqual(["CREATE"]);
+ expect(res.plans[0]!.basename).toBe(record.id);
+ expect(res.plans[0]!.prefId).toBe(`pref-${hostRef(record.id)}`);
+ expect(res.digest).toMatch(/^[0-9a-f]{64}$/);
+ expect(existsSync(preferencePath(vault, hostRef(record.id)))).toBe(false);
+ expect(existsSync(promotionsJson())).toBe(false);
+ expect(promoteSnapshots()).toEqual([]);
+ });
+
+ test("apply creates a page under the trial window with ledger provenance", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ const windowDays = loadBrainConfig(vault).dream.unconfirmed_window_days;
+ const expectedUntil = isoSecond(new Date(NOW.getTime() + windowDays * 24 * 60 * 60 * 1000));
+ const owner = resolvedOwnerFor(
+ vault,
+ preferencePath(vault, hostRef(record.id)),
+ undefined,
+ undefined,
+ );
+
+ const res = promoteHostMemory({ vault, mode: "apply", now: NOW });
+ expect(res.applied).toHaveLength(1);
+ expect(res.snapshotRunId).not.toBeNull();
+
+ // The target page is named for the record, and the renderer derives
+ // the frontmatter id and topic from the SAME record-derived identity,
+ // so an id-keyed lookup lands on the file that exists.
+ const page = readFileSync(preferencePath(vault, hostRef(record.id)), "utf8");
+ expect(page).toContain(`id: pref-${hostRef(record.id)}`);
+ expect(page).toContain(`unconfirmed_until: "${expectedUntil}"`);
+ expect(page).toContain("_status: unconfirmed");
+ // Provenance names the ledger shard and the record id itself.
+ expect(page).toContain('_imported_from: "Brain/log/continuity/2026-06.jsonl"');
+ expect(page).toContain(`host memory write \`${record.id}\``);
+ expect(page).toContain("User prefers dark mode");
+ // Owner wiring follows the shared resolver: a line when the gate
+ // stamps one, none when it is off.
+ if (owner === undefined) expect(page).not.toContain("owner:");
+ else expect(page).toContain(`owner: ${owner}`);
+
+ const manifest = promotionOf(record.id);
+ expect(manifest?.pref_id).toBe(res.plans[0]!.prefId);
+ expect(manifest?.sha256).toBe(sha256Hex("User prefers dark mode"));
+ expect(manifest?.promoted_at).toBe("2026-07-01T12:00:00Z");
+ });
+
+ test("the trial window reads the vault config", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ atomicWriteFileSync(
+ brainConfigPath(vault),
+ "schema_version: 1\ndream:\n unconfirmed_window_days: 3\n",
+ );
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ const page = readFileSync(preferencePath(vault, hostRef(record.id)), "utf8");
+ expect(page).toContain('unconfirmed_until: "2026-07-04T12:00:00Z"');
+ });
+
+ test("the owner stamp lands when the delivery gate is on", () => {
+ process.env["VAULT_AGENT_NAME"] = "promote-agent";
+ atomicWriteFileSync(
+ brainConfigPath(vault),
+ "schema_version: 1\nintegrity:\n owner_scope_delivery: warn\n",
+ );
+ const record = writeHostMemory("User prefers dark mode");
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ const page = readFileSync(preferencePath(vault, hostRef(record.id)), "utf8");
+ expect(page).toContain("owner: promote-agent");
+ });
+
+ test("a second run over unchanged content plans SKIP_UNCHANGED and writes nothing", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ const prefFile = preferencePath(vault, hostRef(record.id));
+ const pageBefore = readFileSync(prefFile, "utf8");
+
+ const second = promoteHostMemory({
+ vault,
+ mode: "apply",
+ now: new Date("2026-07-02T12:00:00Z"),
+ });
+ expect(second.plans.map((p) => p.action)).toEqual(["SKIP_UNCHANGED"]);
+ expect(second.applied).toHaveLength(0);
+ expect(second.skippedUnchanged).toHaveLength(1);
+ expect(second.snapshotRunId).toBeNull();
+
+ expect(readFileSync(prefFile, "utf8")).toBe(pageBefore);
+ // The sidecar records the FIRST landing; a no-op run does not touch it.
+ expect(promotionOf(record.id)?.promoted_at).toBe("2026-07-01T12:00:00Z");
+ });
+
+ test("a page on disk with no promotion history plans CONFLICT; apply still lands the rest", () => {
+ const first = writeHostMemory("User prefers dark mode", "2026-06-20T10:00:00Z");
+ const second = writeHostMemory("User signs commits", "2026-06-21T10:00:00Z");
+ // The conflict fixture: the second page exists with no sidecar entry
+ // behind it, as if written by another writer.
+ writeFileSync(
+ preferencePath(vault, hostRef(second.id)),
+ "---\nkind: brain-preference\n---\n\nhand-written\n",
+ "utf8",
+ );
+
+ let thrown: PromoteConflictsError | undefined;
+ try {
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ } catch (err) {
+ if (err instanceof PromoteConflictsError) thrown = err;
+ }
+ expect(thrown).toBeDefined();
+ expect(thrown!.conflicts.map((c) => c.basename)).toEqual([second.id]);
+ expect(thrown!.partial).not.toBeNull();
+ expect(thrown!.partial!.applied.map((p) => p.basename)).toEqual([first.id]);
+ expect(existsSync(preferencePath(vault, hostRef(first.id)))).toBe(true);
+ // The conflicting page is left exactly as it was found.
+ expect(readFileSync(preferencePath(vault, hostRef(second.id)), "utf8")).toContain(
+ "hand-written",
+ );
+ });
+
+ test("UPDATE re-renders the page and preserves accumulated evidence fields", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ const prefFile = preferencePath(vault, hostRef(record.id));
+
+ // Simulate accumulated evidence.
+ const pref = readFileSync(prefFile, "utf8");
+ writeFileSync(
+ prefFile,
+ pref
+ .replace("_applied_count: 0", "_applied_count: 7")
+ .replace("_evidenced_by: []", "_evidenced_by: ['[[a.md]]']"),
+ "utf8",
+ );
+
+ // The ledger is append-only and a record id is derived from its
+ // content, so content for an existing id cannot honestly change. The
+ // reachable UPDATE is a stale sidecar sha - a manifest hand-merged
+ // across devices - which is exactly the drift the branch exists for.
+ const manifest = JSON.parse(readFileSync(promotionsJson(), "utf8")) as {
+ promotions: Record<string, { sha256: string }>;
+ };
+ manifest.promotions[record.id]!.sha256 = sha256Hex("stale");
+ atomicWriteFileSync(promotionsJson(), JSON.stringify(manifest, null, 2) + "\n");
+
+ const res = promoteHostMemory({ vault, mode: "apply", now: new Date("2026-07-01T12:00:01Z") });
+ expect(res.plans.map((p) => p.action)).toEqual(["UPDATE"]);
+ const after = readFileSync(prefFile, "utf8");
+ expect(after).toContain("_applied_count: 7");
+ expect(after).toContain("_evidenced_by: ['[[a.md]]']");
+ expect(after).toContain("User prefers dark mode");
+ });
+
+ test("private records never promote and are counted through the store door", () => {
+ writeHostMemory(`note <private>${PRIVATE_BODY}</private> end`);
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+
+ expect(res.total).toBe(1);
+ expect(res.privateCount).toBe(1);
+ expect(res.plans).toHaveLength(0);
+ expect(res.skipped).toHaveLength(0);
+ expect(JSON.stringify(res)).not.toContain(PRIVATE_BODY);
+ // Nothing landed: the preferences directory holds no hostmem page.
+ expect(
+ readdirSync(join(vault, "Brain", "preferences")).filter((name) =>
+ name.startsWith("pref-hostmem-"),
+ ),
+ ).toEqual([]);
+ });
+
+ test("a redacted record promotes its masked text and is counted", () => {
+ // Write-time redaction (the redactor's default options) masks a
+ // key=value credential shape; a bare vendor token is NOT masked at
+ // write time - that tighter pass is the export boundary's, per the
+ // export verb's own docblock.
+ const record = writeHostMemory(`token=${FAKE_PROVIDER_KEY} for the staging deploy`);
+ expect(record.redacted).toBe(true);
+ expect(record.private).toBe(false);
+
+ const res = promoteHostMemory({ vault, mode: "apply", now: NOW });
+ expect(res.redactedCount).toBe(1);
+ expect(res.applied).toHaveLength(1);
+ const page = readFileSync(preferencePath(vault, hostRef(record.id)), "utf8");
+ expect(page).toContain("token=***REDACTED***");
+ expect(page).not.toContain(FAKE_PROVIDER_KEY);
+ });
+
+ test("empty content is skipped by name", () => {
+ const record = appendContinuityRecord(vault, {
+ kind: HOST_MEMORY_WRITE_KIND,
+ createdAt: "2026-06-20T10:00:00Z",
+ payload: { action: "add", target: "user", content: " " },
+ });
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(res.skipped).toEqual([{ id: record.id, reason: "empty content" }]);
+ expect(res.plans).toHaveLength(0);
+ });
+
+ test("--month selects exactly the month's window", () => {
+ writeHostMemory("June fact", "2026-06-20T10:00:00Z");
+ const july = writeHostMemory("July fact", "2026-07-01T09:00:00Z");
+ const privateJuly = appendContinuityRecord(vault, {
+ kind: HOST_MEMORY_WRITE_KIND,
+ createdAt: "2026-07-02T09:00:00Z",
+ payload: { action: "add", target: "user", content: `x <private>${PRIVATE_BODY}</private>` },
+ });
+
+ const res = promoteHostMemory({ vault, mode: "dry-run", month: "2026-06", now: NOW });
+ expect(res.total).toBe(1);
+ expect(res.plans).toHaveLength(1);
+ expect(res.plans.map((p) => p.basename)).not.toContain(july.id);
+ expect(res.plans.map((p) => p.basename)).not.toContain(privateJuly.id);
+ expect(res.privateCount).toBe(0);
+ });
+
+ test("an approval digest mismatch throws and writes nothing", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ const dry = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ // The ledger moves between the approved dry run and the apply.
+ writeHostMemory("A later fact", "2026-06-21T10:00:00Z");
+
+ expect(() =>
+ promoteHostMemory({ vault, mode: "apply", approvalDigest: dry.digest, now: NOW }),
+ ).toThrow(PromoteApprovalDigestError);
+ try {
+ promoteHostMemory({ vault, mode: "apply", approvalDigest: dry.digest, now: NOW });
+ } catch (err) {
+ // The remedy must be a command that exists: the verb has no
+ // --dry-run flag, the default IS the dry run (M5).
+ expect((err as Error).message).toContain("(the default is the dry run)");
+ expect((err as Error).message).not.toContain("--dry-run");
+ }
+ expect(existsSync(preferencePath(vault, hostRef(record.id)))).toBe(false);
+ expect(promoteSnapshots()).toEqual([]);
+ expect(promotionOf(record.id)).toBeUndefined();
+
+ // The fresh digest the new dry run prints is what the next apply takes.
+ const fresh = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(fresh.digest).not.toBe(dry.digest);
+ const applied = promoteHostMemory({
+ vault,
+ mode: "apply",
+ approvalDigest: fresh.digest,
+ now: NOW,
+ });
+ expect(applied.applied).toHaveLength(2);
+ });
+
+ test("apply without a digest works - the interactive path", () => {
+ writeHostMemory("User prefers dark mode");
+ const res = promoteHostMemory({ vault, mode: "apply", now: NOW });
+ expect(res.applied).toHaveLength(1);
+ expect(existsSync(preferencePath(vault, hostRef(res.applied[0]!.basename)))).toBe(true);
+ });
+
+ test("a purely numeric first line still lands - the record-derived identity carries the tag rule", () => {
+ // Obsidian tags may carry digits but may not be ONLY digits. The
+ // page's topic comes from the record id, never the display text, so
+ // a numeric first line cannot break the tag rule; it rides along as
+ // the `principle` display text.
+ writeHostMemory("42");
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(res.plans.map((p) => p.action)).toEqual(["CREATE"]);
+ expect(res.skipped).toHaveLength(0);
+ const recordId = res.plans[0]!.basename;
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ const page = readFileSync(preferencePath(vault, hostRef(recordId)), "utf8");
+ expect(page).toContain(`topic: ${hostRef(recordId)}`);
+ expect(page).toContain('principle: "42"');
+ });
+
+ test("two records whose hash tails collide plan onto one named skip, not one overwrite", () => {
+ // The store derives ids from content, so the collision fixture seeds
+ // raw ledger rows whose ids deliberately share a 12-character tail.
+ const shared = "aaaaaaaaaaaaaaaa";
+ writeRawHostRecord(`ctn_20260620000000_${shared}`, "First fact");
+ writeRawHostRecord(`ctn_20260621000000_${shared}`, "Second fact");
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(res.plans).toHaveLength(1);
+ expect(res.skipped).toHaveLength(1);
+ expect(res.skipped[0]!.reason).toContain("already claimed by record");
+ });
+
+ test("a retired page is never resurrected by a re-run", () => {
+ const record = writeHostMemory("User prefers dark mode");
+ promoteHostMemory({ vault, mode: "apply", now: NOW });
+ // The operator (or the dream pass) retires the promoted page.
+ renameSync(preferencePath(vault, hostRef(record.id)), retiredPath(vault, hostRef(record.id)));
+
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(res.plans).toHaveLength(0);
+ expect(res.skipped).toHaveLength(1);
+ expect(res.skipped[0]!.reason).toContain("retired copy exists");
+ expect(existsSync(preferencePath(vault, hostRef(record.id)))).toBe(false);
+ });
+
+ test("apply writes the promote-host-memory snapshot and log event", () => {
+ writeHostMemory("User prefers dark mode");
+ const res = promoteHostMemory({ vault, mode: "apply", now: NOW });
+
+ expect(res.snapshotRunId).not.toBeNull();
+ expect(res.snapshotRunId!).toStartWith("promote-host-memory-");
+ const snapshots = readdirSync(join(vault, "Brain", ".snapshots"));
+ expect(snapshots.some((name) => name.startsWith("promote-host-memory-"))).toBe(true);
+
+ const log = readFileSync(join(vault, "Brain", "log", `${res.localDate}.md`), "utf8");
+ expect(log).toContain("promote-host-memory");
+ expect(log).toContain("created: 1");
+ expect(log).toContain("private_dropped: 0");
+ expect(log).toContain("redacted: 0");
+ });
+
+ test("credential-shaped content is re-scanned and lands masked (review H1)", () => {
+ const urlCred = `postgres://deploy:${fakeCredential("Hunter2", "-Fake")}@db.example.test:5432/app`;
+ const content = `DB is ${urlCred} and the key is ${FAKE_VENDOR_KEY}`;
+ const record = writeHostMemory(content);
+ const res = promoteHostMemory({ vault, mode: "apply", now: NOW });
+
+ // The write-time flag stays false (the ledger redacts under the loose
+ // defaults), and the strict re-scan is what caught these.
+ expect(record.redacted).toBe(false);
+ expect(res.redactedCount).toBe(1);
+
+ const masked = redactStructured(content, {
+ redactTokens: true,
+ redactUrlCredentials: true,
+ }).value as string;
+ const page = readFileSync(preferencePath(vault, hostRef(record.id)), "utf8");
+ expect(page).not.toContain(FAKE_VENDOR_KEY);
+ expect(page).not.toContain("Hunter2-Fake");
+ expect(page).toContain(REDACTION_PLACEHOLDER);
+ // The plan binding covers the masked text: the sidecar's sha is the
+ // sha of what landed, so a re-run stays idempotent.
+ expect(promotionOf(record.id)?.sha256).toBe(sha256Hex(masked));
+ expect(page).toContain(masked.split("\n")[0]!.slice(0, 20));
+ });
+
+ test("a malformed row skips by name and never aborts the run (review M1)", () => {
+ const good = writeHostMemory("User prefers dark mode", "2026-06-20T10:00:00Z");
+ writeRawHostRecordWithCreatedAt(
+ "ctn_20260622000000_feeddadfeeddad0",
+ "Bad date row",
+ "June 23",
+ );
+ writeRawHostRecord("ctn_20260623!:000000_feeddadfeeddad1", "Bad id row");
+ const res = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(res.plans.map((p) => p.action)).toEqual(["CREATE"]);
+ expect(res.plans[0]!.basename).toBe(good.id);
+ const reasons = res.skipped.map((s) => s.reason).toSorted();
+ expect(reasons).toEqual(["non-canonical createdAt", "non-canonical record id"]);
+ });
+
+ test("a corrupt promotion manifest is reported on dry run and refused on apply (review M3)", () => {
+ writeHostMemory("User prefers dark mode");
+ mkdirSync(join(vault, "Brain", ".imports"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", ".imports", "host-memory-promotions.json"),
+ '{"version": 1, "promotions": {"ctn_2026',
+ "utf8",
+ );
+ const dry = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ expect(dry.manifestCorrupt).toBe(true);
+ // The plan computed against the empty history names the loss: the
+ // landed page (none here) would show CONFLICT, the row plans CREATE.
+ expect(dry.plans.map((p) => p.action)).toEqual(["CREATE"]);
+
+ expect(() => promoteHostMemory({ vault, mode: "apply", now: NOW })).toThrow(
+ PromoteManifestCorruptError,
+ );
+ expect(promoteSnapshots()).toEqual([]);
+ // The garbage file is not flattened to an empty set by the run.
+ expect(
+ readFileSync(join(vault, "Brain", ".imports", "host-memory-promotions.json"), "utf8"),
+ ).toBe('{"version": 1, "promotions": {"ctn_2026');
+ });
+
+ test("identical content from repeated writes promotes once (review M4)", () => {
+ writeHostMemory("User prefers dark mode", "2026-06-20T10:00:00Z");
+ writeHostMemory("User prefers dark mode", "2026-06-21T10:00:00Z");
+ writeHostMemory("User prefers dark mode", "2026-06-22T10:00:00Z");
+ const res = promoteHostMemory({ vault, mode: "apply", now: NOW });
+ expect(res.plans).toHaveLength(1);
+ expect(res.skipped).toHaveLength(2);
+ for (const skip of res.skipped) {
+ expect(skip.reason).toMatch(/^same content as record ctn_/);
+ }
+ const pages = readdirSync(join(vault, "Brain", "preferences")).filter((name) =>
+ name.startsWith("pref-hostmem-"),
+ );
+ expect(pages).toHaveLength(1);
+ });
+
+ test("the same content seals identically across runs - the approval binds the plan", () => {
+ writeHostMemory("User prefers dark mode");
+ const first = promoteHostMemory({ vault, mode: "dry-run", now: NOW });
+ const second = promoteHostMemory({
+ vault,
+ mode: "dry-run",
+ now: new Date("2026-08-15T08:30:00Z"),
+ });
+ expect(second.digest).toBe(first.digest);
+ expect(second.localDate).toBe("2026-08-15");
+ });
+});
diff --git a/tests/core/brain/continuity/reader-census.test.ts b/tests/core/brain/continuity/reader-census.test.ts
index 3dee522d..027fc220 100644
--- a/tests/core/brain/continuity/reader-census.test.ts
+++ b/tests/core/brain/continuity/reader-census.test.ts
@@ -5,11 +5,11 @@
* `docs/observability.md` described the read-model's masking policy as if
* it governed the read side: `private` records dropped by default, kept
* only on explicit request. The read-model does exactly that - and almost
- * nothing goes through it. Four modules call
- * `loadNormalizedContinuityRecords`; twenty call `listContinuityRecords`
- * straight off the store, where no `private` drop, no schema-version
- * dispatch, and now no declared-scope filter applies. A policy sentence
- * cannot notice that; a census can.
+ * nothing goes through it. Five modules call
+ * `loadNormalizedContinuityRecords`; twenty-nine call
+ * `listContinuityRecords` straight off the store, where no `private`
+ * drop, no schema-version dispatch, and now no declared-scope filter
+ * applies. A policy sentence cannot notice that; a census can.
*
* So the split is asserted rather than described. Each side is an explicit
* inventory: a module that starts reading continuity records - through
@@ -67,6 +67,10 @@ const READ_MODEL_READERS: Readonly<Record<string, string>> = Object.freeze({
"`o2b brain continuity export|list` - ATOF/ATIF trajectory export and the " +
"usage-decay-ranked listing.",
"src/core/bench/phases.ts": "memory bench harness; replays `session_turn` records per question.",
+ "src/core/brain/continuity/promote-host-memory.ts":
+ "`o2b brain continuity promote` (issue #277) - the host-memory readback; the " +
+ "read-model door is the promotion payload, with `private` records dropped and " +
+ "redacted text never un-masked.",
"src/core/brain/event-trace.ts":
"joins Brain-log events to their continuity records; passes `keepPrivate` " +
"through from the caller rather than deciding it.",
@@ -87,6 +91,10 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({
"complement the two recorded sets fold against.",
"src/core/brain/context-pack-outcome.ts": "reads `context_pack_outcome` for the outcome ledger.",
"src/core/brain/context-receipts.ts": "reads `context_receipt` for list, summary and show.",
+ "src/core/brain/continuity/promote-host-memory.ts":
+ "counts the `private` `host_memory_write` rows the read-model drops, so the " +
+ "promote report states how many records it did not see instead of silently " +
+ "shortening the run.",
"src/core/brain/dedup-telemetry.ts":
"reads `ingest_dedup` rollups. Carries a literal NUL byte, so text tools " +
"that classify by content type do not see it at all.",
@@ -145,7 +153,7 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({
* these say how far the counts may fall before the split stops describing
* anything.
*
- * Four modules read through the read-model and twenty-three read the
+ * Five modules read through the read-model and twenty-nine read the
* store directly. Both numbers are EQUALITIES, not floors.
*
* The direct floor used to sit at twenty against a reality of
@@ -158,14 +166,17 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({
* reader has to be added to one of them regardless and the number costs
* nothing extra to keep true.
*/
-const READ_MODEL_READER_COUNT = 4;
+const READ_MODEL_READER_COUNT = 5;
+// 28 -> 29: the host-memory readback (issue #277) registers the promotion
+// core (`continuity/promote-host-memory.ts`), which counts the private rows
+// the read-model drops through the raw store door.
// 26 -> 27: the answer-trust wave registers the blank-session-identity
// doctor check (`doctor/session-identity-check.ts`), which reads the whole
// store once to count records per kind that name no session.
// 27 -> 28: the session-mining-economy wave registers the explorer console
// collector (`explorer-console.ts`), which reads every kind inside the
// 30-day window for the written-per-day histogram.
-const DIRECT_STORE_READER_COUNT = 28;
+const DIRECT_STORE_READER_COUNT = 29;
/** A file the classifier must see, and that `grep` alone does not. */
diff --git a/uv.lock b/uv.lock
index c5b81737..860b146a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.93.0"
+version = "1.94.0"
source = { editable = "." }