1
import type { Context } from "@earendil-works/chord";2
import { createModels, type Message } from "@earendil-works/pi-ai";3
import {4
type ContextView,5
createRegistry,6
defineTask,7
type EntryDraft,8
type EntryId,9
type EntryRecord,10
Harness,11
type HarnessSettings,12
MemoryStorage,13
type Storage,14
} from "@earendil-works/pi-durable";15
import { afterEach, describe, expect, it, vi } from "vitest";16
import { addTask, assistant, describeMessage, openHarness, system, toolResult, user } from "./harness-support.ts";17
import { context } from "./session-support.ts";19
async function setup() {20
const { harness } = await openHarness(new MemoryStorage());21
const root = await harness.root(context);22
const append = (draft: EntryDraft): Promise<EntryRecord> =>23
root.commit((tx) => tx.appendEntry(root.id, draft), context);24
const message = (model: Message, kind = "message"): Promise<EntryRecord> => append({ kind, model: [model] });25
return { harness, root, append, message };26
}28
/** A Harness over MemoryStorage that counts scanned entry rows, with a 21-entry root transcript. */29
async function countingSetup(options: { readonly settings?: HarnessSettings; readonly now?: () => number } = {}) {30
const scanned = { rows: 0 };31
/** When set, the next range scan waits for it; bounds probes (one row, on the Session line) do not. */32
const hold: { scan?: Promise<void> } = {};33
const memory = new MemoryStorage();34
const storage = new Proxy<Storage>(memory, {35
get(target, key) {36
const value: unknown = Reflect.get(target, key, target);37
if (key === "scanEntries") {38
return async (...args: Parameters<Storage["scanEntries"]>) => {39
const held = args[1] > 1 ? hold.scan : undefined;40
if (held !== undefined) hold.scan = undefined;41
await held;42
const page = await target.scanEntries(...args);43
scanned.rows += page.items.length;44
return page;45
};46
}47
return typeof value === "function" ? value.bind(target) : value;48
},49
});50
const registry = createRegistry();51
const harness = await Harness.open(storage, { models: createModels(), registry, ...options }, context);52
const root = await harness.root(context);53
const first = await root.commit(54
(tx) => tx.appendEntry(root.id, { kind: "message", model: [user("first")] }),55
context,56
);57
for (let index = 0; index < 20; index++) {58
await root.commit(59
(tx) => tx.appendEntry(root.id, { kind: "message", model: [assistant(`old ${index}`)] }),60
context,61
);62
}63
return { harness, registry, root, first, scanned, hold };64
}66
function ids(entries: readonly EntryRecord[]): EntryId[] {67
return entries.map((entry) => entry.id);68
}70
afterEach(() => {71
vi.useRealTimers();72
});74
describe("conversation context", () => {75
it("returns the whole transcript without a head and excludes model-less entries from messages", async () => {76
const { root, append, message } = await setup();77
const first = await message(user("hi"));78
const note = await append({ kind: "note", data: { text: "display only" } });79
const answer = await message(assistant("hello"));80
const view = await root.context(context);81
expect(view.head).toBeUndefined();82
expect(ids(view.entries)).toEqual([first.id, note.id, answer.id]);83
expect(view.messages.map(describeMessage)).toEqual(["user:hi", "assistant:hello"]);84
});86
it("excludes aborted, error, and deferred assistant messages but keeps their raw entries", async () => {87
const { root, message } = await setup();88
await message(user("q"));89
const aborted = await message(assistant("partial", { stopReason: "aborted" }));90
await message(assistant("failed", { stopReason: "error" }));91
await message(assistant("later", { stopReason: "deferred" }));92
await message(assistant("done", { stopReason: "length" }));93
const view = await root.context(context);94
expect(view.entries).toHaveLength(5);95
expect(view.entries[1]!.id).toBe(aborted.id);96
expect(view.messages.map(describeMessage)).toEqual(["user:q", "assistant:done"]);97
});99
it("resolves self heads and uses the newest head marker", async () => {100
const { root, append, message } = await setup();101
await message(user("old"));102
const reset = await append({ kind: "reset", head: "self", model: [user("fresh start")] });103
expect(reset.head).toBe(reset.id);104
const after = await message(assistant("after reset"));105
let view = await root.context(context);106
expect(view.head?.id).toBe(reset.id);107
expect(ids(view.entries)).toEqual([reset.id, after.id]);108
expect(view.messages.map(describeMessage)).toEqual(["user:fresh start", "assistant:after reset"]);110
// A compaction summary heads an earlier kept entry; older head markers in range drop out.111
const summary = await append({ kind: "summary", head: after.id, model: [user("summary")] });112
const tail = await message(user("next"));113
view = await root.context(context);114
expect(view.head?.id).toBe(summary.id);115
expect(ids(view.entries)).toEqual([summary.id, after.id, tail.id]);116
expect(view.messages.map(describeMessage)).toEqual(["user:summary", "assistant:after reset", "user:next"]);117
});119
it("applies the newest edit per target within the active range", async () => {120
const { root, append, message } = await setup();121
const first = await message(user("first"));122
const second = await message(user("second"));123
await append({ kind: "edit", edits: [{ target: first.id, action: "replace", messages: [user("first v2")] }] });124
await append({ kind: "edit", edits: [{ target: first.id, action: "replace", messages: [user("first v3")] }] });125
await append({ kind: "edit", edits: [{ target: second.id, action: "omit" }] });126
let view = await root.context(context);127
expect(view.entries).toHaveLength(5);128
expect(view.messages.map(describeMessage)).toEqual(["user:first v3"]);130
// Edits before the active range no longer apply.131
const reset = await append({ kind: "reset", head: second.id });132
view = await root.context(context);133
expect(view.head?.id).toBe(reset.id);134
expect(view.messages.map(describeMessage)).toEqual([]);135
await append({ kind: "edit", edits: [{ target: second.id, action: "replace", messages: [user("second v2")] }] });136
view = await root.context(context);137
expect(view.messages.map(describeMessage)).toEqual(["user:second v2"]);138
});140
it("keeps positional system messages and orders tool results by call order", async () => {141
const { root, message, append } = await setup();142
await message(system({ preamble: "You help." }), "pi.system");143
await message(user("run tools"));144
await message(assistant("calling", { calls: ["b", "a"] }));145
await message(toolResult("a"));146
await append({ kind: "pi.system", model: [system({ cwd: "/repo" })] });147
await message(toolResult("b"));148
await message(toolResult("zz"));149
await message(assistant("done"));150
const view = await root.context(context);151
expect(view.messages.map(describeMessage)).toEqual([152
"system:preamble",153
"user:run tools",154
"assistant:calling",155
"result:b:result b",156
"result:a:result a",157
"system:cwd",158
"assistant:done",159
]);160
});162
// #10542163
it("leads with a system message that only user messages precede, and keeps later ones in place", async () => {164
const { root, message, append } = await setup();165
await message(user("first"));166
await message(user("steered"));167
await message(system({ preamble: "You help." }), "pi.system");168
await message(assistant("answer"));169
await message(user("next"));170
await message(system({ cwd: "/repo" }), "pi.system");171
let view = await root.context(context);172
expect(view.messages.map(describeMessage)).toEqual([173
"system:preamble",174
"user:first",175
"user:steered",176
"assistant:answer",177
"user:next",178
"system:cwd",179
]);180
// Stored order and contributions stay as committed.181
expect(view.contributions.flat().map(describeMessage).slice(0, 3)).toEqual([182
"user:first",183
"user:steered",184
"system:preamble",185
]);187
// After a reset, the baseline written after the handoff leads too.188
await append({ kind: "reset", head: "self", model: [user("handoff")] });189
await message(system({ preamble: "Baseline." }), "pi.system");190
view = await root.context(context);191
expect(view.messages.map(describeMessage)).toEqual(["system:preamble", "user:handoff"]);192
});194
// #10904195
it("leads with the baseline after a compaction that keeps assistant messages", async () => {196
const { root, message, append } = await setup();197
await message(user("old"));198
const kept = await message(user("kept"));199
await message(assistant("calling", { calls: ["a"] }));200
await message(toolResult("a"));201
await message(assistant("answer"));202
await append({ kind: "summary", head: kept.id, model: [user("summary")] });203
await message(user("next"));204
await message(system({ preamble: "Baseline." }), "pi.system");205
let view = await root.context(context);206
expect(view.messages.map(describeMessage)).toEqual([207
"system:preamble",208
"user:summary",209
"user:kept",210
"assistant:calling",211
"result:a:result a",212
"assistant:answer",213
"user:next",214
]);216
// Later system messages stay in place.217
await message(assistant("done"));218
await message(system({ cwd: "/repo" }), "pi.system");219
view = await root.context(context);220
expect(view.messages.map(describeMessage).slice(0, 2)).toEqual(["system:preamble", "user:summary"]);221
expect(view.messages.map(describeMessage).slice(-2)).toEqual(["assistant:done", "system:cwd"]);222
});224
// #10904225
it("leads with a baseline written after the first answers, when the agent had no section or tool before", async () => {226
const { root, message } = await setup();227
await message(user("first"), "pi.user");228
await message(assistant("answer"), "pi.assistant");229
await message(user("next"), "pi.user");230
await message(system({ plan: "Plan." }), "pi.system");231
const view = await root.context(context);232
expect(view.messages.map(describeMessage)).toEqual([233
"system:plan",234
"user:first",235
"assistant:answer",236
"user:next",237
]);238
});240
// #10904241
it("keeps system messages other than the baseline in place once an assistant message precedes them", async () => {242
const { root, message, append } = await setup();243
await message(user("first"));244
await message(assistant("answer"));245
// Another kind's system message is positional; the baseline after it is not the first system message.246
await message(system({ note: "From here on." }), "host.note");247
await message(system({ preamble: "Baseline." }), "pi.system");248
let view = await root.context(context);249
expect(view.messages.map(describeMessage)).toEqual([250
"user:first",251
"assistant:answer",252
"system:note",253
"system:preamble",254
]);256
// After a compaction that keeps the other kind's system message, the new baseline does not move ahead of it.257
const kept = await message(user("kept"));258
await message(assistant("kept answer"));259
await message(system({ mode: "plan" }), "host.note");260
await append({ kind: "summary", head: kept.id, model: [user("summary")] });261
await message(user("next"));262
await message(system({ preamble: "Baseline." }), "pi.system");263
view = await root.context(context);264
expect(view.messages.map(describeMessage)).toEqual([265
"user:summary",266
"user:kept",267
"assistant:kept answer",268
"system:mode",269
"user:next",270
"system:preamble",271
]);272
});274
// #10904275
it("does not lead with a first system entry written after another system message, even once that is omitted", async () => {276
const { root, message, append } = await setup();277
const host = await message(system({ legacy: "Use the legacy format." }), "host.system");278
await message(user("first"));279
await message(assistant("answer"));280
// Generation wrote this entry against the host's message: it only removes a section, so it is no baseline.281
await message(system({ legacy: null }), "pi.system");282
await append({ kind: "edit", edits: [{ target: host.id, action: "omit" }] });283
let view = await root.context(context);284
expect(view.messages.map(describeMessage)).toEqual(["user:first", "assistant:answer", "system:legacy"]);286
// The same holds for a system message an edit put before it.287
const other = await setup();288
const first = await other.message(user("first"));289
await other.append({290
kind: "edit",291
edits: [{ target: first.id, action: "replace", messages: [user("first"), system({ note: "Note." })] }],292
});293
await other.message(assistant("answer"));294
await other.message(system({ note: null }), "pi.system");295
await other.append({ kind: "edit", edits: [{ target: first.id, action: "replace", messages: [user("first")] }] });296
view = await other.root.context(context);297
expect(view.messages.map(describeMessage)).toEqual(["user:first", "assistant:answer", "system:note"]);298
});300
// #10904301
it("does not lead with a retained, edited, or later system entry in place of the baseline", async () => {302
const { root, message, append } = await setup();303
const kept = await message(user("kept"));304
await message(assistant("answer"));305
const retained = await message(system({ cwd: "/repo" }), "pi.system");306
// Before generation writes the baseline after the head marker, a retained system entry stays in place.307
await append({ kind: "summary", head: kept.id, model: [user("summary")] });308
await message(user("next"));309
let view = await root.context(context);310
expect(view.messages.map(describeMessage)).toEqual([311
"user:summary",312
"user:kept",313
"assistant:answer",314
"system:cwd",315
"user:next",316
]);318
// The baseline omits the retained entry, as generation writes it, and leads.319
const baseline = await append({320
kind: "pi.system",321
model: [system({ preamble: "Baseline." })],322
edits: [{ target: retained.id, action: "omit" }],323
});324
await message(assistant("done"));325
await message(system({ preamble: null }), "pi.system");326
view = await root.context(context);327
expect(view.messages.map(describeMessage)).toEqual([328
"system:preamble",329
"user:summary",330
"user:kept",331
"assistant:answer",332
"user:next",333
"assistant:done",334
"system:preamble",335
]);337
// An omitted baseline leaves no message to lead; the delta after it is not a baseline and stays in place.338
await append({ kind: "edit", edits: [{ target: baseline.id, action: "omit" }] });339
view = await root.context(context);340
expect(view.messages.map(describeMessage)).toEqual([341
"user:summary",342
"user:kept",343
"assistant:answer",344
"user:next",345
"assistant:done",346
"system:preamble",347
]);349
// A replacement of the baseline is not one either.350
await append({351
kind: "edit",352
edits: [{ target: baseline.id, action: "replace", messages: [system({ other: "Other." })] }],353
});354
view = await root.context(context);355
expect(view.messages.map(describeMessage)).toEqual([356
"user:summary",357
"user:kept",358
"assistant:answer",359
"user:next",360
"system:other",361
"assistant:done",362
"system:preamble",363
]);364
});366
it("synthesizes missing tool results after a fork and drops results cut from their call", async () => {367
const { root, message } = await setup();368
await message(user("go"));369
const call = await message(assistant("calling", { calls: ["x", "y"] }));370
await message(toolResult("x"));371
const second = await message(toolResult("y"));372
const child = await root.fork(call.id, { ownership: { kind: "ownerless" } }, context);373
const childView = await child.context(context);374
expect(childView.messages.map(describeMessage)).toEqual([375
"user:go",376
"assistant:calling",377
"result:x:error",378
"result:y:error",379
]);380
const missing = childView.messages[2]!;381
expect(missing).toMatchObject({382
role: "toolResult",383
toolName: "tool-x",384
details: { reason: "missing_result" },385
});387
// A head between a call and its results leaves stray results that are not sent.388
await root.commit((tx) => tx.appendEntry(root.id, { kind: "reset", head: second.id }), context);389
const parentView = await root.context(context);390
expect(parentView.messages.map(describeMessage)).toEqual([]);391
expect(parentView.entries.map((entry) => entry.kind)).toEqual(["reset", "message"]);392
});394
// #10512395
it("reads the context as of an earlier entry, as a fork at that entry starts", async () => {396
const { root, append, message } = await setup();397
const first = await message(user("first"));398
const call = await message(assistant("calling", { calls: ["x", "y"] }));399
const result = await message(toolResult("x"));400
await message(toolResult("y"));401
const edit = await append({402
kind: "edit",403
edits: [{ target: first.id, action: "replace", messages: [user("first v2")] }],404
});405
const reset = await append({ kind: "reset", head: "self", model: [user("fresh start")] });406
const tail = await message(assistant("after reset"));408
for (const at of [first, call, result, edit, reset, tail]) {409
const fork = await root.fork(at.id, { ownership: { kind: "ownerless" } }, context);410
expect(await root.context(context, { at: at.id })).toEqual(await fork.context(context));411
}412
// Stepped back before the edit and the reset: neither applies, and a cut call gets synthesized results.413
expect((await root.context(context, { at: call.id })).messages.map(describeMessage)).toEqual([414
"user:first",415
"assistant:calling",416
"result:x:error",417
"result:y:error",418
]);419
expect(await root.context(context, { at: tail.id })).toEqual(await root.context(context));420
expect(await root.context(context, {})).toEqual(await root.context(context));422
const other = await root.fork(first.id, { ownership: { kind: "ownerless" } }, context);423
await expect(other.context(context, { at: tail.id })).rejects.toThrow("is not visible");424
});426
it("extends a task's context read with only newer entries", async () => {427
const { harness, registry, root, first, scanned } = await countingSetup();428
const Reads = defineTask<Record<string, never>, { phase: "run" }, null>({429
name: "test.context-reads",430
version: 1,431
initial: () => ({ phase: "run" }),432
phases: {433
run: async (_task, runtime, taskContext) => {434
const write = (draft: EntryDraft) =>435
runtime.commit(async (tx) => {436
await tx.appendEntry(root.id, draft);437
return undefined;438
}, taskContext);439
const read = async (at?: EntryId): Promise<{ view: ContextView; rows: number }> => {440
const before = scanned.rows;441
const view = await runtime.context(root.id, taskContext, { at });442
return { view, rows: scanned.rows - before };443
};444
const initial = await read();445
expect(initial.view).toEqual(await root.context(taskContext));447
// Three new entries: the bounds probe reads one row, the extension the three new ones.448
await write({ kind: "message", model: [user("new")] });449
await write({ kind: "note", data: { text: "display only" } });450
await write({ kind: "message", model: [assistant("answer")] });451
const extended = await read();452
expect(extended.rows).toBe(4);453
expect(extended.view).toEqual(await root.context(taskContext));455
// A newer edit of an older entry applies to the extended range.456
await write({ kind: "edit", edits: [{ target: first.id, action: "omit" }] });457
const edited = await read();458
expect(edited.rows).toBe(2);459
expect(edited.view).toEqual(await root.context(taskContext));460
expect(edited.view.messages.map(describeMessage)).not.toContain("user:first");462
// An earlier cutoff reuses the range.463
const cutoff = await read(extended.view.entries.at(-1)!.id);464
expect(cutoff.rows).toBe(0);465
expect(cutoff.view).toEqual(extended.view);467
// A new head marker changes the range: read it whole.468
await write({ kind: "reset", head: "self", model: [user("fresh")] });469
const reset = await read();470
expect(reset.view).toEqual(await root.context(taskContext));471
expect(reset.view.messages.map(describeMessage)).toEqual(["user:fresh"]);473
await runtime.commit(474
() => ({ status: "terminal", outcome: { status: "completed", result: null } }),475
taskContext,476
);477
},478
},479
abort: async (_task, runtime, taskContext) => {480
await runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted" } }), taskContext);481
},482
});483
addTask(registry, Reads);484
const id = await harness.commit(485
(tx) => tx.createTask(Reads, {}, { ownership: { kind: "conversation" }, conversationId: root.id }),486
context,487
);488
harness.resume();489
const settled = await harness.waitForTask(id, context);490
expect(settled.state.outcome).toEqual({ status: "completed", result: null });491
await harness.close(context);492
});494
it("keeps a conversation's context read across its tasks and for the retention period once idle", async () => {495
let clock = 1_000;496
const { harness, registry, root, scanned } = await countingSetup({ now: () => clock });497
const rows: Record<string, number> = {};498
const read = async (name: string, load: () => Promise<ContextView>, taskContext: Context) => {499
const before = scanned.rows;500
const view = await load();501
rows[name] = scanned.rows - before;502
expect(view).toEqual(await root.context(taskContext));503
};504
const Child = defineTask<Record<string, never>, { phase: "run" }, null>({505
name: "test.context-child",506
version: 1,507
initial: () => ({ phase: "run" }),508
phases: {509
run: async (_task, runtime, taskContext) => {510
await runtime.commit(async (tx) => {511
await tx.appendEntry(root.id, { kind: "message", model: [user("from child")] });512
return undefined;513
}, taskContext);514
await read("child", () => runtime.context(root.id, taskContext), taskContext);515
await runtime.commit(() => DONE, taskContext);516
},517
},518
abort: async (_task, runtime, taskContext) => {519
await runtime.commit(() => ABORTED, taskContext);520
},521
});522
const Parent = defineTask<Record<string, never>, { phase: "start" } | { phase: "after" }, null>({523
name: "test.context-parent",524
version: 1,525
initial: () => ({ phase: "start" }),526
phases: {527
start: async (_task, runtime, taskContext) => {528
await read("parent", () => runtime.context(root.id, taskContext), taskContext);529
await runtime.commit(async (tx) => {530
const child = await tx.createTask(531
Child,532
{},533
{ ownership: { kind: "task", taskId: runtime.taskId }, conversationId: root.id },534
);535
return { status: "waiting", checkpoint: { phase: "after" }, on: [child], policy: "allSettled" };536
}, taskContext);537
},538
after: async (_task, runtime, taskContext) => {539
await read("after", () => runtime.context(root.id, taskContext), taskContext);540
await runtime.commit(() => DONE, taskContext);541
},542
},543
abort: async (_task, runtime, taskContext) => {544
await runtime.commit(() => ABORTED, taskContext);545
},546
});547
const Probe = probeTask(read);548
for (const task of [Child, Parent, Probe]) addTask(registry, task);549
harness.resume();550
const options = { ownership: { kind: "conversation" }, conversationId: root.id } as const;551
const parent = await harness.commit((tx) => tx.createTask(Parent, {}, options), context);552
expect((await harness.waitForTask(parent, context)).state.outcome).toEqual(DONE.outcome);553
await root.waitForIdle(context);554
const probe = async (name: string) => {555
const id = await harness.commit((tx) => tx.createTask(Probe, { name }, options), context);556
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);557
await root.waitForIdle(context);558
};559
await probe("idle");560
clock += 600_000;561
await probe("expired");562
// Bounds probes read one row each. The child scans its own new entry; the waiting parent's later invocation and563
// the probe within the retention period scan nothing new. After it, the probe reads the whole transcript again.564
expect(rows).toEqual({ parent: 22, child: 2, after: 1, idle: 1, expired: 23 });565
await harness.close(context);566
});568
it("derives the same view from extended reads as from whole reads", async () => {569
const { harness, registry, root } = await countingSetup();570
// Deterministic pseudo-random transcript (32-bit LCG, high bits): calls and results in any order, missing and571
// stray results, excluded stop reasons, system entries, notes, edits of earlier entries, and head markers.572
let seed = 7;573
const random = (n: number) => {574
seed = (Math.imul(seed, 1_664_525) + 1_013_904_223) >>> 0;575
return Math.floor((seed / 2 ** 32) * n);576
};577
const seen = new Map<string, number>();578
const count = (category: string) => seen.set(category, (seen.get(category) ?? 0) + 1);579
const Steps = defineTask<Record<string, never>, { phase: "run" }, null>({580
name: "test.context-steps",581
version: 1,582
initial: () => ({ phase: "run" }),583
phases: {584
run: async (_task, runtime, taskContext) => {585
const written: EntryRecord[] = [];586
const calls: string[] = [];587
let next = 0;588
const draft = (): EntryDraft => {589
const pick = random(14);590
if (pick < 3) {591
count("user");592
return { kind: "message", model: [user(`u${next++}`)] };593
}594
if (pick < 5) {595
const ids = Array.from({ length: random(3) }, () => `c${next++}`);596
calls.push(...ids);597
const stopReason = (["aborted", "error", "deferred"] as const)[random(9)];598
count(stopReason ?? "assistant");599
return {600
kind: "message",601
model: [assistant(`a${next++}`, { calls: ids, ...(stopReason ? { stopReason } : {}) })],602
};603
}604
if (pick < 8) {605
const matched = calls.length > 0 && random(5) > 0;606
count(matched ? "result" : "stray result");607
const id = matched ? calls.splice(random(calls.length), 1)[0]! : `stray${next++}`;608
return { kind: "message", model: [toolResult(id)] };609
}610
if (pick < 9) {611
// `pi.system` entries can be the baseline that leads the context (#10904).612
const kind = random(2) === 0 ? "pi.system" : "message";613
count(kind === "pi.system" ? "baseline system" : "system");614
return { kind, model: [system({ s: `v${next++}` })] };615
}616
if (pick < 10) {617
count("note");618
return { kind: "note", data: { n: next++ } };619
}620
const target = written[random(written.length)];621
if (pick < 12 && target !== undefined) {622
const omit = random(2) === 0;623
count(omit ? "omit" : "replace");624
const action = omit625
? { action: "omit" as const }626
: { action: "replace" as const, messages: [user(`r${next++}`)] };627
return { kind: "edit", edits: [{ target: target.id, ...action }] };628
}629
if (pick < 13 && target !== undefined) {630
count("head");631
return { kind: "summary", head: target.id, model: [user(`h${next++}`)] };632
}633
count("user");634
return { kind: "message", model: [user(`u${next++}`)] };635
};636
const append = (conversationId: typeof root.id) =>637
runtime.commit(async (tx) => {638
const added = 1 + random(3);639
for (let index = 0; index < added; index++) {640
written.push(await tx.appendEntry(conversationId, draft()));641
}642
return undefined;643
}, taskContext);644
for (let step = 0; step < 150; step++) {645
await append(root.id);646
const whole = await root.context(taskContext);647
expect(await runtime.context(root.id, taskContext)).toEqual(whole);648
const contributed = whole.contributions.flat();649
const first = contributed.findIndex((message) => message.role === "system");650
if (651
first > 0 &&652
whole.messages[0] === contributed[first] &&653
contributed.slice(0, first).some((message) => message.role === "assistant")654
) {655
count("baseline past assistant");656
}657
if (step % 10 === 9) {658
// Overlapping reads, one with an earlier cutoff, share the kept range.659
const at = written[random(written.length)]!.id;660
const [whole, cut] = await Promise.all([661
runtime.context(root.id, taskContext),662
runtime.context(root.id, taskContext, { at }),663
]);664
expect(whole).toEqual(await root.context(taskContext));665
expect(cut).toEqual(await root.context(taskContext, { at }));666
}667
}668
// A fork sees its parent's entries through the fork point and extends with its own.669
const fork = await root.fork(670
written[random(written.length)]!.id,671
{ ownership: { kind: "ownerless" } },672
taskContext,673
);674
for (let step = 0; step < 20; step++) {675
expect(await runtime.context(fork.id, taskContext)).toEqual(await fork.context(taskContext));676
await append(fork.id);677
}678
await runtime.commit(() => DONE, taskContext);679
},680
},681
abort: async (_task, runtime, taskContext) => {682
await runtime.commit(() => ABORTED, taskContext);683
},684
});685
addTask(registry, Steps);686
harness.resume();687
const id = await harness.commit(688
(tx) => tx.createTask(Steps, {}, { ownership: { kind: "conversation" }, conversationId: root.id }),689
context,690
);691
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);692
const categories = [693
"user",694
"assistant",695
"aborted",696
"error",697
"deferred",698
"result",699
"stray result",700
"system",701
"baseline system",702
"baseline past assistant",703
"note",704
];705
for (const category of [...categories, "omit", "replace", "head"]) expect(seen.get(category)).toBeGreaterThan(0);706
await harness.close(context);707
});709
// #10904710
it("finds the baseline among the entries an extended read adds", async () => {711
const { harness, registry, root, first, scanned } = await countingSetup();712
const Steps = defineTask<Record<string, never>, { phase: "run" }, null>({713
name: "test.context-baseline",714
version: 1,715
initial: () => ({ phase: "run" }),716
phases: {717
run: async (_task, runtime, taskContext) => {718
const append = (conversationId: typeof root.id, draft: EntryDraft) =>719
runtime.commit(async (tx) => {720
await tx.appendEntry(conversationId, draft);721
return undefined;722
}, taskContext);723
const read = async (conversation: typeof root) => {724
const before = scanned.rows;725
const view = await runtime.context(conversation.id, taskContext);726
const rows = scanned.rows - before;727
expect(view).toEqual(await conversation.context(taskContext));728
return { messages: view.messages.map(describeMessage), rows };729
};731
// The cached range has answers and no system message; the baseline arrives in a later read.732
expect((await read(root)).messages[0]).toBe("user:first");733
await append(root.id, { kind: "pi.system", model: [system({ plan: "Plan." })] });734
let read2 = await read(root);735
// One bounds probe and the added entry: the range was extended, not derived again.736
expect(read2.rows).toBe(2);737
expect(read2.messages.slice(0, 3)).toEqual(["system:plan", "user:first", "assistant:old 0"]);739
// A system message the cached range already has keeps a later first `pi.system` entry in place.740
const fork = await root.fork(first.id, { ownership: { kind: "ownerless" } }, taskContext);741
await append(fork.id, { kind: "message", model: [assistant("answer")] });742
await append(fork.id, { kind: "host.system", model: [system({ note: "Note." })] });743
expect((await read(fork)).messages).toEqual(["user:first", "assistant:answer", "system:note"]);744
await append(fork.id, { kind: "pi.system", model: [system({ note: null })] });745
read2 = await read(fork);746
expect(read2.rows).toBe(2);747
expect(read2.messages).toEqual(["user:first", "assistant:answer", "system:note", "system:note"]);749
// An omitted system message still rules out a later baseline; the extended read keeps that.750
const omitted = await root.fork(first.id, { ownership: { kind: "ownerless" } }, taskContext);751
await append(omitted.id, { kind: "message", model: [assistant("answer")] });752
let host: EntryRecord | undefined;753
await runtime.commit(async (tx) => {754
host = await tx.appendEntry(omitted.id, {755
kind: "host.system",756
model: [system({ legacy: "Legacy." })],757
});758
return undefined;759
}, taskContext);760
await append(omitted.id, { kind: "edit", edits: [{ target: host!.id, action: "omit" }] });761
expect((await read(omitted)).messages).toEqual(["user:first", "assistant:answer"]);762
await append(omitted.id, { kind: "pi.system", model: [system({ legacy: null })] });763
read2 = await read(omitted);764
expect(read2.rows).toBe(2);765
expect(read2.messages).toEqual(["user:first", "assistant:answer", "system:legacy"]);767
// A first `pi.system` entry without a system message leaves no baseline for a later one to take.768
const empty = await root.fork(first.id, { ownership: { kind: "ownerless" } }, taskContext);769
await append(empty.id, { kind: "pi.system" });770
await append(empty.id, { kind: "message", model: [assistant("answer")] });771
expect((await read(empty)).messages).toEqual(["user:first", "assistant:answer"]);772
await append(empty.id, { kind: "pi.system", model: [system({ s: "Delta." })] });773
read2 = await read(empty);774
expect(read2.rows).toBe(2);775
expect(read2.messages).toEqual(["user:first", "assistant:answer", "system:s"]);776
await runtime.commit(() => DONE, taskContext);777
},778
},779
abort: async (_task, runtime, taskContext) => {780
await runtime.commit(() => ABORTED, taskContext);781
},782
});783
addTask(registry, Steps);784
harness.resume();785
const id = await harness.commit(786
(tx) => tx.createTask(Steps, {}, { ownership: { kind: "conversation" }, conversationId: root.id }),787
context,788
);789
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);790
await harness.close(context);791
});793
it("keeps returned views and kept ranges apart", async () => {794
const { harness, registry, root } = await countingSetup();795
const Mutate = defineTask<Record<string, never>, { phase: "run" }, null>({796
name: "test.context-mutate",797
version: 1,798
initial: () => ({ phase: "run" }),799
phases: {800
run: async (_task, runtime, taskContext) => {801
const view = await runtime.context(root.id, taskContext);802
(view.messages as Message[]).length = 0;803
(view.entries as EntryRecord[]).pop();804
// Kept entries are frozen like MemoryStorage records.805
expect(() => {806
(view.contributions[0]![0] as { content: unknown }).content = "changed";807
}).toThrow(TypeError);808
expect(await runtime.context(root.id, taskContext)).toEqual(await root.context(taskContext));809
await runtime.commit(() => DONE, taskContext);810
},811
},812
abort: async (_task, runtime, taskContext) => {813
await runtime.commit(() => ABORTED, taskContext);814
},815
});816
addTask(registry, Mutate);817
harness.resume();818
const id = await harness.commit(819
(tx) => tx.createTask(Mutate, {}, { ownership: { kind: "conversation" }, conversationId: root.id }),820
context,821
);822
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);823
await harness.close(context);824
});826
it("freezes kept entries deeply even when storage freezes them shallowly", async () => {827
const memory = new MemoryStorage();828
// Fresh copies with only the record itself frozen; their messages stay mutable.829
const storage = new Proxy<Storage>(memory, {830
get(target, key) {831
const value: unknown = Reflect.get(target, key, target);832
if (key === "scanEntries") {833
return async (...args: Parameters<Storage["scanEntries"]>) => {834
const page = await target.scanEntries(...args);835
return { ...page, items: page.items.map((item) => Object.freeze(structuredClone(item))) };836
};837
}838
return typeof value === "function" ? value.bind(target) : value;839
},840
});841
const registry = createRegistry();842
const harness = await Harness.open(storage, { models: createModels(), registry }, context);843
const root = await harness.root(context);844
await root.commit((tx) => tx.appendEntry(root.id, { kind: "message", model: [user("hello")] }), context);845
const Mutate = defineTask<Record<string, never>, { phase: "run" }, null>({846
name: "test.context-shallow",847
version: 1,848
initial: () => ({ phase: "run" }),849
phases: {850
run: async (_task, runtime, taskContext) => {851
const view = await runtime.context(root.id, taskContext);852
expect(() => {853
(view.messages[0] as { content: unknown }).content = "changed";854
}).toThrow(TypeError);855
await runtime.commit(() => DONE, taskContext);856
},857
},858
abort: async (_task, runtime, taskContext) => {859
await runtime.commit(() => ABORTED, taskContext);860
},861
});862
addTask(registry, Mutate);863
harness.resume();864
const id = await harness.commit(865
(tx) => tx.createTask(Mutate, {}, { ownership: { kind: "conversation" }, conversationId: root.id }),866
context,867
);868
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);869
await harness.close(context);870
});872
it("does not keep a read that finishes after its task ended", async () => {873
const { harness, registry, root, scanned, hold } = await countingSetup({ settings: { contextRetentionMs: 0 } });874
const scans = Promise.withResolvers<void>();875
const probeStart = Promise.withResolvers<void>();876
let late: Promise<unknown> | undefined;877
const Late = defineTask<Record<string, never>, { phase: "run" }, null>({878
name: "test.context-late",879
version: 1,880
initial: () => ({ phase: "run" }),881
phases: {882
run: async (_task, runtime, taskContext) => {883
hold.scan = scans.promise;884
late = runtime.context(root.id, taskContext).catch((error: unknown) => error);885
await runtime.commit(() => DONE, taskContext);886
},887
},888
abort: async (_task, runtime, taskContext) => {889
await runtime.commit(() => ABORTED, taskContext);890
},891
});892
const rows: Record<string, number> = {};893
const Probe = probeTask(async (name, load) => {894
await probeStart.promise;895
const before = scanned.rows;896
await load();897
rows[name] = scanned.rows - before;898
});899
for (const task of [Late, Probe]) addTask(registry, task);900
harness.resume();901
const options = { ownership: { kind: "conversation" }, conversationId: root.id } as const;902
const lateId = await harness.commit((tx) => tx.createTask(Late, {}, options), context);903
expect((await harness.waitForTask(lateId, context)).state.outcome).toEqual(DONE.outcome);904
// The conversation is busy again when the late read finishes; its range must not be kept.905
const probeId = await harness.commit((tx) => tx.createTask(Probe, { name: "probe" }, options), context);906
scans.resolve();907
await late;908
probeStart.resolve();909
expect((await harness.waitForTask(probeId, context)).state.outcome).toEqual(DONE.outcome);910
expect(rows).toEqual({ probe: 22 });911
await harness.close(context);912
});914
it("drops an idle conversation's context read on a timer when nothing else runs", async () => {915
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });916
const { harness, registry, root, scanned } = await countingSetup({ settings: { contextRetentionMs: 1_000 } });917
const rows: Record<string, number> = {};918
const Probe = probeTask(async (name, load) => {919
const before = scanned.rows;920
await load();921
rows[name] = scanned.rows - before;922
});923
addTask(registry, Probe);924
harness.resume();925
const options = { ownership: { kind: "conversation" }, conversationId: root.id } as const;926
const probe = async (name: string) => {927
const id = await harness.commit((tx) => tx.createTask(Probe, { name }, options), context);928
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);929
await root.waitForIdle(context);930
};931
const idle = vi.getTimerCount();932
await probe("first");933
expect(vi.getTimerCount()).toBe(idle + 1);934
vi.advanceTimersByTime(1_000);935
expect(vi.getTimerCount()).toBe(idle);936
await probe("second");937
expect(rows).toEqual({ first: 22, second: 22 });938
await harness.close(context);939
});941
it("drops a conversation's context read once idle with zero retention", async () => {942
const { harness, registry, root, scanned } = await countingSetup({ settings: { contextRetentionMs: 0 } });943
const rows: Record<string, number> = {};944
const Probe = probeTask(async (name, load) => {945
const before = scanned.rows;946
await load();947
rows[name] = scanned.rows - before;948
});949
addTask(registry, Probe);950
harness.resume();951
const options = { ownership: { kind: "conversation" }, conversationId: root.id } as const;952
for (const name of ["first", "second"]) {953
const id = await harness.commit((tx) => tx.createTask(Probe, { name }, options), context);954
expect((await harness.waitForTask(id, context)).state.outcome).toEqual(DONE.outcome);955
await root.waitForIdle(context);956
}957
expect(rows).toEqual({ first: 22, second: 22 });958
await harness.close(context);959
});960
});962
const DONE = { status: "terminal", outcome: { status: "completed", result: null } } as const;964
const ABORTED = { status: "terminal", outcome: { status: "aborted" } } as const;966
/** A task that reads its conversation's context once, named by its input. */967
function probeTask(read: (name: string, load: () => Promise<ContextView>, taskContext: Context) => Promise<void>) {968
return defineTask<{ name: string }, { phase: "run" }, null>({969
name: "test.context-probe",970
version: 1,971
initial: () => ({ phase: "run" }),972
phases: {973
run: async (task, runtime, taskContext) => {974
await read(task.input.name, () => runtime.context(runtime.conversationId, taskContext), taskContext);975
await runtime.commit(() => DONE, taskContext);976
},977
},978
abort: async (_task, runtime, taskContext) => {979
await runtime.commit(() => ABORTED, taskContext);980
},981
});982
}