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

ThreadFind.test.ts

864 lines32.0 KB

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