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

v0.10.8: address CodeRabbit review

Sol Aitkenfddbc74302c8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e546ff10..f7f8e144 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1987,6 +1987,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.
+[0.10.8]: https://github.com/itechmeat/open-second-brain/compare/v0.10.7...v0.10.8
+[0.10.7]: https://github.com/itechmeat/open-second-brain/compare/v0.10.6...v0.10.7
[0.10.6]: https://github.com/itechmeat/open-second-brain/compare/v0.10.5...v0.10.6
[0.10.5]: https://github.com/itechmeat/open-second-brain/compare/v0.10.4...v0.10.5
[0.10.4]: https://github.com/itechmeat/open-second-brain/compare/v0.10.3...v0.10.4
diff --git a/docs/plans/2026-05-19-v0.10.8-design.md b/docs/plans/2026-05-19-v0.10.8-design.md
index a1ec17de..d056fa0d 100644
--- a/docs/plans/2026-05-19-v0.10.8-design.md
+++ b/docs/plans/2026-05-19-v0.10.8-design.md
@@ -367,27 +367,38 @@ guarantee).
The current `appendLogEvent` reads the markdown file, appends a block,
writes back atomically. The new version:
-1. Acquires a lock on `Brain/log/` (via `proper-lockfile`, same
- approach as `src/core/event-log.ts`).
-2. Reads `<date>.md` if present.
-3. Reads `<date>.jsonl` if present (only for the rare case where the
- markdown file was hand-edited and the JSONL got out of sync; the
- writer does not validate consistency, only appends).
-4. Appends one block to the markdown and one line to the JSONL.
-5. Writes both files atomically (`atomicWriteFileSync` for each;
- markdown first, then JSONL).
+1. Acquires a lock on `Brain/log/` (via `proper-lockfile`'s `lockSync`
+ wrapped in a small ELOCKED-only retry loop because the sync API
+ forbids built-in retries; same scope as `src/core/event-log.ts`).
+2. Reads `<date>.jsonl` if present.
+3. Builds the new JSONL row via `renderJsonlLine(event)` and writes
+ `<date>.jsonl` atomically (`atomicWriteFileSync`). JSONL is the
+ machine source of truth, so it is written first.
+4. Reads `<date>.md` if present.
+5. Appends the new event block to the markdown and writes
+ `<date>.md` atomically.
6. Releases the lock.
-Atomicity at the pair level: if step 5 fails between the two writes,
-the next call's step 2/3 will see the markdown leading the JSONL by
-one block. The reader (§4.9.4) prefers JSONL but falls back to
-markdown when JSONL is missing; a divergence by one event is
-acceptable and self-heals at the next write.
+Failure model: if step 3 fails the call throws and nothing is written;
+both files stay at their previous (consistent) state. If step 5 fails
+after step 3 succeeded the JSONL is one event ahead of the markdown;
+the reader (§4.9.4) prefers JSONL and returns the correct count, so
+machine consumers (discipline-report, future tooling) keep working
+without manual reconciliation. The human Obsidian view lags by one
+event until the next successful append rewrites the markdown. The
+caller sees the exception from `atomicWriteFileSync(mdPath, …)` and
+can investigate. We deliberately do **not** claim "self-healing":
+markdown is not automatically rebuilt from the JSONL on subsequent
+appends (the writer only reads + appends to whatever markdown is on
+disk). Re-syncing the markdown view, if needed, is an operator step
+(`o2b brain digest` regeneration / hand re-render from JSONL).
Why not a single combined write: the two files have different formats
and different append semantics. Combining them into one transactional
file format buys nothing - the lock already serialises writers, and
-a one-event divergence is bounded and self-healing.
+JSONL-first ordering bounds the visible-to-machine-consumer asymmetry
+to "never" (the consumer always sees the latest event or it has not
+been written at all).
#### 4.9.4 Reader (`src/core/brain/log-jsonl.ts`)
diff --git a/docs/plans/2026-05-19-v0.10.8-impl.md b/docs/plans/2026-05-19-v0.10.8-impl.md
index 095817f8..7c538870 100644
--- a/docs/plans/2026-05-19-v0.10.8-impl.md
+++ b/docs/plans/2026-05-19-v0.10.8-impl.md
@@ -225,21 +225,34 @@ export function appendLogEvent(
const ts = parseIsoUtc(event.timestamp);
const mdPath = logPath(vault, ts.date);
- const jsonlPath = mdPath.replace(/\.md$/, ".jsonl");
+ const jsonlPath = logJsonlPath(vault, ts.date);
// proper-lockfile requires the lock target to exist. Lock the log
// directory itself, created up-front, the same scope used by
- // `src/core/event-log.ts:appendEvent`.
- const logDir = dirname(mdPath);
+ // `src/core/event-log.ts:appendEvent`. The sync API forbids the
+ // built-in `retries` option, so the call is wrapped in a small
+ // ELOCKED-only retry helper (see `acquireLogLock` in the shipped
+ // `log.ts`).
+ const logDir = brainDirs(vault).log;
mkdirSync(logDir, { recursive: true });
- const release = lockfile.lockSync(logDir, {
- retries: { retries: 30, factor: 1.2, minTimeout: 30, maxTimeout: 500 },
- stale: 10_000,
- realpath: false,
- });
+ const release = acquireLogLock(logDir);
try {
+ // ---- JSONL sidecar (machine surface, primary) ---------------------
+ // Write JSONL first: it is the source of truth for `readLogDay`.
+ // If the markdown write below fails, the human Obsidian view lags
+ // by one event, but discipline-report / future machine consumers
+ // keep returning the correct counts.
+ const existingJsonl = existsSync(jsonlPath) ? readFileSync(jsonlPath, "utf8") : "";
+ const line = renderJsonlLine(event);
+ const nextJsonl =
+ existingJsonl === ""
+ ? line + "\n"
+ : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;
+ atomicWriteFileSync(jsonlPath, nextJsonl);
+
+ // ---- Markdown (human surface) -------------------------------------
const existingMd = existsSync(mdPath) ? readFileSync(mdPath, "utf8") : "";
const block = renderEventBlock(event, ts.hms);
let nextMd: string;
@@ -251,14 +264,6 @@ export function appendLogEvent(
if (!nextMd.endsWith("\n")) nextMd += "\n";
atomicWriteFileSync(mdPath, nextMd);
- const existingJsonl = existsSync(jsonlPath) ? readFileSync(jsonlPath, "utf8") : "";
- const line = renderJsonlLine(event);
- const nextJsonl =
- existingJsonl === ""
- ? line + "\n"
- : `${existingJsonl.replace(/\s+$/, "")}\n${line}\n`;
- atomicWriteFileSync(jsonlPath, nextJsonl);
-
return { logPath: mdPath };
} finally {
release();
@@ -266,7 +271,7 @@ export function appendLogEvent(
}
```
-Note: `proper-lockfile` exposes `lockSync` (mirror of `lock`) that returns a release function; we use it to keep `appendLogEvent` synchronous (the existing public contract).
+Note: `proper-lockfile` exposes `lockSync` (mirror of `lock`) that returns a release function; we use it to keep `appendLogEvent` synchronous (the existing public contract). The sync flavour does not support the `retries` option, so the shipped implementation wraps `lockSync` in a small ELOCKED-only retry loop (`acquireLogLock`) instead of passing `retries` directly.
- [ ] **Step 1.5: Run the tests - confirm pass**
diff --git a/hooks/lib/messages.ts b/hooks/lib/messages.ts
index c929c4f0..e7d54210 100644
--- a/hooks/lib/messages.ts
+++ b/hooks/lib/messages.ts
@@ -67,8 +67,8 @@ export function postWriteReminder({
"",
"If a confirmed or unconfirmed preference in `Brain/preferences/`",
"scopes to the artifact you just produced, call",
- "`brain_apply_evidence` with `result: applied | violated` so the",
- "dream pass can update confidence and retire stale rules.",
+ "`brain_apply_evidence` with `result: applied | violated | outdated`",
+ "so the dream pass can update confidence and retire stale rules.",
"",
"If neither a new preference nor an evidence event fits but this",
"turn still produced a durable artifact worth referencing later",
@@ -114,8 +114,9 @@ export function stopGuardrailReason(runtime: HookRuntime = "unknown"): string {
parts.push(
"Pick whichever fits this turn:",
"- a new rule the user just stated → `brain_feedback`",
- "- an active preference applied or violated by the change →",
- " `brain_apply_evidence` with `result: applied | violated`",
+ "- an active preference applied, violated, or made obsolete by the",
+ " change → `brain_apply_evidence` with",
+ " `result: applied | violated | outdated`",
"- a durable narrative milestone → `brain_note`",
"",
"If the change is trivial and not worth recording, just send your",
diff --git a/src/core/brain/log-jsonl.ts b/src/core/brain/log-jsonl.ts
index e9827d73..f831dda6 100644
--- a/src/core/brain/log-jsonl.ts
+++ b/src/core/brain/log-jsonl.ts
@@ -29,6 +29,13 @@ export interface ReadLogDayResult {
readonly warnings: ReadonlyArray<BrainLogParseWarning>;
}
+// Canonical ISO-8601 UTC timestamp shape emitted by `renderJsonlLine`
+// in `log.ts`. Accept the same shape `parseIsoUtc` recognises so the
+// JSONL reader cannot leak a value that the markdown side would
+// reject. Sub-second precision is allowed because `JSON.stringify`
+// of a `Date` produces it; `parseIsoUtc` strips it back to seconds.
+const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
+
/**
* Read one day of Brain log events. Picks the JSONL sidecar when it
* exists; otherwise falls back to parsing the markdown. When neither
@@ -115,6 +122,15 @@ function coerceEntry(
warnings.push({ path, lineNumber, message: "JSONL row missing ts/kind" });
return null;
}
+ // `ts` must match the canonical ISO-8601 UTC shape produced by
+ // `renderJsonlLine` (`YYYY-MM-DDTHH:MM:SSZ`, optional sub-second
+ // precision). Anything looser would let arbitrary strings into
+ // `BrainLogEntry.timestamp` and break downstream consumers that
+ // assume the strict format (e.g. `parseIsoUtc` in `log.ts`).
+ if (!ISO_UTC_TS_RE.test(ts)) {
+ warnings.push({ path, lineNumber, message: `invalid ts format: ${ts}` });
+ return null;
+ }
if (!BRAIN_LOG_EVENT_KIND_SET.has(kind)) {
warnings.push({ path, lineNumber, message: `unknown event kind: ${kind}` });
return null;
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 65283896..0bd1e70f 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -59,7 +59,15 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string
"durable artifact (code shipped, config / instruction edited, " +
"content drafted) and at least one preference in " +
"`Brain/preferences/` scopes to that artifact. Record " +
- "`result: applied | violated` per (preference, artifact) pair.\n" +
+ "`result: applied | violated | outdated` per (preference, " +
+ "artifact) pair.\n" +
+ " - brain_note — call when this turn produced a durable " +
+ "narrative milestone (release shipped, PR merged, fact " +
+ "discovered) that fits neither `brain_feedback` nor " +
+ "`brain_apply_evidence`. Lands one line under event kind " +
+ "`note` in `Brain/log/<today>.md` (and the JSONL sidecar). " +
+ "This is the Brain-native replacement for the retired " +
+ "`event_log_append` tool.\n" +
" - brain_dream — runs the deterministic learning pass " +
"(clusters signals, promotes preferences, retires stale rules). " +
"Usually scheduled via cron, not invoked interactively.\n" +
diff --git a/tests/core/brain.log-jsonl-reader.test.ts b/tests/core/brain.log-jsonl-reader.test.ts
index 2d26a948..975b924d 100644
--- a/tests/core/brain.log-jsonl-reader.test.ts
+++ b/tests/core/brain.log-jsonl-reader.test.ts
@@ -126,6 +126,34 @@ tags: [brain, brain/log]
expect(res.warnings[0]!.lineNumber).toBe(2);
});
+ test("skips rows with malformed ts and surfaces a warning", () => {
+ const dir = brainDirs(tmp).log;
+ mkdirSync(dir, { recursive: true });
+ const lines = [
+ JSON.stringify({
+ ts: "2026-05-19 10:00:00",
+ kind: "feedback",
+ payload: { topic: "bad-ts" },
+ }),
+ JSON.stringify({
+ ts: "2026-05-19T10:00:01Z",
+ kind: "feedback",
+ payload: { topic: "ok" },
+ }),
+ ].join("\n");
+ writeFileSync(
+ logJsonlPath(tmp, "2026-05-19"),
+ lines + "\n",
+ "utf8",
+ );
+
+ const res = readLogDay(tmp, "2026-05-19");
+ expect(res.entries).toHaveLength(1);
+ expect(res.entries[0]!.body["topic"]).toBe("ok");
+ expect(res.warnings).toHaveLength(1);
+ expect(res.warnings[0]!.message).toMatch(/invalid ts format/i);
+ });
+
test("skips rows with unknown event kinds and surfaces a warning", () => {
const dir = brainDirs(tmp).log;
mkdirSync(dir, { recursive: true });
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index 9b96dbed..47bc64ad 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -693,12 +693,17 @@ describe("brain_backlinks", () => {
// brain_note (§32B, v0.10.8)
// ---------------------------------------------------------------------------
-function logFileForToday(vaultDir: string): { md: string; jsonl: string } {
- // The handler uses `new Date()` directly. Pick today's UTC date.
- const today = new Date().toISOString().slice(0, 10);
+function logFilesForLoggedAt(
+ vaultDir: string,
+ loggedAt: string,
+): { md: string; jsonl: string } {
+ // Derive the date from the tool's own `logged_at` payload instead
+ // of `new Date()`. This avoids a flake if the test happens to cross
+ // `00:00:00Z` between the `brain_note` call and the file lookup.
+ const day = loggedAt.slice(0, 10);
return {
- md: logPath(vaultDir, today),
- jsonl: logJsonlPath(vaultDir, today),
+ md: logPath(vaultDir, day),
+ jsonl: logJsonlPath(vaultDir, day),
};
}
@@ -714,7 +719,7 @@ describe("brain_note", () => {
expect(payload.agent).toBe("claude");
expect(typeof payload.logged_at).toBe("string");
- const paths = logFileForToday(vault);
+ const paths = logFilesForLoggedAt(vault, payload.logged_at);
expect(existsSync(paths.md)).toBe(true);
expect(existsSync(paths.jsonl)).toBe(true);
const md = readFileSync(paths.md, "utf8");
@@ -732,11 +737,12 @@ describe("brain_note", () => {
test("redacts secret-shaped tokens before writing", async () => {
const server = makeServer();
await initialize(server);
- await call(server, "brain_note", {
+ const r = (await call(server, "brain_note", {
text: "deployed api_key=sk-abc123 to prod",
- });
+ })) as any;
+ const payload = JSON.parse(r.result.content[0].text);
- const paths = logFileForToday(vault);
+ const paths = logFilesForLoggedAt(vault, payload.logged_at);
const md = readFileSync(paths.md, "utf8");
expect(md).toContain("***REDACTED***");
expect(md).not.toContain("sk-abc123");
@@ -745,9 +751,12 @@ describe("brain_note", () => {
test("collapses multi-line input to one space-joined line", async () => {
const server = makeServer();
await initialize(server);
- await call(server, "brain_note", { text: "line one\nline two" });
+ const r = (await call(server, "brain_note", {
+ text: "line one\nline two",
+ })) as any;
+ const payload = JSON.parse(r.result.content[0].text);
- const paths = logFileForToday(vault);
+ const paths = logFilesForLoggedAt(vault, payload.logged_at);
const md = readFileSync(paths.md, "utf8");
expect(md).toContain("text: line one line two");
});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 1380a73e..c446e73d 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -96,11 +96,18 @@ describe("handshake", () => {
const inst = r.result.instructions as string;
expect(inst).toContain("@hermes-vps-agent");
// v0.9.0+ — instructions advertise Brain tools, not the legacy
- // event_log_append / second_brain_capture path.
+ // `second_brain_capture` path. v0.10.8 instructions may mention
+ // `event_log_append` once, only as the historical name of the
+ // retired tool that `brain_note` now replaces — they must NOT
+ // teach the agent to call it.
expect(inst).toContain("brain_feedback");
expect(inst).toContain("brain_apply_evidence");
- expect(inst).not.toContain("event_log_append");
+ expect(inst).toContain("brain_note");
expect(inst).not.toContain("second_brain_capture");
+ // Allowed mention is the "retired" reference; reject any wording
+ // that frames `event_log_append` as an active tool to call.
+ expect(inst).not.toMatch(/call\s+`?event_log_append`?/i);
+ expect(inst).not.toMatch(/use\s+`?event_log_append`?/i);
});
test("negotiates alternate client version", async () => {