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
18.5 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { createHash } from "node:crypto";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import {
  appendSessionSummary,
  DIVERGENCE_RECORD_SAMPLE_LIMIT,
  getSessionSummary,
  getSessionSummaryReport,
  listSessionSummaries,
  SessionSummaryError,
  type SessionSummaryRecordRef,
} from "../../src/core/brain/session-summary.ts";
import {
  resolveSessionScope,
  SESSION_SCOPE_MAX_LENGTH,
} from "../../src/core/brain/session-scope.ts";
import {
  listContinuityRecords,
  appendContinuityRecord,
} from "../../src/core/brain/continuity/store.ts";
import type { ContinuityRecord } from "../../src/core/brain/continuity/types.ts";

let vault: string;

beforeEach(() => {
  vault = mkdtempSync(join(tmpdir(), "o2b-session-summary-"));
  // 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 });
});

describe("appendSessionSummary", () => {
  test("writes a session-scoped digest and reads it back as a unit", () => {
    const digest = appendSessionSummary(vault, {
      sessionId: "sess-1",
      request: "Add a structured session summary",
      decisions: ["Reuse the continuity store", "Agent supplies categories"],
      learnings: ["session_summary_node is a recall rollup, not a digest"],
      nextSteps: ["Wire the MCP tool"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    expect(digest.sessionId).toBe("sess-1");
    expect(digest.request).toBe("Add a structured session summary");
    expect(digest.decisions).toEqual(["Reuse the continuity store", "Agent supplies categories"]);
    expect(digest.learnings.length).toBe(1);
    expect(digest.nextSteps).toEqual(["Wire the MCP tool"]);

    const read = getSessionSummary(vault, "sess-1");
    expect(read).not.toBeNull();
    expect(read!.id).toBe(digest.id);
    expect(read!.decisions).toEqual(digest.decisions);
  });

  test("rejects a digest with no content in any category (no empty digest)", () => {
    expect(() =>
      appendSessionSummary(vault, {
        sessionId: "sess-empty",
        request: "   ",
        decisions: ["", "  "],
        learnings: [],
        nextSteps: [],
        createdAt: "2026-06-14T10:00:00.000Z",
      }),
    ).toThrow(SessionSummaryError);
  });

  test("trims and drops empty category entries", () => {
    const digest = appendSessionSummary(vault, {
      sessionId: "sess-trim",
      decisions: ["  keep me  ", "", "   "],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    expect(digest.decisions).toEqual(["keep me"]);
    expect(digest.request).toBeNull();
    expect(digest.learnings).toEqual([]);
  });

  test("dedupes an identical re-append for the same session", () => {
    const input = {
      sessionId: "sess-dup",
      decisions: ["one decision"],
      createdAt: "2026-06-14T10:00:00.000Z",
    } as const;
    const first = appendSessionSummary(vault, input);
    const second = appendSessionSummary(vault, input);
    expect(second.id).toBe(first.id);
    expect(listContinuityRecords(vault, { kind: "session_summary_digest" }).length).toBe(1);
  });

  test("getSessionSummary returns the latest digest when several exist", () => {
    appendSessionSummary(vault, {
      sessionId: "sess-multi",
      decisions: ["older"],
      createdAt: "2026-06-14T09:00:00.000Z",
    });
    const newer = appendSessionSummary(vault, {
      sessionId: "sess-multi",
      decisions: ["newer"],
      createdAt: "2026-06-14T11:00:00.000Z",
    });
    expect(getSessionSummary(vault, "sess-multi")!.id).toBe(newer.id);
  });

  test("records source refs to the session and its turns for lineage", () => {
    appendSessionSummary(vault, {
      sessionId: "sess-refs",
      decisions: ["decided"],
      sourceTurnIds: ["t-1", "t-2"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    const record = listContinuityRecords(vault, { kind: "session_summary_digest" })[0]!;
    const refKinds = record.sourceRefs.map((r) => `${r.kind}:${r.id}`);
    expect(refKinds).toContain("session:sess-refs");
    expect(refKinds).toContain("session_turn:t-1");
    expect(refKinds).toContain("session_turn:t-2");
  });
});

describe("byte-identical when unused", () => {
  test("getSessionSummary returns null and the store stays empty when nothing is written", () => {
    expect(getSessionSummary(vault, "never")).toBeNull();
    expect(listSessionSummaries(vault).length).toBe(0);
    expect(listContinuityRecords(vault).length).toBe(0);
  });
});

describe("divergence-aware read (t_59d4c919)", () => {
  test("sequential revisions stay quiet: digest_count counts distinct content, revisions counts rows", () => {
    // A session re-summarized as it evolves is a revision stream, not a
    // conflict: the later digest wins deterministically, so flagging it
    // divergent was noise (v1.78.0 review round).
    const older = appendSessionSummary(vault, {
      sessionId: "sess-div",
      decisions: ["older decision"],
      createdAt: "2026-06-14T09:00:00.000Z",
    });
    const newer = appendSessionSummary(vault, {
      sessionId: "sess-div",
      decisions: ["newer decision"],
      createdAt: "2026-06-14T11:00:00.000Z",
    });

    const report = getSessionSummaryReport(vault, "sess-div");
    expect(report).not.toBeNull();
    // The read still answers with the sorted-latest digest.
    expect(report!.digest.id).toBe(newer.id);
    expect(report!.digest.decisions).toEqual(["newer decision"]);
    expect(report!.digestCount).toBe(2);
    expect(report!.revisions).toBe(2);
    expect("divergent" in report!).toBe(false);
    expect("records" in report!).toBe(false);
    expect(older.id).not.toBe(newer.id);
  });

  test("distinct content hashes meeting at one instant report divergent with the sample", () => {
    // The one shape the store cannot order: two contents in the same
    // created_at instant (two devices distilling differently before their
    // vaults sync, or a same-second race) - latest-wins is not a safe
    // answer, so the read names it.
    const first = appendSessionSummary(vault, {
      sessionId: "sess-conflict",
      decisions: ["device a take"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    const second = appendSessionSummary(vault, {
      sessionId: "sess-conflict",
      decisions: ["device b take"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });

    const report = getSessionSummaryReport(vault, "sess-conflict");
    expect(report).not.toBeNull();
    expect(report!.digestCount).toBe(2);
    expect(report!.revisions).toBe(2);
    expect(report!.divergent).toBe(true);
    const records = report!.records ?? [];
    expect(records.map((r) => r.id).toSorted()).toEqual([first.id, second.id].toSorted());
    expect(new Set(records.map((r) => r.contentHash)).size).toBe(2);
    for (const record of records as ReadonlyArray<SessionSummaryRecordRef>) {
      expect(typeof record.createdAt).toBe("string");
      expect(record.contentHash.length).toBeGreaterThan(0);
    }
  });

  test("the same digest written by two devices before sync counts once, as revisions", () => {
    // Two vaults summarize identically before syncing; after the sync the
    // store holds two rows with one content hash. Content agrees, so the
    // read dedupes to one digest and keeps the row count as revisions.
    const input = {
      sessionId: "sess-two-devices",
      decisions: ["one decision"],
      createdAt: "2026-06-14T10:00:00.000Z",
    } as const;
    appendSessionSummary(vault, input);
    const stored = listContinuityRecords(vault, { kind: "session_summary_digest" })[0]!;
    appendContinuityRecord(vault, {
      kind: "session_summary_digest",
      // Device B wrote before the sync: same content, different instant.
      createdAt: "2026-06-14T12:00:00.000Z",
      sourceRefs: stored.sourceRefs,
      payload: stored.payload,
    });

    const report = getSessionSummaryReport(vault, "sess-two-devices");
    expect(report).not.toBeNull();
    expect(report!.digestCount).toBe(1);
    expect(report!.revisions).toBe(2);
    expect("divergent" in report!).toBe(false);
  });

  test("a single digest reports count 1, revisions 1, and carries no divergent key", () => {
    appendSessionSummary(vault, {
      sessionId: "sess-one",
      decisions: ["the only decision"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    const report = getSessionSummaryReport(vault, "sess-one");
    expect(report).not.toBeNull();
    expect(report!.digestCount).toBe(1);
    expect(report!.revisions).toBe(1);
    expect("divergent" in report!).toBe(false);
    expect("records" in report!).toBe(false);
    // Additive only: the report's own key set is pinned.
    expect(Object.keys(report!).toSorted()).toEqual(["digest", "digestCount", "revisions"]);
  });

  test("a duplicate-content re-append still dedupes to count 1 (no divergence)", () => {
    const input = {
      sessionId: "sess-dup-report",
      decisions: ["one decision"],
      createdAt: "2026-06-14T10:00:00.000Z",
    } as const;
    appendSessionSummary(vault, input);
    appendSessionSummary(vault, input);
    const report = getSessionSummaryReport(vault, "sess-dup-report");
    expect(report!.digestCount).toBe(1);
    expect(report!.revisions).toBe(1);
    expect("divergent" in report!).toBe(false);
  });

  test("an unknown session still reads as null", () => {
    expect(getSessionSummaryReport(vault, "never")).toBeNull();
  });

  test("getSessionSummary stays a thin wrapper over the report's digest", () => {
    appendSessionSummary(vault, {
      sessionId: "sess-wrap",
      decisions: ["wrapped"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    const report = getSessionSummaryReport(vault, "sess-wrap");
    expect(getSessionSummary(vault, "sess-wrap")!.id).toBe(report!.digest.id);
  });

  test("the divergence record list is bounded to the newest entries", () => {
    // Same-instant distinct contents: every append is a distinct digest,
    // and the whole set is one unresolved conflict.
    const total = DIVERGENCE_RECORD_SAMPLE_LIMIT + 2;
    let last: { id: string } | null = null;
    for (let i = 0; i < total; i++) {
      last = appendSessionSummary(vault, {
        sessionId: "sess-bound",
        decisions: [`decision-${i}`],
        createdAt: "2026-06-14T00:00:00.000Z",
      });
    }
    const report = getSessionSummaryReport(vault, "sess-bound");
    expect(report!.divergent).toBe(true);
    expect(report!.digestCount).toBe(total);
    expect(report!.revisions).toBe(total);
    const records = report!.records ?? [];
    expect(records.length).toBe(DIVERGENCE_RECORD_SAMPLE_LIMIT);
    // The newest records are the ones kept, oldest first within the sample.
    expect(records[records.length - 1]!.id).toBe(last!.id);
  });
});

describe("project scope (Task 18)", () => {
  test("carries the project, normalized by the shared session-scope slug rule", () => {
    const digest = appendSessionSummary(vault, {
      sessionId: "sess-proj",
      project: "  Open Second/Brain -- v2!  ",
      decisions: ["scoped"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    // Exactly what resolveSessionScope would produce for the same raw
    // input on the session axis: lowercase, non-alphanumerics collapsed
    // to single dashes, edge dashes trimmed.
    const expected = resolveSessionScope("  Open Second/Brain -- v2!  ");
    expect(expected).toBe("open-second-brain-v2");
    expect(digest.project).toBe(expected);
    expect(getSessionSummary(vault, "sess-proj")!.project).toBe(expected);
  });

  test("caps the slug at the shared session-scope length", () => {
    const digest = appendSessionSummary(vault, {
      sessionId: "sess-long",
      project: "p".repeat(SESSION_SCOPE_MAX_LENGTH + 40),
      decisions: ["scoped"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    expect(digest.project).toBe("p".repeat(SESSION_SCOPE_MAX_LENGTH));
  });

  test("a digest with no project is byte-identical to today, dedupe key included", () => {
    const digest = appendSessionSummary(vault, {
      sessionId: "sess-plain",
      request: "Add a structured session summary",
      decisions: ["Reuse the continuity store"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    expect(digest.project).toBeUndefined();
    expect(Object.keys(digest).toSorted()).toEqual([
      "createdAt",
      "decisions",
      "id",
      "learnings",
      "nextSteps",
      "request",
      "sessionId",
    ]);

    const record = listContinuityRecords(vault, { kind: "session_summary_digest" })[0]!;
    // The pre-project key shape, pinned literally: a changed dedupe key
    // would silently stop deduplicating every digest already on disk.
    const contentHash = createHash("sha256")
      .update(
        JSON.stringify([
          "Add a structured session summary",
          ["Reuse the continuity store"],
          [],
          [],
        ]),
      )
      .digest("hex")
      .slice(0, 16);
    expect(record.payload["dedupe_key"]).toBe(`session_summary_digest:sess-plain:${contentHash}`);
    expect(record.payload["project"]).toBeUndefined();
    expect(Object.keys(record.payload).toSorted()).toEqual([
      "content_hash",
      "decisions",
      "dedupe_key",
      "learnings",
      "next_steps",
      "request",
      "session_id",
    ]);
  });

  test("the same content under two projects are two digests, not one dedupe hit", () => {
    const base = {
      sessionId: "sess-two",
      decisions: ["same decision"],
      createdAt: "2026-06-14T10:00:00.000Z",
    } as const;
    const alpha = appendSessionSummary(vault, { ...base, project: "alpha" });
    const beta = appendSessionSummary(vault, { ...base, project: "beta" });
    const unscoped = appendSessionSummary(vault, base);
    expect(new Set([alpha.id, beta.id, unscoped.id]).size).toBe(3);
    // ...and a re-append under the same project still dedupes.
    expect(appendSessionSummary(vault, { ...base, project: "alpha" }).id).toBe(alpha.id);
  });

  test("rejects a project with no alphanumeric by name rather than dropping it", () => {
    expect(() =>
      appendSessionSummary(vault, {
        sessionId: "sess-bad",
        project: "---",
        decisions: ["scoped"],
        createdAt: "2026-06-14T10:00:00.000Z",
      }),
    ).toThrow(SessionSummaryError);
    expect(() =>
      appendSessionSummary(vault, {
        sessionId: "sess-bad",
        project: "   ",
        decisions: ["scoped"],
        createdAt: "2026-06-14T10:00:00.000Z",
      }),
    ).toThrow(/project/);
    expect(listContinuityRecords(vault, { kind: "session_summary_digest" }).length).toBe(0);
  });

  test("listSessionSummaries filters by project", () => {
    appendSessionSummary(vault, {
      sessionId: "s-a",
      project: "Alpha Project",
      decisions: ["a"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    appendSessionSummary(vault, {
      sessionId: "s-b",
      project: "beta",
      decisions: ["b"],
      createdAt: "2026-06-14T11:00:00.000Z",
    });
    appendSessionSummary(vault, {
      sessionId: "s-c",
      decisions: ["c"],
      createdAt: "2026-06-14T12:00:00.000Z",
    });

    expect(listSessionSummaries(vault).length).toBe(3);
    // The filter normalizes by the same rule as the write.
    const alpha = listSessionSummaries(vault, { project: "alpha-project" });
    expect(alpha.length).toBe(1);
    expect(alpha[0]!.sessionId).toBe("s-a");
    expect(listSessionSummaries(vault, { project: "ALPHA PROJECT" })[0]!.sessionId).toBe("s-a");
    expect(listSessionSummaries(vault, { project: "beta" }).length).toBe(1);
    expect(listSessionSummaries(vault, { project: "nope" }).length).toBe(0);
  });

  test("a malformed project filter is rejected by name, not silently ignored", () => {
    appendSessionSummary(vault, {
      sessionId: "s-a",
      project: "alpha",
      decisions: ["a"],
      createdAt: "2026-06-14T10:00:00.000Z",
    });
    // Silently ignoring it would return every digest - a wrong answer
    // dressed as a successful filter.
    expect(() => listSessionSummaries(vault, { project: "***" })).toThrow(SessionSummaryError);
  });
});

describe("explicit no-session semantics (t_22d58fa7)", () => {
  /**
   * Seed one digest record whose payload names no session, the way a
   * writer that stamps `session_id` conditionally leaves the key absent.
   * `sessionId` replaces the identity wholesale, so a test can also seed a
   * non-string value - the coercion the reads used to perform.
   */
  function seedDigest(sessionId: unknown): ContinuityRecord {
    return appendContinuityRecord(vault, {
      kind: "session_summary_digest",
      createdAt: "2026-06-14T10:00:00.000Z",
      sourceRefs: [{ id: "s-x", kind: "session" }],
      payload: {
        decisions: ["unattributed"],
        content_hash: "0123456789abcdef",
        ...(sessionId !== undefined ? { session_id: sessionId } : {}),
      },
    });
  }

  test("no-session records are skipped by the reads, never matched against the empty string", () => {
    seedDigest(undefined);
    seedDigest(undefined);

    // The reads used to coerce the missing key to "" and answer a report
    // that lumped every unrelated no-session digest into one phantom
    // session; "" asks for a session that no writer ever named.
    expect(getSessionSummaryReport(vault, "")).toBeNull();
    expect(listSessionSummaries(vault, { sessionId: "" })).toEqual([]);
  });

  test("a non-string session_id is excluded, not coerced into a scope match", () => {
    const numeric = seedDigest(7);

    // The read used to stringify 7 and match a scope asked for as "7".
    expect(listSessionSummaries(vault, { sessionId: "7" })).toEqual([]);

    // Unscoped reads still return the record.
    expect(listSessionSummaries(vault).map((digest) => digest.id)).toEqual([numeric.id]);
  });

  test("a no-session digest carries no sessionId key, and a session digest keeps its own", () => {
    const blank = seedDigest(undefined);
    const attributed = appendSessionSummary(vault, {
      sessionId: "s-present",
      decisions: ["attributed"],
      createdAt: "2026-06-14T11:00:00.000Z",
    });

    const digests = listSessionSummaries(vault);
    const blankDigest = digests.find((digest) => digest.id === blank.id)!;
    expect("sessionId" in blankDigest).toBe(false);
    expect(Object.keys(blankDigest).toSorted()).toEqual([
      "createdAt",
      "decisions",
      "id",
      "learnings",
      "nextSteps",
      "request",
    ]);

    const presentDigest = digests.find((digest) => digest.id === attributed.id)!;
    expect(presentDigest.sessionId).toBe("s-present");
  });
});