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

ThreadFind.test.ts

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