From da57e9620ce32d3ec06b943efdb2bd02aeb94937 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 17:39:21 +0800
Subject: [PATCH 01/17] perf(graph): extract only observations captured since
the last extract
Claude Code's per-turn Stop hook POSTs /agentmemory/session/end, so
event::session::stopped runs on every agent turn, not once per session. It
handed mem::graph-extract the session's entire compressed observation list
each time. Downstream, persistGraphDelta takes the MERGE path for every node
and edge it has already seen (kv.get name-index + kv.get nodes + kv.set per
node, and the same three per edge), so turn N re-merged everything from turns
1..N-1.
Measured on the new harness: eight turns of one observation each dispatched
36 observations before this change (1+2+...+8) and 8 after. The growth was
quadratic in turn count, and per #843 nothing written through kv.set is ever
evicted from the iii engine, so that was quadratic permanent heap walking the
engine toward its cap.
The session record now carries a watermark. Two optional fields rather than
one, because a bare max-timestamp watermark is not safe here: observe.ts
dispatches mem::compress fire-and-forget and compress.ts stamps the capture
time, not the write time, so a slow compression lands an older timestamp
after a newer one was already extracted. The count is the tripwire. When the
number of observations newer than the watermark does not exactly account for
the growth since the watermark was recorded, something arrived out of order
(or was evicted) and the whole session is re-sent. Losing a memory is worse
than re-merging one. Both fields are optional, so existing session records
stay valid and simply take the full-extract path once.
The watermark advances only after mem::graph-extract's dispatch is accepted,
so a hand-off that never left is retried on the next turn. fireVoid now
resolves to a dispatch-success boolean to make that observable; the other
callers ignore the value exactly as before.
Limitations:
- Completion is not observable through TriggerAction.Void(). An extract whose
dispatch is accepted but which then fails downstream leaves its delta out
of the graph until someone POSTs /agentmemory/graph/build. Advancing on
completion would mean awaiting LLM work inside the stop handler, which is
the latency this trigger exists to avoid.
- How often the out-of-order fallback fires in a real deployment is not
measured. Compression latency scales with payload size, so timestamp
inversions may be common rather than rare. When the fallback fires it does
exactly what the pre-fix code did on every turn, so this is never worse
than the status quo, but the saving on a busy session is unquantified.
- Interleaving is handled by construction, not by a lock: the (timestamp,
count) pair is only ever written as a matched snapshot from a single run,
and a pair that does not reconcile degrades to a full extract. A stale pair
costs a re-merge; it cannot skip an observation.
Ten tests added. Five fail against unmodified source, including the 36-vs-8
dispatch count. The five that pass by construction cover the fallback branch,
whose correct behaviour is the pre-fix behaviour; they exist as mutation
coverage and kill removing the count tripwire, making the comparison
inclusive, dropping the empty-batch guard, and skipping instead of falling
back.
---
src/triggers/events.ts | 57 ++++-
src/types.ts | 9 +
test/graph-extract-incremental.test.ts | 296 +++++++++++++++++++++++++
3 files changed, 358 insertions(+), 4 deletions(-)
create mode 100644 test/graph-extract-incremental.test.ts
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 4c887f5f9c..7b0ee54255 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -51,15 +51,20 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
payload: data,
});
if (summary?.unchanged === true) return summary;
+ // Resolves true when the trigger was accepted, false when the dispatch
+ // itself failed. Callers that need to know (graph-extract's watermark)
+ // read it; the rest ignore it exactly as before.
const fireVoid = (function_id: string, payload: unknown) =>
sdk
.trigger({ function_id, payload, action: TriggerAction.Void() })
- .catch((err) =>
+ .then(() => true)
+ .catch((err) => {
logger.warn(function_id + " trigger failed", {
sessionId: data.sessionId,
error: err instanceof Error ? err.message : String(err),
- }),
- );
+ });
+ return false;
+ });
if (isReflectEnabled()) {
fireVoid("mem::slot-reflect", { sessionId: data.sessionId });
}
@@ -70,7 +75,51 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
);
const compressed = observations.filter((o) => o.title);
if (compressed.length > 0) {
- fireVoid("mem::graph-extract", { observations: compressed });
+ // /session/end is posted by the per-turn Stop hook, so this handler
+ // runs every agent turn. Re-sending the whole session each time makes
+ // persistGraphDelta re-merge turns 1..N-1 on turn N — quadratic engine
+ // calls, and per #843 every kv.set stays resident in the engine, so
+ // that is quadratic permanent heap. Send only what landed since the
+ // last extract.
+ //
+ // The count is what makes the timestamp watermark safe. mem::compress
+ // is dispatched fire-and-forget (observe.ts) and stamps the capture
+ // time, not the write time, so a slow compression can land an OLDER
+ // timestamp after a newer one was already extracted. When the number
+ // of observations newer than the watermark does not exactly account
+ // for the growth since the watermark was recorded, something arrived
+ // out of order (or was evicted) and we re-send the whole session
+ // rather than skip it. Missing a memory is worse than re-merging one.
+ const session = await kv
+ .get(KV.sessions, data.sessionId)
+ .catch(() => null);
+ const at = session?.graphExtractedAt;
+ const count = session?.graphExtractedCount;
+ let batch = compressed;
+ if (typeof at === "string" && typeof count === "number") {
+ const fresh = compressed.filter((o) => o.timestamp > at);
+ if (fresh.length === compressed.length - count) batch = fresh;
+ }
+ if (batch.length > 0) {
+ const newest = compressed.reduce(
+ (max, o) => (o.timestamp > max ? o.timestamp : max),
+ "",
+ );
+ // Advance only after the dispatch is accepted, so a hand-off that
+ // never left retries on the next turn. Completion is unobservable
+ // through TriggerAction.Void(); an extract that fails downstream
+ // leaves its delta out of the graph until POST /agentmemory/graph/build.
+ if (await fireVoid("mem::graph-extract", { observations: batch })) {
+ await kv.update(KV.sessions, data.sessionId, [
+ { type: "set", path: "graphExtractedAt", value: newest },
+ {
+ type: "set",
+ path: "graphExtractedCount",
+ value: compressed.length,
+ },
+ ]);
+ }
+ }
}
} catch (err) {
logger.warn("graph-extract trigger failed", {
diff --git a/src/types.ts b/src/types.ts
index c6d6a37026..6cb4b5caf3 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -13,6 +13,15 @@ export interface Session {
summary?: string;
commitShas?: string[];
agentId?: string;
+ // Incremental graph-extract watermark. Written as a matched pair from a
+ // single observation-list snapshot: `graphExtractedAt` is the newest
+ // observation timestamp handed to mem::graph-extract, `graphExtractedCount`
+ // is how many compressed observations existed at that moment. The count is
+ // the tripwire for out-of-order arrivals — mem::compress is dispatched
+ // fire-and-forget, so observations do not land in KV in timestamp order.
+ // Absent on session records written before this field existed.
+ graphExtractedAt?: string;
+ graphExtractedCount?: number;
}
export interface ProjectSessionIndexEntry {
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
new file mode 100644
index 0000000000..f2cd07e2de
--- /dev/null
+++ b/test/graph-extract-incremental.test.ts
@@ -0,0 +1,296 @@
+import { describe, it, expect, beforeEach, vi } from "vitest";
+import type { CompressedObservation } from "../src/types.js";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock("../src/config.js", () => ({
+ getAgentId: vi.fn(() => undefined),
+ isConsolidationEnabled: vi.fn(() => false),
+ getConsolidationCooldownMs: vi.fn(() => 300000),
+}));
+
+vi.mock("../src/functions/slots.js", () => ({
+ isReflectEnabled: vi.fn(() => false),
+}));
+
+import { registerEventTriggers } from "../src/triggers/events.js";
+
+// /agentmemory/session/end is posted by Claude Code's per-turn Stop hook, so
+// event::session::stopped runs on EVERY agent turn — not once per session.
+// It used to hand mem::graph-extract the session's entire observation list
+// each time, and persistGraphDelta takes the 3-call MERGE path for every node
+// and edge it has already seen, so turn N re-merged turns 1..N-1. Engine
+// invocations were quadratic in turn count, and per #843 nothing written via
+// kv.set is ever evicted from the iii engine, so that was quadratic permanent
+// heap. These tests pin the extract to the observations captured since the
+// last successful extract.
+
+const SID = "ses_1";
+
+function obs(id: string, timestamp: string): CompressedObservation {
+ return {
+ id,
+ sessionId: SID,
+ timestamp,
+ type: "conversation",
+ title: id,
+ facts: [],
+ narrative: id,
+ concepts: [],
+ files: [],
+ importance: 0.5,
+ };
+}
+
+// A KV that persists writes, so the watermark survives between simulated
+// per-turn stops the way the real session record does.
+function persistentKV() {
+ const store = new Map>();
+ const scope = (s: string) => {
+ if (!store.has(s)) store.set(s, new Map());
+ return store.get(s)!;
+ };
+ return {
+ store,
+ scope,
+ get: vi.fn(async (s: string, k: string) => scope(s).get(k) ?? null),
+ set: vi.fn(async (s: string, k: string, v: unknown) => {
+ scope(s).set(k, v);
+ return v;
+ }),
+ delete: vi.fn(async (s: string, k: string) => {
+ scope(s).delete(k);
+ }),
+ update: vi.fn(
+ async (
+ s: string,
+ k: string,
+ ops: Array<{ type: string; path: string; value?: unknown }>,
+ ) => {
+ const cur = (scope(s).get(k) ?? {}) as Record;
+ for (const op of ops) if (op.type === "set") cur[op.path] = op.value;
+ scope(s).set(k, cur);
+ return cur;
+ },
+ ),
+ list: vi.fn(async (s: string) => [...scope(s).values()]),
+ };
+}
+
+type StoppedHandler = (data: {
+ sessionId: string;
+ skipConsolidation?: boolean;
+}) => Promise;
+
+function mockSdk(opts?: { rejectGraphExtract?: () => boolean }) {
+ const handlers = new Map();
+ const trigger = vi.fn(
+ async (input: { function_id: string; payload?: unknown }) => {
+ if (
+ input.function_id === "mem::graph-extract" &&
+ opts?.rejectGraphExtract?.()
+ ) {
+ throw new Error("dispatch refused");
+ }
+ if (input.function_id === "mem::summarize") {
+ return { summary: "s", sessionId: SID };
+ }
+ return { ok: true };
+ },
+ );
+ return {
+ sdk: {
+ registerFunction: (id: string, h: StoppedHandler) => handlers.set(id, h),
+ registerTrigger: () => {},
+ trigger,
+ },
+ handlers,
+ trigger,
+ };
+}
+
+// Every batch handed to mem::graph-extract, as arrays of observation ids.
+function batches(trigger: ReturnType): string[][] {
+ return trigger.mock.calls
+ .filter((c) => (c[0] as { function_id: string }).function_id === "mem::graph-extract")
+ .map((c) =>
+ (
+ (c[0] as { payload: { observations: CompressedObservation[] } }).payload
+ .observations ?? []
+ ).map((o) => o.id),
+ );
+}
+
+function harness(opts?: { rejectGraphExtract?: () => boolean }) {
+ const kv = persistentKV();
+ const { sdk, handlers, trigger } = mockSdk(opts);
+ registerEventTriggers(sdk as never, kv as never);
+ const stopped = handlers.get("event::session::stopped")!;
+ kv.scope("mem:sessions").set(SID, {
+ id: SID,
+ project: "p",
+ cwd: "/p",
+ startedAt: "2026-01-01T00:00:00.000Z",
+ status: "active",
+ observationCount: 0,
+ });
+ const land = (...os: CompressedObservation[]) => {
+ for (const o of os) kv.scope(`mem:obs:${SID}`).set(o.id, o);
+ };
+ const stop = () => stopped({ sessionId: SID });
+ const session = () =>
+ kv.scope("mem:sessions").get(SID) as Record;
+ return { kv, trigger, stop, land, session };
+}
+
+describe("event::session::stopped graph-extract is incremental", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("hands each turn only the observations captured since the last extract", async () => {
+ const h = harness();
+
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+ h.land(obs("c", "2026-01-01T00:00:03.000Z"));
+ await h.stop();
+ h.land(obs("d", "2026-01-01T00:00:04.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["a", "b"], ["c"], ["d"]]);
+ });
+
+ it("keeps total dispatched observations linear in turn count, not quadratic", async () => {
+ // Pre-fix, 8 turns of one observation each dispatched 1+2+…+8 = 36
+ // observations (and 36 merge passes downstream). Incremental sends 8.
+ const h = harness();
+ for (let i = 1; i <= 8; i++) {
+ h.land(obs(`o${i}`, `2026-01-01T00:00:0${i}.000Z`));
+ await h.stop();
+ }
+ const dispatched = batches(h.trigger).reduce((n, b) => n + b.length, 0);
+ expect(dispatched).toBe(8);
+ });
+
+ it("does not dispatch graph-extract at all when no new observations landed", async () => {
+ const h = harness();
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"));
+ await h.stop();
+ await h.stop();
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["a"]]);
+ });
+
+ it("records the watermark as a matched (timestamp, count) pair on the session", async () => {
+ const h = harness();
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+
+ expect(h.session()).toMatchObject({
+ graphExtractedAt: "2026-01-01T00:00:02.000Z",
+ graphExtractedCount: 2,
+ });
+ });
+});
+
+// The fallback branch. Most of these assert the PRE-FIX behaviour (extract
+// everything) on purpose, so they pass against unmodified source by
+// construction — their job is to kill mutations that would make the watermark
+// silently skip an observation.
+describe("graph-extract watermark never skips an observation", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("extracts the whole session on the first stop, when no watermark exists", async () => {
+ const h = harness();
+ h.land(
+ obs("a", "2026-01-01T00:00:01.000Z"),
+ obs("b", "2026-01-01T00:00:02.000Z"),
+ obs("c", "2026-01-01T00:00:03.000Z"),
+ );
+ await h.stop();
+ expect(batches(h.trigger)).toEqual([["a", "b", "c"]]);
+ });
+
+ it("re-extracts everything when an observation lands out of order below the watermark", async () => {
+ // mem::compress is fire-and-forget, so a slow compression writes an older
+ // timestamp after a newer one was already extracted. Without the count
+ // tripwire that observation would never reach the graph.
+ const h = harness();
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("c", "2026-01-01T00:00:03.000Z"));
+ await h.stop();
+
+ h.land(obs("b", "2026-01-01T00:00:02.000Z"), obs("d", "2026-01-01T00:00:04.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)[1]).toEqual(["a", "c", "b", "d"]);
+ });
+
+ it("re-extracts everything when two observations share the watermark timestamp", async () => {
+ const h = harness();
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"));
+ await h.stop();
+ h.land(obs("b", "2026-01-01T00:00:01.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)[1]).toEqual(["a", "b"]);
+ });
+
+ it("falls back to the whole session when the watermark is half-written", async () => {
+ const h = harness();
+ h.kv.scope("mem:sessions").set(SID, {
+ id: SID,
+ project: "p",
+ cwd: "/p",
+ startedAt: "2026-01-01T00:00:00.000Z",
+ status: "active",
+ observationCount: 0,
+ graphExtractedAt: "2026-01-01T00:00:01.000Z",
+ // graphExtractedCount deliberately missing
+ });
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["a", "b"]]);
+ });
+
+ it("falls back to the whole session when the stored pair is inconsistent", async () => {
+ // Interleaved stops only ever write (at, count) as a matched snapshot from
+ // one run, but a torn or stale pair must still degrade to a full extract
+ // rather than skip anything.
+ const h = harness();
+ h.kv.scope("mem:sessions").set(SID, {
+ id: SID,
+ project: "p",
+ cwd: "/p",
+ startedAt: "2026-01-01T00:00:00.000Z",
+ status: "active",
+ observationCount: 0,
+ graphExtractedAt: "2026-01-01T00:00:03.000Z",
+ graphExtractedCount: 99,
+ });
+ h.land(
+ obs("a", "2026-01-01T00:00:01.000Z"),
+ obs("b", "2026-01-01T00:00:04.000Z"),
+ );
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["a", "b"]]);
+ });
+
+ it("leaves the watermark unset when the extract dispatch fails, so the next stop retries", async () => {
+ let refuse = true;
+ const h = harness({ rejectGraphExtract: () => refuse });
+
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+ expect(h.session().graphExtractedAt).toBeUndefined();
+
+ refuse = false;
+ await h.stop();
+
+ expect(batches(h.trigger)[1]).toEqual(["a", "b"]);
+ expect(h.session()).toMatchObject({ graphExtractedCount: 2 });
+ });
+});
From 253b542fbd201c63bc757ab2d24c05e8d1a852ac Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 17:52:07 +0800
Subject: [PATCH 02/17] fix(graph): fingerprint the extracted set so a swap
cannot skip an observation
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Review of the previous commit found a hole in its tripwire. Comparing the
number of observations at or below the watermark proves the cardinality is
unchanged, not that they are the same observations. A deletion and a late
arrival in the same window cancel out:
snapshot {o1(T1)..o5(T5)} extracted, watermark (T5, 5); then evict removes
o3 and a slow compression lands o2b(T2b
+ obs.reduce((sum, o) => (sum + Date.parse(o.timestamp)) % OBS_DIGEST_MOD, obs.length);
+
async function consolidationDueUnserialized(kv: StateKV): Promise {
const cooldownMs = getConsolidationCooldownMs();
if (cooldownMs <= 0) return true; // debounce disabled
@@ -82,23 +95,24 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
// that is quadratic permanent heap. Send only what landed since the
// last extract.
//
- // The count is what makes the timestamp watermark safe. mem::compress
+ // The digest is what makes the timestamp watermark safe. mem::compress
// is dispatched fire-and-forget (observe.ts) and stamps the capture
// time, not the write time, so a slow compression can land an OLDER
- // timestamp after a newer one was already extracted. When the number
- // of observations newer than the watermark does not exactly account
- // for the growth since the watermark was recorded, something arrived
- // out of order (or was evicted) and we re-send the whole session
- // rather than skip it. Missing a memory is worse than re-merging one.
+ // timestamp after a newer one was already extracted; evict can also
+ // remove one at any point. Whenever the already-extracted half no
+ // longer fingerprints the same, we re-send the whole session rather
+ // than skip it. Missing a memory is worse than re-merging one.
const session = await kv
.get(KV.sessions, data.sessionId)
.catch(() => null);
const at = session?.graphExtractedAt;
- const count = session?.graphExtractedCount;
+ const mark = session?.graphExtractedDigest;
let batch = compressed;
- if (typeof at === "string" && typeof count === "number") {
- const fresh = compressed.filter((o) => o.timestamp > at);
- if (fresh.length === compressed.length - count) batch = fresh;
+ if (typeof at === "string" && typeof mark === "number") {
+ const seen = compressed.filter((o) => o.timestamp <= at);
+ if (observationDigest(seen) === mark) {
+ batch = compressed.filter((o) => o.timestamp > at);
+ }
}
if (batch.length > 0) {
const newest = compressed.reduce(
@@ -114,8 +128,8 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
{ type: "set", path: "graphExtractedAt", value: newest },
{
type: "set",
- path: "graphExtractedCount",
- value: compressed.length,
+ path: "graphExtractedDigest",
+ value: observationDigest(compressed),
},
]);
}
diff --git a/src/types.ts b/src/types.ts
index 6cb4b5caf3..300349c0fd 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -15,13 +15,14 @@ export interface Session {
agentId?: string;
// Incremental graph-extract watermark. Written as a matched pair from a
// single observation-list snapshot: `graphExtractedAt` is the newest
- // observation timestamp handed to mem::graph-extract, `graphExtractedCount`
- // is how many compressed observations existed at that moment. The count is
- // the tripwire for out-of-order arrivals — mem::compress is dispatched
- // fire-and-forget, so observations do not land in KV in timestamp order.
- // Absent on session records written before this field existed.
+ // observation timestamp handed to mem::graph-extract, `graphExtractedDigest`
+ // fingerprints the observations at or below it. The digest is the tripwire —
+ // mem::compress is dispatched fire-and-forget so observations do not land in
+ // KV in timestamp order, and evict can delete one at any time; either way
+ // the already-extracted set changes and the whole session is re-sent rather
+ // than skipping anything. Absent on records written before this existed.
graphExtractedAt?: string;
- graphExtractedCount?: number;
+ graphExtractedDigest?: number;
}
export interface ProjectSessionIndexEntry {
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index f2cd07e2de..8acd04937a 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -139,10 +139,11 @@ function harness(opts?: { rejectGraphExtract?: () => boolean }) {
const land = (...os: CompressedObservation[]) => {
for (const o of os) kv.scope(`mem:obs:${SID}`).set(o.id, o);
};
+ const drop = (id: string) => kv.scope(`mem:obs:${SID}`).delete(id);
const stop = () => stopped({ sessionId: SID });
const session = () =>
kv.scope("mem:sessions").get(SID) as Record;
- return { kv, trigger, stop, land, session };
+ return { kv, trigger, stop, land, drop, session };
}
describe("event::session::stopped graph-extract is incremental", () => {
@@ -183,14 +184,14 @@ describe("event::session::stopped graph-extract is incremental", () => {
expect(batches(h.trigger)).toEqual([["a"]]);
});
- it("records the watermark as a matched (timestamp, count) pair on the session", async () => {
+ it("records the watermark as a matched (timestamp, digest) pair on the session", async () => {
const h = harness();
h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
await h.stop();
expect(h.session()).toMatchObject({
graphExtractedAt: "2026-01-01T00:00:02.000Z",
- graphExtractedCount: 2,
+ graphExtractedDigest: expect.any(Number),
});
});
});
@@ -247,7 +248,7 @@ describe("graph-extract watermark never skips an observation", () => {
status: "active",
observationCount: 0,
graphExtractedAt: "2026-01-01T00:00:01.000Z",
- // graphExtractedCount deliberately missing
+ // graphExtractedDigest deliberately missing
});
h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
await h.stop();
@@ -256,9 +257,9 @@ describe("graph-extract watermark never skips an observation", () => {
});
it("falls back to the whole session when the stored pair is inconsistent", async () => {
- // Interleaved stops only ever write (at, count) as a matched snapshot from
- // one run, but a torn or stale pair must still degrade to a full extract
- // rather than skip anything.
+ // Interleaved stops only ever write (at, digest) as a matched snapshot
+ // from one run, but a torn or stale pair must still degrade to a full
+ // extract rather than skip anything.
const h = harness();
h.kv.scope("mem:sessions").set(SID, {
id: SID,
@@ -268,7 +269,7 @@ describe("graph-extract watermark never skips an observation", () => {
status: "active",
observationCount: 0,
graphExtractedAt: "2026-01-01T00:00:03.000Z",
- graphExtractedCount: 99,
+ graphExtractedDigest: 123456,
});
h.land(
obs("a", "2026-01-01T00:00:01.000Z"),
@@ -279,6 +280,42 @@ describe("graph-extract watermark never skips an observation", () => {
expect(batches(h.trigger)).toEqual([["a", "b"]]);
});
+ it("re-extracts everything when a deletion and a late arrival cancel out", async () => {
+ // evict's per-project cap (evict.ts) is age- and status-independent, so it
+ // can delete an observation from the session that is still being appended
+ // to. If a late compression lands in the same window, a count-based
+ // tripwire nets to zero and the late observation would never be extracted.
+ const h = harness();
+ h.land(
+ obs("a", "2026-01-01T00:00:01.000Z"),
+ obs("c", "2026-01-01T00:00:03.000Z"),
+ obs("e", "2026-01-01T00:00:05.000Z"),
+ );
+ await h.stop();
+
+ h.drop("c"); // evicted
+ h.land(obs("b", "2026-01-01T00:00:02.000Z")); // compressed late
+
+ await h.stop();
+
+ expect(batches(h.trigger)[1]).toEqual(["a", "e", "b"]);
+ });
+
+ it("re-extracts when a late observation carries a timestamp the digest sums to zero", async () => {
+ // observe.ts only validates that a timestamp is a string, so a clock-skewed
+ // client can send the epoch. Date.parse("1970-01-01T00:00:00.000Z") is 0 and
+ // adds nothing to the digest sum — the set size folded into the seed is what
+ // keeps that observation visible.
+ const h = harness();
+ h.land(obs("x", "2026-01-01T00:00:01.000Z"));
+ await h.stop();
+
+ h.land(obs("y", "1970-01-01T00:00:00.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)[1]).toEqual(["x", "y"]);
+ });
+
it("leaves the watermark unset when the extract dispatch fails, so the next stop retries", async () => {
let refuse = true;
const h = harness({ rejectGraphExtract: () => refuse });
@@ -291,6 +328,8 @@ describe("graph-extract watermark never skips an observation", () => {
await h.stop();
expect(batches(h.trigger)[1]).toEqual(["a", "b"]);
- expect(h.session()).toMatchObject({ graphExtractedCount: 2 });
+ expect(h.session()).toMatchObject({
+ graphExtractedDigest: expect.any(Number),
+ });
});
});
From 781e5d15e5f203e3bff3d47095074eafed137f6d Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 17:59:01 +0800
Subject: [PATCH 03/17] docs(graph): record what the smaller extract batch does
and does not change
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Review asked the question the batch-content tests cannot answer: the tests mock
sdk.trigger, so mem::graph-extract never runs and they prove only that the
payload shrank, not that the resulting graph is the same. Traced it.
extractGraphHeuristics (graph.ts:457) loops per observation and every link()
call joins nodes built from that one observation's own files and concepts. Its
nodeByKey and edgeByPair maps are batch-scoped dedup, and persistGraphDelta
performs the same dedup across batches through graphNameIndex and
graphEdgeKey, with mergeNode and mergeEdge unioning sourceObservationIds. So
on the default path the delta produces the identical node and edge set. That
is what makes the previous "perf" framing accurate rather than a quiet
behaviour change.
The opt-in LLM pass is different and worth naming. isGraphExtractionEnabled
requires GRAPH_EXTRACTION_ENABLED=true and is off by default; when on,
buildGraphExtractionPrompt builds ONE prompt from the whole array, so a
per-turn delta of a few observations gives the model less co-occurrence to
work with than a whole-session batch did. Cross-turn relations it used to
propose will not be proposed. Bounded batches are already the norm on that
path, api::graph-build feeds it 25 observations at a time (api.ts:1616), so
this narrows an existing property rather than introducing a new limit.
Also corrects the residual stated in the previous commit, which was narrower
than a sum actually guarantees. The digest is blind to any change to the
already-extracted set whose timestamp total is congruent mod 2^32, not only to
a single swap 49.7 days apart to the millisecond — deleting two and adding two
with a coinciding total would also pass. Still an arithmetic coincidence at
millisecond resolution, but the bound is a coinciding sum, not a coinciding
pair.
One further effect worth knowing, in the direction of better: mergeNode and
mergeEdge union the WHOLE batch's obsIds into every node and edge they touch.
Sending the entire session every turn therefore accumulated every observation
id in the session into sourceObservationIds on every node it merged. The delta
attributes only the observations that were actually in the batch, so
provenance gets narrower and those arrays stop growing per turn.
Comment only, no behaviour change.
---
src/triggers/events.ts | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 88dfe3adcc..e71e1ac842 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -119,6 +119,16 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
(max, o) => (o.timestamp > max ? o.timestamp : max),
"",
);
+ // What the smaller batch costs, for the next person to read this:
+ // extractGraphHeuristics (graph.ts) loops per observation and only
+ // ever links nodes drawn from one observation's own files/concepts,
+ // and persistGraphDelta dedupes across batches through the name and
+ // edge indexes, so the heuristic graph is identical either way. The
+ // opt-in LLM pass (GRAPH_EXTRACTION_ENABLED, off by default) builds
+ // one prompt from the array, so it sees less co-occurrence per call
+ // than a whole-session batch did — bounded batches are already the
+ // norm there, api::graph-build feeds it 25 at a time.
+ //
// Advance only after the dispatch is accepted, so a hand-off that
// never left retries on the next turn. Completion is unobservable
// through TriggerAction.Void(); an extract that fails downstream
From 22ce83035cdd66cf564e9a5283e581bff8ebcf50 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:30:21 +0800
Subject: [PATCH 04/17] fix(graph): fingerprint observation ids, not timestamps
The digest that guards the incremental watermark summed Date.parse of each
timestamp, seeded with the set size. That collides on exactly the case it
was written to catch: evict drops one observation while a late compression
lands another carrying the SAME millisecond. Size is unchanged, the sum is
unchanged, the digest matches, the incremental path is taken, and the late
observation is never handed to mem::graph-extract. On a review of the
watermark logic a skip is otherwise impossible, so the whole correctness
argument rested on this digest.
Fingerprint the sorted observation ids through the existing
fingerprintId() helper instead. Ids differ whatever the timestamps do, and
order-independence is now structural rather than an arithmetic property a
test has to assert. graphExtractedDigest becomes a string.
The pinned test previously used two different milliseconds, which is why it
passed. Moved to the same millisecond; it fails against the arithmetic
digest with the second stop dispatching nothing at all.
---
src/triggers/events.ts | 26 ++++++++++--------------
src/types.ts | 2 +-
test/graph-extract-incremental.test.ts | 28 +++++++-------------------
3 files changed, 19 insertions(+), 37 deletions(-)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index e71e1ac842..a7ca26ee47 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -1,6 +1,6 @@
import { TriggerAction, type IIIClient } from "iii-sdk";
import type { CompressedObservation, Memory, Session } from "../types.js";
-import { KV } from "../state/schema.js";
+import { KV, fingerprintId } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
import { emitLiveEvent } from "../viewer/live-events.js";
import { isReflectEnabled } from "../functions/slots.js";
@@ -18,18 +18,14 @@ import { noteMemoryChange, noteSessionChange } from "../state/viewer-counts.js";
// the per-turn session-stop fan-out.
const CONSOLIDATION_MARKER_KEY = "consolidation:lastRun";
-// Order-independent fingerprint of an observation set, used to tell whether
-// the already-extracted half of a session still looks the way it did at the
-// last graph extract. Counting is not enough: evict's per-project cap
+// Order-independent fingerprint of an observation set: tells whether the
+// already-extracted half of a session still looks the way it did at the last
+// graph extract. Over ids, not counts or timestamps — evict's per-project cap
// (evict.ts, age- and status-independent) can delete an observation from the
-// live session in the same window a late compression lands another, and the
-// two cancel out. Seeded with the set size so a pure size change always shows,
-// and kept under 2^32 so every intermediate stays an exact integer no matter
-// how large the session gets. An unparseable timestamp yields NaN, which never
-// compares equal, so the session falls back to a full extract.
-const OBS_DIGEST_MOD = 0x1_0000_0000;
-const observationDigest = (obs: CompressedObservation[]): number =>
- obs.reduce((sum, o) => (sum + Date.parse(o.timestamp)) % OBS_DIGEST_MOD, obs.length);
+// live session in the same window a late compression lands another, and if the
+// two share a millisecond only the ids tell the sets apart.
+const observationFingerprint = (obs: CompressedObservation[]): string =>
+ fingerprintId("gx", obs.map((o) => o.id).sort().join(","));
async function consolidationDueUnserialized(kv: StateKV): Promise {
const cooldownMs = getConsolidationCooldownMs();
@@ -108,9 +104,9 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
const at = session?.graphExtractedAt;
const mark = session?.graphExtractedDigest;
let batch = compressed;
- if (typeof at === "string" && typeof mark === "number") {
+ if (typeof at === "string" && typeof mark === "string") {
const seen = compressed.filter((o) => o.timestamp <= at);
- if (observationDigest(seen) === mark) {
+ if (observationFingerprint(seen) === mark) {
batch = compressed.filter((o) => o.timestamp > at);
}
}
@@ -139,7 +135,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
{
type: "set",
path: "graphExtractedDigest",
- value: observationDigest(compressed),
+ value: observationFingerprint(compressed),
},
]);
}
diff --git a/src/types.ts b/src/types.ts
index 300349c0fd..9ccc9a04ad 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -22,7 +22,7 @@ export interface Session {
// the already-extracted set changes and the whole session is re-sent rather
// than skipping anything. Absent on records written before this existed.
graphExtractedAt?: string;
- graphExtractedDigest?: number;
+ graphExtractedDigest?: string;
}
export interface ProjectSessionIndexEntry {
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index 8acd04937a..e712ecd648 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -191,7 +191,7 @@ describe("event::session::stopped graph-extract is incremental", () => {
expect(h.session()).toMatchObject({
graphExtractedAt: "2026-01-01T00:00:02.000Z",
- graphExtractedDigest: expect.any(Number),
+ graphExtractedDigest: expect.any(String),
});
});
});
@@ -280,11 +280,12 @@ describe("graph-extract watermark never skips an observation", () => {
expect(batches(h.trigger)).toEqual([["a", "b"]]);
});
- it("re-extracts everything when a deletion and a late arrival cancel out", async () => {
+ it("re-extracts everything when a deletion and a late arrival share a millisecond", async () => {
// evict's per-project cap (evict.ts) is age- and status-independent, so it
// can delete an observation from the session that is still being appended
- // to. If a late compression lands in the same window, a count-based
- // tripwire nets to zero and the late observation would never be extracted.
+ // to. When a late compression lands in the same window AND carries the
+ // same timestamp, size and any timestamp-derived checksum both net to
+ // zero — only the observation ids tell the two sets apart.
const h = harness();
h.land(
obs("a", "2026-01-01T00:00:01.000Z"),
@@ -294,28 +295,13 @@ describe("graph-extract watermark never skips an observation", () => {
await h.stop();
h.drop("c"); // evicted
- h.land(obs("b", "2026-01-01T00:00:02.000Z")); // compressed late
+ h.land(obs("b", "2026-01-01T00:00:03.000Z")); // compressed late, same ms
await h.stop();
expect(batches(h.trigger)[1]).toEqual(["a", "e", "b"]);
});
- it("re-extracts when a late observation carries a timestamp the digest sums to zero", async () => {
- // observe.ts only validates that a timestamp is a string, so a clock-skewed
- // client can send the epoch. Date.parse("1970-01-01T00:00:00.000Z") is 0 and
- // adds nothing to the digest sum — the set size folded into the seed is what
- // keeps that observation visible.
- const h = harness();
- h.land(obs("x", "2026-01-01T00:00:01.000Z"));
- await h.stop();
-
- h.land(obs("y", "1970-01-01T00:00:00.000Z"));
- await h.stop();
-
- expect(batches(h.trigger)[1]).toEqual(["x", "y"]);
- });
-
it("leaves the watermark unset when the extract dispatch fails, so the next stop retries", async () => {
let refuse = true;
const h = harness({ rejectGraphExtract: () => refuse });
@@ -329,7 +315,7 @@ describe("graph-extract watermark never skips an observation", () => {
expect(batches(h.trigger)[1]).toEqual(["a", "b"]);
expect(h.session()).toMatchObject({
- graphExtractedDigest: expect.any(Number),
+ graphExtractedDigest: expect.any(String),
});
});
});
From 32ed3e52aaa70cef1f1884d957fbea6101aa8670 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:31:15 +0800
Subject: [PATCH 05/17] fix(graph): derive the whole watermark pair from the
dispatched batch
`newest` reduced over the full compressed list and the digest fingerprinted
the full compressed list, while the batch handed to mem::graph-extract was
only the tail. Those are equal today because the batch is always
`timestamp > at`, so max(batch) === max(compressed).
They stop being equal the moment anyone caps this batch, and the file's own
comment cites api::graph-build capping at 25 as precedent. A cap would make
`newest` advance past observations that were never dispatched, which is the
exact silent skip the digest exists to prevent, and would leave the digest
covering observations above the watermark so the pair could never match
again.
Reduce over `batch` and fingerprint everything at or below the resulting
watermark. Both fields now come off one predicate, so the invariant holds
locally instead of resting on a max-equality argument in prose.
---
src/triggers/events.ts | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index a7ca26ee47..3ea5acb232 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -111,10 +111,14 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
}
}
if (batch.length > 0) {
- const newest = compressed.reduce(
+ // Both halves of the pair come off the batch actually dispatched, so
+ // capping the batch (api::graph-build already feeds 25 at a time)
+ // cannot advance the watermark past an observation nobody sent.
+ const newest = batch.reduce(
(max, o) => (o.timestamp > max ? o.timestamp : max),
"",
);
+ const extracted = compressed.filter((o) => o.timestamp <= newest);
// What the smaller batch costs, for the next person to read this:
// extractGraphHeuristics (graph.ts) loops per observation and only
// ever links nodes drawn from one observation's own files/concepts,
@@ -135,7 +139,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
{
type: "set",
path: "graphExtractedDigest",
- value: observationFingerprint(compressed),
+ value: observationFingerprint(extracted),
},
]);
}
From ae7b834e35dbb7cb4eb8a2a3148393d62bdd22f0 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:32:22 +0800
Subject: [PATCH 06/17] feat(graph): log when the incremental extract falls
back to a full one
Neither branch logged anything, so a session whose watermark keeps going
stale re-sends its whole observation list every turn and looks identical to
a healthy one from the outside. One line on the mismatch path, carrying the
two set sizes so the cause (a deletion, a late arrival, a half-written pair)
is readable from the log rather than guessed.
---
src/triggers/events.ts | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 3ea5acb232..49beca91b9 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -108,6 +108,14 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
const seen = compressed.filter((o) => o.timestamp <= at);
if (observationFingerprint(seen) === mark) {
batch = compressed.filter((o) => o.timestamp > at);
+ } else {
+ // Otherwise the fallback is silent: a session stuck re-extracting
+ // itself every turn looks exactly like a healthy one.
+ logger.info("graph-extract watermark stale, re-extracting session", {
+ sessionId: data.sessionId,
+ atOrBelow: seen.length,
+ total: compressed.length,
+ });
}
}
if (batch.length > 0) {
From 0a21a06cfc69fc914fab3719e69301103c665125 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:33:19 +0800
Subject: [PATCH 07/17] docs(graph): say what the smaller batch actually
changes
The comment claimed the heuristic graph is "identical either way" and hung
that on persistGraphDelta's dedupe. The dedupe argument is right about the
node and edge SETS and wrong about provenance: mergeNode and mergeEdge
union the whole batch's obsIds (graph.ts), so a whole-session batch stamped
every node and edge with every observation id in the session. The union
cited as proof of equivalence is where the divergence lives.
Post-change provenance is per-batch, which is narrower and more accurate,
and it is read by graph retrieval and by supersede-staling. Net an
improvement, but it ships on the default path and the comment should say
so rather than assert equivalence.
Also drops the GRAPH_EXTRACTION_ENABLED framing. That flag gates only the
LLM pass; the heuristic pass that produces this behaviour always runs.
---
src/triggers/events.ts | 16 +++++++---------
1 file changed, 7 insertions(+), 9 deletions(-)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 49beca91b9..a1f93224ec 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -127,15 +127,13 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
"",
);
const extracted = compressed.filter((o) => o.timestamp <= newest);
- // What the smaller batch costs, for the next person to read this:
- // extractGraphHeuristics (graph.ts) loops per observation and only
- // ever links nodes drawn from one observation's own files/concepts,
- // and persistGraphDelta dedupes across batches through the name and
- // edge indexes, so the heuristic graph is identical either way. The
- // opt-in LLM pass (GRAPH_EXTRACTION_ENABLED, off by default) builds
- // one prompt from the array, so it sees less co-occurrence per call
- // than a whole-session batch did — bounded batches are already the
- // norm there, api::graph-build feeds it 25 at a time.
+ // The node and edge SETS are unchanged: extractGraphHeuristics links
+ // only within a single observation, and persistGraphDelta dedupes
+ // across batches through the name and edge-key indexes. Provenance
+ // does change — mergeNode/mergeEdge union the whole batch's obsIds,
+ // so a whole-session batch stamped every node and edge with every
+ // observation id in the session. Narrower is more accurate, and
+ // graph retrieval and supersede-staling both read it.
//
// Advance only after the dispatch is accepted, so a hand-off that
// never left retries on the next turn. Completion is unobservable
From c3ed775fdd542d0dba941504680a156bfe4cb322 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:36:40 +0800
Subject: [PATCH 08/17] refactor(graph): drop the scaffolding the watermark did
not need
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Three things that carried no weight:
`typeof mark === "string"` was a no-op. The comparison on the next line
already yields false for an absent or legacy-numeric digest, which is the
same fallback the guard produced.
fireVoid grew a boolean return for one of its four callers. Calling
sdk.trigger directly for mem::graph-extract lets a rejected dispatch throw
into the try/catch that was already there, which logs the same message and
skips the watermark write the same way, and restores fireVoid to what the
other three callers use.
The "mem::compress is fire-and-forget so writes are not in timestamp order"
paragraph was duplicated verbatim in types.ts and events.ts. types.ts now
points at events.ts.
Four test cases went with it. Each asserted a mutation another case already
kills: the linear-vs-quadratic count is subsumed by the exact per-turn batch
assertion, the matched-pair case by the same (a wrong watermark changes the
next turn's batch), the synthetic torn pair by the realistic out-of-order
case, and the half-written pair killed nothing at all — it passed with the
guard present or absent. The fake KV's set/delete were never invoked.
---
src/triggers/events.ts | 45 ++++++++--------
src/types.ts | 11 ++--
test/graph-extract-incremental.test.ts | 72 --------------------------
test/graph-heuristic-extract.test.ts | 2 +-
4 files changed, 26 insertions(+), 104 deletions(-)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index a1f93224ec..3b40cd789a 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -60,20 +60,15 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
payload: data,
});
if (summary?.unchanged === true) return summary;
- // Resolves true when the trigger was accepted, false when the dispatch
- // itself failed. Callers that need to know (graph-extract's watermark)
- // read it; the rest ignore it exactly as before.
const fireVoid = (function_id: string, payload: unknown) =>
sdk
.trigger({ function_id, payload, action: TriggerAction.Void() })
- .then(() => true)
- .catch((err) => {
+ .catch((err) =>
logger.warn(function_id + " trigger failed", {
sessionId: data.sessionId,
error: err instanceof Error ? err.message : String(err),
- });
- return false;
- });
+ }),
+ );
if (isReflectEnabled()) {
fireVoid("mem::slot-reflect", { sessionId: data.sessionId });
}
@@ -104,7 +99,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
const at = session?.graphExtractedAt;
const mark = session?.graphExtractedDigest;
let batch = compressed;
- if (typeof at === "string" && typeof mark === "string") {
+ if (typeof at === "string") {
const seen = compressed.filter((o) => o.timestamp <= at);
if (observationFingerprint(seen) === mark) {
batch = compressed.filter((o) => o.timestamp > at);
@@ -135,20 +130,24 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
// observation id in the session. Narrower is more accurate, and
// graph retrieval and supersede-staling both read it.
//
- // Advance only after the dispatch is accepted, so a hand-off that
- // never left retries on the next turn. Completion is unobservable
- // through TriggerAction.Void(); an extract that fails downstream
- // leaves its delta out of the graph until POST /agentmemory/graph/build.
- if (await fireVoid("mem::graph-extract", { observations: batch })) {
- await kv.update(KV.sessions, data.sessionId, [
- { type: "set", path: "graphExtractedAt", value: newest },
- {
- type: "set",
- path: "graphExtractedDigest",
- value: observationFingerprint(extracted),
- },
- ]);
- }
+ // A dispatch that throws skips the watermark write (the catch below
+ // logs it) and retries on the next turn. Accepted is not done —
+ // completion is unobservable through TriggerAction.Void(), so an
+ // extract that fails downstream leaves its delta out of the graph
+ // until POST /agentmemory/graph/build.
+ await sdk.trigger({
+ function_id: "mem::graph-extract",
+ payload: { observations: batch },
+ action: TriggerAction.Void(),
+ });
+ await kv.update(KV.sessions, data.sessionId, [
+ { type: "set", path: "graphExtractedAt", value: newest },
+ {
+ type: "set",
+ path: "graphExtractedDigest",
+ value: observationFingerprint(extracted),
+ },
+ ]);
}
}
} catch (err) {
diff --git a/src/types.ts b/src/types.ts
index 9ccc9a04ad..33f17aea1b 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -13,14 +13,9 @@ export interface Session {
summary?: string;
commitShas?: string[];
agentId?: string;
- // Incremental graph-extract watermark. Written as a matched pair from a
- // single observation-list snapshot: `graphExtractedAt` is the newest
- // observation timestamp handed to mem::graph-extract, `graphExtractedDigest`
- // fingerprints the observations at or below it. The digest is the tripwire —
- // mem::compress is dispatched fire-and-forget so observations do not land in
- // KV in timestamp order, and evict can delete one at any time; either way
- // the already-extracted set changes and the whole session is re-sent rather
- // than skipping anything. Absent on records written before this existed.
+ // Matched incremental graph-extract watermark, written together by
+ // event::session::stopped (triggers/events.ts) — see there for why the
+ // digest is needed. Absent on records written before this existed.
graphExtractedAt?: string;
graphExtractedDigest?: string;
}
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index e712ecd648..3d65d17dad 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -56,13 +56,6 @@ function persistentKV() {
store,
scope,
get: vi.fn(async (s: string, k: string) => scope(s).get(k) ?? null),
- set: vi.fn(async (s: string, k: string, v: unknown) => {
- scope(s).set(k, v);
- return v;
- }),
- delete: vi.fn(async (s: string, k: string) => {
- scope(s).delete(k);
- }),
update: vi.fn(
async (
s: string,
@@ -162,18 +155,6 @@ describe("event::session::stopped graph-extract is incremental", () => {
expect(batches(h.trigger)).toEqual([["a", "b"], ["c"], ["d"]]);
});
- it("keeps total dispatched observations linear in turn count, not quadratic", async () => {
- // Pre-fix, 8 turns of one observation each dispatched 1+2+…+8 = 36
- // observations (and 36 merge passes downstream). Incremental sends 8.
- const h = harness();
- for (let i = 1; i <= 8; i++) {
- h.land(obs(`o${i}`, `2026-01-01T00:00:0${i}.000Z`));
- await h.stop();
- }
- const dispatched = batches(h.trigger).reduce((n, b) => n + b.length, 0);
- expect(dispatched).toBe(8);
- });
-
it("does not dispatch graph-extract at all when no new observations landed", async () => {
const h = harness();
h.land(obs("a", "2026-01-01T00:00:01.000Z"));
@@ -183,17 +164,6 @@ describe("event::session::stopped graph-extract is incremental", () => {
expect(batches(h.trigger)).toEqual([["a"]]);
});
-
- it("records the watermark as a matched (timestamp, digest) pair on the session", async () => {
- const h = harness();
- h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
- await h.stop();
-
- expect(h.session()).toMatchObject({
- graphExtractedAt: "2026-01-01T00:00:02.000Z",
- graphExtractedDigest: expect.any(String),
- });
- });
});
// The fallback branch. Most of these assert the PRE-FIX behaviour (extract
@@ -238,48 +208,6 @@ describe("graph-extract watermark never skips an observation", () => {
expect(batches(h.trigger)[1]).toEqual(["a", "b"]);
});
- it("falls back to the whole session when the watermark is half-written", async () => {
- const h = harness();
- h.kv.scope("mem:sessions").set(SID, {
- id: SID,
- project: "p",
- cwd: "/p",
- startedAt: "2026-01-01T00:00:00.000Z",
- status: "active",
- observationCount: 0,
- graphExtractedAt: "2026-01-01T00:00:01.000Z",
- // graphExtractedDigest deliberately missing
- });
- h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
- await h.stop();
-
- expect(batches(h.trigger)).toEqual([["a", "b"]]);
- });
-
- it("falls back to the whole session when the stored pair is inconsistent", async () => {
- // Interleaved stops only ever write (at, digest) as a matched snapshot
- // from one run, but a torn or stale pair must still degrade to a full
- // extract rather than skip anything.
- const h = harness();
- h.kv.scope("mem:sessions").set(SID, {
- id: SID,
- project: "p",
- cwd: "/p",
- startedAt: "2026-01-01T00:00:00.000Z",
- status: "active",
- observationCount: 0,
- graphExtractedAt: "2026-01-01T00:00:03.000Z",
- graphExtractedDigest: 123456,
- });
- h.land(
- obs("a", "2026-01-01T00:00:01.000Z"),
- obs("b", "2026-01-01T00:00:04.000Z"),
- );
- await h.stop();
-
- expect(batches(h.trigger)).toEqual([["a", "b"]]);
- });
-
it("re-extracts everything when a deletion and a late arrival share a millisecond", async () => {
// evict's per-project cap (evict.ts) is age- and status-independent, so it
// can delete an observation from the session that is still being appended
diff --git a/test/graph-heuristic-extract.test.ts b/test/graph-heuristic-extract.test.ts
index f3bfec805b..0564bbc32b 100644
--- a/test/graph-heuristic-extract.test.ts
+++ b/test/graph-heuristic-extract.test.ts
@@ -96,7 +96,7 @@ describe("keyless graph extraction wiring", () => {
const events = readFileSync("src/triggers/events.ts", "utf-8");
const stopped = events.slice(events.indexOf("event::session::stopped"));
const gate = stopped.indexOf("isGraphExtractionEnabled()");
- const fire = stopped.indexOf('fireVoid("mem::graph-extract"');
+ const fire = stopped.indexOf('"mem::graph-extract"');
expect(fire).toBeGreaterThan(-1);
expect(gate === -1 || gate > fire).toBe(true);
});
From a00adebfa7bfaf0e9be3e2fc4ded935b373d832a Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:40:17 +0800
Subject: [PATCH 09/17] test(graph): pin the graph shape the smaller batch is
supposed to preserve
Nothing verified the claim the whole change rests on. The incremental suite
sets concepts and files to [] and mocks sdk.trigger, so mem::graph-extract
never runs and the graph is never built.
Call extractGraphHeuristics directly with populated concepts and files and
compare one batch of two observations against two batches of one, merged by
(type, name) and edge endpoints the way persistGraphDelta merges them. Node
ids are random, so the comparison is by name throughout. This is what would
catch a future cross-observation link, which is the only way splitting the
batch could change the set.
Also pins order-independence of the fingerprint: the same observation set
listed back in a different order must stay on the incremental path. Kills
the mutation that drops the sort.
---
test/graph-extract-incremental.test.ts | 15 ++++++++++
test/graph-heuristic-extract.test.ts | 41 ++++++++++++++++++++++++++
2 files changed, 56 insertions(+)
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index 3d65d17dad..3cef57fea0 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -164,6 +164,21 @@ describe("event::session::stopped graph-extract is incremental", () => {
expect(batches(h.trigger)).toEqual([["a"]]);
});
+
+ it("stays incremental when kv.list returns the same set in a different order", async () => {
+ // Listing order is the store's, not ours. The same observation set coming
+ // back rearranged is not a change and must not force a full re-extract.
+ const h = harness();
+ h.land(obs("a", "2026-01-01T00:00:01.000Z"), obs("b", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+
+ h.drop("a");
+ h.land(obs("a", "2026-01-01T00:00:01.000Z")); // same observation, now last
+ h.land(obs("c", "2026-01-01T00:00:03.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)[1]).toEqual(["c"]);
+ });
});
// The fallback branch. Most of these assert the PRE-FIX behaviour (extract
diff --git a/test/graph-heuristic-extract.test.ts b/test/graph-heuristic-extract.test.ts
index 0564bbc32b..0d0593858b 100644
--- a/test/graph-heuristic-extract.test.ts
+++ b/test/graph-heuristic-extract.test.ts
@@ -73,6 +73,47 @@ describe("extractGraphHeuristics", () => {
expect(edges.length).toBeLessThanOrEqual(12);
});
+ // event::session::stopped now sends one batch per turn instead of the whole
+ // session. persistGraphDelta merges batches by (type, name) and by edge key,
+ // so splitting a batch must change neither set. Node ids are random, so
+ // compare by name.
+ function shape(results: Array>) {
+ const prov = new Map>();
+ const edges = new Set();
+ for (const r of results) {
+ const named = new Map(r.nodes.map((n) => [n.id, `${n.type}:${n.name}`]));
+ for (const n of r.nodes) {
+ const key = `${n.type}:${n.name}`;
+ const ids = prov.get(key) ?? new Set();
+ for (const id of n.sourceObservationIds) ids.add(id);
+ prov.set(key, ids);
+ }
+ for (const e of r.edges) {
+ const pair = [named.get(e.sourceNodeId)!, named.get(e.targetNodeId)!];
+ edges.add(pair.sort().join("|"));
+ }
+ }
+ return {
+ nodes: [...prov]
+ .map(([key, ids]) => `${key}=${[...ids].sort().join(",")}`)
+ .sort(),
+ edges: [...edges].sort(),
+ };
+ }
+
+ it("builds the same graph whether observations arrive together or one batch at a time", () => {
+ // One shared entity so the merge and provenance union are exercised, and
+ // disjoint ones on either side so any link drawn ACROSS observations
+ // (the only way splitting could change the set) shows up as an edge the
+ // split calls cannot produce.
+ const o1 = obs("o1", ["src/auth.ts", "src/db.ts"], ["authentication"]);
+ const o2 = obs("o2", ["src/db.ts", "src/cache.ts"], ["caching"]);
+
+ expect(
+ shape([extractGraphHeuristics([o1]), extractGraphHeuristics([o2])]),
+ ).toEqual(shape([extractGraphHeuristics([o1, o2])]));
+ });
+
it("never emits self edges or duplicate pairs", () => {
const { edges } = extractGraphHeuristics([
obs("o1", ["a.ts"], ["a"]),
From d457d7ab29582bdaace0c41902147590ede6bd99 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:43:54 +0800
Subject: [PATCH 10/17] test(graph): pin the fallback log to the fallback
The mutation run showed the `typeof at === "string"` guard could be removed
with every test still green: with no watermark the timestamp filter yields
an empty set, that fingerprints to something no absent digest equals, and
the full extract happens anyway. The guard's one remaining job is keeping
the stale-watermark log off every session's first turn, and nothing checked
that.
Assert the log is silent on the first stop and carries the two set sizes on
the fallback path. Also the only coverage the log line has.
---
test/graph-extract-incremental.test.ts | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index 3cef57fea0..a1968075f6 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -16,6 +16,9 @@ vi.mock("../src/functions/slots.js", () => ({
}));
import { registerEventTriggers } from "../src/triggers/events.js";
+import { logger } from "../src/logger.js";
+
+const STALE = "graph-extract watermark stale, re-extracting session";
// /agentmemory/session/end is posted by Claude Code's per-turn Stop hook, so
// event::session::stopped runs on EVERY agent turn — not once per session.
@@ -197,6 +200,8 @@ describe("graph-extract watermark never skips an observation", () => {
);
await h.stop();
expect(batches(h.trigger)).toEqual([["a", "b", "c"]]);
+ // A session that has never been extracted is not a stale watermark.
+ expect(logger.info).not.toHaveBeenCalled();
});
it("re-extracts everything when an observation lands out of order below the watermark", async () => {
@@ -243,6 +248,11 @@ describe("graph-extract watermark never skips an observation", () => {
await h.stop();
expect(batches(h.trigger)[1]).toEqual(["a", "e", "b"]);
+ expect(logger.info).toHaveBeenCalledWith(STALE, {
+ sessionId: SID,
+ atOrBelow: 3,
+ total: 3,
+ });
});
it("leaves the watermark unset when the extract dispatch fails, so the next stop retries", async () => {
From 23a8cf6eef65bcfed5ca8e5aef789f34db097a17 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 19:50:32 +0800
Subject: [PATCH 11/17] test(graph): cover the legacy record every install hits
on upgrade
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
graphExtractedDigest is new, so on the first stop after this ships every
existing session record has graphExtractedAt and no digest. That branch is
traversed once by 100% of real sessions and nothing exercised it — a
permissiveness mutation (`!mark || fingerprint(seen) === mark`, the
"do not punish upgraders with one re-extract" shortcut) passes the entire
1720-test suite untouched, while silently dropping every observation at or
below the stale watermark.
Assert the whole session goes out when the digest is absent and the
observations straddle the watermark. Kills that mutation.
---
test/graph-extract-incremental.test.ts | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index a1968075f6..ac1750d74f 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -204,6 +204,31 @@ describe("graph-extract watermark never skips an observation", () => {
expect(logger.info).not.toHaveBeenCalled();
});
+ it("re-extracts the whole session when the record predates the digest", async () => {
+ // The path every deployed session takes exactly once, on the first stop
+ // after this ships: a session record carrying graphExtractedAt and no
+ // digest at all. An untrustworthy watermark costs one re-extract;
+ // trusting it costs every observation at or below it.
+ const h = harness();
+ h.kv.scope("mem:sessions").set(SID, {
+ id: SID,
+ project: "p",
+ cwd: "/p",
+ startedAt: "2026-01-01T00:00:00.000Z",
+ status: "active",
+ observationCount: 0,
+ graphExtractedAt: "2026-01-01T00:00:02.000Z",
+ // graphExtractedDigest absent — written by a build that had none
+ });
+ h.land(
+ obs("a", "2026-01-01T00:00:01.000Z"),
+ obs("b", "2026-01-01T00:00:03.000Z"),
+ );
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["a", "b"]]);
+ });
+
it("re-extracts everything when an observation lands out of order below the watermark", async () => {
// mem::compress is fire-and-forget, so a slow compression writes an older
// timestamp after a newer one was already extracted. Without the count
From b1f8d66784ec0685c5af826d8630ad036eec56af Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 22:07:51 +0800
Subject: [PATCH 12/17] refactor(graph): drop the derived set that always
equalled its source
`extracted` filtered `compressed` down to observations at or below `newest`,
and returned `compressed` on every reachable path. On the fallback branch
`batch` IS `compressed`, so `newest` is its maximum. On the incremental branch
`batch` is the tail above `at` and non-empty, so `newest` is the maximum of the
whole list either way. Verified algebraically and by exhaustive enumeration.
It was scaffolding for a batch cap that does not exist. Without it, a future
cap makes the next turn fingerprint miss and the session falls back to a full
re-extract, which the log added alongside it now makes visible rather than
silent. Nothing is skipped either way, and `newest` reducing over `batch` is
what actually closes that hazard.
The comment claimed both halves of the watermark pair came off the dispatched
batch. Only `newest` did; the fingerprint came off `compressed` through a
filter that excluded nothing. Says what the code does now, and drops two
paragraphs that restated what the tests already execute.
---
src/triggers/events.ts | 24 ++++++++++--------------
1 file changed, 10 insertions(+), 14 deletions(-)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index 3b40cd789a..cd3b55fcc5 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -114,25 +114,21 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
}
}
if (batch.length > 0) {
- // Both halves of the pair come off the batch actually dispatched, so
- // capping the batch (api::graph-build already feeds 25 at a time)
- // cannot advance the watermark past an observation nobody sent.
+ // Off the dispatched batch, so a future cap cannot advance the
+ // watermark past an observation nobody sent.
const newest = batch.reduce(
(max, o) => (o.timestamp > max ? o.timestamp : max),
"",
);
- const extracted = compressed.filter((o) => o.timestamp <= newest);
- // The node and edge SETS are unchanged: extractGraphHeuristics links
- // only within a single observation, and persistGraphDelta dedupes
- // across batches through the name and edge-key indexes. Provenance
- // does change — mergeNode/mergeEdge union the whole batch's obsIds,
+ // Same node and edge sets either way — pinned by
+ // graph-heuristic-extract.test.ts. Provenance narrows, which is the
+ // real change: mergeNode/mergeEdge union the whole batch's obsIds,
// so a whole-session batch stamped every node and edge with every
- // observation id in the session. Narrower is more accurate, and
- // graph retrieval and supersede-staling both read it.
+ // observation id in the session.
//
- // A dispatch that throws skips the watermark write (the catch below
- // logs it) and retries on the next turn. Accepted is not done —
- // completion is unobservable through TriggerAction.Void(), so an
+ // Accepted is not done. A throw skips the watermark write and
+ // retries next turn (pinned by graph-extract-incremental.test.ts),
+ // but completion is unobservable through TriggerAction.Void(), so an
// extract that fails downstream leaves its delta out of the graph
// until POST /agentmemory/graph/build.
await sdk.trigger({
@@ -145,7 +141,7 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
{
type: "set",
path: "graphExtractedDigest",
- value: observationFingerprint(extracted),
+ value: observationFingerprint(compressed),
},
]);
}
From 5bc5f777747e0bd88a92286613439125ce615880 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Thu, 27 Aug 2026 22:08:06 +0800
Subject: [PATCH 13/17] docs(test): point at the rationale instead of keeping a
third copy
The quadratic-heap explanation lived in three files. An earlier commit
replaced the copy in types.ts with a pointer to events.ts and left the one in
this test header untouched.
---
test/graph-extract-incremental.test.ts | 11 ++---------
1 file changed, 2 insertions(+), 9 deletions(-)
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index ac1750d74f..29738ed3fa 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -20,15 +20,8 @@ import { logger } from "../src/logger.js";
const STALE = "graph-extract watermark stale, re-extracting session";
-// /agentmemory/session/end is posted by Claude Code's per-turn Stop hook, so
-// event::session::stopped runs on EVERY agent turn — not once per session.
-// It used to hand mem::graph-extract the session's entire observation list
-// each time, and persistGraphDelta takes the 3-call MERGE path for every node
-// and edge it has already seen, so turn N re-merged turns 1..N-1. Engine
-// invocations were quadratic in turn count, and per #843 nothing written via
-// kv.set is ever evicted from the iii engine, so that was quadratic permanent
-// heap. These tests pin the extract to the observations captured since the
-// last successful extract.
+// These tests pin the extract to the observations captured since the last
+// successful one. Why that matters is in src/triggers/events.ts.
const SID = "ses_1";
From 8901b5f727df073520582410f48c17bd5f6ee95d Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Fri, 30 Oct 2026 12:18:04 +0800
Subject: [PATCH 14/17] test(graph): cover a row titled below the watermark,
pin the in-place upgrade gap
Main writes a titled synthetic row at capture, so the late arrivals the
watermark comment described no longer come from a slow first compression.
They come from a legacy untitled row titled by mem::compression-retry, or
from import/replay landing an older timestamp in a live session. The new
test pins that such a row still reaches the graph.
The second test pins a limitation shared with a timestamp-only marker: a
row rewritten in place by mem::compress keeps its id and timestamp, so it
is not re-extracted.
Co-Authored-By: Claude Opus 5.5
---
src/triggers/events.ts | 11 +++++----
test/graph-extract-incremental.test.ts | 32 ++++++++++++++++++++++++++
2 files changed, 38 insertions(+), 5 deletions(-)
diff --git a/src/triggers/events.ts b/src/triggers/events.ts
index cd3b55fcc5..ddf603a3e6 100644
--- a/src/triggers/events.ts
+++ b/src/triggers/events.ts
@@ -86,11 +86,12 @@ export function registerEventTriggers(sdk: IIIClient, kv: StateKV): void {
// that is quadratic permanent heap. Send only what landed since the
// last extract.
//
- // The digest is what makes the timestamp watermark safe. mem::compress
- // is dispatched fire-and-forget (observe.ts) and stamps the capture
- // time, not the write time, so a slow compression can land an OLDER
- // timestamp after a newer one was already extracted; evict can also
- // remove one at any point. Whenever the already-extracted half no
+ // The digest is what makes the timestamp watermark safe. Rows keep
+ // their capture time, not the write time, so one can become
+ // extractable below the watermark: a legacy untitled row titled late
+ // by mem::compression-retry, or a row restored by
+ // import/replay into a live session. Evict can also remove one at any
+ // point. Whenever the already-extracted half no
// longer fingerprints the same, we re-send the whole session rather
// than skip it. Missing a memory is worse than re-merging one.
const session = await kv
diff --git a/test/graph-extract-incremental.test.ts b/test/graph-extract-incremental.test.ts
index 29738ed3fa..252eec1f23 100644
--- a/test/graph-extract-incremental.test.ts
+++ b/test/graph-extract-incremental.test.ts
@@ -289,4 +289,36 @@ describe("graph-extract watermark never skips an observation", () => {
graphExtractedDigest: expect.any(String),
});
});
+ it("extracts a row that gets its title below the watermark", async () => {
+ // A legacy untitled row (hookType, no title) is skipped until
+ // mem::compression-retry titles it, and the title keeps the capture time.
+ const h = harness();
+ const untitled = { id: "b", sessionId: SID, timestamp: "2026-01-01T00:00:01.000Z", hookType: "post_tool_use" };
+ h.land(untitled as unknown as CompressedObservation, obs("a", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+ h.land(obs("b", "2026-01-01T00:00:01.000Z"));
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["a"], ["b", "a"]]);
+ });
+});
+
+// Pins current behaviour, not desired behaviour. The digest is over ids, and
+// the timestamp marker sees only timestamps, so neither notices a row whose
+// content changed in place.
+describe("graph-extract watermark known limitations", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("does not re-extract a row upgraded in place by compression (known limitation, shared with the timestamp marker)", async () => {
+ // observe.ts writes a titled synthetic row with no concepts; mem::compress
+ // later rewrites it with the same id and timestamp. A stop that ran in
+ // between already extracted the synthetic version.
+ const h = harness();
+ h.land(obs("b", "2026-01-01T00:00:01.000Z"), obs("a", "2026-01-01T00:00:02.000Z"));
+ await h.stop();
+ h.land({ ...obs("b", "2026-01-01T00:00:01.000Z"), concepts: ["auth"] });
+ await h.stop();
+
+ expect(batches(h.trigger)).toEqual([["b", "a"]]);
+ });
});
From 62f593c85395d48ada56668ef41d2a1772608240 Mon Sep 17 00:00:00 2001
From: Omar Gerardo
Date: Fri, 30 Oct 2026 12:18:04 +0800
Subject: [PATCH 15/17] docs: sync the test-count badge
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 4 ++--
README.md | 4 ++--
READMEs/README.ar-SA.md | 4 ++--
READMEs/README.bn-BD.md | 4 ++--
READMEs/README.cs-CZ.md | 4 ++--
READMEs/README.da-DK.md | 4 ++--
READMEs/README.de-DE.md | 4 ++--
READMEs/README.el-GR.md | 4 ++--
READMEs/README.es-ES.md | 4 ++--
READMEs/README.fi-FI.md | 4 ++--
READMEs/README.fr-FR.md | 4 ++--
READMEs/README.he-IL.md | 4 ++--
READMEs/README.hi-IN.md | 4 ++--
READMEs/README.hu-HU.md | 4 ++--
READMEs/README.id-ID.md | 4 ++--
READMEs/README.it-IT.md | 4 ++--
READMEs/README.ja-JP.md | 4 ++--
READMEs/README.ko-KR.md | 4 ++--
READMEs/README.nb-NO.md | 4 ++--
READMEs/README.nl-NL.md | 4 ++--
READMEs/README.pl-PL.md | 4 ++--
READMEs/README.pt-BR.md | 4 ++--
READMEs/README.pt-PT.md | 4 ++--
READMEs/README.ro-RO.md | 4 ++--
READMEs/README.ru-RU.md | 4 ++--
READMEs/README.sv-SE.md | 4 ++--
READMEs/README.th-TH.md | 4 ++--
READMEs/README.tl-PH.md | 4 ++--
READMEs/README.tr-TR.md | 4 ++--
READMEs/README.uk-UA.md | 4 ++--
READMEs/README.ur-PK.md | 4 ++--
READMEs/README.vi-VN.md | 4 ++--
READMEs/README.zh-CN.md | 4 ++--
READMEs/README.zh-TW.md | 4 ++--
assets/tags/light/stat-tests.svg | 4 ++--
assets/tags/stat-tests.svg | 4 ++--
scripts/docs-sync.state.json | 2 +-
37 files changed, 73 insertions(+), 73 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
index 6c88f558e2..c53122c1e1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -101,7 +101,7 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
## Testing
-- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (4,000+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests.
+- Before every commit run, in order: `npm run build`, `npm run skills:gen`, `npm run docs:sync`, `npm run skills:check`, `npm test` (4,100+ tests). Commit anything the generators changed. CI runs the same build, skills check and tests.
- Before any npm publish: `npm run release:gate` must pass. It installs the packed tarballs into a clean home and runs capture, recovery, restart, export/import, MCP and status checks against the installed CLI (see CONTRIBUTING.md, Release process)
- Mock pattern: `vi.mock("iii-sdk")` with mock `sdk.trigger`, `kv.get/set/list`
- Test files go in `test/` with `.test.ts` extension
@@ -114,4 +114,4 @@ Hook scripts in `src/hooks/` are standalone Node.js scripts (no iii-sdk import).
- 6 MCP resources, 3 MCP prompts
- 12 hooks, 17 skills
- 322+ iii functions
-- 4,000+ tests
+- 4,100+ tests
diff --git a/README.md b/README.md
index 0cc41b258a..b371b080e4 100644
--- a/README.md
+++ b/README.md
@@ -69,7 +69,7 @@
-
+
@@ -1307,7 +1307,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.md
index 3199b8a8d7..432c2446ec 100644
--- a/READMEs/README.ar-SA.md
+++ b/READMEs/README.ar-SA.md
@@ -71,7 +71,7 @@
-
+
@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.md
index 8fe8425a88..8a85ba1375 100644
--- a/READMEs/README.bn-BD.md
+++ b/READMEs/README.bn-BD.md
@@ -69,7 +69,7 @@
-
+
@@ -1255,7 +1255,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.md
index d0960e654a..6733e9778b 100644
--- a/READMEs/README.cs-CZ.md
+++ b/READMEs/README.cs-CZ.md
@@ -69,7 +69,7 @@
-
+
@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.md
index 0c124bb1b3..986f11e1c0 100644
--- a/READMEs/README.da-DK.md
+++ b/READMEs/README.da-DK.md
@@ -69,7 +69,7 @@
-
+
@@ -1249,7 +1249,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md
index 25d246df90..7a7aee598b 100644
--- a/READMEs/README.de-DE.md
+++ b/READMEs/README.de-DE.md
@@ -69,7 +69,7 @@
-
+
@@ -1247,7 +1247,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.md
index 9fdaf0a8ed..da436a98c1 100644
--- a/READMEs/README.el-GR.md
+++ b/READMEs/README.el-GR.md
@@ -69,7 +69,7 @@
-
+
@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md
index 9e646f18ae..9a2add4427 100644
--- a/READMEs/README.es-ES.md
+++ b/READMEs/README.es-ES.md
@@ -69,7 +69,7 @@
-
+
@@ -1243,7 +1243,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.md
index 0af45964b9..f0d7093a4f 100644
--- a/READMEs/README.fi-FI.md
+++ b/READMEs/README.fi-FI.md
@@ -69,7 +69,7 @@
-
+
@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md
index 6e8a3510ae..60ed0f017a 100644
--- a/READMEs/README.fr-FR.md
+++ b/READMEs/README.fr-FR.md
@@ -69,7 +69,7 @@
-
+
@@ -1250,7 +1250,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.md
index 6cd626a723..580e9069b0 100644
--- a/READMEs/README.he-IL.md
+++ b/READMEs/README.he-IL.md
@@ -71,7 +71,7 @@
-
+
@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md
index c8fbebef85..04eb563111 100644
--- a/READMEs/README.hi-IN.md
+++ b/READMEs/README.hi-IN.md
@@ -69,7 +69,7 @@
-
+
@@ -1256,7 +1256,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.md
index 864dbdb03c..2951739da5 100644
--- a/READMEs/README.hu-HU.md
+++ b/READMEs/README.hu-HU.md
@@ -69,7 +69,7 @@
-
+
@@ -1239,7 +1239,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.md
index 37ee206858..b9b300ebfc 100644
--- a/READMEs/README.id-ID.md
+++ b/READMEs/README.id-ID.md
@@ -69,7 +69,7 @@
-
+
@@ -1256,7 +1256,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.md
index 8bf8a07fc9..76c4267bd3 100644
--- a/READMEs/README.it-IT.md
+++ b/READMEs/README.it-IT.md
@@ -69,7 +69,7 @@
-
+
@@ -1249,7 +1249,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md
index ce2d9dee07..5f3bd8dd2d 100644
--- a/READMEs/README.ja-JP.md
+++ b/READMEs/README.ja-JP.md
@@ -69,7 +69,7 @@
-
+
@@ -1255,7 +1255,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md
index 9958760be9..75ea0ac701 100644
--- a/READMEs/README.ko-KR.md
+++ b/READMEs/README.ko-KR.md
@@ -69,7 +69,7 @@
-
+
@@ -1254,7 +1254,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.md
index 56ebebc6ba..59f55f0809 100644
--- a/READMEs/README.nb-NO.md
+++ b/READMEs/README.nb-NO.md
@@ -69,7 +69,7 @@
-
+
@@ -1247,7 +1247,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.md
index 569d1fb29c..d5f8c62a3d 100644
--- a/READMEs/README.nl-NL.md
+++ b/READMEs/README.nl-NL.md
@@ -69,7 +69,7 @@
-
+
@@ -1243,7 +1243,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.md
index bdbe4eea32..d20aa558c1 100644
--- a/READMEs/README.pl-PL.md
+++ b/READMEs/README.pl-PL.md
@@ -69,7 +69,7 @@
-
+
@@ -1239,7 +1239,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md
index b076d8d82e..c6c37e69f3 100644
--- a/READMEs/README.pt-BR.md
+++ b/READMEs/README.pt-BR.md
@@ -69,7 +69,7 @@
-
+
@@ -1247,7 +1247,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.md
index 36ff810e19..0b57b1b8db 100644
--- a/READMEs/README.pt-PT.md
+++ b/READMEs/README.pt-PT.md
@@ -69,7 +69,7 @@
-
+
@@ -1243,7 +1243,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.md
index 890afccaef..3e1f4c5870 100644
--- a/READMEs/README.ro-RO.md
+++ b/READMEs/README.ro-RO.md
@@ -69,7 +69,7 @@
-
+
@@ -1235,7 +1235,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md
index af94d55bbb..3ea4e5de29 100644
--- a/READMEs/README.ru-RU.md
+++ b/READMEs/README.ru-RU.md
@@ -69,7 +69,7 @@
-
+
@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.md
index a130b39bd2..3c3e72e866 100644
--- a/READMEs/README.sv-SE.md
+++ b/READMEs/README.sv-SE.md
@@ -69,7 +69,7 @@
-
+
@@ -1249,7 +1249,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.md
index b549a34e6a..76671822b6 100644
--- a/READMEs/README.th-TH.md
+++ b/READMEs/README.th-TH.md
@@ -69,7 +69,7 @@
-
+
@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.md
index 2d4dcfe47d..ff68ebdba6 100644
--- a/READMEs/README.tl-PH.md
+++ b/READMEs/README.tl-PH.md
@@ -69,7 +69,7 @@
-
+
@@ -1251,7 +1251,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md
index 0b08152ae9..a5d36b5299 100644
--- a/READMEs/README.tr-TR.md
+++ b/READMEs/README.tr-TR.md
@@ -69,7 +69,7 @@
-
+
@@ -1241,7 +1241,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.md
index ad26bff5c1..4033a79f17 100644
--- a/READMEs/README.uk-UA.md
+++ b/READMEs/README.uk-UA.md
@@ -69,7 +69,7 @@
-
+
@@ -1242,7 +1242,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.md
index 62602b9130..53f941522e 100644
--- a/READMEs/README.ur-PK.md
+++ b/READMEs/README.ur-PK.md
@@ -71,7 +71,7 @@
-
+
@@ -1246,7 +1246,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.md
index 3a7879a3f5..2be083144f 100644
--- a/READMEs/README.vi-VN.md
+++ b/READMEs/README.vi-VN.md
@@ -69,7 +69,7 @@
-
+
@@ -1251,7 +1251,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md
index b12e7fe2fd..a96226f914 100644
--- a/READMEs/README.zh-CN.md
+++ b/READMEs/README.zh-CN.md
@@ -69,7 +69,7 @@
-
+
@@ -1252,7 +1252,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md
index bfd866fee0..5ed8dc3dce 100644
--- a/READMEs/README.zh-TW.md
+++ b/READMEs/README.zh-TW.md
@@ -69,7 +69,7 @@
-
+
@@ -1244,7 +1244,7 @@ curl -X POST http://localhost:3111/agentmemory/graph/compact -H "Authorization:
```bash
npm run dev # Hot reload
npm run build # Production build
-npm test # 4,000+ tests
+npm test # 4,100+ tests
npm run test:integration # API tests (requires running services)
```
diff --git a/assets/tags/light/stat-tests.svg b/assets/tags/light/stat-tests.svg
index 915e1bab9d..7248bfad00 100644
--- a/assets/tags/light/stat-tests.svg
+++ b/assets/tags/light/stat-tests.svg
@@ -1,5 +1,5 @@
-