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

fix(brain): CodeRabbit review hardening for the unreleased v1.26.0 (#128)

Sol Aitken61a9ad66004a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index beedf744..e371f9f4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,14 @@ A memory-signal provenance and lifecycle integrity layer that closes five gaps i
- **Declared-thesis register with new-note monitor.** A new `Brain/theses/` frontmatter kind records operator positions (statement, supporting and counter evidence, last-updated, falsification criterion). A monitor evaluates each newly-ingested note against active theses, flagging support or contradiction, reuses the obligations cadence machinery for a staleness check and a thesis-graveyard pass, and alerts when incoming evidence matches a thesis documented falsification scenario.
- **Session-bracketing memory wrapper for Aider.** A new `scripts/o2b-aider` wrapper (also `o2b aider wrap`) brackets an Aider session: it re-renders the static context sidecar at start, execs the Aider binary with the injected `read:` context, and at session end runs the write-back half (capture and persist the session into the Brain), mirroring Hermes `prefetch`, `sync_turn`, and `on_session_end`. The install-time sidecar adapter stays as the fallback for users who do not run through the wrapper.
+### Fixed
+
+- **Shared preference no longer deletable by `forget-source`.** `deleteBySource` now reads a preference's managed `_evidenced_by` links (not only the legacy `evidenced_by` key) and applies the foreign-evidence guard to preferences matched by a `[[source]]` wikilink, so a preference folded from any foreign signal is reported, never auto-deleted on `--confirm`.
+- **Provenance folded into idempotency hashes.** The preference idempotency hash now includes `owner`, and the session-checkpoint hash now includes `host` and `sourceTurnIds`, so a retry that changes only owner-visibility or checkpoint provenance raises `IdempotencyPayloadMismatchError` instead of silently deduping under the wrong scope.
+- **Apply-evidence honors the idempotency ledger verdict.** `appendApplyEvidence` now acts on `rememberKey`'s return value: a concurrent same-key write with a different payload raises the mismatch error, and a same-payload race returns the winner's row as a deduped result instead of a second normal write.
+- **Partial `forget-source` cleanup stays auditable.** A `removeFile` failure mid-cleanup now still writes the `source_invalidation` audit record for the paths already removed before rethrowing, so a retry can reconstruct the state.
+- **CLI error contracts.** `brain batch-plan` with no `<source-dir>` now exits 2 as a usage error, and `brain forget-source --json` emits a parseable `{ ok: false, message }` envelope on a runtime failure instead of plain-text stderr.
+
## [1.25.0] - 2026-07-07
An economics and observability layer for the context pack. Five new
diff --git a/src/cli/brain/verbs/batch-plan.ts b/src/cli/brain/verbs/batch-plan.ts
index 3f4d75b8..f3d46e42 100644
--- a/src/cli/brain/verbs/batch-plan.ts
+++ b/src/cli/brain/verbs/batch-plan.ts
@@ -11,7 +11,7 @@
*/
import { planBatches } from "../../../core/brain/ingest/batch-plan.ts";
-import { brainVerbContext, fail, info, ok, okJson, parse } from "../helpers.ts";
+import { brainVerbContext, fail, info, ok, okJson, parse, usageError } from "../helpers.ts";
/** Default caps, mirroring the MCP surface (1 MiB / 25 files per batch). */
const DEFAULT_MAX_BATCH_BYTES = 1024 * 1024;
@@ -35,7 +35,7 @@ export async function cmdBrainBatchPlan(argv: string[]): Promise<number> {
});
const sourceDir = positional[0];
if (!sourceDir) {
- return fail(
+ return usageError(
"usage: o2b brain batch-plan <source-dir> [--max-bytes N] [--max-files N] [--json]",
);
}
diff --git a/src/cli/brain/verbs/forget-source.ts b/src/cli/brain/verbs/forget-source.ts
index a82ee05d..bb77acf5 100644
--- a/src/cli/brain/verbs/forget-source.ts
+++ b/src/cli/brain/verbs/forget-source.ts
@@ -92,6 +92,13 @@ export async function cmdBrainForgetSource(argv: string[]): Promise<number> {
info(" re-run with --confirm to delete");
return 0;
} catch (err) {
- return fail((err as Error).message ?? String(err));
+ const message = (err as Error).message ?? String(err);
+ // In `--json` mode automation expects a parseable envelope even on a
+ // runtime failure; a plain-text `fail()` would break the JSON contract.
+ if (flags["json"]) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
}
}
diff --git a/src/core/brain/apply-evidence.ts b/src/core/brain/apply-evidence.ts
index 375e2eae..286cb03a 100644
--- a/src/core/brain/apply-evidence.ts
+++ b/src/core/brain/apply-evidence.ts
@@ -37,6 +37,7 @@ import {
computePayloadHash,
IdempotencyPayloadMismatchError,
lookupKey,
+ REMEMBER_KEY_STATUS,
rememberKey,
} from "./idempotency-ledger.ts";
import { appendLogEvent, type AppendLogEventResult, type BrainLogEntry } from "./log.ts";
@@ -285,14 +286,35 @@ export function appendApplyEvidence(
};
const result: AppendLogEventResult = appendLogEvent(vault, entry);
- // Record the key AFTER the row lands so a future retry dedupes.
+ // Record the key AFTER the row lands so a future retry dedupes. Under a
+ // concurrent same-key race the unlocked lookupKey above can miss a rival
+ // write; rememberKey re-checks under its shard lock and returns the verdict,
+ // which we MUST act on (the ledger never throws β€” the writer decides).
if (idKey && idContentHash !== undefined) {
- rememberKey(vault, {
+ const remembered = rememberKey(vault, {
key: idKey,
contentHash: idContentHash,
createdAt: timestamp,
ref: { logged_at: timestamp, log_path: relative(vault, result.logPath) },
});
+ if (remembered.status === REMEMBER_KEY_STATUS.payload_mismatch) {
+ throw new IdempotencyPayloadMismatchError(
+ idKey,
+ remembered.record.contentHash,
+ idContentHash,
+ );
+ }
+ if (remembered.status === REMEMBER_KEY_STATUS.duplicate_match) {
+ // A rival process won the key with the same payload between our unlocked
+ // lookup and this locked record; report the winner's row as the deduped
+ // result instead of a second normal write.
+ const ref = (remembered.record.ref ?? {}) as { logged_at?: string; log_path?: string };
+ return {
+ logged_at: ref.logged_at ?? timestamp,
+ log_path: ref.log_path ? join(vault, ref.log_path) : result.logPath,
+ deduped: true,
+ };
+ }
}
return { logged_at: timestamp, log_path: result.logPath };
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index c3433ee2..3e8ea8d9 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -405,6 +405,10 @@ function preferencePayloadFields(
scope: input.scope?.trim(),
status: input.status,
evidenced_by: [...input.evidenced_by],
+ // `owner` drives owner-scoped visibility and is written to frontmatter,
+ // so a retry that only changes it must NOT silently dedupe β€” fold it into
+ // the idempotency hash (mirrors the write path at recordPreference).
+ owner: input.owner?.trim(),
};
}
diff --git a/src/core/brain/session-checkpoint.ts b/src/core/brain/session-checkpoint.ts
index c81a3f3e..5427348d 100644
--- a/src/core/brain/session-checkpoint.ts
+++ b/src/core/brain/session-checkpoint.ts
@@ -156,6 +156,11 @@ function checkpointPayloadFields(input: SessionCheckpointInput): Record<string,
learnings: input.learnings ? [...input.learnings] : undefined,
next_steps: input.nextSteps ? [...input.nextSteps] : undefined,
diary: input.diary,
+ // `host` and `sourceTurnIds` are written to disk (appendSessionSummary), so
+ // a retry with the same session id but different provenance must raise the
+ // mismatch error rather than silently deduping.
+ host: input.host,
+ source_turn_ids: input.sourceTurnIds ? [...input.sourceTurnIds] : undefined,
};
}
diff --git a/src/core/brain/source-cleanup.ts b/src/core/brain/source-cleanup.ts
index c753a66f..19642141 100644
--- a/src/core/brain/source-cleanup.ts
+++ b/src/core/brain/source-cleanup.ts
@@ -242,7 +242,12 @@ function directMatch(
const kind = classifyKind(vault, absPath);
const sourceLinks = stringArrayField(meta, "source");
- const evidencedBy = stringArrayField(meta, "evidenced_by");
+ // Managed `_evidenced_by` links take precedence over the legacy plain key
+ // (see evidencedByLinks). Reading only the plain key here let a preference
+ // whose evidence lives in `_evidenced_by` slip past the foreign-evidence
+ // guard in computeDeletable and be auto-deleted as a first-pass wikilink
+ // match, even when it is a shared fold.
+ const evidencedBy = evidencedByLinks(meta);
const base = {
absPath,
path: vaultRelative(absPath, vault),
@@ -373,7 +378,11 @@ function computeDeletable(
// A signal citing a second source is a shared observation β€” report it.
if (!tracesSolelyToSource(raw, canonical)) return false;
// A preference folded from any foreign signal is a shared fold β€” report it.
- if (raw.match === "evidenced_by") {
+ // This holds however the preference was first matched: a second-pass
+ // `evidenced_by` fold OR a first-pass `[[source]]` wikilink match that also
+ // carries evidence links. Keying only on match === "evidenced_by" let a
+ // wikilink-matched shared preference reach `--confirm` deletion.
+ if (raw.kind === "preference" && raw.evidencedBy.length > 0) {
const targets = raw.evidencedBy.map((link) => wikilinkTarget(link));
if (!targets.every((t) => derivedSignalIds.has(t))) return false;
}
@@ -496,28 +505,13 @@ export function deleteBySource(
// Confirmed path β€” delete the derived entries first, then (opt-in) the
// originals, then drop the manifest entry (an index artifact).
const deleted: string[] = [];
- for (const entry of derived) {
- if (removeFile(vault, entry.path)) deleted.push(entry.path);
- }
- if (includeOriginals) {
- for (const original of originals) {
- if (removeFile(vault, original)) deleted.push(original);
- }
- }
-
let manifestEntryRemoved = false;
- if (manifestKey !== null && existsSync(manifestPath(vault))) {
- const entries = { ...readManifest(vault).entries };
- if (entries[manifestKey] !== undefined) {
- delete entries[manifestKey];
- manifestEntryRemoved = writeManifestAtomic(vault, entries);
- }
- }
// Audit only a run that actually changed something; a no-op re-run writes
- // no record (idempotent).
- let auditRecordId: string | null = null;
- if (deleted.length > 0 || manifestEntryRemoved) {
+ // no record (idempotent). Factored so both the success path AND a partial
+ // failure can persist the record of what was already removed.
+ const writeInvalidationAudit = (): string | null => {
+ if (deleted.length === 0 && !manifestEntryRemoved) return null;
const agent = opts.agent?.trim() ? opts.agent.trim() : "delete_by_source";
const record = appendContinuitySourceInvalidation(vault, {
createdAt: isoSecond(opts.now ?? new Date()),
@@ -527,9 +521,42 @@ export function deleteBySource(
`${manifestEntryRemoved ? " and the ingest manifest entry" : ""}` +
`${includeOriginals ? " (originals included)" : ""}`,
});
- auditRecordId = record.id;
+ return record.id;
+ };
+
+ let auditRecordId: string | null = null;
+ try {
+ for (const entry of derived) {
+ if (removeFile(vault, entry.path)) deleted.push(entry.path);
+ }
+ if (includeOriginals) {
+ for (const original of originals) {
+ if (removeFile(vault, original)) deleted.push(original);
+ }
+ }
+
+ if (manifestKey !== null && existsSync(manifestPath(vault))) {
+ const entries = { ...readManifest(vault).entries };
+ if (entries[manifestKey] !== undefined) {
+ delete entries[manifestKey];
+ manifestEntryRemoved = writeManifestAtomic(vault, entries);
+ }
+ }
+ } catch (err) {
+ // A removeFile (or manifest write) that throws mid-cleanup would otherwise
+ // exit before the audit append, leaving already-deleted paths with no
+ // record for a retry to reconstruct. Persist what was removed so far, then
+ // rethrow; never let an audit-write error mask the original failure.
+ try {
+ writeInvalidationAudit();
+ } catch {
+ /* swallow: the original error below is the one that matters */
+ }
+ throw err;
}
+ auditRecordId = writeInvalidationAudit();
+
return Object.freeze({
source: canonical,
confirmed: true,
diff --git a/tests/cli/brain-batch-plan-forget-source.test.ts b/tests/cli/brain-batch-plan-forget-source.test.ts
new file mode 100644
index 00000000..5041ddb3
--- /dev/null
+++ b/tests/cli/brain-batch-plan-forget-source.test.ts
@@ -0,0 +1,24 @@
+/**
+ * CR #127.1 / #127.2: CLI error-contract fixes.
+ * #1 `brain batch-plan` with no <source-dir> is a USAGE error -> exit 2.
+ * #2 `brain forget-source --json` must emit a JSON error envelope (not
+ * plain-text) when a runtime failure is caught, so automation can parse it.
+ */
+import { expect, test } from "bun:test";
+import { runCli } from "../helpers/run-cli.ts";
+
+test("batch-plan without <source-dir> exits 2 (usage error) β€” CR #127.1", async () => {
+ const r = await runCli(["brain", "batch-plan"]);
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("usage:");
+});
+
+test("forget-source --json emits a JSON error envelope on runtime failure β€” CR #127.2", async () => {
+ // No resolvable vault -> brainVerbContext throws inside the try, hitting the
+ // catch. With --json the catch must return a parseable {ok:false} envelope.
+ const r = await runCli(["brain", "forget-source", "ghost-source.md", "--json"]);
+ expect(r.returncode).toBe(1);
+ const parsed = JSON.parse(r.stdout.trim());
+ expect(parsed.ok).toBe(false);
+ expect(typeof parsed.message).toBe("string");
+});
diff --git a/tests/core/brain/session-checkpoint-idempotency.test.ts b/tests/core/brain/session-checkpoint-idempotency.test.ts
new file mode 100644
index 00000000..56b0f75f
--- /dev/null
+++ b/tests/core/brain/session-checkpoint-idempotency.test.ts
@@ -0,0 +1,51 @@
+/**
+ * CR #127.6: `host` and `sourceTurnIds` are written to disk by
+ * `saveSessionCheckpoint`, so a retry with the SAME session id but DIFFERENT
+ * provenance must raise `IdempotencyPayloadMismatchError` rather than silently
+ * deduping. They must therefore be part of the checkpoint content hash.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { saveSessionCheckpoint } from "../../../src/core/brain/session-checkpoint.ts";
+import { IdempotencyPayloadMismatchError } from "../../../src/core/brain/idempotency-ledger.ts";
+
+let vault: string;
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-checkpoint-idem-"));
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const base = {
+ sessionId: "sess-1",
+ agent: "tester",
+ request: "wire the thing",
+ createdAt: "2026-06-01T00:00:00Z",
+};
+
+describe("saveSessionCheckpoint idempotency covers provenance (CR #127.6)", () => {
+ test("same session id + same payload dedupes", () => {
+ const first = saveSessionCheckpoint(vault, { ...base, host: "claude" });
+ const second = saveSessionCheckpoint(vault, { ...base, host: "claude" });
+ expect(second.deduped).toBe(true);
+ expect(first.sessionId).toBe("sess-1");
+ });
+
+ test("same session id + different host throws", () => {
+ saveSessionCheckpoint(vault, { ...base, host: "claude" });
+ expect(() => saveSessionCheckpoint(vault, { ...base, host: "codex" })).toThrow(
+ IdempotencyPayloadMismatchError,
+ );
+ });
+
+ test("same session id + different sourceTurnIds throws", () => {
+ saveSessionCheckpoint(vault, { ...base, sourceTurnIds: ["t1", "t2"] });
+ expect(() => saveSessionCheckpoint(vault, { ...base, sourceTurnIds: ["t1", "t3"] })).toThrow(
+ IdempotencyPayloadMismatchError,
+ );
+ });
+});
diff --git a/tests/core/brain/source-cleanup.test.ts b/tests/core/brain/source-cleanup.test.ts
index 0bef256c..046b4a03 100644
--- a/tests/core/brain/source-cleanup.test.ts
+++ b/tests/core/brain/source-cleanup.test.ts
@@ -250,3 +250,42 @@ describe("deleteBySource β€” confirmed cleanup", () => {
expect(second.auditRecordId).toBeNull();
});
});
+
+describe("deleteBySource β€” shared preference via managed _evidenced_by (CR #127.7)", () => {
+ test("a wikilink-matched preference evidenced by a FOREIGN signal is reported, never deleted", () => {
+ seedContaminatedVault();
+
+ // A signal that derives from the OTHER (legit) source β€” foreign to SOURCE.
+ const foreign = writeSignal(vault, {
+ topic: "external",
+ signal: "positive",
+ agent: "tester",
+ principle: "Derived from a legitimate, unrelated source.",
+ created_at: "2026-06-01T00:00:00Z",
+ date: "2026-06-01",
+ slug: "external-derived",
+ source: [`[[${OTHER_SOURCE}]]`],
+ });
+
+ // A shared preference whose evidence lives in the MANAGED `_evidenced_by`
+ // key (points at the foreign signal), and whose body also mentions
+ // [[SOURCE]]. It is a shared fold: deleting SOURCE must NOT remove it.
+ const sharedPref = join(vault, "Brain", "preferences", "pref-shared-external.md");
+ writeFileSync(
+ sharedPref,
+ `---\nid: pref-shared-external\n_evidenced_by: ["[[${foreign.id}]]"]\n---\n` +
+ `A shared preference that also mentions [[${SOURCE}]] in prose.\n`,
+ "utf8",
+ );
+
+ const plan = deleteBySource(vault, SOURCE, { confirm: true, now: NOW });
+
+ const rel = "Brain/preferences/pref-shared-external.md";
+ // It must be reported as a protected mention, not queued for deletion.
+ expect(plan.mentions.some((m) => m.path === rel)).toBe(true);
+ expect(plan.derived.some((d) => d.path === rel)).toBe(false);
+ expect(plan.deleted).not.toContain(rel);
+ // And it survives on disk.
+ expect(existsSync(sharedPref)).toBe(true);
+ });
+});
diff --git a/tests/core/brain/writer-idempotency.test.ts b/tests/core/brain/writer-idempotency.test.ts
index 52c46293..24be366a 100644
--- a/tests/core/brain/writer-idempotency.test.ts
+++ b/tests/core/brain/writer-idempotency.test.ts
@@ -133,6 +133,26 @@ describe("writePreference idempotency key", () => {
IdempotencyPayloadMismatchError,
);
});
+
+ test("same key + different owner throws (CR #127.4)", () => {
+ const base = {
+ slug: "rule-owner",
+ topic: "coding",
+ principle: "prefer X",
+ created_at: "2026-05-14T10:00:00Z",
+ unconfirmed_until: "2026-05-14T10:00:00Z",
+ status: "confirmed" as const,
+ evidenced_by: ["[[sig-1]]"],
+ idempotency_key: "pref-key-owner",
+ owner: "alice",
+ };
+ writePreference(vault, base);
+ // `owner` drives owner-scoped visibility, so a retry that only changes it
+ // must raise the mismatch rather than silently deduping under the old owner.
+ expect(() => writePreference(vault, { ...base, owner: "bob" })).toThrow(
+ IdempotencyPayloadMismatchError,
+ );
+ });
});
describe("appendApplyEvidence idempotency key", () => {