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
/**
* Kernel 2 (atomic multi-operation write core) unit tests, note-op
* vocabulary (W1, t_3ff3fe77).
*
* The core validates and projects an ordered operation list in memory
* first, then commits to disk as a unit; the first invalid operation
* aborts with a typed {@link WriteBatchError} naming the operation index
* and no disk write happens. Note operations reuse the exact
* create-note safety envelope (path traversal, Brain machinery root,
* vault-scope exclusions) and atomic-write semantics.
*
* The nothing-writes-silently wave (unit B) adds two refusals to that
* vocabulary, pinned below:
*
* 1. `target_unreadable` - a note that exists and cannot be read is no
* longer projected as an empty note, for update and for append. The
* refusal names the path and the reason, and the file is untouched.
* 1b. `target_frontmatter_lossy` - the same refusal for the other thing
* the parser can report: a frontmatter line it could not express and
* dropped. The read-modify-write re-serialises the parsed map, so
* writing would delete that line and report success.
* 2. `blank_overwrite_refused` - an update may not replace a body that
* carries text with a blank one unless `allowEmpty` says so.
* Whitespace-only is blank; a create of a genuinely new empty note
* is not an update and is unaffected.
*/
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import {
existsSync,
chmodSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import {
applyWriteBatch,
WRITE_BATCH_RECEIPT_STATUS,
WriteBatchError,
type WriteOperation,
} from "../../../src/core/brain/write-batch.ts";
import { PRIVACY_MARKER_KEYS } from "../../../src/core/graph/privacy-markers.ts";
import {
ORIGIN_CHANNEL,
clearOriginChannel,
setOriginChannel,
} from "../../../src/core/origin-channel.ts";
import { WriteRefusedError } from "../../../src/core/brain/pending/pending-lanes.ts";
import { queryDecisionLedger } from "../../../src/core/brain/permissions/ledger.ts";
import * as ledger from "../../../src/core/brain/idempotency-ledger.ts";
import {
IdempotencyKeyError,
IdempotencyPayloadMismatchError,
} from "../../../src/core/brain/idempotency-ledger.ts";
import { writeSignal } from "../../../src/core/brain/signal.ts";
import { listNoteWrites, type NoteWriteRecord } from "../../../src/core/brain/notes/write-log.ts";
import {
NOTE_WRITE_NO_PRIOR,
pruneWriteImages,
} from "../../../src/core/brain/notes/write-record.ts";
import { writeImagePath } from "../../../src/core/brain/paths.ts";
import { applyPendingLane } from "../../../src/core/brain/pending/pending-lanes.ts";
import { sha256Hex } from "../../../src/core/integrity/digest.ts";
import { CHMOD_CANNOT_DENY, IS_WINDOWS } from "../../helpers/platform.ts";
let vault: string;
beforeEach(() => {
vault = mkdtempSync(join(tmpdir(), "o2b-write-batch-"));
// A legacy tree: these tests pin the page layout of an unswitched
// machine (a vault with no `Brain/` is store-only, task 2.10).
mkdirSync(join(vault, "Brain"), { recursive: true });
});
afterEach(() => rmSync(vault, { recursive: true, force: true }));
function seedNote(rel: string, body: string, frontmatter = ""): string {
const abs = join(vault, rel);
mkdirSync(join(abs, ".."), { recursive: true });
const fm = frontmatter ? `---\n${frontmatter}\n---\n\n` : "";
writeFileSync(abs, `${fm}${body}\n`, "utf8");
return abs;
}
describe("applyWriteBatch note operations", () => {
test("a single create_note op writes the file and reports applied:1", () => {
const res = applyWriteBatch(vault, [
{
kind: "create_note",
path: "Notes/New.md",
frontmatter: { title: "New", tags: ["a", "b"] },
content: "Hello body.",
},
]);
expect(res.applied).toBe(1);
expect(res.done).toBe(true);
const md = readFileSync(join(vault, "Notes/New.md"), "utf8");
expect(md).toContain("title: New");
expect(md).toContain("Hello body.");
expect(res.results[0]).toMatchObject({ kind: "create_note", path: "Notes/New.md" });
});
test("update_note merges frontmatter keys and replaces the body", () => {
seedNote("Notes/Doc.md", "old body", "title: Doc\nstatus: draft");
applyWriteBatch(vault, [
{
kind: "update_note",
path: "Notes/Doc.md",
frontmatter: { status: "final", owner: "me" },
body: "new body",
},
]);
const md = readFileSync(join(vault, "Notes/Doc.md"), "utf8");
// Merged: existing title preserved, status overridden, owner added.
expect(md).toContain("title: Doc");
expect(md).toContain("status: final");
expect(md).toContain("owner: me");
expect(md).toContain("new body");
expect(md).not.toContain("old body");
});
test("update_note with only frontmatter keeps the existing body", () => {
seedNote("Notes/Doc.md", "keep me", "title: Doc");
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Doc.md", frontmatter: { status: "final" } },
]);
const md = readFileSync(join(vault, "Notes/Doc.md"), "utf8");
expect(md).toContain("keep me");
expect(md).toContain("status: final");
});
test("append_note appends to the existing body without touching frontmatter", () => {
seedNote("Notes/Doc.md", "first line", "title: Doc");
applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Doc.md", content: "second line" }]);
const md = readFileSync(join(vault, "Notes/Doc.md"), "utf8");
expect(md).toContain("title: Doc");
expect(md).toContain("first line");
expect(md).toContain("second line");
expect(md.indexOf("first line")).toBeLessThan(md.indexOf("second line"));
});
test("update_note on a missing target is a typed error and writes nothing", () => {
let thrown: unknown;
try {
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Ghost.md", body: "x" }]);
} catch (err) {
thrown = err;
}
expect(thrown).toBeInstanceOf(WriteBatchError);
expect((thrown as WriteBatchError).code).toBe("target_missing");
expect((thrown as WriteBatchError).index).toBe(0);
expect(existsSync(join(vault, "Notes/Ghost.md"))).toBe(false);
});
test("append_note on a missing target is a typed error", () => {
expect(() =>
applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Ghost.md", content: "x" }]),
).toThrow(WriteBatchError);
});
test("update_note requires at least frontmatter or a body", () => {
seedNote("Notes/Doc.md", "body", "title: Doc");
try {
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("invalid_operation");
}
});
test("update_note refuses reserved boundary keys in caller frontmatter (t_sec_reserved_keys)", () => {
// `visibility` is the read-boundary token field: one merged key would
// demote a private page out of the boundary without ever reading it.
seedNote("Notes/Private.md", "secret body", "title: Private\nvisibility: private");
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Private.md", frontmatter: { visibility: "team" } },
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("reserved_frontmatter_key");
expect((err as WriteBatchError).details).toMatchObject({
path: "Notes/Private.md",
key: "visibility",
});
}
// The boundary survived the refused update byte-for-byte.
expect(readFileSync(join(vault, "Notes/Private.md"), "utf8")).toContain("visibility: private");
// `origin_channel` is the server-derived creation stamp: a merged key
// would forge the channel a note did not arrive through.
seedNote("Notes/Sourced.md", "body", "title: S\norigin_channel: mcp");
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Sourced.md", frontmatter: { origin_channel: "cli" } },
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("reserved_frontmatter_key");
}
expect(readFileSync(join(vault, "Notes/Sourced.md"), "utf8")).toContain("origin_channel: mcp");
// A batch aborts wholesale in the projection phase, so a reserved key
// in one op leaves the other op's file untouched too.
seedNote("Notes/Other.md", "body", "title: O");
expect(() =>
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Other.md", frontmatter: { status: "final" } },
{ kind: "update_note", path: "Notes/Private.md", frontmatter: { visibility: "team" } },
]),
).toThrow(WriteBatchError);
expect(readFileSync(join(vault, "Notes/Other.md"), "utf8")).not.toContain("status: final");
});
test("an mcp-lane update of a cli-stamped page re-stamps the channel it did not earn", () => {
seedNote("Notes/Operator.md", "operator body", "title: O\norigin_channel: cli");
setOriginChannel(ORIGIN_CHANNEL.mcpTool);
try {
const res = applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Operator.md", body: "agent-authored body" },
]);
expect(res.results[0]).toMatchObject({ kind: "update_note", updated: true });
} finally {
clearOriginChannel();
}
const md = readFileSync(join(vault, "Notes/Operator.md"), "utf8");
// The stamp now names the process that wrote the page's current
// words; the delivery side reads `cli` as operator-authored plain
// text, so the inherited stamp could not survive the mutation.
expect(md).toContain("origin_channel: mcp-tool");
expect(md).not.toContain("origin_channel: cli");
expect(md).toContain("agent-authored body");
});
test("an mcp-lane append of a cli-stamped page re-stamps the channel too", () => {
seedNote("Notes/Operator.md", "operator body", "title: O\norigin_channel: cli");
setOriginChannel(ORIGIN_CHANNEL.mcpTool);
try {
const res = applyWriteBatch(vault, [
{ kind: "append_note", path: "Notes/Operator.md", content: "appended by agent" },
]);
expect(res.results[0]).toMatchObject({ kind: "append_note", appended: true });
} finally {
clearOriginChannel();
}
const md = readFileSync(join(vault, "Notes/Operator.md"), "utf8");
expect(md).toContain("origin_channel: mcp-tool");
expect(md).not.toContain("origin_channel: cli");
expect(md).toContain("operator body");
expect(md).toContain("appended by agent");
});
test("an unclaimed-process mutation of a cli-stamped page stamps unset", () => {
seedNote("Notes/Operator.md", "operator body", "title: O\norigin_channel: cli");
// No lane claimed this process, so the mutation's channel is the
// explicit `unset` literal - the stamp a page inherits but its
// writer did not earn is rewritten to THAT, never left as `cli`:
// the delivery side reads a surviving `cli` as operator-authored
// plain text, which words an unclaimed process wrote are not.
clearOriginChannel();
try {
applyWriteBatch(vault, [
{ kind: "append_note", path: "Notes/Operator.md", content: "unclaimed text" },
]);
} finally {
clearOriginChannel();
}
const md = readFileSync(join(vault, "Notes/Operator.md"), "utf8");
expect(md).toContain("origin_channel: unset");
expect(md).not.toContain("origin_channel: cli");
expect(md).not.toContain("origin_channel: mcp-tool");
});
test("a cli-lane mutation keeps the operator stamp it earned", () => {
seedNote("Notes/Operator.md", "operator body", "title: O\norigin_channel: cli");
setOriginChannel(ORIGIN_CHANNEL.cli);
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Operator.md", body: "operator's own edit" },
]);
} finally {
clearOriginChannel();
}
const md = readFileSync(join(vault, "Notes/Operator.md"), "utf8");
expect(md).toContain("origin_channel: cli");
expect(md).not.toContain("origin_channel: mcp-tool");
});
test("a mutation never backfills a stamp onto a legacy page", () => {
seedNote("Notes/Legacy.md", "legacy body", "title: L");
setOriginChannel(ORIGIN_CHANNEL.mcpTool);
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Legacy.md", body: "agent-authored body" },
]);
} finally {
clearOriginChannel();
}
const md = readFileSync(join(vault, "Notes/Legacy.md"), "utf8");
// No stamp existed, so none is added: absence means "written before
// the stamp existed" and the delivery side already fails closed on it.
expect(md).not.toContain("origin_channel");
});
test("update_note refuses the informal privacy marker keys, creation does not", () => {
// The marker keys are boundary state like `visibility`: the read roots
// resolve `access: private` (and its two siblings) to the reserved
// remote-deny token, so a merged `access: ""` would clear the
// reservation without the caller ever naming the boundary.
for (const markerKey of PRIVACY_MARKER_KEYS) {
const rel = `Notes/Marked-${markerKey}.md`;
seedNote(rel, "body", `title: M\n${markerKey}: private`);
let thrown: unknown;
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: rel, frontmatter: { [markerKey]: "" } },
]);
throw new Error("expected throw");
} catch (err) {
thrown = err;
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("reserved_frontmatter_key");
// The refusal names the key, in the visibility posture.
expect((err as WriteBatchError).message).toContain(markerKey);
expect((err as WriteBatchError).message).toContain("edit the note directly");
expect((err as WriteBatchError).details).toMatchObject({ path: rel, key: markerKey });
}
// The marker survived the refused update byte-for-byte.
expect(readFileSync(join(vault, rel), "utf8")).toContain(`${markerKey}: private`);
}
// Creation is not restricted: the guard lives at the update merge, so
// a caller may still author a marker through create_note.
const res = applyWriteBatch(vault, [
{
kind: "create_note",
path: "Notes/Authored.md",
frontmatter: { title: "A", access: "private" },
content: "body",
},
]);
expect(res.applied).toBe(1);
expect(readFileSync(join(vault, "Notes/Authored.md"), "utf8")).toContain("access: private");
});
test("update_note writes a marker key whose deny status stands still", () => {
// The guard is about the note's deny status, not the key's presence:
// a value that denies nothing (`read-only`), or a move between two
// non-deny values, is note content like any other key's.
seedNote("Notes/ReadOnly.md", "body", "title: R\naccess: read-only");
const res = applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/ReadOnly.md", frontmatter: { access: "read-only" } },
]);
expect(res.applied).toBe(1);
expect(readFileSync(join(vault, "Notes/ReadOnly.md"), "utf8")).toContain("access: read-only");
seedNote("Notes/Move.md", "body", "title: M\naccess: public");
const moved = applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Move.md", frontmatter: { access: "team" } },
]);
expect(moved.applied).toBe(1);
expect(readFileSync(join(vault, "Notes/Move.md"), "utf8")).toContain("access: team");
// A marker note is otherwise a normal note: an update that leaves the
// deny status standing still writes its other content keys as usual.
seedNote("Notes/Marked.md", "body", "title: K\naccess: private");
const sideBySide = applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Marked.md", frontmatter: { status: "final" } },
]);
expect(sideBySide.applied).toBe(1);
const marked = readFileSync(join(vault, "Notes/Marked.md"), "utf8");
expect(marked).toContain("access: private");
expect(marked).toContain("status: final");
});
test("update_note refuses a merge that clears or forges the note's deny value", () => {
// Clearing: `access: private` rewritten to a non-deny value would lift
// the reservation without the caller ever naming the boundary.
seedNote("Notes/Clear.md", "body", "title: C\naccess: private");
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Clear.md", frontmatter: { access: "public" } },
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("reserved_frontmatter_key");
expect((err as WriteBatchError).message).toContain("access");
expect((err as WriteBatchError).message).toContain("edit the note directly");
expect((err as WriteBatchError).details).toMatchObject({
path: "Notes/Clear.md",
key: "access",
});
}
expect(readFileSync(join(vault, "Notes/Clear.md"), "utf8")).toContain("access: private");
// Forging: a deny value the note did not carry arrives the same way,
// silently, through the same merge.
seedNote("Notes/Forge.md", "body", "title: F\nsensitivity: internal");
try {
applyWriteBatch(vault, [
{
kind: "update_note",
path: "Notes/Forge.md",
frontmatter: { sensitivity: "confidential" },
},
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("reserved_frontmatter_key");
expect((err as WriteBatchError).details).toMatchObject({
path: "Notes/Forge.md",
key: "sensitivity",
});
}
expect(readFileSync(join(vault, "Notes/Forge.md"), "utf8")).toContain("sensitivity: internal");
});
test("update_note matches reserved keys whatever their case", () => {
// The frontmatter parser keeps a key's spelling, so `Access:` is a
// different map key from `access:` - but it states the same boundary
// claim, and a guard reading only the lower-case form would wave it
// through the merge.
seedNote("Notes/Cased.md", "body", "title: X");
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Cased.md", frontmatter: { Access: "private" } },
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("reserved_frontmatter_key");
expect((err as WriteBatchError).details).toMatchObject({
path: "Notes/Cased.md",
key: "Access",
});
}
seedNote("Notes/Privately.md", "body", "title: P\nvisibility: private");
expect(() =>
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Privately.md", frontmatter: { Visibility: "team" } },
]),
).toThrow(WriteBatchError);
expect(readFileSync(join(vault, "Notes/Privately.md"), "utf8")).toContain(
"visibility: private",
);
});
test("create_note refuses to clobber an existing note", () => {
seedNote("Notes/Dup.md", "original");
try {
applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Dup.md", content: "new" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("exists");
}
expect(readFileSync(join(vault, "Notes/Dup.md"), "utf8")).toContain("original");
});
test("path traversal is refused via the create-note safety envelope", () => {
try {
applyWriteBatch(vault, [{ kind: "update_note", path: "../escape.md", body: "x" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("invalid_path");
}
expect(existsSync(join(vault, "..", "escape.md"))).toBe(false);
});
test("the Brain machinery root is refused", () => {
try {
applyWriteBatch(vault, [{ kind: "create_note", path: "Brain/sneaky.md", content: "x" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("excluded");
}
});
test("an empty operations list is a typed error", () => {
expect(() => applyWriteBatch(vault, [])).toThrow(WriteBatchError);
});
test("an unknown op kind aborts with the operation index", () => {
seedNote("Notes/Doc.md", "body", "title: Doc");
try {
applyWriteBatch(vault, [
{ kind: "append_note", path: "Notes/Doc.md", content: "x" },
// deliberately malformed op at index 1
{ kind: "frobnicate" } as never,
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("invalid_operation");
expect((err as WriteBatchError).index).toBe(1);
}
});
test("a later invalid op aborts the whole batch: earlier ops do not land", () => {
const abs = seedNote("Notes/A.md", "unchanged", "title: A");
const before = readFileSync(abs, "utf8");
expect(() =>
applyWriteBatch(vault, [
// op 0: a valid update to an existing note.
{ kind: "update_note", path: "Notes/A.md", body: "would change" },
// op 1: invalid - target does not exist. Must abort before commit.
{ kind: "update_note", path: "Notes/Missing.md", body: "y" },
]),
).toThrow(WriteBatchError);
// Op 0 must NOT have landed because op 1 failed validation first.
expect(readFileSync(abs, "utf8")).toBe(before);
});
test("two operations targeting the same note in one batch are refused", () => {
seedNote("Notes/A.md", "body", "title: A");
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/A.md", body: "one" },
{ kind: "append_note", path: "Notes/A.md", content: "two" },
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("duplicate_target");
expect((err as WriteBatchError).index).toBe(1);
}
});
test("update_note refuses a blank body over a note that has one", () => {
const abs = seedNote("Notes/Doc.md", "worth keeping", "title: Doc");
const before = readFileSync(abs, "utf8");
try {
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("blank_overwrite_refused");
expect((err as WriteBatchError).index).toBe(0);
// The refusal names the note, not just the operation index.
expect((err as WriteBatchError).message).toContain("Notes/Doc.md");
expect((err as WriteBatchError).details).toMatchObject({ path: "Notes/Doc.md" });
}
expect(readFileSync(abs, "utf8")).toBe(before);
});
test("a whitespace-only body is a blank one: the parser would trim it away", () => {
const abs = seedNote("Notes/Doc.md", "worth keeping", "title: Doc");
const before = readFileSync(abs, "utf8");
expect(() =>
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: " \n\t\n" }]),
).toThrow(WriteBatchError);
expect(readFileSync(abs, "utf8")).toBe(before);
});
test("allowEmpty clears the body deliberately, keeping the frontmatter", () => {
const abs = seedNote("Notes/Doc.md", "worth keeping", "title: Doc");
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Doc.md", body: "", allowEmpty: true },
]);
const md = readFileSync(abs, "utf8");
expect(md).toContain("title: Doc");
expect(md).not.toContain("worth keeping");
});
test("a frontmatter-only update never trips the blank guard", () => {
seedNote("Notes/Doc.md", "worth keeping", "title: Doc");
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Doc.md", frontmatter: { status: "final" } },
]);
const md = readFileSync(join(vault, "Notes/Doc.md"), "utf8");
expect(md).toContain("worth keeping");
expect(md).toContain("status: final");
});
test("creating a genuinely new empty note is untouched by the guard", () => {
const res = applyWriteBatch(vault, [
{ kind: "create_note", path: "Notes/Empty.md", frontmatter: { title: "Empty" } },
]);
expect(res.applied).toBe(1);
const md = readFileSync(join(vault, "Notes/Empty.md"), "utf8");
expect(md).toContain("title: Empty");
});
test("an update on a note that cannot be read is refused, and nothing is written", () => {
// A directory standing where a note should be: `existsSync` says
// yes and `readFileSync` raises EISDIR - an existing target the
// process cannot read, without depending on permission bits.
const abs = join(vault, "Notes/Doc.md");
mkdirSync(abs, { recursive: true });
try {
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "replacement" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("target_unreadable");
expect((err as WriteBatchError).message).toContain("Notes/Doc.md");
// The reason travels with the refusal; a bare "could not read"
// would leave the operator guessing between a permission bit and
// a missing mount.
expect(String((err as WriteBatchError).details["reason"])).toContain("EISDIR");
}
expect(statSync(abs).isDirectory()).toBe(true);
});
test("an append onto a note that cannot be read is refused, and nothing is written", () => {
const abs = join(vault, "Notes/Doc.md");
mkdirSync(abs, { recursive: true });
try {
applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Doc.md", content: "more" }]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("target_unreadable");
}
expect(statSync(abs).isDirectory()).toBe(true);
});
test("an update on a note whose frontmatter the scanner cannot express is refused", () => {
// The line scanner has no branch for a continuation line, so it drops
// it and says so. A read-modify-write re-serialises the PARSED map, so
// proceeding would delete that line from disk and answer updated: true.
const abs = seedNote("Notes/Odd.md", "body", "title: Odd\n continued indent line");
const before = readFileSync(abs, "utf8");
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Odd.md", frontmatter: { reviewed: "2026-08-23" } },
]);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(WriteBatchError);
expect((err as WriteBatchError).code).toBe("target_frontmatter_lossy");
expect((err as WriteBatchError).message).toContain("Notes/Odd.md");
expect(String((err as WriteBatchError).details["reason"])).toContain("continued indent line");
}
expect(readFileSync(abs, "utf8")).toBe(before);
});
test("an append onto such a note is refused too - it rewrites the same frontmatter", () => {
const abs = seedNote("Notes/Odd.md", "body", "title: Odd\n continued indent line");
const before = readFileSync(abs, "utf8");
expect(() =>
applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Odd.md", content: "more" }]),
).toThrow(WriteBatchError);
expect(readFileSync(abs, "utf8")).toBe(before);
});
test("frontmatter the scanner does express is updated as before", () => {
// The refusal is scoped to a line the parser reported dropping: a
// comment and a block list are both consumed, not dropped.
const abs = seedNote("Notes/Fine.md", "body", "# a comment\ntags:\n - one\ntitle: Fine");
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Fine.md", frontmatter: { status: "final" } },
]);
const md = readFileSync(abs, "utf8");
expect(md).toContain("status: final");
expect(md).toContain("title: Fine");
});
// Root bypasses the permission bits this case needs, and on Windows chmod
// only sets the read-only attribute, which never makes a file unreadable.
test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable-by-permission note is refused rather than blanked",
() => {
const abs = seedNote("Notes/Secret.md", "the body that must survive", "title: Secret");
const before = readFileSync(abs, "utf8");
chmodSync(abs, 0o000);
try {
expect(() =>
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Secret.md", body: "new" }]),
).toThrow(WriteBatchError);
} finally {
chmodSync(abs, 0o600);
}
expect(readFileSync(abs, "utf8")).toBe(before);
},
);
test("an unreadable target at op 1 aborts the batch before op 0 lands", () => {
const kept = seedNote("Notes/A.md", "unchanged", "title: A");
const before = readFileSync(kept, "utf8");
mkdirSync(join(vault, "Notes/B.md"), { recursive: true });
expect(() =>
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/A.md", body: "would change" },
{ kind: "update_note", path: "Notes/B.md", body: "y" },
]),
).toThrow(WriteBatchError);
expect(readFileSync(kept, "utf8")).toBe(before);
});
// The Windows counterpart of the two permission cases above: chmod sets
// the read-only attribute, the note stays readable, and the rewrite's
// rename onto it would fail with a raw EPERM mid-commit. It is refused
// in the projection instead, under the same named code.
test.skipIf(!IS_WINDOWS)(
"a note with the read-only attribute is refused as target_unreadable, untouched",
() => {
const abs = seedNote("Notes/Locked.md", "the body that must survive", "title: Locked");
const before = readFileSync(abs, "utf8");
chmodSync(abs, 0o444);
try {
for (const op of [
{ kind: "update_note", path: "Notes/Locked.md", body: "new" },
{ kind: "append_note", path: "Notes/Locked.md", content: "more" },
] as const) {
let caught: unknown;
try {
applyWriteBatch(vault, [op]);
} catch (err) {
caught = err;
}
expect(caught).toBeInstanceOf(WriteBatchError);
expect((caught as WriteBatchError).code).toBe("target_unreadable");
expect((caught as WriteBatchError).details["path"]).toBe("Notes/Locked.md");
}
} finally {
chmodSync(abs, 0o644);
}
expect(readFileSync(abs, "utf8")).toBe(before);
expect(listNoteWrites(vault).writes).toHaveLength(0);
},
);
// Root bypasses filesystem permission bits, and a Windows directory marked
// read-only still accepts new files, so the read-only-directory injection
// cannot force a write failure on either.
test.skipIf(CHMOD_CANNOT_DENY)("a mid-write failure leaves the target byte-identical", () => {
const dir = join(vault, "Notes");
const abs = seedNote("Notes/Doc.md", "original body", "title: Doc");
const before = readFileSync(abs, "utf8");
chmodSync(dir, 0o500); // r-x: readable for the projection, not writable for the commit
try {
expect(() =>
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "new body" }]),
).toThrow();
} finally {
chmodSync(dir, 0o700);
}
// The atomic temp-file + rename pipeline never touched the target.
expect(readFileSync(abs, "utf8")).toBe(before);
});
});
/**
* Attributable note writes (who-wrote-what, Task A / t_662f4e82).
*
* The kernel is one of the two seams every note mutation funnels through,
* so this is where "exactly one event per write" is pinned - along with
* the before-image, which is what makes a recorded write undoable rather
* than merely visible.
*/
describe("applyWriteBatch note-write attribution", () => {
function noteWrites(): ReadonlyArray<NoteWriteRecord> {
return listNoteWrites(vault).writes;
}
test("each of the three note operations appends exactly one event", () => {
seedNote("Notes/Doc.md", "original body", "title: Doc");
applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Fresh.md", content: "fresh" }]);
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "next body" }]);
applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Doc.md", content: "more" }]);
const writes = noteWrites();
expect(writes).toHaveLength(3);
expect(writes.map((w) => `${w.op} ${w.target}`).toSorted()).toEqual([
"append Notes/Doc.md",
"create Notes/Fresh.md",
"update Notes/Doc.md",
]);
});
test("every note result carries the id of the event that attributes it", () => {
seedNote("Notes/Doc.md", "original body", "title: Doc");
const res = applyWriteBatch(vault, [
{ kind: "create_note", path: "Notes/Fresh.md", content: "fresh" },
{ kind: "update_note", path: "Notes/Doc.md", body: "next body" },
]);
const ids = res.results.map((r) => ("write_id" in r ? r.write_id : null));
for (const id of ids) expect(id).toMatch(/^nw_\d{14}_[0-9a-f]{16}$/);
expect(new Set(noteWrites().map((w) => w.write_id))).toEqual(new Set(ids as string[]));
// The audit half is a pair: an id present means no reason is owed.
for (const r of res.results) expect("audit_reason" in r).toBe(false);
});
test("an update records the bytes it replaced and the bytes it wrote", () => {
const abs = seedNote("Notes/Doc.md", "original body", "title: Doc");
const before = readFileSync(abs, "utf8");
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "next body" }]);
const after = readFileSync(abs, "utf8");
const write = noteWrites()[0]!;
expect(write.hash_before).toBe(sha256Hex(before));
expect(write.hash_after).toBe(sha256Hex(after));
expect(write.bytes_before).toBe(Buffer.byteLength(before, "utf8"));
expect(write.bytes_after).toBe(Buffer.byteLength(after, "utf8"));
// The before-image holds the exact prior bytes, keyed by their hash.
expect(readFileSync(writeImagePath(vault, write.hash_before), "utf8")).toBe(before);
});
test("a create records no prior content and stores no image", () => {
applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Fresh.md", content: "fresh" }]);
const write = noteWrites()[0]!;
expect(write.hash_before).toBe(NOTE_WRITE_NO_PRIOR);
expect(write.bytes_before).toBe(0);
expect(pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed).toEqual([]);
});
test("returning a note to a former state re-uses the image already stored", () => {
const abs = seedNote("Notes/Doc.md", "one", "title: Doc");
const first = readFileSync(abs, "utf8");
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "two" }]);
const second = readFileSync(abs, "utf8");
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "one" }]);
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "two" }]);
// Three rewrites, two distinct prior contents, two image files.
expect(noteWrites()).toHaveLength(3);
const stored = pruneWriteImages(vault, { olderThanDays: 0, dryRun: true }).removed;
expect(stored.toSorted()).toEqual([sha256Hex(first), sha256Hex(second)].toSorted());
});
test("the before-image is stored before the rewrite, so a failed store leaves the note as it was", () => {
const abs = seedNote("Notes/Doc.md", "original body", "title: Doc");
const before = readFileSync(abs, "utf8");
// A file where the image directory belongs makes the store throw, the
// way ENOSPC or EACCES under the images directory would.
const imagesDir = dirname(writeImagePath(vault, sha256Hex(before)));
mkdirSync(dirname(imagesDir), { recursive: true });
writeFileSync(imagesDir, "not a directory");
expect(() =>
applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Doc.md", body: "next body" }]),
).toThrow();
// The prior bytes were never replaced without their image, so a retry
// is not mistaken for a byte-identical re-apply.
expect(readFileSync(abs, "utf8")).toBe(before);
expect(noteWrites()).toEqual([]);
});
test("a refused batch records nothing, because no bytes were written", () => {
seedNote("Notes/Doc.md", "original body", "title: Doc");
expect(() =>
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Doc.md", body: "next body" },
{ kind: "update_note", path: "Notes/Missing.md", body: "never" },
]),
).toThrow(WriteBatchError);
expect(noteWrites()).toEqual([]);
});
});
describe("applyWriteBatch client request receipts (t_b34439d9)", () => {
const OPS: ReadonlyArray<WriteOperation> = [
{
kind: "create_note",
path: "Notes/Receipt.md",
frontmatter: { title: "Receipt" },
content: "written once",
},
];
test("without a request id the result carries no receipt and behavior is unchanged", () => {
const res = applyWriteBatch(vault, OPS);
expect(res.applied).toBe(1);
expect(Object.hasOwn(res, "receipt")).toBe(false);
});
test("a fresh request id applies once with an applied receipt", () => {
const res = applyWriteBatch(vault, OPS, { requestId: "req-1" });
expect(res.receipt).toEqual({ requestId: "req-1", status: WRITE_BATCH_RECEIPT_STATUS.applied });
expect(readFileSync(join(vault, "Notes/Receipt.md"), "utf8")).toContain("written once");
});
test("a repeated id with the same payload returns the retained result as a duplicate", () => {
applyWriteBatch(vault, OPS, { requestId: "req-2" });
const before = readFileSync(join(vault, "Notes/Receipt.md"), "utf8");
const retry = applyWriteBatch(vault, OPS, { requestId: "req-2" });
expect(retry.receipt).toEqual({
requestId: "req-2",
status: WRITE_BATCH_RECEIPT_STATUS.duplicate,
});
// The retained original receipt, not a fresh application.
expect(retry.applied).toBe(1);
expect(retry.done).toBe(true);
expect(readFileSync(join(vault, "Notes/Receipt.md"), "utf8")).toBe(before);
});
test("a repeated id with a different payload throws and writes nothing", () => {
applyWriteBatch(vault, OPS, { requestId: "req-3" });
const before = readFileSync(join(vault, "Notes/Receipt.md"), "utf8");
expect(() =>
applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Other.md", content: "x" }], {
requestId: "req-3",
}),
).toThrow(IdempotencyPayloadMismatchError);
expect(existsSync(join(vault, "Notes/Other.md"))).toBe(false);
expect(readFileSync(join(vault, "Notes/Receipt.md"), "utf8")).toBe(before);
});
test("an invalid request id surfaces the ledger's named key error before any write", () => {
for (const bad of ["", " ", "x".repeat(257)]) {
expect(() => applyWriteBatch(vault, OPS, { requestId: bad })).toThrow(IdempotencyKeyError);
}
expect(existsSync(join(vault, "Notes/Receipt.md"))).toBe(false);
});
});
describe("applyWriteBatch request receipt integrity (t_b34439d9 audit)", () => {
const LOG_OP: ReadonlyArray<WriteOperation> = [
{ kind: "append_log_line", input: { text: "receipt race line" } },
];
test("a rival that records the same id with a different payload mid-batch: this call's writes landed and the receipt says so", () => {
applyWriteBatch(vault, LOG_OP, { requestId: "race-1" });
// The unlocked pre-write consult misses the rival's record, as it does
// when a concurrent process records between the consult and the commit.
const spy = spyOn(ledger, "lookupKey").mockReturnValueOnce(null);
try {
const res = applyWriteBatch(
vault,
[{ kind: "append_log_line", input: { text: "a different line" } }],
{ requestId: "race-1" },
);
expect(res.receipt).toEqual({
requestId: "race-1",
status: WRITE_BATCH_RECEIPT_STATUS.payload_conflict,
});
expect(res.applied).toBe(1);
expect(res.done).toBe(true);
const [only] = res.results;
expect(only?.kind).toBe("append_log_line");
const logged = readFileSync(join(vault, (only as { log_path: string }).log_path), "utf8");
expect(logged).toContain("a different line");
} finally {
spy.mockRestore();
}
// The id stays bound to the rival's payload: a retry of this call's
// operations under it is refused, and writes nothing more.
expect(() =>
applyWriteBatch(vault, [{ kind: "append_log_line", input: { text: "a different line" } }], {
requestId: "race-1",
}),
).toThrow(IdempotencyPayloadMismatchError);
});
test("a rival that records the same id and payload mid-batch is named, never reported as applied", () => {
applyWriteBatch(vault, LOG_OP, { requestId: "race-2" });
const spy = spyOn(ledger, "lookupKey").mockReturnValueOnce(null);
try {
const res = applyWriteBatch(vault, LOG_OP, { requestId: "race-2" });
expect(res.receipt).toEqual({
requestId: "race-2",
status: WRITE_BATCH_RECEIPT_STATUS.concurrent_duplicate,
});
} finally {
spy.mockRestore();
}
});
test("a request id does not collide with a brain_feedback idempotency key of the same text", () => {
writeSignal(vault, {
topic: "shared-key-topic",
signal: "positive",
agent: "claude",
principle: "Keep keys apart.",
created_at: "2026-05-01T10:00:00Z",
date: "2026-05-01",
slug: "shared-key-topic",
idempotency_key: "shared-key",
});
const res = applyWriteBatch(vault, LOG_OP, { requestId: "shared-key" });
expect(res.receipt).toEqual({
requestId: "shared-key",
status: WRITE_BATCH_RECEIPT_STATUS.applied,
});
});
test("a non-array operations value with a request id is refused by name", () => {
for (const bad of [null, 42, {}]) {
expect(() =>
applyWriteBatch(vault, bad as unknown as ReadonlyArray<WriteOperation>, {
requestId: "shape-1",
}),
).toThrow(WriteBatchError);
}
});
});
/**
* The review gate (write-side trust, Task 9): a create op stages per-op
* under the notes lane's disposition while update and append ops stay
* direct. The kernel is untouched - a staged create never touches the
* real path, so validate-all-then-commit still projects every op against
* the same pre-batch state.
*/
describe("applyWriteBatch staged creates (review gate)", () => {
const NOTES_ENV = "OPEN_SECOND_BRAIN_WRITE_APPROVAL_NOTES_ENABLED";
let saved: string | undefined;
afterEach(() => {
if (saved === undefined) delete process.env[NOTES_ENV];
else process.env[NOTES_ENV] = saved;
saved = undefined;
});
function gateOn(): void {
saved = process.env[NOTES_ENV];
process.env[NOTES_ENV] = "true";
}
test("a create op stages and reports receipt status staged with the pending id", () => {
gateOn();
const res = applyWriteBatch(vault, [
{ kind: "create_note", path: "Notes/Staged.md", content: "reviewed bytes" },
]);
expect(res.applied).toBe(1);
const only = res.results[0]!;
expect(only).toMatchObject({
kind: "create_note",
path: "Notes/Staged.md",
created: false,
staged: true,
});
if (only.kind !== "create_note" || only.created !== false) throw new Error("unreachable");
const stagedPath = join(vault, "Brain/pending/notes", `${only.pending_id}.md`);
expect(readFileSync(stagedPath, "utf8")).toContain("reviewed bytes");
// Nothing exists at the publish target: the review boundary is entry.
expect(existsSync(join(vault, "Notes/Staged.md"))).toBe(false);
});
test("update and append ops against published notes stay direct under the gate", () => {
gateOn();
seedNote("Notes/Direct.md", "existing body");
const res = applyWriteBatch(vault, [
{ kind: "create_note", path: "Notes/Staged.md", content: "staged" },
{ kind: "append_note", path: "Notes/Direct.md", content: "appended text" },
]);
const staged = res.results[0]!;
const appended = res.results[1]!;
expect(
staged.kind === "create_note" && staged.created === false && staged.staged === true,
).toBe(true);
expect(appended.kind === "append_note" && appended.appended).toBe(true);
expect(readFileSync(join(vault, "Notes/Direct.md"), "utf8")).toContain("appended text");
});
test("an apply of the staged create publishes the exact bytes the batch staged", () => {
gateOn();
const res = applyWriteBatch(vault, [
{
kind: "create_note",
path: "Notes/Round.md",
frontmatter: { title: "Round" },
content: "round trip",
},
]);
const only = res.results[0]!;
if (only.kind !== "create_note" || only.created !== false) throw new Error("unreachable");
const stagedBytes = readFileSync(
join(vault, "Brain/pending/notes", `${only.pending_id}.md`),
"utf8",
);
const applied = applyPendingLane(vault, only.pending_id);
expect(readFileSync(applied.path, "utf8")).toBe(stagedBytes);
expect(applied.path).toBe(join(vault, "Notes/Round.md"));
});
test("an occupied target refuses as exists even under the gate", () => {
gateOn();
seedNote("Notes/Taken.md", "already here");
expect(() =>
applyWriteBatch(vault, [{ kind: "create_note", path: "Notes/Taken.md", content: "x" }]),
).toThrow(WriteBatchError);
});
});
describe("applyWriteBatch under a permissions document", () => {
const DOC = () => join(vault, "Brain", "_permissions.yaml");
function writeDoc(text: string): void {
mkdirSync(join(vault, "Brain"), { recursive: true });
writeFileSync(DOC(), text, "utf8");
}
test("a deny refuses an update of an admitted note, by name, before any byte", () => {
seedNote("Notes/Admitted.md", "original body");
writeDoc("version: 1\ndefault_action: deny\n");
let refused: WriteRefusedError | undefined;
try {
applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Admitted.md", body: "rewritten" },
]);
} catch (err) {
refused = err instanceof WriteRefusedError ? err : undefined;
}
expect(refused).toBeInstanceOf(WriteRefusedError);
expect(refused?.action).toBe("write");
expect(refused?.target).toBe("Notes/Admitted.md");
expect(refused?.rule).toBe("default");
// Mutation is not a door around the rule: the note keeps its bytes,
// and exactly one deny row records the refusal.
expect(readFileSync(join(vault, "Notes/Admitted.md"), "utf8")).toContain("original body");
const rows = queryDecisionLedger(vault, { verdict: "deny" });
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ action: "write", target: "Notes/Admitted.md" });
});
test("a deny refuses an append the same way", () => {
seedNote("Notes/Appended.md", "first line");
writeDoc("version: 1\ndefault_action: deny\n");
expect(() =>
applyWriteBatch(vault, [{ kind: "append_note", path: "Notes/Appended.md", content: "more" }]),
).toThrow(WriteRefusedError);
expect(readFileSync(join(vault, "Notes/Appended.md"), "utf8")).not.toContain("more");
expect(queryDecisionLedger(vault, { verdict: "deny" })).toHaveLength(1);
});
test("an ask mutates without staging and without a row", () => {
seedNote("Notes/Asked.md", "before");
writeDoc("version: 1\ndefault_action: ask\n");
const res = applyWriteBatch(vault, [
{ kind: "update_note", path: "Notes/Asked.md", body: "after" },
]);
expect(res.results[0]).toMatchObject({ kind: "update_note", updated: true });
expect(readFileSync(join(vault, "Notes/Asked.md"), "utf8")).toContain("after");
// The review boundary is ENTRY: a mutation never re-stages and the
// consult that ran is deny-only, so an ask leaves no ledger row.
expect(queryDecisionLedger(vault)).toEqual([]);
});
test("an allow mutates exactly as it did before the consult existed", () => {
seedNote("Notes/Allowed.md", "before");
writeDoc("version: 1\ndefault_action: allow\n");
const res = applyWriteBatch(vault, [
{ kind: "append_note", path: "Notes/Allowed.md", content: "tail" },
]);
expect(res.results[0]).toMatchObject({ kind: "append_note", appended: true });
expect(readFileSync(join(vault, "Notes/Allowed.md"), "utf8")).toContain("tail");
expect(queryDecisionLedger(vault)).toEqual([]);
});
});