feat: graph context injection — the session's prior knowledge, steered in at session start (vision-context-injection.md)

One shot per chat, fired at the first turn's onFinish: the session's
topic (its only typed message) is embedded as an EmbeddingGemma retrieval
query; the semantically closest graph propositions are selected under the
session's token budget (pure budget, no similarity threshold — the
decided doctrine) and delivered as a marker-only steer through the wake
pipeline, queuing behind pending questions like every sub-agent result.

- contracts: ChatSettings.graphContextTokens (default 1024, max 4096,
  step 128, 0 = off); GraphContextData + graphContextText; the
  graph-context JobKind + buildGraphContextSteer (id steer_ctx_<chatId>)
- core/graph-context.ts: brute-force cosine top-K, greedy chars/4 fill
  under budget, most-recent UnderstandingLevel fold, count cap 64,
  parse-don't-cast at the marker seam
- server: embedQuery (role-asymmetric query format, same warm singleton
  — vector-space parity by construction); the runner (startGraphContext-
  Injection one-shot gates; runGraphContextJob validates ledger parity);
  wake branches (chatIdOf/jobIdOf, finalizeJob done, recoverStaleJobs
  re-deliver or contextRespawn); abortJob kills context jobs SILENTLY
  (nothing was promised in the lesson); turn-service trigger seam
- adapter: data-graph-context flattens to the canonical block (malformed
  parts have no model face)
- UI: the budget slider (home dock + /chat/new draft, the session-data
  strip); the quiet SystemLine "~537 · 10 propositions"; dock kind
  "Knowledge context"; model-picker PUT now spreads settings (a model
  pick can no longer clear the sibling override)

