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
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
describeSessionRecall,
expandSessionRecall,
importSessionRecall,
searchSessionRecall,
} from "../../../src/core/brain/session-recall.ts";
import * as continuityStore from "../../../src/core/brain/continuity/store.ts";
import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
import type { ContinuityRecord } from "../../../src/core/brain/continuity/types.ts";
import type { SessionTurn } from "../../../src/core/brain/sessions/types.ts";
let vault: string;
beforeEach(() => {
vault = mkdtempSync(join(tmpdir(), "o2b-session-recall-"));
// A legacy Brain/ tree: an unswitched machine (a vault without one is store-only).
mkdirSync(join(vault, "Brain"), { recursive: true });
});
afterEach(() => {
rmSync(vault, { recursive: true, force: true });
});
function turn(turnId: string, role: SessionTurn["role"], text: string): SessionTurn {
return {
turnId,
role,
text,
timestamp: `2026-05-20T17:00:0${turnId.slice(-1)}.000Z`,
};
}
describe("session recall DAG", () => {
test("an import lists the continuity store a fixed number of times, whatever its turns", () => {
// A lookup per turn that re-read the whole log made an import
// quadratic in its turns: a few hundred turns cost seconds of a
// capture hook on a store-only machine, where every read verifies
// every record.
const listings = (sessionId: string, count: number): number => {
const turns = Array.from({ length: count }, (_, i) =>
turn(`t${i}`, i % 2 === 0 ? "user" : "assistant", `turn ${i} of ${sessionId}`),
);
const spy = spyOn(continuityStore, "listContinuityRecords");
try {
importSessionRecall(vault, { sessionId, turns, createdAt: "2026-05-20T17:00:00.000Z" });
return spy.mock.calls.length;
} finally {
spy.mockRestore();
}
};
const small = listings("session-small", 2);
expect(small).toBeGreaterThan(0);
expect(listings("session-large", 60)).toBe(small);
});
test("a turn repeated within one import is written once", () => {
const repeated = turn("t1", "user", "Need receipt search.");
const imported = importSessionRecall(vault, {
sessionId: "session-r",
turns: [repeated, turn("t2", "assistant", "Noted."), repeated],
createdAt: "2026-05-20T17:00:00.000Z",
});
expect(imported.rawTurns[2]!.id).toBe(imported.rawTurns[0]!.id);
expect(
continuityStore
.listContinuityRecords(vault, { kind: "session_turn" })
.filter((record) => record.payload["session_id"] === "session-r"),
).toHaveLength(2);
});
test("imports raw turns and deterministic two-depth summary nodes idempotently", () => {
const turns = [
turn("t1", "user", "Need receipt search."),
turn("t2", "assistant", "Decision: build continuity receipts."),
turn("t3", "user", "Need session recall."),
turn("t4", "assistant", "Outcome: tests cover recall."),
];
const first = importSessionRecall(vault, {
sessionId: "session-a",
turns,
summaryGroupSize: 2,
createdAt: "2026-05-20T17:00:00.000Z",
});
const second = importSessionRecall(vault, {
sessionId: "session-a",
turns,
summaryGroupSize: 2,
createdAt: "2026-05-20T17:00:00.000Z",
});
expect(first.rawTurns).toHaveLength(4);
expect(first.summaryNodes.map((record) => record.payload["depth"])).toEqual([1, 1, 2]);
expect(first.rawTurns.map((record) => record.id)).toEqual(
second.rawTurns.map((record) => record.id),
);
expect(describeSessionRecall(vault, { sessionId: "session-a" })).toMatchObject({
session_id: "session-a",
raw_turns: 4,
summary_nodes: 3,
depths: { "1": 2, "2": 1 },
});
});
test("searches bounded raw and summary hits and expands exact raw lineage", () => {
const imported = importSessionRecall(vault, {
sessionId: "session-a",
turns: [
turn("t1", "user", "Find continuity receipt details."),
turn("t2", "assistant", "Summary mentions receipts and tests."),
turn("t3", "user", "Unrelated turn."),
],
summaryGroupSize: 2,
createdAt: "2026-05-20T17:00:00.000Z",
});
const search = searchSessionRecall(vault, {
query: "receipt",
sessionId: "session-a",
limit: 4,
});
expect(search.hits.some((hit) => hit.kind === "session_turn")).toBe(true);
expect(search.hits.some((hit) => hit.kind === "session_summary_node")).toBe(true);
expect(search.hits.every((hit) => hit.snippet.length <= 160)).toBe(true);
const expanded = expandSessionRecall(vault, {
id: imported.summaryNodes.find((record) => record.payload["depth"] === 2)!.id,
rawLimit: 2,
});
expect(expanded.immediate_sources).toHaveLength(2);
expect(expanded.raw_content.map((item) => item.turn_id)).toEqual(["t1", "t2"]);
expect(expanded.next_cursor).toBe("2");
});
test("annotates each hit with the 1-based line span of the snippet match", () => {
importSessionRecall(vault, {
sessionId: "session-b",
turns: [turn("t1", "user", "First line.\nSecond line mentions receipts.")],
summaryGroupSize: 2,
createdAt: "2026-05-20T17:00:00.000Z",
});
const search = searchSessionRecall(vault, {
query: "receipts",
sessionId: "session-b",
limit: 4,
});
const hit = search.hits.find((candidate) => candidate.kind === "session_turn");
expect(hit?.line_start).toBe(2);
expect(hit?.line_end).toBe(2);
});
test("line span stays correct when an earlier line lowercases to more code units", () => {
// U+0130 (Turkish dotted capital I) lowercases to two code units, so a
// match offset taken from the lowercased copy would be shifted ahead of
// its true position in the original text. Nine of them on line 1 shift a
// line-2 match onto line 3 under the bug; the offset must index the
// original text so the line span stays line 2.
importSessionRecall(vault, {
sessionId: "session-locale",
turns: [turn("t1", "user", `${"İ".repeat(9)}\nreceipts\nfinal line three`)],
summaryGroupSize: 2,
createdAt: "2026-05-20T18:00:00.000Z",
});
const search = searchSessionRecall(vault, {
query: "receipts",
sessionId: "session-locale",
limit: 4,
});
const hit = search.hits.find((candidate) => candidate.kind === "session_turn");
expect(hit).toBeDefined();
expect(hit?.line_start).toBe(2);
expect(hit?.line_end).toBe(2);
});
});
describe("session recall - include_raw plus extracted discriminator (C2 / t_ac1d36ea)", () => {
function seed(): void {
importSessionRecall(vault, {
sessionId: "session-raw",
turns: [
turn("t1", "user", "Find continuity receipt details."),
turn("t2", "assistant", "Summary mentions receipts and tests."),
],
summaryGroupSize: 2,
createdAt: "2026-05-20T17:00:00.000Z",
});
}
test("flag omitted is byte-identical: no extracted, no raw on any hit", () => {
seed();
const search = searchSessionRecall(vault, {
query: "receipt",
sessionId: "session-raw",
limit: 4,
});
for (const hit of search.hits) {
expect("extracted" in hit).toBe(false);
expect("raw" in hit).toBe(false);
}
});
test("include_raw stamps extracted (summary=true, turn=false) and inlines raw captures", () => {
seed();
const search = searchSessionRecall(vault, {
query: "receipt",
sessionId: "session-raw",
limit: 4,
includeRaw: true,
});
const turnHit = search.hits.find((hit) => hit.kind === "session_turn");
const summaryHit = search.hits.find((hit) => hit.kind === "session_summary_node");
expect(turnHit?.extracted).toBe(false);
expect(summaryHit?.extracted).toBe(true);
// A raw capture carries itself; a derived record carries its source turns.
expect(turnHit?.raw?.map((raw) => raw.turn_id)).toEqual([turnHit?.turn_id ?? ""]);
expect(summaryHit?.raw?.map((raw) => raw.turn_id)).toEqual(["t1", "t2"]);
expect(summaryHit?.raw?.every((raw) => raw.text.length > 0)).toBe(true);
});
test("raw payloads respect the clip contract: a tiny raw budget drops text, keeps identity", () => {
seed();
const search = searchSessionRecall(vault, {
query: "receipt",
sessionId: "session-raw",
limit: 4,
includeRaw: true,
rawBudgetChars: 90,
});
const summaryHit = search.hits.find((hit) => hit.kind === "session_summary_node");
expect(summaryHit?.raw?.length).toBe(2);
// Under the tiny budget the large `text` field is clipped away while the
// identity-bearing turn_id survives (clipPayloadToBudget protected keys).
for (const raw of summaryHit?.raw ?? []) {
expect(raw.text).toBe("");
expect(raw.turn_id.length).toBeGreaterThan(0);
}
});
});
function turnAt(turnId: string, text: string, timestamp: string): SessionTurn {
return { turnId, role: "user", text, timestamp };
}
const parseMs = (iso: string): number => Date.parse(iso);
const byString = (a: string, b: string): number => a.localeCompare(b);
describe("session recall — since/before time bounds (S1 / t_347e8224)", () => {
function seed(): void {
importSessionRecall(vault, {
sessionId: "session-time",
turns: [
turnAt("t1", "chronology alpha needle", "2026-01-10T09:00:00.000Z"),
turnAt("t2", "chronology beta needle", "2026-03-15T09:00:00.000Z"),
turnAt("t3", "chronology gamma needle", "2026-06-20T09:00:00.000Z"),
],
summaryGroupSize: 8,
createdAt: "2026-06-20T09:00:00.000Z",
});
}
function turnIdsFor(input: { sinceMs?: number; untilMs?: number }): string[] {
return searchSessionRecall(vault, {
query: "needle",
sessionId: "session-time",
...input,
})
.hits.filter((h) => h.kind === "session_turn")
.map((h) => h.turn_id ?? "");
}
test("sinceMs excludes turns before the lower bound", () => {
seed();
expect(turnIdsFor({ sinceMs: parseMs("2026-03-01T00:00:00.000Z") }).toSorted(byString)).toEqual(
["t2", "t3"],
);
});
test("untilMs excludes turns after the upper bound", () => {
seed();
expect(turnIdsFor({ untilMs: parseMs("2026-04-01T00:00:00.000Z") }).toSorted(byString)).toEqual(
["t1", "t2"],
);
});
test("since + until keep only turns inside the window", () => {
seed();
expect(
turnIdsFor({
sinceMs: parseMs("2026-02-01T00:00:00.000Z"),
untilMs: parseMs("2026-04-01T00:00:00.000Z"),
}),
).toEqual(["t2"]);
});
test("no bounds is byte-identical to the unbounded search (all three turns)", () => {
seed();
expect(turnIdsFor({}).toSorted(byString)).toEqual(["t1", "t2", "t3"]);
});
});
describe("session recall - explicit no-session semantics (t_22d58fa7)", () => {
/**
* Seed one raw turn whose payload names no session, the way the
* conditional telemetry writers leave the key absent. `override`
* replaces the identity wholesale, so a test can also seed a non-string
* value - the coercion the read path used to perform.
*/
function seedUnattributedTurn(sessionId: unknown): ContinuityRecord {
return appendContinuityRecord(vault, {
kind: "session_turn",
createdAt: "2026-05-20T17:30:00.000Z",
payload: {
turn_id: "tno",
role: "user",
text: "unattributed needle",
...(sessionId !== undefined ? { session_id: sessionId } : {}),
},
});
}
function seedAttributedSession(): void {
importSessionRecall(vault, {
sessionId: "session-a",
turns: [turn("t1", "user", "attributed needle")],
summaryGroupSize: 2,
createdAt: "2026-05-20T17:00:00.000Z",
});
}
test("a record without session_id is excluded from scoped recall and kept by unscoped search", () => {
seedAttributedSession();
seedUnattributedTurn(undefined);
const scoped = searchSessionRecall(vault, { query: "needle", sessionId: "session-a" });
expect(scoped.hits.map((hit) => hit.turn_id)).toEqual(["t1"]);
const unscoped = searchSessionRecall(vault, { query: "needle" });
expect(unscoped.hits.map((hit) => hit.turn_id).toSorted()).toEqual(["t1", "tno"]);
});
test("a non-string session_id is excluded, not coerced into a scope match", () => {
seedAttributedSession();
const numeric = seedUnattributedTurn(42);
const nulled = seedUnattributedTurn(null);
// The read used to coerce 42 to "42" and match a scope asked for as
// "42"; a number names no session and must never match one.
const scoped = searchSessionRecall(vault, { query: "needle", sessionId: "42" });
expect(scoped.hits).toHaveLength(0);
const unscoped = searchSessionRecall(vault, { query: "needle" });
const unscopedIds = unscoped.hits.map((hit) => hit.id);
expect(unscopedIds).toContain(numeric.id);
expect(unscopedIds).toContain(nulled.id);
});
test("the lineage ledger's blank-id omission is pinned: a blank record contributes no link", () => {
seedAttributedSession();
appendContinuityRecord(vault, {
kind: "session_turn",
createdAt: "2026-05-20T17:40:00.000Z",
payload: {
turn_id: "tblank",
role: "user",
text: "blank lineage needle",
root_session_id: "root-blank",
parent_session_id: "root-blank",
},
});
// The blank record stamps a root but no session id, so it joins no
// lineage map and cannot turn the flat session into a chain.
const described = describeSessionRecall(vault, { sessionId: "session-a" });
expect("lineage_root" in described).toBe(false);
expect("segments" in described).toBe(false);
const scoped = searchSessionRecall(vault, { query: "needle", sessionId: "session-a" });
expect(scoped.hits.every((hit) => hit.turn_id !== "tblank")).toBe(true);
});
});