Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadFind.test.ts

825 lines30.2 KB

1import { assert, it, describe } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 PlanId,
6 RunId,
7 RuntimeRequestId,
8 TurnItemId,
9 type OrchestrationV2TurnItem,
10 type OrchestrationV2Run,
11 type OrchestrationV2ThreadHistoryPage,
12 ProjectId,
13 ProviderInstanceId,
14 ThreadId,
15 type OrchestrationV2DomainEvent,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as SqlClient from "effect/sql/SqlClient";
21import * as Stream from "effect/Stream";
22​
23import * as SqlitePersistence from "../persistence/Sqlite.ts";
24import * as ProjectionStore from "./ProjectionStore.ts";
25import * as ProjectStore from "./ProjectStore.ts";
26import * as EventStore from "./EventStore.ts";
27import {
28 encodeThreadHistoryCursor,
29 selectHistoryPageFromCursor,
30 THREAD_HISTORY_PAGE_POLICY,
31} from "./threadHistoryPaging.ts";
32import { projectTurnItemForWire } from "./WireProjection.ts";
33​
34const layerTest = Layer.mergeAll(EventStore.layer, ProjectionStore.layer, ProjectStore.layer).pipe(
35 Layer.provideMerge(SqlitePersistence.layerMemory),
36);
37​
38const providerInstanceId = ProviderInstanceId.make("codex");
39const at = (minute: number) => DateTime.makeUnsafe(Date.UTC(2026, 8, 27, 0, minute));
40​
41const createProject = (projectId: ProjectId) =>
42 Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
43 projects.apply({
44 sequence: 0,
45 eventId: EventId.make(`created:${projectId}`),
46 aggregateKind: "project",
47 aggregateId: projectId,
48 occurredAt: DateTime.formatIso(at(0)),
49 commandId: null,
50 causationEventId: null,
51 correlationId: null,
52 metadata: {},
53 type: "project.created",
54 payload: {
55 projectId,
56 title: projectId,
57 workspaceRoot: `/work/${projectId}`,
58 defaultModelSelection: null,
59 scripts: [],
60 createdAt: DateTime.formatIso(at(0)),
61 updatedAt: DateTime.formatIso(at(0)),
62 },
63 }),
64 );
65​
66const thread = (
67 threadId: ThreadId,
68 projectId: ProjectId,
69 overrides: { readonly archivedAt?: DateTime.Utc; readonly deletedAt?: DateTime.Utc } = {},
70): OrchestrationV2DomainEvent => ({
71 id: EventId.make(`created:${threadId}`),
72 type: "thread.created",
73 threadId,
74 providerInstanceId,
75 occurredAt: at(0),
76 payload: {
77 createdBy: "user",
78 creationSource: "web",
79 id: threadId,
80 projectId,
81 title: threadId,
82 providerInstanceId,
83 modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
84 runtimeMode: "full-access",
85 interactionMode: "default",
86 branch: null,
87 worktreePath: null,
88 activeProviderThreadId: null,
89 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
90 forkedFrom: null,
91 createdAt: at(0),
92 updatedAt: at(0),
93 archivedAt: overrides.archivedAt ?? null,
94 settledOverride: null,
95 settledAt: null,
96 lastVisitedAt: null,
97 deletedAt: overrides.deletedAt ?? null,
98 },
99});
100​
101const threadId = ThreadId.make("thread:find");
102const projectId = ProjectId.make("project:find");
103const runId = RunId.make("run:find");
104​
105function item(
106 id: string,
107 ordinal: number,
108 text: string,
109 kind: "user_message" | "assistant_message" | "proposed_plan" = "assistant_message",
110 owner = threadId,
111): Extract<
112 OrchestrationV2TurnItem,
113 { type: "user_message" | "assistant_message" | "proposed_plan" }
114> {
115 const base = {
116 id: TurnItemId.make(id),
117 threadId: owner,
118 runId,
119 nodeId: null,
120 providerThreadId: null,
121 providerTurnId: null,
122 nativeItemRef: null,
123 parentItemId: null,
124 ordinal,
125 status: "completed" as const,
126 title: null,
127 startedAt: at(100 - ordinal),
128 completedAt: at(100 - ordinal),
129 updatedAt: at(1),
130 };
131 if (kind === "proposed_plan")
132 return { ...base, type: kind, planId: PlanId.make(id), markdown: text, streaming: false };
133 if (kind === "user_message")
134 return {
135 ...base,
136 type: kind,
137 messageId: MessageId.make(id),
138 text,
139 inputIntent: "turn_start",
140 attachments: [],
141 createdBy: "user",
142 creationSource: "web",
143 };
144 return { ...base, type: kind, messageId: MessageId.make(id), text, streaming: false };
146​
147function run(
148 owner = threadId,
149 id = runId,
150 ordinal = 1,
151 status: OrchestrationV2Run["status"] = "completed",
152): Extract<OrchestrationV2DomainEvent, { type: "run.created" }> {
153 return {
154 id: EventId.make(`run:${owner}:${id}:${status}`),
155 threadId: owner,
156 occurredAt: at(1),
157 type: "run.created",
158 payload: {
159 id,
160 threadId: owner,
161 ordinal,
162 providerInstanceId,
163 modelSelection: { instanceId: providerInstanceId, model: "gpt-6" },
164 providerThreadId: null,
165 userMessageId: MessageId.make("prompt"),
166 rootNodeId: null,
167 activeAttemptId: null,
168 status,
169 requestedAt: at(1),
170 startedAt: at(1),
171 completedAt: at(2),
172 checkpointId: null,
173 contextHandoffId: null,
174 },
175 };
177​
178const commit = Effect.fn("ThreadFindTest.commit")(function* (
179 events: readonly OrchestrationV2DomainEvent[],
180) {
181 const store = yield* EventStore.EventStoreV2;
182 const projection = yield* ProjectionStore.ProjectionStoreV2;
183 yield* store.append({ events });
184 yield* Effect.forEach(events, projection.apply, { discard: true });
185});
186const putItems = (items: readonly OrchestrationV2TurnItem[], version = "initial") =>
187 commit(
188 items.map((payload) => ({
189 id: EventId.make(`${payload.threadId}:${payload.id}:${version}`),
190 threadId: payload.threadId,
191 occurredAt: at(1),
192 type: "turn-item.updated" as const,
193 payload,
194 })),
195 );
196const setup = Effect.gen(function* () {
197 yield* createProject(projectId);
198 yield* commit([thread(threadId, projectId), run()]);
199 return yield* ProjectionStore.ProjectionStoreV2;
200});
201​
202describe("V2 thread find", () => {
203 it.effect("finishes one snapshot while later searches include newly inserted matches", () =>
204 Effect.gen(function* () {
205 const projection = yield* setup;
206 yield* putItems([
207 item("selected", 1, "snapshot needle"),
208 item("last", 2, "snapshot last needle"),
209 ]);
210 const frames = yield* projection.searchThreadStream({ threadId, query: "needle" }).pipe(
211 Stream.tap((frame) =>
212 frame.complete === false
213 ? putItems([item("inserted", 0, "snapshot inserted needle")], "during-search")
214 : Effect.void,
215 ),
216 Stream.runCollect,
217 );
218 assert.equal(frames.length, 2);
219 assert.equal(frames[1]!.totalMatches, 2);
220 assert.deepEqual(frames[1]!.match, frames[0]!.match);
221 const updated = yield* projection.searchThread({
222 threadId,
223 query: "needle",
224 start: { entryId: "selected", occurrence: 0 },
225 });
226 assert.equal(updated.totalMatches, 3);
227 assert.equal(updated.activeIndex, 1);
228 assert.equal(updated.match?.entryId, "selected");
229 }).pipe(Effect.provide(layerTest)),
230 );
231​
232 it.effect("returns bounded navigation counts around the selection, including wraparound", () =>
233 Effect.gen(function* () {
234 const projection = yield* setup;
235 yield* putItems(
236 Array.from({ length: 30 }, (_, i) =>
237 item(`message:${i}`, i, "needle ".repeat((i % 3) + 1)),
238 ),
239 );
240 const current = yield* projection.searchThread({
241 threadId,
242 query: "needle",
243 start: { entryId: "message:14", occurrence: 1 },
244 });
245 assert.equal(current.totalMatches, 60);
246 assert.equal(current.activeIndex, 28);
247 assert.equal(current.navigation?.length, 17);
248 assert.deepEqual(
249 current.navigation?.map((entry) => entry.entryId),
250 Array.from({ length: 17 }, (_, i) => `message:${i + 6}`),
251 );
252 assert.deepEqual(
253 current.navigation?.find((entry) => entry.entryId === "message:14"),
254 {
255 entryId: "message:14",
256 runId,
257 startIndex: 27,
258 count: 3,
259 },
260 );
261 const first = yield* projection.searchThread({ threadId, query: "needle" });
262 assert.equal(first.navigation?.length, 17);
263 assert.include(first.navigation?.map((entry) => entry.entryId) ?? [], "message:29");
264 const empty = yield* projection.searchThread({ threadId, query: "absent" });
265 assert.deepEqual(empty.navigation, []);
266 }).pipe(Effect.provide(layerTest)),
267 );
268​
269 it.effect("keeps navigation compact for a message with thousands of occurrences", () =>
270 Effect.gen(function* () {
271 const projection = yield* setup;
272 yield* putItems([item("many", 1, "needle ".repeat(5000))]);
273 const result = yield* projection.searchThread({ threadId, query: "needle", index: 2000 });
274 assert.equal(result.totalMatches, 5000);
275 assert.equal(result.match?.occurrence, 2000);
276 assert.deepEqual(result.navigation, [{ entryId: "many", runId, startIndex: 0, count: 5000 }]);
277 assert.isBelow(JSON.stringify(result).length, 500);
278 }).pipe(Effect.provide(layerTest)),
279 );
280​
281 it.effect("cycles relative to the current match when new matches are inserted", () =>
282 Effect.gen(function* () {
283 const projection = yield* setup;
284 yield* putItems([
285 item("first", 10, "needle"),
286 item("current", 20, "needle"),
287 item("last", 30, "needle"),
288 ]);
289 const initial = yield* projection.searchThread({ threadId, query: "needle", index: 1 });
290 assert.equal(initial.match?.entryId, "current");
291 yield* putItems([
292 item("new-before", 15, "needle"),
293 item("new-after", 25, "needle"),
294 item("new-last", 40, "needle"),
295 ]);
296 const start = { entryId: "current", occurrence: 0 };
297 const refreshed = yield* projection.searchThread({ threadId, query: "needle", start });
298 assert.equal(refreshed.totalMatches, 6);
299 assert.equal(refreshed.activeIndex, 2);
300 assert.equal(refreshed.match?.entryId, "current");
301 const next = yield* projection.searchThread({ threadId, query: "needle", start, offset: 1 });
302 assert.equal(next.match?.entryId, "new-after");
303 const previous = yield* projection.searchThread({
304 threadId,
305 query: "needle",
306 start,
307 offset: -1,
308 });
309 assert.equal(previous.match?.entryId, "new-before");
310 const end = yield* projection.searchThread({
311 threadId,
312 query: "needle",
313 start: { entryId: "last", occurrence: 0 },
314 offset: 1,
315 });
316 assert.equal(end.match?.entryId, "new-last");
317 const wrapped = yield* projection.searchThread({
318 threadId,
319 query: "needle",
320 start: { entryId: "new-last", occurrence: 0 },
321 offset: 1,
322 });
323 assert.equal(wrapped.match?.entryId, "first");
324 const backwards = yield* projection.searchThread({
325 threadId,
326 query: "needle",
327 start: { entryId: "first", occurrence: 0 },
328 offset: -1,
329 });
330 assert.equal(backwards.match?.entryId, "new-last");
331 }).pipe(Effect.provide(layerTest)),
332 );
333​
334 it.effect("searches visible rendered messages and plans in canonical item order", () =>
335 Effect.gen(function* () {
336 const projection = yield* setup;
337 yield* putItems([
338 item("user", 1, "Check **the build**", "user_message"),
339 item("assistant", 2, "check the build twice: check the build"),
340 item("plan-item", 3, "# Check the build\nShip it", "proposed_plan"),
341 item("url", 4, "[documentation](https://hidden.example/needle)"),
342 ]);
343 const matches = [];
344 for (let index = 0; index < 4; index++) {
345 const result = yield* projection.searchThread({
346 threadId,
347 query: "CHECK THE BUILD",
348 index,
349 });
350 assert.equal(result.totalMatches, 4);
351 matches.push(result.match);
352 }
353 assert.deepEqual(matches, [
354 { entryId: "user", runId, occurrence: 0 },
355 { entryId: "assistant", runId, occurrence: 0 },
356 { entryId: "assistant", runId, occurrence: 1 },
357 { entryId: "plan-item", runId, occurrence: 0 },
358 ]);
359 assert.equal(
360 (yield* projection.searchThread({ threadId, query: "hidden.example" })).totalMatches,
361 0,
362 );
363 assert.equal(
364 (yield* projection.searchThread({ threadId, query: "check", index: 99 })).activeIndex,
365 3,
366 );
367 }).pipe(Effect.provide(layerTest)),
368 );
369​
370 it.effect("searches displayed skill labels and invalidates parsed text when labels change", () =>
371 Effect.gen(function* () {
372 const projection = yield* setup;
373 yield* putItems([item("skill", 1, "Use $test-t3-app now")]);
374 const input = {
375 threadId,
376 query: "T3 App Testing",
377 skills: [{ name: "test-t3-app", displayName: "T3 App Testing" }],
378 };
379 assert.equal((yield* projection.searchThread(input)).totalMatches, 1);
380 assert.equal((yield* projection.searchThread({ ...input, skills: [] })).totalMatches, 0);
381 yield* putItems(
382 [item("skill-plan", 2, "# Verify\nUse $test-t3-app now", "proposed_plan")],
383 "plan",
384 );
385 assert.equal((yield* projection.searchThread(input)).totalMatches, 1);
386 assert.equal(
387 (yield* projection.searchThread({ ...input, query: "$test-t3-app" })).totalMatches,
388 1,
389 );
390 assert.equal((yield* projection.searchThread({ ...input, query: "App" })).totalMatches, 2);
391 }).pipe(Effect.provide(layerTest)),
392 );
393​
394 it.effect("never mixes message versions when the searched thread changes during a scan", () =>
395 Effect.gen(function* () {
396 const projection = yield* setup;
397 const sql = yield* SqlClient.SqlClient;
398 const items = Array.from({ length: 260 }, (_, i) => item(`message:${i}`, i, "needle"));
399 yield* putItems(items);
400 const updated = items.map((item) =>
401 item.type === "assistant_message" ? { ...item, text: "needle needle" } : item,
402 );
403 const [during] = yield* Effect.all(
404 [
405 projection.searchThread({ threadId, query: "needle" }),
406 sql.withTransaction(putItems(updated, "concurrent")),
407 ],
408 { concurrency: "unbounded" },
409 );
410 assert.include([260, 520], during.totalMatches);
411 assert.equal(
412 (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,
413 520,
414 );
415 }).pipe(Effect.provide(layerTest)),
416 );
417​
418 it.effect("starts at the reading position and wraps when no later match exists", () =>
419 Effect.gen(function* () {
420 const projection = yield* setup;
421 yield* putItems([
422 item("first", 1, "needle"),
423 item("reading", 2, "needle above, needle below"),
424 item("between", 3, "nothing"),
425 item("last", 4, "needle"),
426 item("end", 5, "nothing"),
427 ]);
428 const from = (entryId: string, occurrence = 0) =>
429 projection.searchThread({ threadId, query: "needle", start: { entryId, occurrence } });
430 assert.equal((yield* from("reading")).activeIndex, 1);
431 const below = yield* from("reading", 1);
432 assert.equal(below.activeIndex, 2);
433 assert.equal(below.match?.occurrence, 1);
434 assert.equal((yield* from("between")).match?.entryId, "last");
435 assert.equal((yield* from("reading", 2)).activeIndex, 3);
436 assert.equal((yield* from("end")).match?.entryId, "first");
437 assert.equal((yield* from("missing")).activeIndex, 0);
438 const explicit = yield* projection.searchThread({
439 threadId,
440 query: "needle",
441 start: { entryId: "last", occurrence: 0 },
442 index: 1,
443 });
444 assert.equal(explicit.match?.entryId, "reading");
445 }).pipe(Effect.provide(layerTest)),
446 );
447​
448 it.effect("finds matches beyond the recent history window", () =>
449 Effect.gen(function* () {
450 const projection = yield* setup;
451 const items = Array.from({ length: 520 }, (_, i) =>
452 item(`message:${i}`, i + 1, i === 8 || i === 510 ? "sentinel" : "other message"),
453 );
454 yield* putItems(items);
455 const first = yield* projection.searchThread({ threadId, query: "sentinel" });
456 const last = yield* projection.searchThread({ threadId, query: "sentinel", index: 1 });
457 assert.equal(first.totalMatches, 2);
458 assert.equal(first.match?.entryId, "message:8");
459 assert.equal(last.match?.entryId, "message:510");
460 }).pipe(Effect.provide(layerTest)),
461 );
462​
463 it.effect("invalidates cached counts when streamed text changes or a run rolls back", () =>
464 Effect.gen(function* () {
465 const projection = yield* setup;
466 const original = item("streaming", 1, "needle");
467 yield* putItems([original]);
468 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
469 if (original.type !== "assistant_message") return;
470 yield* putItems([{ ...original, text: "needle needle", streaming: true }], "streaming");
471 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 2);
472 const updated = run(threadId, runId, 1, "rolled_back");
473 yield* commit([{ ...updated, type: "run.updated" }]);
474 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 0);
475 }).pipe(Effect.provide(layerTest)),
476 );
477​
478 it.effect(
479 "does not search undispatched inputs, cancelled queue rows, or folded question answers",
480 () =>
481 Effect.gen(function* () {
482 const projection = yield* setup;
483 const queuedRunId = RunId.make("queued:cancelled");
484 yield* commit([run(threadId, queuedRunId, 2, "cancelled")]);
485 const queued = item("cancelled", 1, "needle", "user_message");
486 if (queued.type !== "user_message") return;
487 const answer = item("async-answer:question", 2, "needle", "user_message");
488 const question: OrchestrationV2TurnItem = {
489 ...item("question", 3, ""),
490 type: "user_input_request",
491 requestId: RuntimeRequestId.make("question"),
492 questions: [],
493 questionAnswer: { requestId: "question", answers: {}, attachmentsByQuestionId: {} },
494 };
495 yield* putItems([
496 { ...queued, runId: queuedRunId, inputIntent: "queued_turn" },
497 answer,
498 question,
499 ]);
500 const event: OrchestrationV2DomainEvent = {
501 id: EventId.make("undispatched"),
502 threadId,
503 occurredAt: at(2),
504 type: "message.updated",
505 payload: {
506 id: MessageId.make("undispatched"),
507 threadId,
508 runId: null,
509 nodeId: null,
510 role: "user",
511 text: "needle",
512 attachments: [],
513 streaming: false,
514 createdBy: "user",
515 creationSource: "web",
516 createdAt: at(2),
517 updatedAt: at(2),
518 },
519 };
520 yield* commit([event]);
521 const result = yield* projection.searchThread({ threadId, query: "needle" });
522 assert.equal(result.totalMatches, 0);
523 assert.isNull(result.match);
524 }).pipe(Effect.provide(layerTest)),
525 );
526​
527 it.effect(
528 "searches inherited fork history through the fork boundary, using source item identities",
529 () =>
530 Effect.gen(function* () {
531 const projection = yield* setup;
532 const parent = ThreadId.make("thread:parent");
533 const laterRun = RunId.make("run:later");
534 const parentRun = RunId.make("run:parent");
535 yield* commit([
536 thread(parent, projectId),
537 run(parent, parentRun),
538 run(parent, laterRun, 2),
539 ]);
540 yield* putItems([
541 { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },
542 { ...item("after-fork", 2, "needle", "assistant_message", parent), runId: laterRun },
543 ]);
544 const child = thread(threadId, projectId);
545 if (child.type !== "thread.created") return;
546 yield* commit([
547 {
548 ...child,
549 id: EventId.make("child:fork"),
550 type: "thread.metadata-updated",
551 payload: {
552 ...child.payload,
553 forkedFrom: { type: "run", threadId: parent, runId: parentRun },
554 },
555 },
556 ]);
557 yield* putItems([item("local", 1, "needle")]);
558 const inherited = yield* projection.searchThread({ threadId, query: "needle" });
559 assert.equal(inherited.totalMatches, 2);
560 assert.equal(inherited.match?.entryId, "inherited");
561 assert.equal(
562 (yield* projection.searchThread({ threadId, query: "needle", index: 1 })).match?.entryId,
563 "local",
564 );
565 const snapshot = yield* projection.getThreadSnapshot(threadId);
566 const history = yield* projection.getThreadHistoryPage(
567 threadId,
568 encodeThreadHistoryCursor({
569 snapshotSequence: snapshot.snapshotSequence,
570 sourceThreadId: threadId,
571 sourceItemId: "local",
572 position: 2,
573 }),
574 );
575 assert.deepEqual(
576 history.items,
577 snapshot.projection.visibleTurnItems
578 .slice(0, -1)
579 .map((row) => ({ ...row, item: projectTurnItemForWire(row.item) })),
580 );
581 assert.equal(history.items[0]?.sourceThreadId, parent);
582 assert.equal(history.items.at(-1)?.item.type, "fork");
583 yield* putItems(
584 [{ ...item("inherited", 1, "gone", "assistant_message", parent), runId: parentRun }],
585 "parent-update",
586 );
587 assert.equal(
588 (yield* projection.searchThread({ threadId, query: "needle" })).totalMatches,
589 1,
590 );
591 }).pipe(Effect.provide(layerTest)),
592 );
593​
594 it.effect("rejects deleted threads and keeps results scoped to their thread", () =>
595 Effect.gen(function* () {
596 const projection = yield* setup;
597 const other = ThreadId.make("thread:other");
598 yield* commit([thread(other, projectId), run(other, RunId.make("run:other"))]);
599 yield* putItems([
600 item("shared-id", 1, "needle"),
601 item("other-id", 1, "other text", "assistant_message", other),
602 ]);
603 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
604 assert.equal(
605 (yield* projection.searchThread({ threadId: other, query: "needle" })).totalMatches,
606 0,
607 );
608 const deleted = thread(threadId, projectId, { deletedAt: at(3) });
609 if (deleted.type !== "thread.created") return;
610 yield* commit([{ ...deleted, id: EventId.make("deleted"), type: "thread.deleted" }]);
611 const error = yield* Effect.flip(projection.searchThread({ threadId, query: "needle" }));
612 assert.equal(error._tag, "ProjectionStoreThreadNotFoundError");
613 const historyError = yield* Effect.flip(
614 projection.getThreadHistoryPage(
615 threadId,
616 encodeThreadHistoryCursor({
617 snapshotSequence: 0,
618 sourceThreadId: threadId,
619 sourceItemId: "shared-id",
620 position: 0,
621 }),
622 ),
623 );
624 assert.equal(historyError._tag, "ProjectionStoreThreadNotFoundError");
625 }).pipe(Effect.provide(layerTest)),
626 );
627​
628 it.effect("invalidates a cached fork search when its empty source gains its first message", () =>
629 Effect.gen(function* () {
630 const projection = yield* setup;
631 const parent = ThreadId.make("thread:empty-parent");
632 const parentRun = RunId.make("run:empty-parent");
633 yield* commit([thread(parent, projectId), run(parent, parentRun)]);
634 const child = thread(threadId, projectId);
635 if (child.type !== "thread.created") return;
636 yield* commit([
637 {
638 ...child,
639 id: EventId.make("child:empty-fork"),
640 type: "thread.metadata-updated",
641 payload: {
642 ...child.payload,
643 forkedFrom: { type: "run", threadId: parent, runId: parentRun },
644 },
645 },
646 ]);
647 yield* putItems([item("local", 1, "needle")]);
648 assert.equal((yield* projection.searchThread({ threadId, query: "needle" })).totalMatches, 1);
649 yield* putItems([
650 { ...item("inherited", 1, "needle", "assistant_message", parent), runId: parentRun },
651 ]);
652 const updated = yield* projection.searchThread({ threadId, query: "needle" });
653 assert.equal(updated.totalMatches, 2);
654 assert.equal(updated.match?.entryId, "inherited");
655 }).pipe(Effect.provide(layerTest)),
656 );
657});
658​
659describe("V2 history materialization", () => {
660 it.effect(
661 "combines history pages through a match's message identity without skipping intervening turns",
662 () =>
663 Effect.gen(function* () {
664 const projection = yield* setup;
665 const items = Array.from({ length: 45 }, (_, turn) => [
666 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
667 {
668 ...item(`answer:${turn}`, turn * 3 + 1, `answer ${turn}`),
669 messageId: MessageId.make(`message:${turn}`),
670 },
671 {
672 ...item(`tool:${turn}`, turn * 3 + 2, ""),
673 type: "command_execution" as const,
674 input: "pwd",
675 output: "huge output".repeat(1000),
676 exitCode: 0,
677 },
678 ]).flat();
679 yield* putItems(items);
680 const snapshot = yield* projection.getThreadSnapshot(threadId);
681 const cursor = encodeThreadHistoryCursor({
682 snapshotSequence: snapshot.snapshotSequence,
683 sourceThreadId: threadId,
684 sourceItemId: "absent",
685 position: items.length,
686 });
687 const ordinary = yield* projection.getThreadHistoryPage(threadId, cursor);
688 assert.equal(ordinary.items[0]?.sourceItemId, "user:25");
689 const targeted = yield* projection.getThreadHistoryPage(threadId, cursor, "message:10");
690 assert.equal(targeted.items[0]?.sourceItemId, "user:10");
691 assert.deepEqual(
692 targeted.items.map((row) => row.sourceItemId),
693 items.slice(30).map((entry) => entry.id),
694 );
695 const conversation = yield* projection.getThreadHistoryPage(
696 threadId,
697 cursor,
698 "message:10",
699 true,
700 );
701 assert.equal(conversation.nextCursor, targeted.nextCursor);
702 assert.equal(conversation.hasMoreHistory, targeted.hasMoreHistory);
703 assert.deepEqual(
704 conversation.items.map((row) => row.sourceItemId),
705 targeted.items
706 .filter((row) => row.item.type !== "command_execution")
707 .map((row) => row.sourceItemId),
708 );
709 assert.equal(conversation.items.length, 70);
710 assert.equal(targeted.items.length, 105);
711 assert.isTrue(targeted.hasMoreHistory);
712 const earlier = yield* projection.getThreadHistoryPage(threadId, targeted.nextCursor!);
713 assert.deepEqual(
714 earlier.items.map((row) => row.sourceItemId),
715 items.slice(0, 30).map((entry) => entry.id),
716 );
717 assert.isFalse(earlier.hasMoreHistory);
718 const capped = yield* projection.getThreadHistoryPage(threadId, cursor, "message:0");
719 assert.equal(capped.items[0]?.sourceItemId, "user:5");
720 const absent = yield* projection.getThreadHistoryPage(
721 threadId,
722 cursor,
723 "another-thread-message",
724 );
725 assert.deepEqual(absent, ordinary);
726 }).pipe(Effect.provide(layerTest)),
727 );
728​
729 it.effect("pages long turns without duplicating or skipping messages", () =>
730 Effect.gen(function* () {
731 const projection = yield* setup;
732 const items = Array.from({ length: 45 }, (_, turn) => [
733 item(`user:${turn}`, turn * 3, `turn ${turn}`, "user_message"),
734 {
735 ...item(`steer:${turn}`, turn * 3 + 1, "steer", "user_message"),
736 inputIntent: "steer" as const,
737 },
738 item(
739 `answer:${turn}`,
740 turn * 3 + 2,
741 turn === 40 ? "large ".repeat(200_000) : `answer ${turn}`,
742 ),
743 ]).flat();
744 yield* putItems(items);
745 const snapshot = yield* projection.getThreadSnapshot(threadId);
746 const rows = snapshot.projection.visibleTurnItems.map((row) => ({
747 ...row,
748 item: projectTurnItemForWire(row.item),
749 }));
750 let cursor: string | null = encodeThreadHistoryCursor({
751 snapshotSequence: snapshot.snapshotSequence,
752 sourceThreadId: threadId,
753 sourceItemId: "absent",
754 position: rows.length,
755 });
756 const collected: string[] = [];
757 while (cursor !== null) {
758 const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(
759 threadId,
760 cursor,
761 );
762 assert.deepEqual(page, {
763 snapshotSequence: snapshot.snapshotSequence,
764 ...selectHistoryPageFromCursor({
765 items: rows,
766 cursor,
767 snapshotSequence: snapshot.snapshotSequence,
768 }),
769 });
770 // A turn larger than the byte budget is split, but only a lone oversized item may exceed it.
771 assert.isTrue(
772 page.items.length === 1 ||
773 Buffer.byteLength(JSON.stringify(page.items), "utf8") <=
774 THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes,
775 );
776 collected.unshift(...page.items.map((row) => String(row.sourceItemId)));
777 cursor = page.nextCursor;
778 }
779 assert.deepEqual(
780 collected,
781 items.map((entry) => String(entry.id)),
782 );
783 }).pipe(Effect.provide(layerTest)),
784 );
785​
786 it.effect("enforces fallback item and byte limits and always admits an oversized row", () =>
787 Effect.gen(function* () {
788 const projection = yield* setup;
789 yield* putItems(
790 Array.from({ length: 80 }, (_, ordinal) =>
791 item(`row:${ordinal}`, ordinal, ordinal < 78 ? "small" : "large ".repeat(200_000)),
792 ),
793 );
794 const snapshot = yield* projection.getThreadSnapshot(threadId);
795 const rows = snapshot.projection.visibleTurnItems.map((row) => ({
796 ...row,
797 item: projectTurnItemForWire(row.item),
798 }));
799 let cursor: string | null = encodeThreadHistoryCursor({
800 snapshotSequence: snapshot.snapshotSequence,
801 sourceThreadId: threadId,
802 sourceItemId: "absent",
803 position: rows.length,
804 });
805 const sizes: number[] = [];
806 while (cursor !== null) {
807 const page: OrchestrationV2ThreadHistoryPage = yield* projection.getThreadHistoryPage(
808 threadId,
809 cursor,
810 );
811 assert.deepEqual(page, {
812 snapshotSequence: snapshot.snapshotSequence,
813 ...selectHistoryPageFromCursor({
814 items: rows,
815 cursor,
816 snapshotSequence: snapshot.snapshotSequence,
817 }),
818 });
819 sizes.push(page.items.length);
820 cursor = page.nextCursor;
821 }
822 assert.deepEqual(sizes, [1, 1, 75, 3]);
823 }).pipe(Effect.provide(layerTest)),
824 );
825});