Live-smoked end to end on the real embedder + real GLM: seeded ledger
(10 propositions), session on "modal logic: possible worlds and the
necessity box" — job in the dock, queued behind the prober's question,
delivered on the answer, SystemLine in the transcript, wake turn reads
the block and continues the probe. Gates: tsc, lint, 459/459, build.
This commit is contained in:
amosblomqvist
2026-09-15 07:54:50 +03:00
parent ecb293a77d
commit 1d45d77303
25 changed files with 1443 additions and 28 deletions
+291
View File
@@ -0,0 +1,291 @@
/**
* Graph context injection — the pure core (docs/vision-context-injection.md):
* selection doctrine, level fold, block text, the marker-part parser, and
* the runner's pure gates (topic/budget/one-shot). Deterministic, zero
* network, zero stores — hand-made vectors.
*/
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import type { UIMessage } from "ai";
import {
buildGraphContextSteer,
steerDelivered,
GRAPH_CONTEXT_TOKENS_DEFAULT,
GRAPH_CONTEXT_TOKENS_MAX,
GRAPH_CONTEXT_TOKENS_STEP,
graphContextText,
type GraphContextData,
} from "../src/core/contracts.ts";
import {
currentUnderstanding,
GRAPH_CONTEXT_MAX_PROPOSITIONS,
graphContextOfMessage,
hasContext,
isUnderstandingLevel,
selectGraphContext,
} from "../src/core/graph-context.ts";
import {
contextToolCallId,
effectiveContextBudget,
topicOf,
} from "../src/agent/subagents/graph-context.ts";
import type { GraphNode, LedgerEvent } from "../src/core/contracts/graph.ts";
function unit(i: number): number[] {
const v = new Array(8).fill(0);
v[i] = 1;
return v;
}
function node(id: string, statement: string): GraphNode {
return {
id,
name: id,
statement,
aliases: [],
provenance: [],
createdAt: "2026-09-14T00:00:00.000Z",
};
}
function obs(nodeId: string, level: string, at: string, chatId = "chat_x"): LedgerEvent {
return { nodeId, kind: "observation", chatId, at, note: level };
}
/** A text-bearing user message (the learner's typed speech). */
function userText(text: string): UIMessage {
return { id: `m_${text.length}`, role: "user", parts: [{ type: "text", text }] };
}
/** A marker-only user message (steer scaffolding — no text). */
function marker(type: string, data: unknown): UIMessage {
return { id: `m_${type}`, role: "user", parts: [{ type, data } as never] };
}
describe("currentUnderstanding — the most-recent fold", () => {
it("latest observation wins, across chats, ledger order breaks ties", () => {
const events = [
obs("n1", "shaky", "2026-09-01T00:00:00Z", "chat_a"),
obs("n1", "solid", "2026-09-10T00:00:00Z", "chat_b"),
obs("n2", "resisted", "2026-09-05T00:00:00Z"),
obs("n2", "accepted", "2026-09-05T00:00:00Z"), // same at → later line wins
];
const levels = currentUnderstanding(events);
assert.equal(levels.get("n1"), "solid");
assert.equal(levels.get("n2"), "accepted");
assert.equal(levels.size, 2);
});
it("off-scale notes never count (the closed list is the only vocabulary)", () => {
assert.equal(isUnderstandingLevel("solid"), true);
assert.equal(isUnderstandingLevel("pretty good"), false);
const levels = currentUnderstanding([obs("n1", "confident", "2026-09-01T00:00:00Z")]);
assert.equal(levels.size, 0);
});
it("quiz outcome events and null nodes are not observations", () => {
const events: LedgerEvent[] = [
{ nodeId: "n1", kind: "correct", chatId: "c", at: "2026-09-01T00:00:00Z" },
{ nodeId: null, kind: "observation", chatId: "c", at: "2026-09-01T00:00:00Z", note: "solid" },
];
assert.equal(currentUnderstanding(events).size, 0);
});
});
describe("selectGraphContext — similarity orders, the budget is the only amount control", () => {
const base = {
chatId: "chat_1",
query: unit(0),
events: [] as LedgerEvent[],
};
it("fills similarity-descending and stops before exceeding the budget", () => {
const vectors = { a: unit(0), b: unit(0), c: unit(7) };
const nodes = [
node("a", "Water boils at 100°C at sea level."),
node("b", "Evaporation cools the surrounding air."),
node("c", "The Schrödinger equation is linear."),
];
// budget 55 (framing) + ~9 tokens for statement a ≈ fits exactly one line.
const data = selectGraphContext({ ...base, vectors, nodes, budget: 66 });
assert.deepEqual(
data.propositions.map((p) => p.id),
["a"],
);
assert.equal(data.tokens <= 66, true);
assert.equal(data.budget, 66);
});
it("an oversized line is skipped, a later smaller one may still fit (no threshold, pure budget)", () => {
const vectors = { big: unit(0), small: unit(0), off: unit(7) };
const big = "X".repeat(400); // ~100 tokens — bigger than the whole budget
const nodes = [
node("big", big),
node("small", "Ice melts."),
node("off", "Irrelevant."),
];
// budget 60: 'big' (~100 tokens) is skipped outright; 'small' (4 tokens
// incl. the level slot + framing 55 = 59) fits; 'off' (63) doesn't.
const data = selectGraphContext({ ...base, vectors, nodes, budget: 60 });
assert.deepEqual(
data.propositions.map((p) => p.id),
["small"],
);
});
it("annotates each line with the folded current level (null when unobserved)", () => {
const vectors = { a: unit(0), b: unit(0) };
const nodes = [node("a", "A."), node("b", "B.")];
const events = [obs("b", "shaky", "2026-09-10T00:00:00Z")];
const data = selectGraphContext({ ...base, vectors, nodes, events, budget: 4096 });
const byId = Object.fromEntries(data.propositions.map((p) => [p.id, p]));
assert.equal(byId.a!.level, null);
assert.equal(byId.b!.level, "shaky");
});
it("the count cap bounds even a huge budget", () => {
const vectors: Record<string, number[]> = {};
const nodes: GraphNode[] = [];
for (let i = 0; i < GRAPH_CONTEXT_MAX_PROPOSITIONS + 10; i++) {
const id = `n${i}`;
vectors[id] = unit(0);
nodes.push(node(id, `Statement ${i}.`));
}
const data = selectGraphContext({ ...base, vectors, nodes, budget: GRAPH_CONTEXT_TOKENS_MAX });
assert.equal(data.propositions.length, GRAPH_CONTEXT_MAX_PROPOSITIONS);
});
it("dimension-mismatched vectors and duplicate node lines are handled", () => {
const vectors = { ok: unit(0), stale: [1, 2, 3] };
const nodes = [
node("ok", "Fine."),
node("dup", "First line."),
node("dup", "Second line never redefines."),
];
// "dup" has no vector anyway; the pin is that the scan neither throws
// nor scores the stale-dim vector.
const data = selectGraphContext({ ...base, vectors, nodes, budget: 4096 });
assert.deepEqual(
data.propositions.map((p) => p.id),
["ok"],
);
});
});
describe("graphContextText + hasContext — the canonical block", () => {
it("carries the counts in the header, the level tag per line, the gloss at the end", () => {
const data: GraphContextData = {
chatId: "c1",
budget: 1024,
tokens: 42,
propositions: [
{ id: "n1", statement: "Water boils at 100°C.", level: "solid" },
{ id: "n2", statement: "Humidity slows evaporation.", level: null },
],
};
const text = graphContextText(data);
assert.match(text, /2 propositions, ~42 tokens/);
assert.match(text, /- \[solid\] Water boils at 100°C\./);
assert.match(text, /- Humidity slows evaporation\./);
assert.match(text, /Do not re-teach solid ground\./);
});
it("an empty selection has no text and no context", () => {
const empty: GraphContextData = { chatId: "c1", budget: 1024, tokens: 55, propositions: [] };
assert.equal(graphContextText(empty), "");
assert.equal(hasContext(empty), false);
});
});
describe("graphContextOfMessage — parse-don't-cast at the marker seam", () => {
it("round-trips a well-formed part", () => {
const msg = marker("data-graph-context", {
chatId: "c1",
budget: 512,
tokens: 60,
propositions: [{ id: "n1", statement: "S.", level: "shaky" }],
});
const data = graphContextOfMessage(msg);
assert.equal(data?.chatId, "c1");
assert.equal(data?.propositions[0]?.level, "shaky");
});
it("rejects malformed shapes wholesale (bad level, bad budget, non-array)", () => {
assert.equal(graphContextOfMessage(marker("data-graph-context", { chatId: "c" })), null);
assert.equal(
graphContextOfMessage(
marker("data-graph-context", {
chatId: "c",
budget: 512,
tokens: 1,
propositions: [{ id: "n", statement: "s", level: "kinda" }],
}),
),
null,
);
assert.equal(
graphContextOfMessage(
marker("data-graph-context", { chatId: "c", budget: 999999, tokens: 1, propositions: [] }),
),
null,
);
});
it("absent part → null", () => {
assert.equal(graphContextOfMessage(userText("hello")), null);
});
});
describe("buildGraphContextSteer — the marker-only delivery", () => {
it("id is deterministic per chat; metadata carries chat + job; one part", () => {
const data: GraphContextData = {
chatId: "chat_9",
budget: 1024,
tokens: 10,
propositions: [{ id: "n1", statement: "S.", level: null }],
};
const steer = buildGraphContextSteer({ chatId: "chat_9", jobId: "job_1" }, data);
assert.equal(steer.id, "steer_ctx_chat_9");
assert.equal(steer.role, "user");
assert.deepEqual(steer.metadata, { graphContext: { chatId: "chat_9", jobId: "job_1" } });
assert.equal(steer.parts.length, 1);
assert.equal(steer.parts[0]!.type, "data-graph-context");
// steerDelivered keys on the id — the one-shot guard.
assert.equal(steerDelivered([steer], "steer_ctx_chat_9"), true);
});
});
describe("the runner's pure gates", () => {
it("topicOf: exactly one typed message is the topic; steers and answers never count", () => {
assert.equal(topicOf([userText("the water cycle")]), "the water cycle");
assert.equal(topicOf([]), null);
assert.equal(topicOf([userText("a"), userText("b")]), null);
// A quiz answer: tool-output part, no text — probing never breaks the gate.
const answer: UIMessage = {
id: "m_ans",
role: "user",
parts: [{ type: "tool-quiz", toolCallId: "t1", state: "output-available", input: {}, output: {} } as never],
};
assert.equal(topicOf([userText("topic"), answer, marker("data-probe-handoff", { chatId: "c" })]), "topic");
// Multi-part text joins into the topic.
assert.equal(topicOf([userText("a"), userText("")]), "a");
});
it("effectiveContextBudget: absent = the default (on), 0 = off, set = set", () => {
assert.equal(effectiveContextBudget(undefined), GRAPH_CONTEXT_TOKENS_DEFAULT);
assert.equal(effectiveContextBudget({}), GRAPH_CONTEXT_TOKENS_DEFAULT);
assert.equal(effectiveContextBudget({ graphContextTokens: 0 }), 0);
assert.equal(effectiveContextBudget({ graphContextTokens: 2048 }), 2048);
});
it("the decided knobs: default 1024, max 4096, step 128", () => {
assert.equal(GRAPH_CONTEXT_TOKENS_DEFAULT, 1024);
assert.equal(GRAPH_CONTEXT_TOKENS_MAX, 4096);
assert.equal(GRAPH_CONTEXT_TOKENS_STEP, 128);
});
it("contextToolCallId is deterministic per chat (the one-shot dedup key)", () => {
assert.equal(contextToolCallId("chat_abc"), "ctx_chat_abc");
});
});
+316
View File
@@ -0,0 +1,316 @@
/**
* Graph context injection — the runner + the wake integration
* (docs/vision-context-injection.md). The trigger gates, the failure
* modes, the one happy delivery (real wake pipeline, fake turn runner,
* scripted embedder), and the SILENT abort (the decided contrast with
* teacher-dispatched sub-agents, which abort with a steer).
*
* Cleanup follows tests/jobs.test.ts: files removed in finally/after.
*/
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as path from "node:path";
import { after, describe, it } from "node:test";
import { deliverJobResult, setTurnRunner } from "../src/server/jobs.ts";
import { abortJob } from "../src/server/jobs.ts";
import { persistTurn } from "../src/server/turn-service.ts";
import { startGraphContextInjection, runGraphContextJob, type GraphContextDeps } from "../src/agent/subagents/graph-context.ts";
import { chatStore } from "../src/store/chats.ts";
import { jobStore } from "../src/store/jobs.ts";
import { PATHS } from "../config.ts";
import type { EmbeddingsLedger, GraphNode, LedgerEvent } from "../src/core/contracts/graph.ts";
import type { JobRecord, SteerMessage } from "../src/core/contracts.ts";
const createdChats: string[] = [];
const createdJobs: string[] = [];
function trackChat(id: string) {
createdChats.push(id);
}
function trackJob(id: string) {
createdJobs.push(id);
}
after(() => {
for (const id of createdChats) {
try {
fs.unlinkSync(path.join(PATHS.chats, `${id}.json`));
} catch {
/* already gone */
}
}
for (const id of createdJobs) {
try {
fs.unlinkSync(path.join(PATHS.data, "jobs", `${id}.json`));
} catch {
/* already gone */
}
}
});
function waitFor(cond: () => boolean, timeoutMs = 8000, what = "condition"): Promise<void> {
return new Promise((resolve, reject) => {
const started = Date.now();
const tick = () => {
if (cond()) return resolve();
if (Date.now() - started > timeoutMs) return reject(new Error(`timeout waiting for ${what}`));
setTimeout(tick, 25);
};
tick();
});
}
function unit(i: number): number[] {
const v = new Array(8).fill(0);
v[i] = 1;
return v;
}
function node(id: string, statement: string): GraphNode {
return { id, name: id, statement, aliases: [], provenance: [], createdAt: "2026-09-14T00:00:00.000Z" };
}
/** A minimal in-memory graph store — the runner only reads. */
function fakeGraphStore(opts: {
vectors?: Record<string, number[]>;
nodes?: GraphNode[];
events?: LedgerEvent[];
model?: string;
dim?: number;
}): Pick<GraphContextDeps["graphStore"], "readNodes" | "readEvents" | "readEmbeddings"> {
const ledger: EmbeddingsLedger = {
model: opts.model ?? "test-embed",
dim: opts.dim ?? 8,
vectors: opts.vectors ?? {},
clusters: [],
updatedAt: "2026-09-14T00:00:00.000Z",
};
return {
readNodes: () => opts.nodes ?? [],
readEvents: () => opts.events ?? [],
readEmbeddings: () => ledger,
};
}
/** A chat at session start: exactly one typed message (the topic). */
function newTopicChat(label: string, settings?: Record<string, unknown>): { id: string } {
const chat = chatStore.createChat(`Test: ${label}`);
trackChat(chat.id);
chatStore.saveMessages(chat.id, [
{ id: "u1", role: "user", parts: [{ type: "text", text: "the water cycle" }] },
] as never);
if (settings) chatStore.saveSettings(chat.id, settings as never);
return { id: chat.id };
}
/** The scripted embedder: deterministic query vectors, recorded topics. */
function fakeEmbedder(vec: number[] = unit(0)) {
const topics: string[] = [];
return {
topics,
embedder: {
model: "test-embed",
dim: 8,
embedQuery: async (text: string) => {
topics.push(text);
return vec;
},
},
};
}
function deps(
graph: Pick<GraphContextDeps["graphStore"], "readNodes" | "readEvents" | "readEmbeddings">,
embedder: GraphContextDeps["embedder"],
deliver: (steer: SteerMessage) => Promise<void>,
): GraphContextDeps {
return { chatStore, jobStore, graphStore: graph, embedder, deliver };
}
describe("startGraphContextInjection — the one-shot gates", () => {
it("starts at session start: job kind graph-context, deterministic toolCallId, runner runs to delivery", async () => {
const { id: chatId } = newTopicChat("injection happy gate");
const graph = fakeGraphStore({
vectors: { n1: unit(0) },
nodes: [node("n1", "Water evaporates from oceans.")],
});
const { embedder, topics } = fakeEmbedder();
const delivered: SteerMessage[] = [];
const d = deps(graph, embedder, async (steer) => {
delivered.push(steer);
});
const job = startGraphContextInjection(d, chatId);
assert.ok(job, "a chat at session start with budget on starts the injection");
trackJob(job.id);
assert.equal(job.kind, "graph-context");
assert.equal(job.toolCallId, `ctx_${chatId}`);
await waitFor(() => delivered.length > 0, 8000, "delivery");
assert.deepEqual(topics, ["the water cycle"], "the topic is the session's only typed message");
const steer = delivered[0]!;
assert.equal(steer.id, `steer_ctx_${chatId}`);
assert.equal(steer.parts.length, 1);
assert.equal(steer.parts[0]!.type, "data-graph-context");
// One shot: a second trigger does nothing (job exists).
assert.equal(startGraphContextInjection(d, chatId), null);
});
it("budget 0 (off) never starts; a session past its start never injects", async () => {
const { id: off } = newTopicChat("injection off", { graphContextTokens: 0 });
const { id: rolling } = (() => {
const chat = chatStore.createChat("Test: two typed messages");
trackChat(chat.id);
chatStore.saveMessages(chat.id, [
{ id: "u1", role: "user", parts: [{ type: "text", text: "topic" }] },
{ id: "u2", role: "user", parts: [{ type: "text", text: "a second message" }] },
] as never);
return { id: chat.id };
})();
const graph = fakeGraphStore({ vectors: { n1: unit(0) }, nodes: [node("n1", "S.")] });
const d = deps(graph, fakeEmbedder().embedder, async () => {});
assert.equal(startGraphContextInjection(d, off), null, "0 budget = off");
assert.equal(startGraphContextInjection(d, rolling), null, "no retroactive injection");
assert.equal(jobStore.listJobs(off).length, 0);
assert.equal(jobStore.listJobs(rolling).length, 0);
assert.equal(startGraphContextInjection(d, "chat_missing"), null, "unknown chat");
});
it("an ERRORED context job still blocks re-injection (one shot means one shot)", async () => {
const { id: chatId } = newTopicChat("injection error one-shot");
const graph = fakeGraphStore({ vectors: {} }); // empty ledger → the run errors
const d = deps(graph, fakeEmbedder().embedder, async () => {});
const job = startGraphContextInjection(d, chatId);
assert.ok(job);
trackJob(job.id);
await waitFor(() => jobStore.getJob(job.id)!.status === "error", 8000, "job errors");
assert.match(jobStore.getJob(job.id)!.error ?? "", /no embeddings yet/);
// Re-trigger with a now-populated ledger: still nothing.
const populated = deps(
fakeGraphStore({ vectors: { n1: unit(0) }, nodes: [node("n1", "S.")] }),
fakeEmbedder().embedder,
async () => {},
);
assert.equal(startGraphContextInjection(populated, chatId), null);
});
});
describe("runGraphContextJob — failure modes are honest errors, never phantom deliveries", () => {
it("a stale ledger (model/dim mismatch) errors with the parity reason", async () => {
const { id: chatId } = newTopicChat("injection stale ledger");
const chat = chatStore.createChat(`Test: ${chatId}`); // placeholder to satisfy lint-free compile
trackChat(chat.id);
const job = jobStore.createJob({ kind: "graph-context", chatId, toolCallId: `ctx_${chatId}` });
trackJob(job.id);
// Ledger stamped with a DIFFERENT model than the embedder.
const d = deps(fakeGraphStore({ vectors: { n1: unit(0) }, model: "other-model" }), fakeEmbedder().embedder, async () => {});
await runGraphContextJob(d, job.id);
const got = jobStore.getJob(job.id)!;
assert.equal(got.status, "error");
assert.match(got.error ?? "", /stale/);
});
it("nothing fitting the budget errors rather than delivering an empty block", async () => {
// Budget below the framing overhead: nothing can fit, ever.
const { id: chatId } = newTopicChat("injection empty selection", { graphContextTokens: 10 });
const job = jobStore.createJob({ kind: "graph-context", chatId, toolCallId: `ctx_${chatId}` });
trackJob(job.id);
// Query orthogonal to every vector; budget can hold nothing.
const graph = fakeGraphStore({ vectors: { n1: unit(7) }, nodes: [node("n1", "A very long statement indeed.")] });
const d = deps(graph, fakeEmbedder(unit(0)).embedder, async () => {});
await runGraphContextJob(d, job.id);
const got = jobStore.getJob(job.id)!;
assert.equal(got.status, "error");
assert.match(got.error ?? "", /nothing relevant fit the budget/);
});
});
describe("the injection + the wake pipeline (end to end, fake turn runner)", () => {
it("delivers through the wake: the record gains the marker steer, the job flips done, the dock kind rides along", async () => {
const { id: chatId } = newTopicChat("injection wake delivery");
const graph = fakeGraphStore({
vectors: { n1: unit(0), n2: unit(0) },
nodes: [node("n1", "Water evaporates from oceans."), node("n2", "Condensation forms clouds.")],
events: [
{ nodeId: "n1", kind: "observation", chatId: "chat_old", at: "2026-09-10T00:00:00Z", note: "solid" },
],
});
const fired: { chatId: string; last: SteerMessage }[] = [];
setTurnRunner(async (cid, messages) => {
// Mimic the real wake turn: write-ahead persistence of the incoming
// messages (the handler does this), then 200.
await persistTurn(chatStore, cid, messages as never, false);
fired.push({ chatId: cid, last: messages[messages.length - 1] as SteerMessage });
return 200;
});
const d = deps(graph, fakeEmbedder().embedder, deliverJobResult);
const job = startGraphContextInjection(d, chatId);
assert.ok(job);
trackJob(job.id);
await waitFor(() => (jobStore.getJob(job.id)?.status ?? "running") === "done", 8000, "wake flipped the job");
const got = jobStore.getJob(job.id)!;
assert.equal(got.status, "done");
assert.equal(got.activity, "delivered");
// The transcript carries the marker steer (audit trail + dedup key).
const record = chatStore.getChat(chatId)!;
const steerMsg = record.messages.find((m) => m.id === `steer_ctx_${chatId}`);
assert.ok(steerMsg, "the steer persisted to the record");
const part = steerMsg.parts[0] as { type: string; data: { propositions?: unknown[] } };
assert.equal(part.type, "data-graph-context");
assert.ok(part.data.propositions!.length >= 1);
// The server-side turn fired once, with the steer as its last input.
assert.equal(fired.length, 1);
assert.equal(fired[0]!.chatId, chatId);
assert.equal(fired[0]!.last.id, `steer_ctx_${chatId}`);
});
it("aborts SILENTLY: the record flips, the teacher is never told (nothing was promised)", async () => {
const { id: chatId } = newTopicChat("injection abort");
// A hanging embedder — killed mid-call, like the research abort test.
let release: (() => void) | null = null;
const hanging = new Promise<void>((resolve) => {
release = resolve;
});
const embedder = {
model: "test-embed",
dim: 8,
embedQuery: () => hanging.then(() => unit(0)),
};
const fired: number[] = [];
setTurnRunner(async () => {
fired.push(1);
return 200;
});
const graph = fakeGraphStore({ vectors: { n1: unit(0) }, nodes: [node("n1", "S.")] });
const d = deps(graph, embedder, deliverJobResult);
const job = startGraphContextInjection(d, chatId);
assert.ok(job);
trackJob(job.id);
await waitFor(() => jobStore.getJob(job.id)!.activity === "embedding topic", 8000, "run started");
const outcome = abortJob(job.id);
assert.ok(outcome.ok);
const got = jobStore.getJob(job.id)!;
assert.equal(got.status, "error");
assert.equal(got.error, "Aborted by learner");
release!(); // unwind the hanging call; the abort check exits silently
await waitFor(() => fired.length >= 0, 50, "settle");
await new Promise((r) => setTimeout(r, 150));
assert.equal(fired.length, 0, "NO abort steer — the decided contrast with sub-agent jobs");
assert.equal(jobStore.getJob(job.id)!.status, "error", "terminal");
// And the chat record never gained a context steer.
const record = chatStore.getChat(chatId)!;
assert.equal(
record.messages.some((m) => m.id === `steer_ctx_${chatId}`),
false,
);
});
});
+32
View File
@@ -85,4 +85,36 @@ describe("record-adapter: system message flattening", () => {
]);
assert.equal(out.length, 0, "no model face at all — skipped");
});
it("the graph-context steer flattens to the canonical prior-knowledge block", () => {
const out = recordToPiMessages([
userParts([
{
type: "data-graph-context",
id: "ctx1",
data: {
chatId: "chat_1",
budget: 1024,
tokens: 64,
propositions: [
{ id: "n1", statement: "Water boils at 100°C.", level: "solid" },
{ id: "n2", statement: "Evaporation cools things.", level: null },
],
},
},
]),
]);
assert.equal(out.length, 1, "one user message — the marker part is the model face");
const got = texts(out);
assert.equal(got.length, 1);
assert.match(got[0]!, /Prior-knowledge context/);
assert.match(got[0]!, /\[solid\] Water boils at 100°C\./);
});
it("a malformed graph-context part has no model face — the message is skipped wholesale", () => {
const out = recordToPiMessages([
userParts([{ type: "data-graph-context", id: "ctx2", data: { chatId: "chat_1" } }]),
]);
assert.equal(out.length, 0, "parse-don't-cast: no validated data, no face");
});
});
+12
View File
@@ -152,6 +152,18 @@ describe("activity section render", () => {
assert.match(html, /activity-total-cost[^>]*>—</);
});
it("renders a graph-context job as 'Knowledge context' — the dock's fourth kind", () => {
const html = renderToStaticMarkup(
<ActivitySection
feed={{ jobs: [job({ id: "jctx", kind: "graph-context", activity: "selecting propositions", title: "Water cycle" })], extractions: [] }}
/>,
);
assert.match(html, /data-testid="activity-blob-job"/);
assert.match(html, /Knowledge context/);
assert.match(html, /selecting propositions/);
assert.match(html, /data-testid="activity-abort"/, "END kills the injection like any job");
});
it("shows total running cost when jobs are priced", () => {
const usage = {
model: "z-ai/glm-5.3-flash",
+35
View File
@@ -84,6 +84,41 @@ describe("DraftShell — the sessionless surface", () => {
assert.ok(/rounded-2xl[^>]*pointer-events-auto|pointer-events-auto[^>]*rounded-2xl/.test(html));
});
it("renders the knowledge-context slider at the decided default (absent settings = on, 1024)", () => {
const html = renderToStaticMarkup(
<DraftShell
busy={false}
text=""
onChange={() => {}}
onSend={() => {}}
settings={undefined}
onSettingsSaved={() => {}}
/>,
);
assert.ok(html.includes('data-testid="graph-context-control"'));
// The slider's default position: 1024 of 4096, step 128 (decided).
assert.ok(html.includes('min="0"') && html.includes('max="4096"') && html.includes('step="128"'));
assert.ok(html.includes("1k tokens"), "the readout shows the default budget, not 0 — default is ON");
assert.ok(html.includes("Knowledge context"), "the control is labeled");
// Absent settings render the default — never 'off'.
assert.ok(!html.includes(">off<"));
});
it("an explicit 0 renders as off — the learner turned the graph off for this session", () => {
const html = renderToStaticMarkup(
<DraftShell
busy={false}
text=""
onChange={() => {}}
onSend={() => {}}
settings={{ graphContextTokens: 0 }}
onSettingsSaved={() => {}}
/>,
);
assert.ok(html.includes('data-testid="graph-context-value"'));
assert.ok(html.includes(">off<"));
});
it("no chat id anywhere — nothing in the markup references a session", () => {
const html = renderToStaticMarkup(
<DraftShell