Storage ports: ChatStore/GraphStore/JobStore + adapters + core inversion (stage 3)

Per-entity semantic ports (src/core/ports.ts), one adapter family
(src/store/*, fs JSON/JSONL), exactly one composition point
(src/server/stores.ts). Dependency direction is now machine-checked:
adapters implement core interfaces; core never imports an adapter.

The inversion:
- core/graph.ts (emitChat/getGraph/graphSnapshot/foldStaleChats) is now
  pure — it takes the storage ports as explicit parameters (GraphDeps).
  No store imports; newGraphNodeId is local; node id format unchanged.
- core/graph-context.ts buildGraphContext() no longer defaults to the
  live ledgers: the chat-handler hands in getGraph(graphStore) per turn.
- store adapters export exactly one object each implementing their port
  (chatStore/graphStore/jobStore); bodies otherwise verbatim.
  NodeMapping + SessionCheckpoint moved store/graph -> core/contracts
  (they ARE contract shapes); CreateJobInit/JobPatch live in ports.
- titleFromPrompt moved store/chats -> core/contracts (pure helper,
  planNodeStatus precedent). Store modules now contain persistence only.
- server/stores.ts is the composition root; server/{chats,graph,jobs}.ts
  and chat-handler wire from it; agent (plan tools, sub-agent runner)
  call the port objects. The shell surface (@/src/server exports) is
  unchanged.

Lint law extended: the whole of src/core is now a purity zone (was a
file glob with a graph/graph-context exemption). Verified it fires on
core->store imports; tsc clean, 190/190 tests, eslint clean, prod build
clean (prerender 6/6). Tests pass deps explicitly — graph.test uses the
same fs-adapter pair stores.ts wires in production; graph-context.test
keeps its in-memory ledgers as a GraphStore implementation.
This commit is contained in:
Amos
2026-08-31 20:00:12 +03:00
parent e92140f993
commit 1167157c23
24 changed files with 434 additions and 282 deletions
+10 -10
View File
@@ -19,7 +19,7 @@ import { MockLanguageModelV4, simulateReadableStream } from "ai/test";
import type { LanguageModelV4StreamPart } from "@ai-sdk/provider";
import { createTeacherAgent } from "../src/agent/teacher-agent.ts";
import { handleChatRequest } from "../src/server/chat-handler.ts";
import { createChat, getChat, saveMessages } from "../src/store/chats.ts";
import { chatStore } from "../src/store/chats.ts";
import { buildAnswer, coerceCorrectAnswer, normalizeOptions, resolveCorrect, type QuestionData } from "../src/core/question-core.ts";
import { findPendingToolCall } from "../src/core/pending.ts";
import { PATHS } from "../config.ts";
@@ -113,14 +113,14 @@ describe("teacher chat flow (scripted model)", () => {
it("quiz tool call persists as a pending part; the answer continues the lesson", async () => {
const calls: string[][] = [];
const agent = createTeacherAgent(scriptedModel(calls));
const chat = createChat("Test: solar system");
const chat = chatStore.createChat("Test: solar system");
createdChats.push(chat.id);
// ── Turn 1: learner opens with a topic; teacher probes with a quiz ──
const firstUser = { id: "u1", role: "user", parts: [{ type: "text", text: "teach me the solar system" }] };
await drain(await handleChatRequest(post(chat.id, [firstUser]), agent));
const saved1 = getChat(chat.id)!;
const saved1 = chatStore.getChat(chat.id)!;
assert.equal(saved1.messages.length, 2, "user message + assistant response persisted");
const assistantMsg = saved1.messages[1]!;
assert.equal(assistantMsg.role, "assistant");
@@ -170,7 +170,7 @@ describe("teacher chat flow (scripted model)", () => {
// ── The teacher reacts — as a CONTINUATION of the same assistant message
// (the last client message is the assistant message carrying the tool
// output, so the new text appends to that message's parts). ──
const saved2 = getChat(chat.id)!;
const saved2 = chatStore.getChat(chat.id)!;
assert.equal(saved2.messages.length, 2, "the reaction continues the same assistant message");
const finalParts = saved2.messages[1]!.parts;
const textPart = finalParts.find((p) => p.type === "text");
@@ -200,7 +200,7 @@ describe("teacher chat flow (scripted model)", () => {
// tool-input-start chunk. If a transport change ever stopped emitting
// it, the indicator would silently die — pin the protocol.
const agent = createTeacherAgent(scriptedModel([]));
const chat = createChat("Test: protocol pin");
const chat = chatStore.createChat("Test: protocol pin");
createdChats.push(chat.id);
const firstUser = { id: "u1", role: "user", parts: [{ type: "text", text: "quiz me" }] };
const body = await drain(await handleChatRequest(post(chat.id, [firstUser]), agent));
@@ -214,7 +214,7 @@ describe("teacher chat flow (scripted model)", () => {
it("persists even when the stream is aborted (resume keeps partial state)", async () => {
const calls: string[][] = [];
const agent = createTeacherAgent(scriptedModel(calls));
const chat = createChat("Test: abort");
const chat = chatStore.createChat("Test: abort");
createdChats.push(chat.id);
const req = post(chat.id, [{ id: "u1", role: "user", parts: [{ type: "text", text: "quiz me" }] }]);
@@ -226,17 +226,17 @@ describe("teacher chat flow (scripted model)", () => {
await reader.cancel();
// Give onFinish a tick to fire.
await new Promise((r) => setTimeout(r, 50));
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
assert.ok(saved.messages.length >= 1, "partial transcript persisted");
});
});
describe("chat store", () => {
it("round-trips and lists chats", async () => {
const chat = createChat("Store test");
const chat = chatStore.createChat("Store test");
createdChats.push(chat.id);
saveMessages(chat.id, [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] }]);
const loaded = getChat(chat.id)!;
chatStore.saveMessages(chat.id, [{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] }]);
const loaded = chatStore.getChat(chat.id)!;
assert.equal(loaded.messages.length, 1);
assert.equal(loaded.title, "Store test");
});
+18 -18
View File
@@ -43,8 +43,8 @@ import { runDemoBuilder } from "../src/agent/subagents/demo-builder.ts";
import { headlessOverride, type DemoRunResult, type HeadlessApi } from "../src/agent/subagents/headless.ts";
import { demoModelOverride, runDemoJob, runVisualJob, spawnPendingJobs, visualModelOverride } from "../src/agent/subagents/runner.ts";
import { runVisualMaker } from "../src/agent/subagents/visual-maker.ts";
import { createChat, getChat, saveMessages } from "../src/store/chats.ts";
import { createJob, findJobByToolCallId, getJob, listJobs } from "../src/store/jobs.ts";
import { chatStore } from "../src/store/chats.ts";
import { jobStore } from "../src/store/jobs.ts";
import { handleChatRequest } from "../src/server/chat-handler.ts";
import { createTeacherAgent } from "../src/agent/teacher-agent.ts";
import { artifactRenderers } from "../components/artifacts/index.ts";
@@ -447,9 +447,9 @@ async function drain(res: Response): Promise<string> {
describe("demo/visual job runners", () => {
it("runDemoJob fulfills the part with a tested DemoResult and marks the job done", async () => {
const chat = createChat("Test: demo runner");
const chat = chatStore.createChat("Test: demo runner");
createdChats.push(chat.id);
saveMessages(chat.id, [
chatStore.saveMessages(chat.id, [
{ id: "u1", role: "user", parts: [{ type: "text", text: "show me compounding" }] },
{
id: "a1",
@@ -458,7 +458,7 @@ describe("demo/visual job runners", () => {
},
] as never);
const job = createJob({ kind: "demo", chatId: chat.id, toolCallId: "call-d1" });
const job = jobStore.createJob({ kind: "demo", chatId: chat.id, toolCallId: "call-d1" });
createdJobs.push(job.id);
// runDemoJob has no headless injection point — the module override is the seam.
@@ -475,14 +475,14 @@ describe("demo/visual job runners", () => {
headlessOverride.current = undefined;
}
const done = getJob(job.id)!;
const done = jobStore.getJob(job.id)!;
assert.equal(done.status, "done");
assert.equal(done.activity, "run_demo: clean", "final activity line recorded");
const result = done.result as { title: string; html: string; tested: boolean };
assert.equal(result.title, "Compound interest");
assert.equal(result.tested, true);
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
const part = saved.messages[1]!.parts.find((p) => p.type === "tool-demo");
assert.ok(part && part.type === "tool-demo", "demo tool part persisted");
assert.equal(part.state, "output-available", "part fulfilled");
@@ -490,9 +490,9 @@ describe("demo/visual job runners", () => {
});
it("runVisualJob fulfills the part even on failure and marks the job error", async () => {
const chat = createChat("Test: visual runner failure");
const chat = chatStore.createChat("Test: visual runner failure");
createdChats.push(chat.id);
saveMessages(chat.id, [
chatStore.saveMessages(chat.id, [
{ id: "u1", role: "user", parts: [{ type: "text", text: "draw it" }] },
{
id: "a1",
@@ -501,16 +501,16 @@ describe("demo/visual job runners", () => {
},
] as never);
const job = createJob({ kind: "visual", chatId: chat.id, toolCallId: "call-v1" });
const job = jobStore.createJob({ kind: "visual", chatId: chat.id, toolCallId: "call-v1" });
createdJobs.push(job.id);
await runVisualJob(job.id, { model: scriptedModel([{ text: "cannot" }]) });
const errored = getJob(job.id)!;
const errored = jobStore.getJob(job.id)!;
assert.equal(errored.status, "error");
assert.match(errored.error ?? "", /never wrote an SVG/);
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
const part = saved.messages[1]!.parts.find((p) => p.type === "tool-visual");
assert.ok(part && part.type === "tool-visual", "visual tool part persisted");
assert.equal(part.state, "output-available", "failure still fulfills the part");
@@ -520,7 +520,7 @@ describe("demo/visual job runners", () => {
});
it("the spawn hook dispatches a demo part to the demo runner (kind→runner map)", async () => {
const chat = createChat("Test: demo spawn dispatch");
const chat = chatStore.createChat("Test: demo spawn dispatch");
createdChats.push(chat.id);
// A teacher that calls demo on turn 1 (scripted stream, like jobs.test.ts).
@@ -571,25 +571,25 @@ describe("demo/visual job runners", () => {
),
);
const job = findJobByToolCallId(chat.id, "call-d2");
const job = jobStore.findJobByToolCallId(chat.id, "call-d2");
assert.ok(job, "spawn hook created a job for the demo part");
assert.equal(job!.kind, "demo");
createdJobs.push(job!.id);
// The background runner (fire-and-forget) completes with the overrides.
await waitFor(() => getJob(job!.id)!.status !== "running", 5000, "demo job completion");
const done = getJob(job!.id)!;
await waitFor(() => jobStore.getJob(job!.id)!.status !== "running", 5000, "demo job completion");
const done = jobStore.getJob(job!.id)!;
assert.equal(done.status, "done");
assert.equal(done.activity, "run_demo: clean");
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
const part = saved.messages[1]!.parts.find((p) => p.type === "tool-demo");
assert.ok(part && part.type === "tool-demo", "demo tool part persisted");
assert.equal(part.state, "output-available", "demo part fulfilled by the background runner");
// Idempotency: re-running the spawn hook creates no second job.
spawnPendingJobs(chat.id, saved.messages);
assert.equal(listJobs(chat.id).length, 1, "no duplicate job for the same tool part");
assert.equal(jobStore.listJobs(chat.id).length, 1, "no duplicate job for the same tool part");
} finally {
demoModelOverride.current = undefined;
headlessOverride.current = undefined;
+25 -23
View File
@@ -23,7 +23,8 @@ import { MockLanguageModelV4, simulateReadableStream } from "ai/test";
import type { LanguageModelV4StreamPart } from "@ai-sdk/provider";
import type { GraphEdge, GraphNode, LedgerEvent } from "../src/core/contracts.ts";
import type { NodeStateClass } from "../src/core/contracts.ts";
import { emitChat, type GraphLedgers } from "../src/core/graph.ts";
import { emitChat, getGraph } from "../src/core/graph.ts";
import type { GraphStore } from "../src/core/ports.ts";
import {
buildGraphContext,
GRAPH_CONTEXT_HEADER,
@@ -32,8 +33,9 @@ import {
} from "../src/core/graph-context.ts";
import { createTeacherAgent } from "../src/agent/teacher-agent.ts";
import { handleChatRequest } from "../src/server/chat-handler.ts";
import { createChat, getChat, saveMessages, saveTree } from "../src/store/chats.ts";
import { type NodeMapping, type SessionCheckpoint } from "../src/store/graph.ts";
import { chatStore } from "../src/store/chats.ts";
import type { NodeMapping, SessionCheckpoint } from "../src/core/contracts.ts";
import { graphStore } from "../src/store/graph.ts";
import { createTree } from "../src/core/plan-tree.ts";
import { PATHS } from "../config.ts";
@@ -176,9 +178,9 @@ describe("buildGraphContext", () => {
it("reads the live ledgers without throwing (read-only integration)", () => {
// Other suites (graph.test.ts) mutate data/graph concurrently, so only
// assert the shape of the result, never its content. Read-only is
// structural: buildGraphContext only ever calls getGraph().
const out = buildGraphContext();
// assert the shape of the result, never its content. Structural note:
// the caller now hands in getGraph(graphStore) — the entry point is pure.
const out = buildGraphContext(getGraph(graphStore));
assert.ok(out === null || out.includes(GRAPH_CONTEXT_HEADER));
});
});
@@ -248,10 +250,10 @@ describe("graph-context injection (chat-flow style)", () => {
assert.ok(context, "fixture graph renders a block");
// Exactly what chat-handler does per request when no agent is passed:
// createTeacherAgent(model, tools, buildGraphContext()).
// createTeacherAgent(model, tools, buildGraphContext(getGraph(graphStore))).
const prompts: string[] = [];
const agent = createTeacherAgent(capturingModel(prompts), undefined, context);
const chat = createChat("Test: graph context injection");
const chat = chatStore.createChat("Test: graph context injection");
createdChats.push(chat.id);
await drain(
@@ -279,7 +281,7 @@ describe("graph-context injection (chat-flow style)", () => {
it("no block is injected when the context is null (new learner)", async () => {
const prompts: string[] = [];
const agent = createTeacherAgent(capturingModel(prompts));
const chat = createChat("Test: no graph context");
const chat = chatStore.createChat("Test: no graph context");
createdChats.push(chat.id);
await drain(
await handleChatRequest(
@@ -295,7 +297,7 @@ describe("graph-context injection (chat-flow style)", () => {
// ─── exact-match merge (emitChat dedup) ─────────────────────────────────────
/** An in-memory stand-in for the five ledgers (see GraphLedgers in graph.ts). */
/** An in-memory stand-in for the five ledgers (the GraphStore port, core/ports.ts). */
function memoryLedgers() {
const nodes: GraphNode[] = [];
const edges: GraphEdge[] = [];
@@ -313,31 +315,31 @@ function memoryLedgers() {
readMappings: () => mappings.map((m) => ({ ...m })),
appendCheckpoint: (c: SessionCheckpoint) => void checkpoints.push(c),
readCheckpoints: () => checkpoints.map((c) => ({ ...c })),
// Test accessors (not part of the GraphLedgers surface).
// Test accessors (not part of the GraphStore surface).
counts: { get nodes() { return nodes.length; }, get mappings() { return mappings.length; } },
} satisfies GraphLedgers & { counts: { nodes: number; mappings: number } };
} satisfies GraphStore & { counts: { nodes: number; mappings: number } };
}
/** A real chat record with a stored tree (emitChat reads the real chat store). */
function fixtureChat(title: string, tree: ReturnType<typeof createTree>) {
const chat = createChat(title);
const chat = chatStore.createChat(title);
createdChats.push(chat.id);
saveTree(chat.id, tree);
saveMessages(chat.id, [{ id: "u1", role: "user", parts: [{ type: "text", text: "go" }] }]);
return getChat(chat.id)!;
chatStore.saveTree(chat.id, tree);
chatStore.saveMessages(chat.id, [{ id: "u1", role: "user", parts: [{ type: "text", text: "go" }] }]);
return chatStore.getChat(chat.id)!;
}
describe("exact-match merge (emitChat)", () => {
it("maps a case/whitespace-identical title onto the existing node instead of duplicating", () => {
const ledgers = memoryLedgers();
const chat1 = fixtureChat("Merge A", createTree([{ id: "cr", title: "Chain rule intuition" }], []));
let stats = emitChat(chat1.id, ledgers);
let stats = emitChat(chat1.id, { chatStore, graphStore: ledgers });
assert.deepEqual(stats, { nodes: 1, edges: 0, events: 0 });
const firstId = ledgers.readNodes()[0]!.id;
// Second session, same proposition: different casing + padding.
const chat2 = fixtureChat("Merge B", createTree([{ id: "cr2", title: " chain Rule INTUITION " }], []));
stats = emitChat(chat2.id, ledgers);
stats = emitChat(chat2.id, { chatStore, graphStore: ledgers });
assert.deepEqual(stats, { nodes: 0, edges: 0, events: 0 }, "no duplicate node appended");
assert.equal(ledgers.counts.nodes, 1, "still exactly one graph node");
@@ -357,7 +359,7 @@ describe("exact-match merge (emitChat)", () => {
createdAt: "2026-08-22T00:00:00.000Z",
});
const chat = fixtureChat("Merge alias", createTree([{ id: "d", title: "The Derivative" }], []));
const stats = emitChat(chat.id, ledgers);
const stats = emitChat(chat.id, { chatStore, graphStore: ledgers });
assert.deepEqual(stats, { nodes: 0, edges: 0, events: 0 }, "alias match → no new node");
assert.deepEqual(ledgers.readMappings(), [{ chatId: chat.id, treeNodeId: "d", graphNodeId: "n_alias" }]);
});
@@ -365,12 +367,12 @@ describe("exact-match merge (emitChat)", () => {
it("does NOT fuzzy-match near-identical titles (that stays deferred)", () => {
const ledgers = memoryLedgers();
const chat1 = fixtureChat("Fuzzy A", createTree([{ id: "cr", title: "Chain rule intuition" }], []));
emitChat(chat1.id, ledgers);
emitChat(chat1.id, { chatStore, graphStore: ledgers });
const chat2 = fixtureChat(
"Fuzzy B",
createTree([{ id: "cr2", title: "Chain rules intuition" }], []),
);
const stats = emitChat(chat2.id, ledgers);
const stats = emitChat(chat2.id, { chatStore, graphStore: ledgers });
assert.equal(stats.nodes, 1, "near-miss titles stay separate nodes");
assert.equal(ledgers.counts.nodes, 2);
});
@@ -387,7 +389,7 @@ describe("exact-match merge (emitChat)", () => {
[{ from: "base", to: "chain" }],
),
);
emitChat(chat1.id, ledgers);
emitChat(chat1.id, { chatStore, graphStore: ledgers });
// Second session re-teaches the same two propositions (exact titles)
// and asserts the same edge — it must dedupe onto the existing nodes.
@@ -401,7 +403,7 @@ describe("exact-match merge (emitChat)", () => {
[{ from: "base", to: "chain" }],
),
);
const stats = emitChat(chat2.id, ledgers);
const stats = emitChat(chat2.id, { chatStore, graphStore: ledgers });
// A new ASSERTION line is appended (provenance is honest) — reads merge
// by (from,to,type), so the derived graph still has one edge with both
// sessions in its provenance.
+29 -26
View File
@@ -15,11 +15,14 @@ import type { UIMessage } from "ai";
import type { PlanTree, PlanToolResult } from "../src/core/contracts.ts";
import type { QuestionAnswerData } from "../src/core/question-core.ts";
import { createTree, markDone, removeNode } from "../src/core/plan-tree.ts";
import { emitChat, foldStaleChats, getGraph, graphSnapshot } from "../src/core/graph.ts";
import { graphLedgers } from "../src/store/graph.ts";
import { createChat, getChat, saveMessages, saveTree } from "../src/store/chats.ts";
import { emitChat, foldStaleChats, getGraph, graphSnapshot, type GraphDeps } from "../src/core/graph.ts";
import { graphStore } from "../src/store/graph.ts";
import { chatStore } from "../src/store/chats.ts";
import { LEDGER_FILES, PATHS } from "../config.ts";
/** The wired fs adapters, exactly what src/server/stores.ts passes in production. */
const graphDeps = { chatStore, graphStore } as const satisfies GraphDeps;
// ─── ledger isolation (backup-and-clear of data/graph/*.jsonl) ──────────────
const LEDGER_PATHS = Object.values(LEDGER_FILES);
@@ -95,11 +98,11 @@ function answer(over: Partial<QuestionAnswerData>): QuestionAnswerData {
/** Create a chat in the real store with a tree and messages; returns the record. */
function fixtureChat(title: string, tree: PlanTree | null, messages: UIMessage[]) {
const chat = createChat(title);
const chat = chatStore.createChat(title);
createdChats.push(chat.id);
if (tree) saveTree(chat.id, tree);
saveMessages(chat.id, messages);
return getChat(chat.id)!;
if (tree) chatStore.saveTree(chat.id, tree);
chatStore.saveMessages(chat.id, messages);
return chatStore.getChat(chat.id)!;
}
/** The fixture tree: alpha → beta, gamma free-floating, alpha done. */
@@ -188,9 +191,9 @@ let chat2Id = "";
/** Everything the graph holds for a set of chats (other processes' test
* emissions run concurrently against the same files — scope, never assume). */
function scopedGraph(chatIds: string[]) {
const graph = getGraph();
const graph = getGraph(graphStore);
const nodeIds = new Set(
graphLedgers
graphStore
.readMappings()
.filter((m) => chatIds.includes(m.chatId))
.map((m) => m.graphNodeId),
@@ -204,7 +207,7 @@ function scopedGraph(chatIds: string[]) {
describe("graph emission (emitChat)", () => {
it("folds tree nodes/edges and quiz/mark_done events with the probe/check boundary", () => {
const stats = emitChat(chat1.id);
const stats = emitChat(chat1.id, graphDeps);
assert.deepEqual(stats, { nodes: 3, edges: 1, events: 6 });
const graph = scopedGraph([chat1.id]);
@@ -262,14 +265,14 @@ describe("graph emission (emitChat)", () => {
});
it("is idempotent — re-emission appends nothing", () => {
const stats = emitChat(chat1.id);
const stats = emitChat(chat1.id, graphDeps);
assert.deepEqual(stats, { nodes: 0, edges: 0, events: 0 });
const graph = scopedGraph([chat1.id]);
assert.equal(graph.nodes.length, 3);
assert.equal(graph.edges.length, 1);
assert.equal(graph.events.length, 6);
// exactly one checkpoint line per fold, though — checkpoints are a log
assert.equal(graphLedgers.readCheckpoints().filter((c) => c.chatId === chat1.id).length, 2);
assert.equal(graphStore.readCheckpoints().filter((c) => c.chatId === chat1.id).length, 2);
});
it("accumulates edge provenance when another chat maps onto the same nodes", () => {
@@ -288,13 +291,13 @@ describe("graph emission (emitChat)", () => {
assistant("a1", [planPart("p1", "plan_init", { nodes: [], edges: [] }, tree2)]),
]);
const before = getGraph();
const before = getGraph(graphStore);
const gAlpha = before.nodes.find((n) => n.statement === "Alpha intuition")!.id;
const gBeta = before.nodes.find((n) => n.statement === "Beta rule")!.id;
graphLedgers.appendMapping({ chatId: chat2.id, treeNodeId: "alpha", graphNodeId: gAlpha });
graphLedgers.appendMapping({ chatId: chat2.id, treeNodeId: "beta", graphNodeId: gBeta });
graphStore.appendMapping({ chatId: chat2.id, treeNodeId: "alpha", graphNodeId: gAlpha });
graphStore.appendMapping({ chatId: chat2.id, treeNodeId: "beta", graphNodeId: gBeta });
const stats = emitChat(chat2.id);
const stats = emitChat(chat2.id, graphDeps);
assert.deepEqual(stats, { nodes: 0, edges: 1, events: 0 });
chat2Id = chat2.id;
@@ -305,7 +308,7 @@ describe("graph emission (emitChat)", () => {
});
it("derives node states, sessions, and node provenance in graphSnapshot", () => {
const snap = graphSnapshot();
const snap = graphSnapshot(graphDeps);
const idByStatement = new Map(snap.nodes.map((n) => [n.statement, n.id]));
assert.equal(snap.nodeStates[idByStatement.get("Alpha intuition")!], "taught");
assert.equal(snap.nodeStates[idByStatement.get("Beta rule")!], "missed");
@@ -336,7 +339,7 @@ describe("graph emission (emitChat)", () => {
assistant("a2", [planPart("p2", "plan_remove_node", { id: "y" }, prunedTree)]),
]);
const stats = emitChat(chat.id);
const stats = emitChat(chat.id, graphDeps);
assert.deepEqual(stats, { nodes: 1, edges: 0, events: 0 }); // y pruned, edge cascaded away
const graph = scopedGraph([chat.id]);
@@ -345,7 +348,7 @@ describe("graph emission (emitChat)", () => {
});
it("returns zeros for unknown chats", () => {
assert.deepEqual(emitChat("chat_does_not_exist"), { nodes: 0, edges: 0, events: 0 });
assert.deepEqual(emitChat("chat_does_not_exist", graphDeps), { nodes: 0, edges: 0, events: 0 });
});
});
@@ -366,11 +369,11 @@ describe("catch-up (foldStaleChats)", () => {
]),
]);
const folded = foldStaleChats();
const folded = foldStaleChats(graphDeps);
assert.ok(folded >= 1, "the catch-up fixture was folded");
assert.equal(graphLedgers.readCheckpoints().filter((c) => c.chatId === chat.id).length, 1);
assert.equal(graphStore.readCheckpoints().filter((c) => c.chatId === chat.id).length, 1);
const snap = graphSnapshot();
const snap = graphSnapshot(graphDeps);
const solo = snap.nodes.find((n) => n.statement === "Solo node");
assert.ok(solo, "solo node was emitted by the catch-up fold");
assert.equal(snap.nodeStates[solo.id], "known"); // correct check, no taught event
@@ -378,8 +381,8 @@ describe("catch-up (foldStaleChats)", () => {
// Already checkpointed → not folded again (other test files' chats may
// legitimately fold here, so assert on THIS chat only).
foldStaleChats();
assert.equal(graphLedgers.readCheckpoints().filter((c) => c.chatId === chat.id).length, 1);
foldStaleChats(graphDeps);
assert.equal(graphStore.readCheckpoints().filter((c) => c.chatId === chat.id).length, 1);
});
});
@@ -388,14 +391,14 @@ describe("catch-up (foldStaleChats)", () => {
describe("graph ledger store", () => {
it("round-trips lines and skips corrupt / foreign-shaped lines (strict reads)", () => {
const node = { id: "n_storetest", statement: "Store test", aliases: [], kind: "truth" as const, createdAt: "2026-08-22T00:00:00.000Z" };
graphLedgers.appendNode(node);
graphStore.appendNode(node);
// A torn append and a legacy V0-shaped node (different schema) — both skipped.
fs.appendFileSync(
LEDGER_FILES.nodes,
`{not json}\n${JSON.stringify({ id: "legacy", statement: "Legacy shape", domain: "x", state: "known" })}\n`,
"utf-8",
);
const nodes = graphLedgers.readNodes().filter((n) => n.id === "n_storetest" || n.id === "legacy");
const nodes = graphStore.readNodes().filter((n) => n.id === "n_storetest" || n.id === "legacy");
assert.equal(nodes.length, 1);
assert.equal(nodes[0]!.statement, "Store test");
});
+24 -26
View File
@@ -24,8 +24,8 @@ import { MockLanguageModelV4, simulateReadableStream } from "ai/test";
import type { LanguageModelV4StreamPart } from "@ai-sdk/provider";
import { createTeacherAgent } from "../src/agent/teacher-agent.ts";
import { handleChatRequest } from "../src/server/chat-handler.ts";
import { createChat, getChat } from "../src/store/chats.ts";
import { createJob, findJobByToolCallId, getJob, listJobs, updateJob } from "../src/store/jobs.ts";
import { chatStore } from "../src/store/chats.ts";
import { jobStore } from "../src/store/jobs.ts";
import { researchModelOverride, runResearchJob, spawnPendingJobs } from "../src/agent/subagents/runner.ts";
import { createResearcherAgent } from "../src/agent/subagents/researcher.ts";
import { PATHS } from "../config.ts";
@@ -86,32 +86,32 @@ function post(chatId: string, messages: unknown[]): Request {
describe("job store", () => {
it("create → get → update → list round-trips", () => {
const job = createJob({ kind: "research", chatId: "chat_storetest", toolCallId: "call-store" });
const job = jobStore.createJob({ kind: "research", chatId: "chat_storetest", toolCallId: "call-store" });
trackJob(job.id);
assert.match(job.id, /^job_/);
assert.equal(job.status, "running");
assert.equal(job.activity, "starting");
const loaded = getJob(job.id)!;
const loaded = jobStore.getJob(job.id)!;
assert.equal(loaded.toolCallId, "call-store");
assert.equal(loaded.kind, "research");
const updated = updateJob(job.id, { activity: 'web_search: "test"', status: "done", result: { brief: "b" } })!;
const updated = jobStore.updateJob(job.id, { activity: 'web_search: "test"', status: "done", result: { brief: "b" } })!;
assert.equal(updated.activity, 'web_search: "test"');
assert.equal(updated.status, "done");
assert.ok(updated.updatedAt >= job.updatedAt);
// immutable identity fields survive a patch
assert.equal(updated.toolCallId, "call-store");
assert.equal(getJob(updated.id)!.toolCallId, "call-store");
assert.equal(jobStore.getJob(updated.id)!.toolCallId, "call-store");
const listed = listJobs("chat_storetest");
const listed = jobStore.listJobs("chat_storetest");
assert.ok(listed.some((j) => j.id === job.id));
assert.equal(listJobs("chat_other").some((j) => j.id === job.id), false, "jobs are scoped to their chat");
assert.equal(jobStore.listJobs("chat_other").some((j) => j.id === job.id), false, "jobs are scoped to their chat");
const byTool = findJobByToolCallId("chat_storetest", "call-store");
const byTool = jobStore.findJobByToolCallId("chat_storetest", "call-store");
assert.equal(byTool?.id, job.id);
assert.equal(findJobByToolCallId("chat_storetest", "call-missing"), null);
assert.equal(jobStore.findJobByToolCallId("chat_storetest", "call-missing"), null);
});
});
@@ -155,7 +155,7 @@ function researchCallingTeacher(): MockLanguageModelV4 {
describe("spawn hook (async protocol §2)", () => {
it("a pending research part in the final assistant message spawns exactly one job", async () => {
const chat = createChat("Test: research spawn");
const chat = chatStore.createChat("Test: research spawn");
trackChat(chat.id);
const agent = createTeacherAgent(researchCallingTeacher());
@@ -163,13 +163,13 @@ describe("spawn hook (async protocol §2)", () => {
await drain(await handleChatRequest(post(chat.id, [firstUser]), agent));
// The research part is pending (input-available) in the stored chat.
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
const part = saved.messages[1]!.parts.find((p) => p.type === "tool-research");
assert.ok(part && part.type === "tool-research", "research tool part persisted");
assert.equal(part.state, "input-available", "job tool part stays pending until the runner fulfills it");
// A job record exists for it.
const job = findJobByToolCallId(chat.id, "call-r1");
const job = jobStore.findJobByToolCallId(chat.id, "call-r1");
assert.ok(job, "spawn hook created a job record");
assert.equal(job!.kind, "research");
assert.equal(job!.status, "running");
@@ -177,7 +177,7 @@ describe("spawn hook (async protocol §2)", () => {
// Re-running the spawn hook (idempotency) does not create a second job.
spawnPendingJobs(chat.id, saved.messages);
assert.equal(listJobs(chat.id).length, 1, "no duplicate job for the same tool part");
assert.equal(jobStore.listJobs(chat.id).length, 1, "no duplicate job for the same tool part");
});
});
@@ -249,7 +249,7 @@ describe("research runner (async protocol §3)", () => {
it("fulfills the part with a ResearchResult and marks the job done with activity recorded", async () => {
const restoreFetch = stubFetch();
try {
const chat = createChat("Test: runner completion");
const chat = chatStore.createChat("Test: runner completion");
trackChat(chat.id);
// A pending research part, as the spawn hook would find it.
@@ -265,23 +265,22 @@ describe("research runner (async protocol §3)", () => {
},
] as never;
// saveMessages requires the chat to exist; use the store directly.
const { saveMessages } = await import("../src/store/chats.ts");
saveMessages(chat.id, messages);
chatStore.saveMessages(chat.id, messages);
const job = createJob({ kind: "research", chatId: chat.id, toolCallId: "call-run1" });
const job = jobStore.createJob({ kind: "research", chatId: chat.id, toolCallId: "call-run1" });
trackJob(job.id);
await runResearchJob(job.id, { model: researcherModel() });
// The job is done, with the activity line from the tool call.
const done = getJob(job.id)!;
const done = jobStore.getJob(job.id)!;
assert.equal(done.status, "done");
assert.equal(done.activity, 'web_search: "sigma.js latest version"', "activity line recorded");
assert.ok(done.result, "result stored on the job");
// The stored chat's part flipped to output-available with a
// ResearchResult-shaped output.
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
const part = saved.messages[1]!.parts.find((p) => p.type === "tool-research");
assert.ok(part && part.type === "tool-research");
assert.equal(part.state, "output-available");
@@ -300,10 +299,9 @@ describe("research runner (async protocol §3)", () => {
throw new Error("model exploded");
},
});
const chat = createChat("Test: runner failure");
const chat = chatStore.createChat("Test: runner failure");
trackChat(chat.id);
const { saveMessages } = await import("../src/store/chats.ts");
saveMessages(chat.id, [
chatStore.saveMessages(chat.id, [
{ id: "u1", role: "user", parts: [{ type: "text", text: "hi" }] },
{
id: "a1",
@@ -312,16 +310,16 @@ describe("research runner (async protocol §3)", () => {
},
] as never);
const job = createJob({ kind: "research", chatId: chat.id, toolCallId: "call-err1" });
const job = jobStore.createJob({ kind: "research", chatId: chat.id, toolCallId: "call-err1" });
trackJob(job.id);
await runResearchJob(job.id, { model: failing });
const errored = getJob(job.id)!;
const errored = jobStore.getJob(job.id)!;
assert.equal(errored.status, "error");
assert.match(errored.error ?? "", /model exploded/);
const saved = getChat(chat.id)!;
const saved = chatStore.getChat(chat.id)!;
const part = saved.messages[1]!.parts.find((p) => p.type === "tool-research");
assert.ok(part && part.type === "tool-research");
assert.equal(part.state, "output-available", "failure still fulfills the part");
+11 -11
View File
@@ -26,7 +26,7 @@ import {
updateNode,
} from "../src/core/plan-tree.ts";
import { planTools } from "../src/agent/tools/plan.ts";
import { createChat, getChat } from "../src/store/chats.ts";
import { chatStore } from "../src/store/chats.ts";
import { PATHS } from "../config.ts";
const N = (id: string, title = id, summary?: string) => ({ id, title, ...(summary ? { summary } : {}) });
@@ -228,7 +228,7 @@ async function exec(tools: ReturnType<typeof planTools>, name: string, input: un
}
function newChat(title: string): string {
const chat = createChat(title);
const chat = chatStore.createChat(title);
createdChats.push(chat.id);
return chat.id;
}
@@ -251,7 +251,7 @@ describe("plan tools (execute against the real store)", () => {
assert.equal(res.tree.nodes.length, 2);
assert.deepEqual(res.tree.edges, [{ from: "truth", to: "goal" }]);
const saved = getChat(chatId)!.tree;
const saved = chatStore.getChat(chatId)!.tree;
assert.ok(saved, "tree persisted to the chat record");
assert.deepEqual(saved, res.tree);
});
@@ -268,7 +268,7 @@ describe("plan tools (execute against the real store)", () => {
assert.equal(res.error, "Tree already initialized — use the mutation tools");
assert.deepEqual(res.tree.nodes.map((n: { id: string }) => n.id), ["a"], "existing tree returned, not wiped");
const saved = getChat(chatId)!.tree!;
const saved = chatStore.getChat(chatId)!.tree!;
assert.deepEqual(saved.nodes.map((n) => n.id), ["a"]);
});
@@ -288,7 +288,7 @@ describe("plan tools (execute against the real store)", () => {
assert.equal(res.ok, false);
assert.match(res.error!, /cycle/);
assert.deepEqual(res.tree, emptyTree());
assert.equal(getChat(chatId)!.tree, undefined, "nothing persisted on failure");
assert.equal(chatStore.getChat(chatId)!.tree, undefined, "nothing persisted on failure");
});
it("mutation round-trip: add node with parents, set current, mark done — each persists", async () => {
@@ -315,17 +315,17 @@ describe("plan tools (execute against the real store)", () => {
["ratelimit→burst", "ratelimit→detour"],
);
assert.equal(added.tree.version, 2);
assert.deepEqual(getChat(chatId)!.tree!, added.tree, "add_node persisted");
assert.deepEqual(chatStore.getChat(chatId)!.tree!, added.tree, "add_node persisted");
const current = await exec(tools, "plan_set_current", { id: "detour" });
assert.equal(current.ok, true);
assert.equal(current.tree.currentNodeId, "detour");
assert.equal(getChat(chatId)!.tree!.currentNodeId, "detour", "set_current persisted");
assert.equal(chatStore.getChat(chatId)!.tree!.currentNodeId, "detour", "set_current persisted");
const done = await exec(tools, "plan_mark_done", { id: "ratelimit" });
assert.equal(done.ok, true);
assert.deepEqual(done.tree.doneNodeIds, ["ratelimit"]);
assert.deepEqual(getChat(chatId)!.tree!.doneNodeIds, ["ratelimit"], "mark_done persisted");
assert.deepEqual(chatStore.getChat(chatId)!.tree!.doneNodeIds, ["ratelimit"], "mark_done persisted");
assert.equal(done.tree.version, 4);
});
@@ -333,7 +333,7 @@ describe("plan tools (execute against the real store)", () => {
const chatId = newChat("Plan tools: invalid ops");
const tools = planTools({ chatId });
await exec(tools, "plan_init", { nodes: [{ id: "a", title: "A" }] });
const before = getChat(chatId)!.tree!;
const before = chatStore.getChat(chatId)!.tree!;
const dup = await exec(tools, "plan_add_node", { id: "a", title: "Impostor" });
assert.equal(dup.ok, false);
@@ -348,7 +348,7 @@ describe("plan tools (execute against the real store)", () => {
assert.equal(badEdge.ok, false);
assert.match(badEdge.error!, /self-loop/);
assert.deepEqual(getChat(chatId)!.tree!, before, "record untouched by failed ops");
assert.deepEqual(chatStore.getChat(chatId)!.tree!, before, "record untouched by failed ops");
});
it("mutation tools work on a fresh (uninitialized) chat: the tree seeds from empty", async () => {
@@ -357,7 +357,7 @@ describe("plan tools (execute against the real store)", () => {
const res = await exec(tools, "plan_add_node", { id: "a", title: "A" });
assert.equal(res.ok, true);
assert.equal(res.tree.nodes.length, 1);
assert.ok(getChat(chatId)!.tree, "tree seeded without plan_init");
assert.ok(chatStore.getChat(chatId)!.tree, "tree seeded without plan_init");
});
it("unknown chat returns ok:false with the empty tree", async () => {