Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(multi): stability pass for #627 #640 #474 #638 #431 #544 #563 (#648)

Rohit Ghumaref027c20309cc
diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts
index 718100f4..cc7a44d8 100644
--- a/plugin/opencode/agentmemory-capture.ts
+++ b/plugin/opencode/agentmemory-capture.ts
@@ -64,6 +64,12 @@ const stashedFiles = new Map<string, Set<string>>();
const seenSubtaskIds = new Map<string, Set<string>>();
const seenToolCallIds = new Map<string, Set<string>>();
const contextInjectedSessions = new Set<string>();
+// #431: cache the context returned by POST /session/start so the chat
+// system-transform hook can inject it without a second /context fetch.
+// Auto-injection now happens at session.created (immediately) AND at
+// the first prompt_submit (fallback for older OpenCode builds that
+// don't implement experimental.chat.system.transform).
+const startContextCache = new Map<string, string>();
function stashFor(sid: string): Set<string> {
let s = stashedFiles.get(sid);
@@ -178,16 +184,26 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {
seenSubtaskIds.delete(activeSessionId);
seenToolCallIds.delete(activeSessionId);
contextInjectedSessions.delete(activeSessionId);
- await post("/session/start", {
- sessionId: activeSessionId,
+ // Snapshot the session id locally — `activeSessionId` is mutable
+ // and another `session.created` event during the await could
+ // rebind it, causing context to be cached against the wrong key.
+ const sessionId = activeSessionId;
+ const startResult = await postJson("/session/start", {
+ sessionId,
title: info?.title ?? null,
parentID: info?.parentID ?? null,
version: info?.version ?? null,
project: projectPath,
cwd: projectPath,
});
- if (pendingConfig && activeSessionId) {
- await observe(activeSessionId, "config_loaded", pendingConfig);
+ // #431: cache the context returned at session/start so the
+ // chat.system.transform hook injects it without a second fetch.
+ const startCtx = (startResult as any)?.context;
+ if (typeof startCtx === "string" && startCtx.length > 0) {
+ startContextCache.set(sessionId, startCtx);
+ }
+ if (pendingConfig) {
+ await observe(sessionId, "config_loaded", pendingConfig);
pendingConfig = null;
}
}
@@ -257,6 +273,7 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {
post("/consolidate-pipeline", { tier: "all", force: true }, 30000);
if (sid === activeSessionId) activeSessionId = null;
stashedFiles.delete(sid);
+ startContextCache.delete(sid);
seenSubtaskIds.delete(sid);
seenToolCallIds.delete(sid);
contextInjectedSessions.delete(sid);
@@ -588,11 +605,19 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {
if (!contextInjectedSessions.has(sid)) {
if (!Array.isArray(output.system)) return;
output.system.push(AGENTMEMORY_INSTRUCTIONS);
- const result = await postJson("/context", {
- sessionId: sid,
- project: projectPath,
- });
- const ctx = (result as any)?.context;
+ // #431: prefer the context already fetched at session.created;
+ // fall back to a fresh /context call if the cache missed (e.g.
+ // session resumed across plugin reloads).
+ let ctx = startContextCache.get(sid);
+ if (typeof ctx !== "string" || ctx.length === 0) {
+ const result = await postJson("/context", {
+ sessionId: sid,
+ project: projectPath,
+ });
+ ctx = (result as any)?.context;
+ } else {
+ startContextCache.delete(sid);
+ }
if (typeof ctx === "string" && ctx.length > 0) {
output.system.push(ctx);
}
diff --git a/src/cli.ts b/src/cli.ts
index e1ea9757..04462379 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -411,6 +411,33 @@ function clearEnginePidfile(): void {
} catch {}
}
+// Worker pidfile (#640, #474): the agentmemory worker process
+// (`node dist/index.mjs`) is spawned by iii-exec inside the engine. When
+// `agentmemory stop` kills only the engine pid, the worker can survive
+// (detached spawn, signal not propagated, or kept alive by a wrapper
+// script). On the next start, the orphaned worker reconnects to the new
+// engine and shows up as a duplicate registration. We write the worker
+// pid from src/index.ts on boot so stop can find and reap it.
+function workerPidfilePath(): string {
+ return join(homedir(), ".agentmemory", "worker.pid");
+}
+
+function readWorkerPidfile(): number | null {
+ try {
+ const pidStr = readFileSync(workerPidfilePath(), "utf-8").trim();
+ const pid = parseInt(pidStr, 10);
+ return Number.isFinite(pid) && pid > 0 ? pid : null;
+ } catch {
+ return null;
+ }
+}
+
+function clearWorkerPidfile(): void {
+ try {
+ unlinkSync(workerPidfilePath());
+ } catch {}
+}
+
function writeEngineState(state: EngineState): void {
try {
const statePath = engineStatePath();
@@ -2151,6 +2178,7 @@ async function stopDockerEngine(composeFile: string, port: number): Promise<void
});
clearEnginePidfile();
clearEngineState();
+ clearWorkerPidfile();
if (!ok) {
p.log.error(
`docker compose down failed. The engine may still be running on :${port}. Inspect with:\n docker compose -f ${composeFile} ps`,
@@ -2172,6 +2200,7 @@ async function runStop(): Promise<void> {
p.log.info(`No engine responding on port ${port}.`);
clearEnginePidfile();
clearEngineState();
+ clearWorkerPidfile();
p.outro("Nothing to stop.");
return;
}
@@ -2181,21 +2210,44 @@ async function runStop(): Promise<void> {
const portPids = findEnginePidsByPort(port);
const pidfilePid = readEnginePidfile();
+ // #640 + #474: read the worker pid up front so the engine-down branch
+ // can still reap an orphaned worker process (the common failure mode
+ // where a wrapper script kept the worker alive across engine restarts).
+ const workerPid = readWorkerPidfile();
if (!running) {
- if (portPids.length === 0 && pidfilePid === null) {
+ if (portPids.length === 0 && pidfilePid === null && workerPid === null) {
clearEnginePidfile();
clearEngineState();
+ clearWorkerPidfile();
p.outro("Nothing to stop.");
return;
}
+ if (workerPid !== null && portPids.length === 0 && pidfilePid === null) {
+ // Engine already gone but worker is lingering — reap it directly
+ // instead of preserving for manual cleanup.
+ const s = p.spinner();
+ s.start(`Stopping orphaned agentmemory worker (pid ${workerPid})...`);
+ const ok = await signalAndWait(workerPid, "SIGTERM", 3000);
+ s.stop(ok ? `Stopped worker pid ${workerPid}` : `Failed to stop worker pid ${workerPid}`);
+ clearEnginePidfile();
+ clearEngineState();
+ clearWorkerPidfile();
+ if (!ok) {
+ p.log.error(`Worker pid ${workerPid} survived SIGKILL. Investigate with \`ps\`.`);
+ process.exit(1);
+ }
+ p.outro("Stopped orphaned worker. Memories persisted to disk.");
+ return;
+ }
const survivors = new Set<number>(portPids);
if (pidfilePid) survivors.add(pidfilePid);
+ if (workerPid) survivors.add(workerPid);
p.log.warn(
`Engine not responding on :${port}, but ${survivors.size} process(es) still hold the port or pidfile: ${[...survivors].join(", ")}`,
);
p.log.info(
- `Preserving ~/.agentmemory/iii.pid. Investigate before manual cleanup:\n ps -p ${[...survivors].join(",")} -o pid,ppid,comm,etime\n ${IS_WINDOWS ? "netstat -ano | findstr :" + port : "lsof -i :" + port}`,
+ `Preserving ~/.agentmemory/iii.pid + worker.pid. Investigate before manual cleanup:\n ps -p ${[...survivors].join(",")} -o pid,ppid,comm,etime\n ${IS_WINDOWS ? "netstat -ano | findstr :" + port : "lsof -i :" + port}`,
);
process.exit(1);
}
@@ -2220,7 +2272,15 @@ async function runStop(): Promise<void> {
if (pidfilePid) candidates.add(pidfilePid);
for (const pid of portPids) candidates.add(pid);
- if (candidates.size === 0) {
+ // #640 + #474: stop must also reap the agentmemory worker process
+ // (`node dist/index.mjs`). If only the engine is killed, the worker can
+ // survive (detached spawn / signal not propagated) and reconnect to the
+ // next engine as a duplicate registration. workerPid was read above so
+ // the engine-down branch could also reap orphans.
+ const workerCandidates = new Set<number>();
+ if (workerPid) workerCandidates.add(workerPid);
+
+ if (candidates.size === 0 && workerCandidates.size === 0) {
p.log.error(
`Could not locate engine process. Try:\n ${IS_WINDOWS ? "netstat -ano | findstr :" + port : "lsof -i :" + port + " -t | xargs kill -9"}`,
);
@@ -2235,11 +2295,20 @@ async function runStop(): Promise<void> {
s.stop(ok ? `Stopped pid ${pid}` : `Failed to stop pid ${pid}`);
if (!ok) allStopped = false;
}
+ for (const pid of workerCandidates) {
+ if (candidates.has(pid)) continue;
+ const s = p.spinner();
+ s.start(`Stopping agentmemory worker (pid ${pid})...`);
+ const ok = await signalAndWait(pid, "SIGTERM", 3000);
+ s.stop(ok ? `Stopped worker pid ${pid}` : `Failed to stop worker pid ${pid}`);
+ if (!ok) allStopped = false;
+ }
clearEnginePidfile();
clearEngineState();
+ clearWorkerPidfile();
if (!allStopped) {
- p.log.error("One or more engine processes survived SIGKILL. Investigate with `ps`.");
+ p.log.error("One or more processes survived SIGKILL. Investigate with `ps`.");
process.exit(1);
}
p.outro("Stopped. Memories persisted to disk; restart anytime with: npx @agentmemory/agentmemory");
diff --git a/src/functions/observe.ts b/src/functions/observe.ts
index 57e2f7df..6994bdc5 100644
--- a/src/functions/observe.ts
+++ b/src/functions/observe.ts
@@ -214,6 +214,37 @@ export function registerObserveFunction(
}
}
await kv.update(KV.sessions, payload.sessionId, updates);
+ } else if (
+ typeof payload.project === "string" &&
+ payload.project.trim().length > 0 &&
+ typeof payload.cwd === "string" &&
+ payload.cwd.trim().length > 0
+ ) {
+ // #638: OpenCode (and any plugin that skips POST /session/start)
+ // can fire observations before the session record exists. Without
+ // an implicit create, those observations stack up but
+ // `memory_sessions` never lists them, and summarize bails with
+ // "Session not found for summarize". Create the session now from
+ // the observation payload — but only when project + cwd are
+ // present (HookPayload contract). Older test payloads without
+ // those fields keep their original no-op behaviour.
+ const trimmedPrompt =
+ typeof raw.userPrompt === "string"
+ ? raw.userPrompt.replace(/\s+/g, " ").trim().slice(0, 200)
+ : undefined;
+ const ts = new Date().toISOString();
+ await kv.set(KV.sessions, payload.sessionId, {
+ id: payload.sessionId,
+ project: payload.project,
+ cwd: payload.cwd,
+ startedAt: payload.timestamp ?? ts,
+ updatedAt: ts,
+ status: "active",
+ observationCount: 1,
+ ...(trimmedPrompt && trimmedPrompt.length > 0
+ ? { firstPrompt: trimmedPrompt }
+ : {}),
+ });
}
// Per-observation LLM compression is opt-in as of 0.8.8 (#138).
diff --git a/src/index.ts b/src/index.ts
index d02b3dc7..3428139f 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -98,6 +98,33 @@ import { registerHealthMonitor } from "./health/monitor.js";
import { initMetrics, OTEL_CONFIG } from "./telemetry/setup.js";
import { VERSION } from "./version.js";
import { bootLog } from "./logger.js";
+import { mkdirSync, writeFileSync, unlinkSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { homedir } from "node:os";
+
+// #640 + #474: the worker process (this file) is spawned by iii-exec
+// inside the engine. When `agentmemory stop` kills only the engine pid,
+// this worker can survive (detached spawn, signal not propagated, or a
+// wrapper script keeps it running) and reconnects to the next engine as
+// a duplicate worker. Write the worker pid alongside iii.pid so
+// `agentmemory stop` can reap us too.
+function workerPidfilePath(): string {
+ return join(homedir(), ".agentmemory", "worker.pid");
+}
+function writeWorkerPidfile(): void {
+ try {
+ const p = workerPidfilePath();
+ mkdirSync(dirname(p), { recursive: true });
+ writeFileSync(p, `${process.pid}\n`, { encoding: "utf-8" });
+ } catch {
+ // best-effort; stop still has the engine pidfile + port scan fallback
+ }
+}
+function clearWorkerPidfile(): void {
+ try {
+ unlinkSync(workerPidfilePath());
+ } catch {}
+}
function hasGetMeter(
sdk: unknown,
@@ -186,6 +213,8 @@ async function main() {
},
});
+ writeWorkerPidfile();
+
const kv = new StateKV(sdk);
const secret = getEnvVar("AGENTMEMORY_SECRET");
const metricsStore = new MetricsStore(kv);
@@ -554,6 +583,7 @@ async function main() {
console.warn(`[agentmemory] Failed to save index on shutdown:`, err);
});
await sdk.shutdown();
+ clearWorkerPidfile();
process.exit(0);
};
process.on("SIGINT", shutdown);
diff --git a/src/providers/openai.ts b/src/providers/openai.ts
index 88e10829..438b2f4e 100644
--- a/src/providers/openai.ts
+++ b/src/providers/openai.ts
@@ -129,15 +129,19 @@ export class OpenAIProvider implements MemoryProvider {
}
const data = (await response.json()) as {
- choices?: Array<{ message?: { content?: string; reasoning?: string } }>;
+ choices?: Array<{
+ message?: { content?: string; reasoning?: string; reasoning_content?: string };
+ }>;
};
const message = data.choices?.[0]?.message;
const content = message?.content;
if (content) {
return content;
}
- // Fallback: some thinking models return reasoning but no content
- const reasoning = message?.reasoning;
+ // Fallback: some thinking models return reasoning but no content.
+ // DeepSeek V4 / Qwen3 / GLM / Kimi return `reasoning_content`;
+ // older OpenAI o-series + some compatibles return `reasoning`. #627
+ const reasoning = message?.reasoning ?? message?.reasoning_content;
if (reasoning) {
return reasoning;
}
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 66eaadc2..57c28a86 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -1039,11 +1039,30 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/profile", http_method: "GET" },
});
- sdk.registerFunction("api::export",
+ sdk.registerFunction("api::export",
async (req: ApiRequest): Promise<Response> => {
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
- const result = await sdk.trigger({ function_id: "mem::export", payload: {} });
+ // #544: mem::export already supports maxSessions/offset internally,
+ // but the HTTP endpoint hardcoded an empty payload — so /export on a
+ // real corpus (40 sessions × 34K observations × 8K memories) hit the
+ // iii engine invocation timeout and `agentmemory status` reported 0.
+ // Pass through the query-string pagination so callers can chunk.
+ const rawMax = req.query_params?.["maxSessions"];
+ const rawOffset = req.query_params?.["offset"];
+ const payload: { maxSessions?: number; offset?: number } = {};
+ if (typeof rawMax === "string") {
+ const n = Number(rawMax);
+ if (Number.isInteger(n) && n > 0) payload.maxSessions = n;
+ }
+ if (typeof rawOffset === "string") {
+ const n = Number(rawOffset);
+ if (Number.isInteger(n) && n >= 0) payload.offset = n;
+ }
+ const result = await sdk.trigger({
+ function_id: "mem::export",
+ payload,
+ });
return { status_code: 200, body: result };
},
);
@@ -1473,7 +1492,48 @@ export function registerApiTriggers(
const memories = await kv.list<import("../types.js").Memory>(KV.memories);
const latest = req.query_params?.["latest"] === "true";
const filtered = latest ? memories.filter((m) => m.isLatest) : memories;
- return { status_code: 200, body: { memories: filtered } };
+
+ // #544: viewer + `agentmemory status` were hitting this endpoint to
+ // count memories. On a real corpus (8K+ memories) the unbounded
+ // response either timed out at the iii engine boundary ("Invocation
+ // stopped") or arrived too large for the viewer to render — so the
+ // UI showed 0 memories despite a healthy store. Two opt-in modes:
+ // ?count=true — totals only, no payload
+ // ?limit=N&offset=M — page slice (default unlimited for back-compat)
+ if (req.query_params?.["count"] === "true") {
+ return {
+ status_code: 200,
+ body: {
+ total: memories.length,
+ latestCount: memories.filter((m) => m.isLatest).length,
+ },
+ };
+ }
+
+ const rawLimit = req.query_params?.["limit"];
+ const rawOffset = req.query_params?.["offset"];
+ const parsedLimit =
+ typeof rawLimit === "string" ? Number(rawLimit) : Number.NaN;
+ const parsedOffset =
+ typeof rawOffset === "string" ? Number(rawOffset) : Number.NaN;
+ const limit =
+ Number.isInteger(parsedLimit) && parsedLimit > 0
+ ? Math.min(parsedLimit, 5000)
+ : undefined;
+ const offset =
+ Number.isInteger(parsedOffset) && parsedOffset >= 0 ? parsedOffset : 0;
+ const sliced =
+ limit !== undefined ? filtered.slice(offset, offset + limit) : filtered;
+
+ return {
+ status_code: 200,
+ body: {
+ memories: sliced,
+ total: filtered.length,
+ offset,
+ limit: limit ?? null,
+ },
+ };
},
);
sdk.registerTrigger({
diff --git a/src/viewer/index.html b/src/viewer/index.html
index a4a3561c..ecb779e8 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -1267,7 +1267,7 @@
var results = await Promise.all([
apiGet('health'),
apiGet('sessions'),
- apiGet('memories?latest=true'),
+ apiGet('memories?latest=true&limit=500'),
apiGet('graph/stats'),
apiGet('audit?limit=5'),
apiGet('semantic'),
@@ -1581,7 +1581,13 @@
}, 30000);
}
- var graphSim = { nodes: [], edges: [], running: false, canvas: null, ctx: null, raf: null, panX: 0, panY: 0, zoom: 1, dragNode: null, mouseX: 0, mouseY: 0 };
+ var graphSim = { nodes: [], edges: [], running: false, canvas: null, ctx: null, raf: null, panX: 0, panY: 0, zoom: 1, dragNode: null, mouseX: 0, mouseY: 0, tickCount: 0, quietTicks: 0 };
+ function wakeGraphSim() {
+ graphSim.quietTicks = 0;
+ if (graphSim.running && !graphSim.raf) {
+ graphSim.raf = requestAnimationFrame(runSimulation);
+ }
+ }
async function loadGraph() {
var el = document.getElementById('view-graph');
@@ -1760,6 +1766,8 @@
}
lastMX = e.clientX;
lastMY = e.clientY;
+ // #563: wake the simulation if it parked itself after settling
+ wakeGraphSim();
});
canvas.addEventListener('mousemove', function(e) {
var dx = e.clientX - lastMX;
@@ -1816,6 +1824,9 @@
e.preventDefault();
var factor = e.deltaY > 0 ? 0.9 : 1.1;
graphSim.zoom = Math.max(0.1, Math.min(5, graphSim.zoom * factor));
+ // #563: zoom is visually meaningless if the rAF loop is parked —
+ // wake the simulation so the next frame redraws at the new scale.
+ wakeGraphSim();
}, { passive: false });
canvas.addEventListener('dblclick', function(e) {
var c = canvasCoords(e);
@@ -1830,6 +1841,7 @@
window.zoomGraph = function(dir) {
var factor = dir > 0 ? 1.25 : 0.8;
graphSim.zoom = Math.max(0.1, Math.min(5, graphSim.zoom * factor));
+ wakeGraphSim();
};
window.recenterGraph = function() {
graphSim.zoom = 1;
@@ -1839,6 +1851,7 @@
graphSim.panX = cw / 2;
graphSim.panY = ch / 2;
}
+ wakeGraphSim();
};
function selectGraphNode(simNode) {
@@ -1900,10 +1913,19 @@
var nodes = graphSim.nodes;
var edges = graphSim.edges;
var nodeCount = nodes.length;
- var damping = 0.9;
- var repulsion = nodeCount > 100 ? 2000 : nodeCount > 50 ? 1200 : 800;
+ graphSim.tickCount = (graphSim.tickCount || 0) + 1;
+ // #563: dense graphs (>1000 nodes) used to oscillate forever
+ // because the per-node force pile-up exceeded what 0.9 damping
+ // could bleed off each tick. Tick-decay tightens damping over
+ // time so the layout actually settles; a per-node velocity cap
+ // prevents any single node from being launched off-screen by an
+ // accumulated kick before damping catches up.
+ var coolBoost = Math.min(0.4, graphSim.tickCount / 1500);
+ var damping = 0.9 - coolBoost;
+ var repulsion = nodeCount > 1000 ? 3000 : nodeCount > 100 ? 2000 : nodeCount > 50 ? 1200 : 800;
var attraction = nodeCount > 100 ? 0.002 : 0.005;
- var centerGravity = nodeCount > 100 ? 0.005 : 0.01;
+ var centerGravity = nodeCount > 1000 ? 0.012 : nodeCount > 100 ? 0.005 : 0.01;
+ var velocityCap = nodeCount > 1000 ? 6 : nodeCount > 200 ? 12 : 24;
var nodeMap = {};
nodes.forEach(function(n) { nodeMap[n.id] = n; });
@@ -1923,8 +1945,14 @@
}
fx -= n.x * centerGravity;
fy -= n.y * centerGravity;
- n.vx = (n.vx + fx) * damping;
- n.vy = (n.vy + fy) * damping;
+ var nvx = (n.vx + fx) * damping;
+ var nvy = (n.vy + fy) * damping;
+ // Velocity cap (#563): keep any single node from being launched
+ // off-screen by a one-tick force spike.
+ if (nvx > velocityCap) nvx = velocityCap; else if (nvx < -velocityCap) nvx = -velocityCap;
+ if (nvy > velocityCap) nvy = velocityCap; else if (nvy < -velocityCap) nvy = -velocityCap;
+ n.vx = nvx;
+ n.vy = nvy;
}
edges.forEach(function(e) {
@@ -1941,13 +1969,28 @@
if (graphSim.dragNode !== t) { t.vx -= fx; t.vy -= fy; }
});
+ var totalKineticEnergy = 0;
nodes.forEach(function(n) {
if (graphSim.dragNode === n) return;
n.x += n.vx;
n.y += n.vy;
+ totalKineticEnergy += n.vx * n.vx + n.vy * n.vy;
});
+ // #563: park the simulation when the layout is quiet to save CPU.
+ // Pick up again when a drag/interaction wakes the loop.
+ var rmsVelocity = nodes.length > 0 ? Math.sqrt(totalKineticEnergy / nodes.length) : 0;
+ if (rmsVelocity < 0.05 && graphSim.tickCount > 60 && !graphSim.dragNode) {
+ graphSim.quietTicks = (graphSim.quietTicks || 0) + 1;
+ } else {
+ graphSim.quietTicks = 0;
+ }
+
renderGraph();
+ if (graphSim.quietTicks > 30) {
+ graphSim.raf = null;
+ return;
+ }
graphSim.raf = requestAnimationFrame(runSimulation);
}
@@ -2218,8 +2261,12 @@
async function loadMemories() {
var el = document.getElementById('view-memories');
el.innerHTML = '<div class="loading">Loading memories...</div>';
- var result = await apiGet('memories?latest=true');
+ // #544: cap at 2000 so the viewer remains responsive on large
+ // corpora. Older endpoints returned the full unbounded list which
+ // hit the iii invocation timeout and the UI fell through to 0.
+ var result = await apiGet('memories?latest=true&limit=2000');
state.memories.items = (result && result.memories) || [];
+ state.memories.total = (result && typeof result.total === 'number') ? result.total : state.memories.items.length;
state.memories.loaded = true;
renderMemories();
}
diff --git a/test/fetch-timeout.test.ts b/test/fetch-timeout.test.ts
index 58cd2111..5b2cd7c9 100644
--- a/test/fetch-timeout.test.ts
+++ b/test/fetch-timeout.test.ts
@@ -276,3 +276,71 @@ describe("OpenAIProvider timeout env precedence (#446)", () => {
});
});
+// ─────────────────────────────────────────────────────────────
+// #627 — OpenAI provider must read message.reasoning_content
+// DeepSeek V4 / Qwen3 / GLM / Kimi return reasoning_content (with
+// underscore); only checking `reasoning` left thinking-model output
+// dropped on the floor and tripped the compress circuit breaker.
+// ─────────────────────────────────────────────────────────────
+describe("OpenAIProvider thinking-model fallback (#627)", () => {
+ beforeEach(() => {
+ delete process.env["OPENAI_TIMEOUT_MS"];
+ delete process.env["AGENTMEMORY_LLM_TIMEOUT_MS"];
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ function mockOpenAIResponse(body: object): void {
+ vi.spyOn(globalThis, "fetch").mockImplementation(
+ (async () =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ })) as typeof fetch,
+ );
+ }
+
+ it("returns reasoning_content when content is empty (DeepSeek V4 / Qwen3 shape)", async () => {
+ mockOpenAIResponse({
+ choices: [
+ {
+ message: {
+ content: "",
+ reasoning_content: "thinking-mode output",
+ },
+ },
+ ],
+ });
+ const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);
+ const out = await provider.compress("system", "user");
+ expect(out).toBe("thinking-mode output");
+ });
+
+ it("still returns reasoning (no underscore) for older o-series shape", async () => {
+ mockOpenAIResponse({
+ choices: [{ message: { content: "", reasoning: "older shape" } }],
+ });
+ const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);
+ const out = await provider.compress("system", "user");
+ expect(out).toBe("older shape");
+ });
+
+ it("content wins over both reasoning fields when present", async () => {
+ mockOpenAIResponse({
+ choices: [
+ {
+ message: {
+ content: "real content",
+ reasoning: "ignore",
+ reasoning_content: "also ignore",
+ },
+ },
+ ],
+ });
+ const provider = new OpenAIProvider("test-key", "gpt-4o-mini", 1024);
+ const out = await provider.compress("system", "user");
+ expect(out).toBe("real content");
+ });
+});
+
diff --git a/test/memories-pagination.test.ts b/test/memories-pagination.test.ts
new file mode 100644
index 00000000..cd7eb3e7
--- /dev/null
+++ b/test/memories-pagination.test.ts
@@ -0,0 +1,42 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "node:fs";
+
+// #544: /memories and /export must support count + pagination so the
+// viewer and `agentmemory status` work on large corpora (8K+ memories)
+// without timing out at the iii engine boundary.
+describe("memories + export pagination (#544)", () => {
+ const api = readFileSync("src/triggers/api.ts", "utf-8");
+
+ it("api::memories accepts count=true and returns total + latestCount", () => {
+ expect(api).toMatch(/req\.query_params\?\.\["count"\]\s*===\s*"true"/);
+ expect(api).toMatch(/total:\s*memories\.length/);
+ expect(api).toMatch(/latestCount:\s*memories\.filter/);
+ });
+
+ it("api::memories accepts limit + offset query params", () => {
+ expect(api).toMatch(/query_params\?\.\["limit"\]/);
+ expect(api).toMatch(/query_params\?\.\["offset"\]/);
+ expect(api).toMatch(/filtered\.slice\(offset/);
+ expect(api).toMatch(/total:\s*filtered\.length/);
+ });
+
+ it("api::memories caps limit at 5000 to bound response size", () => {
+ expect(api).toMatch(/Math\.min\(parsedLimit,\s*5000\)/);
+ });
+
+ it("api::export passes through maxSessions + offset query params", () => {
+ expect(api).toMatch(/query_params\?\.\["maxSessions"\]/);
+ expect(api).toMatch(/query_params\?\.\["offset"\]/);
+ // The payload object is named `payload` in our handler; assert it is
+ // forwarded to mem::export rather than the previous empty object.
+ expect(api).toMatch(
+ /sdk\.trigger\(\{\s*function_id:\s*"mem::export",\s*payload,/m,
+ );
+ });
+
+ it("viewer dashboard caps memories?latest fetch with limit", () => {
+ const viewer = readFileSync("src/viewer/index.html", "utf-8");
+ expect(viewer).toMatch(/memories\?latest=true&limit=500/);
+ expect(viewer).toMatch(/memories\?latest=true&limit=2000/);
+ });
+});
diff --git a/test/observe-implicit-session.test.ts b/test/observe-implicit-session.test.ts
new file mode 100644
index 00000000..b0272bc7
--- /dev/null
+++ b/test/observe-implicit-session.test.ts
@@ -0,0 +1,144 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+vi.mock("../src/logger.js", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+function mockKV() {
+ const store = new Map<string, Map<string, unknown>>();
+ return {
+ store,
+ get: async <T>(scope: string, key: string): Promise<T | null> =>
+ (store.get(scope)?.get(key) as T) ?? null,
+ set: async <T>(scope: string, key: string, data: T): Promise<T> => {
+ if (!store.has(scope)) store.set(scope, new Map());
+ store.get(scope)!.set(key, data);
+ return data;
+ },
+ update: async (scope: string, key: string, updates: Array<{ path: string; value: unknown }>) => {
+ const m = store.get(scope);
+ if (!m) return;
+ const v = (m.get(key) as Record<string, unknown>) ?? {};
+ for (const u of updates) v[u.path] = u.value;
+ m.set(key, v);
+ },
+ delete: async (scope: string, key: string) => {
+ store.get(scope)?.delete(key);
+ },
+ list: async <T>(scope: string): Promise<T[]> => {
+ const m = store.get(scope);
+ return m ? (Array.from(m.values()) as T[]) : [];
+ },
+ };
+}
+
+function mockSdk() {
+ const fns = new Map<string, Function>();
+ return {
+ fns,
+ registerFunction: (
+ idOrOpts: string | { id: string },
+ fn: Function,
+ ) => {
+ const id = typeof idOrOpts === "string" ? idOrOpts : idOrOpts.id;
+ fns.set(id, fn);
+ },
+ trigger: async (
+ idOrInput: string | { function_id: string; payload: unknown; action?: unknown },
+ data?: unknown,
+ ) => {
+ const id = typeof idOrInput === "string" ? idOrInput : idOrInput.function_id;
+ const payload = typeof idOrInput === "string" ? data : idOrInput.payload;
+ const fn = fns.get(id);
+ if (fn) return fn(payload);
+ return null;
+ },
+ };
+}
+
+describe("observe implicit session create (#638)", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ it("creates the session on first observe when project+cwd present and session record missing", async () => {
+ const { registerObserveFunction } = await import("../src/functions/observe.js");
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ const result = (await sdk.trigger("mem::observe", {
+ sessionId: "ses_opencode_abc",
+ project: "/home/user/myrepo",
+ cwd: "/home/user/myrepo",
+ hookType: "prompt_submit",
+ timestamp: new Date().toISOString(),
+ data: { prompt: "ship the helm chart" },
+ })) as { observationId: string };
+
+ expect(result.observationId).toBeTruthy();
+
+ const sessionScope = kv.store.get("mem:sessions");
+ expect(sessionScope).toBeTruthy();
+ const session = sessionScope!.get("ses_opencode_abc") as Record<string, unknown>;
+ expect(session).toBeTruthy();
+ expect(session.id).toBe("ses_opencode_abc");
+ expect(session.project).toBe("/home/user/myrepo");
+ expect(session.cwd).toBe("/home/user/myrepo");
+ expect(session.status).toBe("active");
+ expect(session.observationCount).toBe(1);
+ expect(session.firstPrompt).toBe("ship the helm chart");
+ });
+
+ it("does not implicit-create when project+cwd missing (test-payload back-compat)", async () => {
+ const { registerObserveFunction } = await import("../src/functions/observe.js");
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ await sdk.trigger("mem::observe", {
+ sessionId: "ses_no_project",
+ hookType: "post_tool_use",
+ timestamp: new Date().toISOString(),
+ data: { tool_name: "Read", tool_input: { file_path: "x.ts" } },
+ });
+
+ const sessionScope = kv.store.get("mem:sessions");
+ // Either no scope at all, or no entry for this session
+ expect(sessionScope?.get("ses_no_project")).toBeUndefined();
+ });
+
+ it("does not overwrite an existing session when one already exists", async () => {
+ const { registerObserveFunction } = await import("../src/functions/observe.js");
+ const sdk = mockSdk();
+ const kv = mockKV();
+ registerObserveFunction(sdk as never, kv as never);
+
+ await kv.set("mem:sessions", "ses_existing", {
+ id: "ses_existing",
+ project: "/orig/project",
+ cwd: "/orig/cwd",
+ startedAt: "2026-01-01T00:00:00Z",
+ status: "active",
+ observationCount: 7,
+ firstPrompt: "original first prompt",
+ });
+
+ await sdk.trigger("mem::observe", {
+ sessionId: "ses_existing",
+ project: "/different/project",
+ cwd: "/different/cwd",
+ hookType: "post_tool_use",
+ timestamp: new Date().toISOString(),
+ data: { tool_name: "Read" },
+ });
+
+ const session = kv.store.get("mem:sessions")!.get("ses_existing") as Record<string, unknown>;
+ // Original project + firstPrompt preserved
+ expect(session.project).toBe("/orig/project");
+ expect(session.firstPrompt).toBe("original first prompt");
+ // Counter bumped, updatedAt refreshed
+ expect(session.observationCount).toBe(8);
+ expect(session.updatedAt).toBeTruthy();
+ });
+});
diff --git a/test/opencode-auto-context.test.ts b/test/opencode-auto-context.test.ts
new file mode 100644
index 00000000..c00593cb
--- /dev/null
+++ b/test/opencode-auto-context.test.ts
@@ -0,0 +1,37 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "node:fs";
+
+// #431: OpenCode plugin needs zero-config memory injection. Plugin
+// already wires experimental.chat.system.transform; this PR threads
+// the /session/start context through a cache so injection happens
+// without a second /context fetch and is documented as the
+// SessionStart-equivalent behaviour.
+describe("OpenCode plugin auto-context injection (#431)", () => {
+ const plugin = readFileSync(
+ "plugin/opencode/agentmemory-capture.ts",
+ "utf-8",
+ );
+
+ it("captures context returned by POST /session/start", () => {
+ expect(plugin).toMatch(/startContextCache\s*=\s*new Map<string,\s*string>/);
+ expect(plugin).toMatch(
+ /postJson\(["']\/session\/start["']/,
+ );
+ // Snapshot `activeSessionId` into a local before the await so the cached
+ // context binds to the session that opened it, not a later one.
+ expect(plugin).toMatch(
+ /const\s+sessionId\s*=\s*activeSessionId[\s\S]*?startContextCache\.set\(sessionId/,
+ );
+ });
+
+ it("chat.system.transform reads cached context first, falls back to /context", () => {
+ expect(plugin).toMatch(/startContextCache\.get\(sid\)/);
+ expect(plugin).toMatch(/postJson\(["']\/context["']/);
+ expect(plugin).toMatch(/startContextCache\.delete\(sid\)/);
+ });
+
+ it("session.deleted clears the cache to avoid stale entries", () => {
+ const deletedBlock = plugin.slice(plugin.indexOf("session.deleted"));
+ expect(deletedBlock).toMatch(/startContextCache\.delete\(sid\)/);
+ });
+});
diff --git a/test/stop-worker-pidfile.test.ts b/test/stop-worker-pidfile.test.ts
new file mode 100644
index 00000000..c70aaf1a
--- /dev/null
+++ b/test/stop-worker-pidfile.test.ts
@@ -0,0 +1,35 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "node:fs";
+
+// #640 + #474: stop must also kill the worker process, not just the
+// iii engine. We expose the worker pidfile from src/index.ts and read it
+// from src/cli.ts. Static check that both files agree on the path
+// (~/.agentmemory/worker.pid) and that stop reads it.
+describe("stop reaps the worker process (#640, #474)", () => {
+ it("src/index.ts writes worker.pid alongside iii.pid", () => {
+ const source = readFileSync("src/index.ts", "utf-8");
+ expect(source).toMatch(/workerPidfilePath\(\)/);
+ expect(source).toMatch(/"worker\.pid"/);
+ expect(source).toMatch(/writeWorkerPidfile\(\)/);
+ expect(source).toMatch(/clearWorkerPidfile\(\)/);
+ });
+
+ it("src/cli.ts reads worker.pid in runStop and signals it on stop", () => {
+ const source = readFileSync("src/cli.ts", "utf-8");
+ expect(source).toMatch(/workerPidfilePath\(\)/);
+ expect(source).toMatch(/"worker\.pid"/);
+ expect(source).toMatch(/readWorkerPidfile\(\)/);
+ expect(source).toMatch(/clearWorkerPidfile\(\)/);
+ // Verify stop wiring: workerCandidates set is built from the pidfile
+ // and signaled alongside the engine pids.
+ expect(source).toMatch(/workerCandidates/);
+ expect(source).toMatch(/Stopping agentmemory worker/);
+ });
+
+ it("both files agree on the pidfile path: ~/.agentmemory/worker.pid", () => {
+ const indexSrc = readFileSync("src/index.ts", "utf-8");
+ const cliSrc = readFileSync("src/cli.ts", "utf-8");
+ expect(indexSrc).toMatch(/\.agentmemory["'].*worker\.pid|"worker\.pid"/);
+ expect(cliSrc).toMatch(/\.agentmemory["'].*worker\.pid|"worker\.pid"/);
+ });
+});
diff --git a/test/viewer-graph-cooldown.test.ts b/test/viewer-graph-cooldown.test.ts
new file mode 100644
index 00000000..d5bf49a2
--- /dev/null
+++ b/test/viewer-graph-cooldown.test.ts
@@ -0,0 +1,38 @@
+import { describe, it, expect } from "vitest";
+import { readFileSync } from "node:fs";
+
+// #563: viewer graph kept bouncing on >1000 nodes because damping
+// alone could not bleed off the per-frame force pile-up. Cool-down
+// adds tick-decayed damping, a per-node velocity cap, and parks the
+// raf loop when total kinetic energy drops below an epsilon.
+describe("viewer graph cool-down (#563)", () => {
+ const viewer = readFileSync("src/viewer/index.html", "utf-8");
+
+ it("tracks a tickCount that grows each simulation step", () => {
+ expect(viewer).toMatch(/graphSim\.tickCount\s*=\s*\(graphSim\.tickCount\s*\|\|\s*0\)\s*\+\s*1/);
+ });
+
+ it("adds tick-decay to damping (coolBoost scales with tickCount)", () => {
+ expect(viewer).toMatch(/coolBoost\s*=\s*Math\.min\(0\.4,\s*graphSim\.tickCount\s*\/\s*1500\)/);
+ expect(viewer).toMatch(/damping\s*=\s*0\.9\s*-\s*coolBoost/);
+ });
+
+ it("caps per-node velocity by node-count band", () => {
+ expect(viewer).toMatch(
+ /velocityCap\s*=\s*nodeCount\s*>\s*1000\s*\?\s*6/,
+ );
+ expect(viewer).toMatch(/nvx\s*>\s*velocityCap/);
+ expect(viewer).toMatch(/nvy\s*>\s*velocityCap/);
+ });
+
+ it("parks the raf loop once the layout is quiet for 30 ticks", () => {
+ expect(viewer).toMatch(/rmsVelocity/);
+ expect(viewer).toMatch(/quietTicks/);
+ expect(viewer).toMatch(/if\s*\(graphSim\.quietTicks\s*>\s*30\)/);
+ });
+
+ it("wakes the parked loop on mousedown so drag still responds", () => {
+ expect(viewer).toMatch(/graphSim\.quietTicks\s*=\s*0/);
+ expect(viewer).toMatch(/if\s*\(graphSim\.running\s*&&\s*!graphSim\.raf\)/);
+ });
+});