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

ThreadSearch.test.ts

1,165 lines46.5 KB

1import { assert, it } from "@effect/vitest";
2import {
3 EventId,
4 MessageId,
5 ProjectId,
6 ProviderInstanceId,
7 ThreadId,
8 type OrchestrationV2DomainEvent,
9 type ThreadLinkedPullRequest,
10} from "@t3tools/contracts";
11import * as NodeServices from "@effect/platform-node/NodeServices";
12import * as DateTime from "effect/DateTime";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as TestClock from "effect/testing/TestClock";
16import * as FileSystem from "effect/FileSystem";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Path from "effect/Path";
20import * as SqlClient from "effect/sql/SqlClient";
21import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
22​
23import * as SqlitePersistence from "../persistence/Sqlite.ts";
24import * as ProjectionStore from "./ProjectionStore.ts";
25import * as ProjectStore from "./ProjectStore.ts";
26import * as ThreadSearch from "./ThreadSearch.ts";
27​
28const layerTest = Layer.mergeAll(
29 ThreadSearch.layer,
30 ProjectionStore.layer,
31 ProjectStore.layer,
32).pipe(Layer.provideMerge(SqlitePersistence.layerMemory));
33​
34const providerInstanceId = ProviderInstanceId.make("codex");
35const at = (minute: number) => DateTime.makeUnsafe(Date.UTC(2026, 8, 27, 0, minute));
36​
37const createProject = (projectId: ProjectId) =>
38 Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
39 projects.apply({
40 sequence: 0,
41 eventId: EventId.make(`created:${projectId}`),
42 aggregateKind: "project",
43 aggregateId: projectId,
44 occurredAt: DateTime.formatIso(at(0)),
45 commandId: null,
46 causationEventId: null,
47 correlationId: null,
48 metadata: {},
49 type: "project.created",
50 payload: {
51 projectId,
52 title: projectId,
53 workspaceRoot: `/work/${projectId}`,
54 defaultModelSelection: null,
55 scripts: [],
56 createdAt: DateTime.formatIso(at(0)),
57 updatedAt: DateTime.formatIso(at(0)),
58 },
59 }),
60 );
61​
62const thread = (
63 threadId: ThreadId,
64 projectId: ProjectId,
65 overrides: {
66 readonly archivedAt?: DateTime.Utc;
67 readonly deletedAt?: DateTime.Utc;
68 readonly subagentOf?: ThreadId;
69 readonly sideChatOf?: ThreadId;
70 readonly title?: string;
71 readonly settledAt?: DateTime.Utc;
72 readonly linkedPullRequest?: ThreadLinkedPullRequest;
73 readonly branchPullRequest?: ThreadLinkedPullRequest;
74 } = {},
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: overrides.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 linkedPullRequest: overrides.linkedPullRequest ?? null,
94 branchPullRequest: overrides.branchPullRequest ?? null,
95 activeProviderThreadId: null,
96 lineage: overrides.subagentOf
97 ? {
98 parentThreadId: overrides.subagentOf,
99 relationshipToParent: "subagent",
100 rootThreadId: overrides.subagentOf,
101 }
102 : overrides.sideChatOf
103 ? {
104 parentThreadId: overrides.sideChatOf,
105 relationshipToParent: "fork",
106 rootThreadId: overrides.sideChatOf,
107 sideChat: true,
108 }
109 : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
110 forkedFrom: null,
111 createdAt: at(0),
112 updatedAt: at(0),
113 archivedAt: overrides.archivedAt ?? null,
114 settledOverride: overrides.settledAt === undefined ? null : "settled",
115 settledAt: overrides.settledAt ?? null,
116 lastVisitedAt: null,
117 deletedAt: overrides.deletedAt ?? null,
118 },
119});
120​
121const message = (
122 threadId: ThreadId,
123 id: string,
124 role: "user" | "assistant" | "system",
125 text: string,
126 options: {
127 readonly minute?: number;
128 readonly streaming?: boolean;
129 readonly createdBy?: "user" | "agent";
130 } = {},
131): OrchestrationV2DomainEvent => ({
132 id: EventId.make(`message:${id}`),
133 type: "message.updated",
134 threadId,
135 providerInstanceId,
136 occurredAt: at(options.minute ?? 1),
137 payload: {
138 createdBy: options.createdBy ?? (role === "user" ? "user" : "agent"),
139 creationSource: role === "user" ? "web" : "provider",
140 id: MessageId.make(id),
141 threadId,
142 runId: null,
143 nodeId: null,
144 role,
145 text,
146 attachments: [],
147 streaming: options.streaming ?? false,
148 createdAt: at(options.minute ?? 1),
149 updatedAt: at(options.minute ?? 1),
150 },
151});
152​
153it.effect.each([true, false])(
154 "ThreadSearch excludes bootstrap text before the hit and candidate limits (indexed: %s)",
155 (indexed) =>
156 Effect.gen(function* () {
157 const projections = yield* ProjectionStore.ProjectionStoreV2;
158 const search = yield* ThreadSearch.ThreadSearch;
159 const sql = yield* SqlClient.SqlClient;
160 const project = ProjectId.make("project:attachments");
161 const threadId = ThreadId.make("thread:attachments");
162 yield* createProject(project);
163 yield* Effect.forEach(
164 [
165 thread(threadId, project),
166 message(threadId, "ordinary", "user", "Review the attached files in context", {
167 minute: 1,
168 }),
169 message(threadId, "attachment", "user", ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, { minute: 2 }),
170 message(
171 threadId,
172 "ultrathink",
173 "user",
174 `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
175 { minute: 3 },
176 ),
177 ],
178 projections.apply,
179 { discard: true },
180 );
181 if (!indexed) {
182 yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
183 yield* sql`DROP TRIGGER orchestration_v2_message_search_update`;
184 yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`;
185 yield* sql`DROP TABLE orchestration_v2_message_search`;
186 }
187 assert.deepEqual((yield* search.search({ query: "conversation context" })).matches, []);
188 assert.deepEqual((yield* search.search({ query: "ultrathink" })).matches, []);
189 assert.deepEqual(
190 (yield* search.search({ query: "attached files" })).matches.map((match) => [
191 match.messageId,
192 match.snippet,
193 ]),
194 [[MessageId.make("ordinary"), "Review the attached files in context"]],
195 );
196 for (const text of [
197 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
198 `Ultrathink:\n${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
199 `uLtRaThInK:\r\n\t\u00a0${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
200 ]) {
201 yield* sql`
202 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${indexed ? 10_000 : 2000})
203 INSERT INTO orchestration_v2_projection_messages
204 (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
205 SELECT 'attachment-limit:' || i, ${threadId}, 'user', 0,
206 ${DateTime.formatIso(at(5))}, ${DateTime.formatIso(at(5))}, json_object('text', ${text})
207 FROM n
208 `;
209 assert.deepEqual(
210 (yield* search.search({ query: "context" })).matches.map((match) => match.messageId),
211 [MessageId.make("ordinary")],
212 );
213 yield* sql`
214 DELETE FROM orchestration_v2_projection_messages WHERE message_id LIKE 'attachment-limit:%'
215 `;
216 }
217 }).pipe(Effect.provide(layerTest)),
218);
219​
220it.effect("ThreadSearch excludes legacy placeholders still in the index", () =>
221 Effect.gen(function* () {
222 const projections = yield* ProjectionStore.ProjectionStoreV2;
223 const search = yield* ThreadSearch.ThreadSearch;
224 const sql = yield* SqlClient.SqlClient;
225 const project = ProjectId.make("project:legacy-attachments");
226 const threadId = ThreadId.make("thread:legacy-attachments");
227 yield* createProject(project);
228 // Simulate the pre-upgrade trigger, which indexed attachment placeholders.
229 yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
230 yield* sql`
231 CREATE TRIGGER orchestration_v2_message_search_insert
232 AFTER INSERT ON orchestration_v2_projection_messages
233 BEGIN
234 INSERT INTO orchestration_v2_message_search (rowid, text)
235 VALUES (new.rowid, json_extract(new.payload_json, '$.text'));
236 END
237 `;
238 yield* Effect.forEach(
239 [
240 thread(threadId, project),
241 message(threadId, "ordinary", "user", "Review the attached files in context"),
242 message(threadId, "attachment", "user", ATTACHMENT_ONLY_BOOTSTRAP_PROMPT),
243 message(
244 threadId,
245 "ultrathink",
246 "user",
247 `uLtRaThInK:\r\n\t\u00a0${ATTACHMENT_ONLY_BOOTSTRAP_PROMPT}`,
248 ),
249 ],
250 projections.apply,
251 { discard: true },
252 );
253 assert.lengthOf(
254 yield* sql`SELECT rowid FROM orchestration_v2_message_search WHERE orchestration_v2_message_search MATCH '"context"'`,
255 3,
256 );
257 assert.deepEqual((yield* search.search({ query: "conversation context" })).matches, []);
258 assert.deepEqual((yield* search.search({ query: "ultrathink" })).matches, []);
259 assert.deepEqual(
260 (yield* search.search({ query: "context" })).matches.map((match) => match.messageId),
261 [MessageId.make("ordinary")],
262 );
263 }).pipe(Effect.provide(layerTest)),
264);
265​
266it.layer(layerTest)("ThreadSearch", (it) => {
267 it.effect("reads the newest hits without sorting all of them", () =>
268 Effect.gen(function* () {
269 const sql = yield* SqlClient.SqlClient;
270 for (const match of ['"needle"', null]) {
271 const plan = yield* sql<{
272 readonly detail: string;
273 }>`EXPLAIN QUERY PLAN ${ThreadSearch.messageHitsQuery(sql, { match, substrings: "[]", projectId: null, excludedThreadIds: "[]" })}`;
274 assert.isFalse(
275 plan.some((row) => row.detail.includes("TEMP B-TREE")),
276 plan.map((row) => row.detail).join("\n"),
277 );
278 if (match !== null) {
279 assert.lengthOf(
280 plan.filter((row) =>
281 row.detail.startsWith("SEARCH messages USING INTEGER PRIMARY KEY"),
282 ),
283 1,
284 plan.map((row) => row.detail).join("\n"),
285 );
286 }
287 }
288 }),
289 );
290​
291 it.effect("returns one finished user or assistant match per active thread", () =>
292 Effect.gen(function* () {
293 const projections = yield* ProjectionStore.ProjectionStoreV2;
294 const search = yield* ThreadSearch.ThreadSearch;
295 const project = ProjectId.make("project:search");
296 const deletedProject = ProjectId.make("project:search-deleted");
297 yield* createProject(project);
298 yield* createProject(deletedProject);
299 yield* Effect.flatMap(ProjectStore.ProjectStoreV2, (projects) =>
300 projects.apply({
301 sequence: 0,
302 eventId: EventId.make("deleted:project"),
303 aggregateKind: "project",
304 aggregateId: deletedProject,
305 occurredAt: DateTime.formatIso(at(2)),
306 commandId: null,
307 causationEventId: null,
308 correlationId: null,
309 metadata: {},
310 type: "project.deleted",
311 payload: { projectId: deletedProject, deletedAt: DateTime.formatIso(at(2)) },
312 }),
313 );
314​
315 const both = ThreadId.make("thread:both");
316 const assistantOnly = ThreadId.make("thread:assistant");
317 const events: ReadonlyArray<OrchestrationV2DomainEvent> = [
318 thread(both, project),
319 message(both, "both-assistant", "assistant", "needle from the answer", { minute: 3 }),
320 message(both, "both-user-old", "user", "older needle question", { minute: 1 }),
321 message(both, "both-user-new", "user", "newer needle question", { minute: 2 }),
322 thread(assistantOnly, project),
323 message(assistantOnly, "assistant-only", "assistant", "needle in an answer"),
324 message(assistantOnly, "assistant-streaming", "user", "needle still typing", {
325 streaming: true,
326 }),
327 message(assistantOnly, "assistant-system", "system", "needle system prompt"),
328 thread(ThreadId.make("thread:archived"), project, { archivedAt: at(1) }),
329 message(ThreadId.make("thread:archived"), "archived", "user", "needle archived"),
330 thread(ThreadId.make("thread:deleted"), project, { deletedAt: at(1) }),
331 message(ThreadId.make("thread:deleted"), "deleted", "user", "needle deleted"),
332 thread(ThreadId.make("thread:orphaned"), deletedProject),
333 message(ThreadId.make("thread:orphaned"), "orphaned", "user", "needle orphaned"),
334 ];
335 yield* Effect.forEach(events, projections.apply, { discard: true });
336​
337 const result = yield* search.search({ query: "NEEDLE", limit: 20 });
338 assert.deepEqual(
339 result.matches
340 .map((match) => [match.threadId, match.source, match.snippet, match.messageId])
341 .toSorted(([left], [right]) => String(left).localeCompare(String(right))),
342 [
343 [assistantOnly, "assistant", "needle in an answer", "assistant-only"],
344 [both, "user", "newer needle question", "both-user-new"],
345 ],
346 );
347 assert.lengthOf((yield* search.search({ query: "needle", limit: 1 })).matches, 1);
348 assert.deepEqual((yield* search.search({ query: "ne%le" })).matches, []);
349 }),
350 );
351​
352 it.effect("indexes a message when it finishes streaming and follows later edits", () =>
353 Effect.gen(function* () {
354 const projections = yield* ProjectionStore.ProjectionStoreV2;
355 const search = yield* ThreadSearch.ThreadSearch;
356 const project = ProjectId.make("project:search-sync");
357 const threadId = ThreadId.make("thread:sync");
358 yield* createProject(project);
359 yield* projections.apply(thread(threadId, project));
360 const threadIds = (query: string) =>
361 search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
362​
363 yield* projections.apply(
364 message(threadId, "sync", "assistant", "streaming draft", { streaming: true }),
365 );
366 assert.deepEqual(yield* threadIds("draft"), []);
367​
368 yield* projections.apply(message(threadId, "sync", "assistant", "finished answer"));
369 assert.deepEqual(yield* threadIds("finished"), [threadId]);
370​
371 yield* projections.apply(message(threadId, "sync", "assistant", "edited reply"));
372 assert.deepEqual(yield* threadIds("finished"), []);
373 assert.deepEqual(yield* threadIds("edited"), [threadId]);
374 }),
375 );
376​
377 it.effect("matches inside identifiers and skips hidden threads and short tokens", () =>
378 Effect.gen(function* () {
379 const projections = yield* ProjectionStore.ProjectionStoreV2;
380 const search = yield* ThreadSearch.ThreadSearch;
381 const project = ProjectId.make("project:search-tokens");
382 const parent = ThreadId.make("thread:tokens-parent");
383 const subagent = ThreadId.make("thread:tokens-subagent");
384 const sideChat = ThreadId.make("thread:tokens-side-chat");
385 yield* createProject(project);
386 yield* Effect.forEach(
387 [
388 thread(parent, project),
389 message(parent, "parent", "user", "Rename ThreadSearchService before shipping"),
390 thread(subagent, project, { subagentOf: parent }),
391 message(subagent, "subagent", "assistant", "ThreadSearchService renamed"),
392 thread(sideChat, project, { sideChatOf: parent, title: "ThreadSearchService question" }),
393 message(sideChat, "side-chat", "user", "Why rename ThreadSearchService?"),
394 ],
395 projections.apply,
396 { discard: true },
397 );
398​
399 const result = yield* search.search({ query: "search servi" });
400 assert.deepEqual(
401 result.matches.map((match) => [match.threadId, match.snippet]),
402 [[parent, "Rename ThreadSearchService before shipping"]],
403 );
404 // "ab" alone cannot use the index; with a longer token it narrows the hits.
405 assert.deepEqual((yield* search.search({ query: "ab" })).matches, []);
406 assert.lengthOf((yield* search.search({ query: "renam be" })).matches, 1);
407 assert.lengthOf((yield* search.search({ query: "renam ab" })).matches, 0);
408 }),
409 );
410​
411 it.effect("indexes neither subagent messages nor rewrites that keep the text", () =>
412 Effect.gen(function* () {
413 const sql = yield* SqlClient.SqlClient;
414 const projections = yield* ProjectionStore.ProjectionStoreV2;
415 const project = ProjectId.make("project:search-index-writes");
416 const parent = ThreadId.make("thread:index-parent");
417 const subagent = ThreadId.make("thread:index-subagent");
418 yield* createProject(project);
419 yield* Effect.forEach(
420 [
421 thread(parent, project),
422 message(parent, "index-parent", "assistant", "parent answer"),
423 thread(subagent, project, { subagentOf: parent }),
424 message(subagent, "index-subagent", "assistant", "subagent answer"),
425 ],
426 projections.apply,
427 { discard: true },
428 );
429 const indexedThreads = sql<{ readonly threadId: string }>`
430 SELECT messages.thread_id AS "threadId"
431 FROM orchestration_v2_message_search AS search
432 INNER JOIN orchestration_v2_projection_messages AS messages
433 ON messages.rowid = search.rowid
434 WHERE messages.thread_id IN (${parent}, ${subagent})
435 `.pipe(Effect.map((rows) => rows.map((row) => row.threadId)));
436 assert.deepEqual(yield* indexedThreads, [parent]);
437​
438 // total_changes counts trigger writes, so 1 means the index was untouched.
439 const changes = sql<{ readonly n: number }>`SELECT total_changes() AS n`.pipe(
440 Effect.map(([row]) => row?.n ?? 0),
441 );
442 const before = yield* changes;
443 yield* sql`
444 UPDATE orchestration_v2_projection_messages
445 SET payload_json = json_set(payload_json, '$.updatedAt', '2026-09-27T01:00:00.000Z')
446 WHERE message_id = 'index-parent'
447 `;
448 assert.strictEqual((yield* changes) - before, 1);
449 assert.deepEqual(yield* indexedThreads, [parent]);
450 }),
451 );
452});
453​
454it.layer(layerTest)("ThreadSearch filters before it ranks", (it) => {
455 it.effect("orders message matches by when they were written, not by row order", () =>
456 Effect.gen(function* () {
457 const projections = yield* ProjectionStore.ProjectionStoreV2;
458 const search = yield* ThreadSearch.ThreadSearch;
459 const project = ProjectId.make("project:written");
460 yield* createProject(project);
461 const recent = ThreadId.make("thread:written-recent");
462 const imported = ThreadId.make("thread:written-imported");
463 // An imported history lands after newer messages in row order.
464 yield* Effect.forEach(
465 [
466 thread(recent, project),
467 message(recent, "written-recent", "user", "kestrel deploy notes", { minute: 30 }),
468 thread(imported, project),
469 message(imported, "written-imported", "user", "kestrel deploy notes", { minute: 1 }),
470 ],
471 projections.apply,
472 { discard: true },
473 );
474 const { matches } = yield* search.search({ query: "kestrel" });
475 assert.deepEqual(
476 matches.map((match) => match.threadId),
477 [recent, imported],
478 );
479 }),
480 );
481​
482 it.effect("ranks a thread about the word above a passing mention", () =>
483 Effect.gen(function* () {
484 const projections = yield* ProjectionStore.ProjectionStoreV2;
485 const search = yield* ThreadSearch.ThreadSearch;
486 const project = ProjectId.make("project:about");
487 yield* createProject(project);
488 const about = ThreadId.make("thread:about-osprey");
489 const mention = ThreadId.make("thread:mention-osprey");
490 yield* Effect.forEach(
491 [
492 thread(about, project),
493 ...Array.from({ length: 12 }, (_, index) =>
494 message(about, `about-osprey-${index}`, "assistant", `osprey step ${index}`, {
495 minute: 2,
496 }),
497 ),
498 thread(mention, project),
499 message(mention, "mention-osprey", "user", "also check osprey", { minute: 5 }),
500 ],
501 projections.apply,
502 { discard: true },
503 );
504 const { matches } = yield* search.search({ query: "osprey" });
505 assert.deepEqual(
506 matches.map((match) => [match.threadId, match.hits]),
507 [
508 [about, 12],
509 [mention, 1],
510 ],
511 );
512 }),
513 );
514​
515 it.effect("counts a thread's hits at its best match only", () =>
516 Effect.gen(function* () {
517 const projections = yield* ProjectionStore.ProjectionStoreV2;
518 const search = yield* ThreadSearch.ThreadSearch;
519 const project = ProjectId.make("project:best-hits");
520 yield* createProject(project);
521 const clarks = ThreadId.make("thread:clarks");
522 const larks = ThreadId.make("thread:lark-many");
523 yield* Effect.forEach(
524 [
525 thread(clarks, project),
526 message(clarks, "clarks-lark", "user", "Lark once", { minute: 3 }),
527 ...Array.from({ length: 31 }, (_, index) =>
528 message(clarks, `clarks-${index}`, "assistant", "Clark the plan", { minute: 3 }),
529 ),
530 thread(larks, project),
531 ...Array.from({ length: 8 }, (_, index) =>
532 message(larks, `lark-many-${index}`, "assistant", "Lark again", { minute: 3 }),
533 ),
534 ],
535 projections.apply,
536 { discard: true },
537 );
538 const { matches } = yield* search.search({ query: "lark" });
539 assert.deepEqual(
540 matches.map((match) => [match.threadId, match.hits]),
541 [
542 [larks, 8],
543 [clarks, 1],
544 ],
545 );
546 }),
547 );
548​
549 it.effect("finds a visible match behind hundreds of hidden or narrower hits", () =>
550 Effect.gen(function* () {
551 const projections = yield* ProjectionStore.ProjectionStoreV2;
552 const search = yield* ThreadSearch.ThreadSearch;
553 const project = ProjectId.make("project:crowded");
554 const parent = ThreadId.make("thread:crowded-parent");
555 const subagent = ThreadId.make("thread:crowded-subagent");
556 const older = ThreadId.make("thread:crowded-older");
557 yield* createProject(project);
558 yield* Effect.forEach(
559 [
560 thread(parent, project),
561 thread(subagent, project, { subagentOf: parent }),
562 thread(older, project),
563 ...Array.from({ length: 450 }, (_, index) =>
564 message(subagent, `subagent-${index}`, "assistant", "needle needle"),
565 ),
566 ...Array.from({ length: 450 }, (_, index) =>
567 message(older, `older-${index}`, "assistant", "pnpm 11 pnpm"),
568 ),
569 message(parent, "parent-needle", "user", "a needle in a long haystack of other words"),
570 // Agent-written notices in user messages are not indexed, so they never read as "You".
571 message(older, "older-notice", "user", "needle update from a watched pull request", {
572 createdBy: "agent",
573 }),
574 message(parent, "parent-pnpm", "user", "moved the repo to pnpm 12 today"),
575 ],
576 projections.apply,
577 { discard: true },
578 );
579​
580 const threadIds = (query: string) =>
581 search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
582 assert.deepEqual(yield* threadIds("needle"), [parent]);
583 assert.deepEqual(yield* threadIds("pnpm 12"), [parent]);
584 }),
585 );
586​
587 it.effect("keeps a thread picked for the query when the limit cuts", () =>
588 Effect.gen(function* () {
589 const projections = yield* ProjectionStore.ProjectionStoreV2;
590 const search = yield* ThreadSearch.ThreadSearch;
591 const sql = yield* SqlClient.SqlClient;
592 const project = ProjectId.make("project:plover");
593 const busy = ThreadId.make("thread:plover-busy");
594 const picked = ThreadId.make("thread:plover-picked");
595 yield* createProject(project);
596 yield* Effect.forEach(
597 [
598 thread(busy, project),
599 message(busy, "plover-1", "user", "plover notes", { minute: 3 }),
600 message(busy, "plover-2", "user", "more plover notes", { minute: 4 }),
601 thread(picked, project),
602 message(picked, "plover-old", "user", "one plover mention", { minute: 1 }),
603 ],
604 projections.apply,
605 { discard: true },
606 );
607 const threadIds = () =>
608 search
609 .search({ query: "plover", limit: 1 })
610 .pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
611 assert.deepEqual(yield* threadIds(), [busy]);
612 // A pick at time 0 would read as no pick.
613 yield* TestClock.adjust("1 day");
614 const at = DateTime.toEpochMillis(yield* DateTime.now);
615 yield* sql`
616 UPDATE orchestration_v2_projection_threads
617 SET payload_json = json_set(payload_json, '$.opens', json(${JSON.stringify({
618 openedAt: at,
619 score: 1,
620 picks: [{ query: "plover", at }],
621 })}))
622 WHERE thread_id = ${picked}
623 `;
624 assert.deepEqual(yield* threadIds(), [picked]);
625 }),
626 );
627​
628 it.effect("finds a curly apostrophe for a straight one and back", () =>
629 Effect.gen(function* () {
630 const projections = yield* ProjectionStore.ProjectionStoreV2;
631 const search = yield* ThreadSearch.ThreadSearch;
632 const project = ProjectId.make("project:apostrophes");
633 const curly = ThreadId.make("thread:apostrophe-curly");
634 const straight = ThreadId.make("thread:apostrophe-straight");
635 yield* createProject(project);
636 yield* Effect.forEach(
637 [
638 thread(curly, project),
639 message(curly, "apostrophe-curly", "user", "the gannet\u2019s nest"),
640 thread(straight, project),
641 message(straight, "apostrophe-straight", "user", "a kittiwake's nest"),
642 ],
643 projections.apply,
644 { discard: true },
645 );
646 const threadIds = (query: string) =>
647 search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
648 assert.deepEqual(yield* threadIds("gannet's"), [curly]);
649 assert.deepEqual(yield* threadIds("kittiwake\u2019s"), [straight]);
650 }),
651 );
652​
653 it.effect("leaves out answers to an agent's question, which show in its card", () =>
654 Effect.gen(function* () {
655 const projections = yield* ProjectionStore.ProjectionStoreV2;
656 const search = yield* ThreadSearch.ThreadSearch;
657 const project = ProjectId.make("project:answers");
658 const asked = ThreadId.make("thread:answers");
659 yield* createProject(project);
660 yield* Effect.forEach(
661 [
662 thread(asked, project),
663 message(asked, "async-answer:request-1", "user", "use the albatross drive"),
664 ],
665 projections.apply,
666 { discard: true },
667 );
668 assert.deepEqual((yield* search.search({ query: "albatross" })).matches, []);
669 }),
670 );
671​
672 it.effect("matches messages as they read, with links as their text", () =>
673 Effect.gen(function* () {
674 const projections = yield* ProjectionStore.ProjectionStoreV2;
675 const search = yield* ThreadSearch.ThreadSearch;
676 const project = ProjectId.make("project:heron");
677 const labeled = ThreadId.make("thread:heron-label");
678 const addressOnly = ThreadId.make("thread:heron-address");
679 yield* createProject(project);
680 yield* Effect.forEach(
681 [
682 thread(labeled, project),
683 message(labeled, "heron-label", "assistant", "See [the heron plan](https://x.dev/a) now"),
684 thread(addressOnly, project),
685 message(addressOnly, "heron-address", "user", "Read [this](https://heron.dev/b)"),
686 ],
687 projections.apply,
688 { discard: true },
689 );
690 const { matches } = yield* search.search({ query: "heron" });
691 assert.deepEqual(
692 matches.map((match) => [match.threadId, match.snippet]),
693 [[labeled, "See the heron plan now"]],
694 );
695 }),
696 );
697​
698 it.effect("reads at most the newest 10,000 index hits, however many the filters drop", () =>
699 Effect.gen(function* () {
700 const projections = yield* ProjectionStore.ProjectionStoreV2;
701 const search = yield* ThreadSearch.ThreadSearch;
702 const sql = yield* SqlClient.SqlClient;
703 const project = ProjectId.make("project:kestrel");
704 const old = ThreadId.make("thread:kestrel-old");
705 const busy = ThreadId.make("thread:kestrel-busy");
706 yield* createProject(project);
707 yield* Effect.forEach(
708 [
709 thread(old, project),
710 message(old, "kestrel-old", "user", "kestrel ci is red"),
711 thread(busy, project),
712 ],
713 projections.apply,
714 { discard: true },
715 );
716 const insertBusy = (count: number) => sql`
717 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${count})
718 INSERT INTO orchestration_v2_projection_messages
719 (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
720 SELECT 'kestrel-busy-' || i, ${busy}, 'assistant', 0, ${DateTime.formatIso(at(5))},
721 ${DateTime.formatIso(at(5))}, json_object('text', 'kestrel packages')
722 FROM n
723 `;
724 const threadIds = (query: string) =>
725 search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
726 yield* insertBusy(9_999);
727 assert.deepEqual(yield* threadIds("kestrel ci"), [old]);
728 yield* sql`DELETE FROM orchestration_v2_projection_messages WHERE thread_id = ${busy}`;
729 yield* insertBusy(10_000);
730 assert.deepEqual(yield* threadIds("kestrel ci"), []);
731 }),
732 );
733});
734​
735it.layer(layerTest)("ThreadSearch across scripts and without the index", (it) => {
736 it.effect(
737 "matches Korean, Japanese, and two-character Chinese words, and whole short words",
738 () =>
739 Effect.gen(function* () {
740 const projections = yield* ProjectionStore.ProjectionStoreV2;
741 const search = yield* ThreadSearch.ThreadSearch;
742 const sql = yield* SqlClient.SqlClient;
743 const project = ProjectId.make("project:scripts");
744 const threadId = ThreadId.make("thread:scripts");
745 const drafts = ThreadId.make("thread:drafts");
746 const addresses = ThreadId.make("thread:addresses");
747 yield* createProject(project);
748 yield* Effect.forEach(
749 [
750 thread(threadId, project),
751 message(threadId, "korean", "user", "검색 기능을 고쳐 주세요"),
752 message(threadId, "japanese", "user", "がんばって検索します"),
753 message(threadId, "chinese", "user", "明天部署到生产环境"),
754 message(threadId, "fts", "assistant", "the FTS index is ready"),
755 thread(drafts, project),
756 message(drafts, "drafts", "assistant", "saved two drafts and shifts"),
757 message(threadId, "camel", "assistant", "Configure enableFTS today"),
758 message(threadId, "accented", "user", "Review Résumé indexing"),
759 thread(addresses, project),
760 message(addresses, "addresses", "user", "This addresses Résumé indexing"),
761 ],
762 projections.apply,
763 { discard: true },
764 );
765 const threadIds = (query: string) =>
766 search
767 .search({ query })
768 .pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
769​
770 // Short words must start a word, which camelCase and accented words do.
771 for (const query of ["검색 기능", "がんばって", "部署", "fts", "enable"]) {
772 assert.deepEqual(yield* threadIds(query), [threadId], query);
773 }
774 // "res" inside "addresses" does not hide the accented word after it.
775 assert.sameMembers(yield* threadIds("res"), [threadId, addresses]);
776 // A word beats the same letters inside a longer word, even in an older message.
777 const trust = ThreadId.make("thread:trust");
778 const rust = ThreadId.make("thread:rust");
779 yield* Effect.forEach(
780 [
781 thread(rust, project),
782 message(rust, "rust", "assistant", "Rust rewrite notes"),
783 thread(trust, project),
784 message(trust, "trust", "user", "We trust the build"),
785 ],
786 projections.apply,
787 { discard: true },
788 );
789 const { matches } = yield* search.search({ query: "rust" });
790 assert.deepEqual(
791 matches.map((match) => [match.threadId, (match.quality ?? 1) <= 0.3]),
792 [
793 [rust, false],
794 [trust, true],
795 ],
796 );
797 // Without the index (an SQLite build without FTS5 trigrams) search scans instead.
798 yield* sql`DROP TABLE orchestration_v2_message_search`;
799 assert.deepEqual(yield* threadIds("検索"), [threadId]);
800 assert.deepEqual(yield* threadIds("fts"), [threadId]);
801 }),
802 );
803});
804​
805it.layer(layerTest)("ThreadSearch.searchOlderSettled", (it) => {
806 it.effect("returns older settled title matches in scope, then older message hits", () =>
807 Effect.gen(function* () {
808 const projections = yield* ProjectionStore.ProjectionStoreV2;
809 const search = yield* ThreadSearch.ThreadSearch;
810 const project = ProjectId.make("project:kestrel");
811 const other = ProjectId.make("project:kestrel-other");
812 yield* createProject(project);
813 yield* createProject(other);
814 const id = (name: string) => ThreadId.make(`thread:kestrel-${name}`);
815 const old = at(10);
816 yield* Effect.forEach(
817 [
818 thread(id("old"), project, { title: "Kestrel nest", settledAt: old }),
819 thread(id("recent"), project, { title: "Kestrel nest", settledAt: at(50) }),
820 thread(id("open"), project, { title: "Kestrel nest" }),
821 thread(id("child"), project, { title: "Kestrel nest", subagentOf: id("old") }),
822 thread(id("elsewhere"), other, { title: "Kestrel nest", settledAt: old }),
823 thread(id("note"), project, { title: "Unrelated", settledAt: old }),
824 thread(id("new-note"), project, { title: "Unrelated", settledAt: at(50) }),
825 ],
826 projections.apply,
827 { discard: true },
828 );
829 const before = DateTime.formatIso(at(30));
830 const messageThreadIds = [id("new-note"), id("note"), id("old")];
831 assert.sameMembers(
832 [...(yield* search.searchOlderSettled({ query: "kestrel", before, messageThreadIds }))],
833 [id("old"), id("elsewhere"), id("note")],
834 );
835 // The scope applies to titles and message hits; message hits follow the titles in order.
836 assert.deepEqual(
837 yield* search.searchOlderSettled({
838 query: "kestrel",
839 before,
840 projectIds: [project],
841 messageThreadIds: [id("elsewhere"), ...messageThreadIds],
842 }),
843 [id("old"), id("note")],
844 );
845 // A palette also matches the environment's name.
846 assert.include(
847 yield* search.searchOlderSettled({
848 query: "laptop unrelated",
849 before,
850 environmentLabel: "Laptop",
851 messageThreadIds: [],
852 }),
853 id("note"),
854 );
855 }),
856 );
857​
858 it.effect("matches the branch and linked pull requests, like the palette", () =>
859 Effect.gen(function* () {
860 const projections = yield* ProjectionStore.ProjectionStoreV2;
861 const search = yield* ThreadSearch.ThreadSearch;
862 const project = ProjectId.make("project:heron");
863 yield* createProject(project);
864 const pullRequest = (number: number): ThreadLinkedPullRequest => ({
865 projectId: project,
866 repository: "acme/heron",
867 number,
868 url: `https://github.com/acme/heron/pull/${number}`,
869 });
870 const branch = ThreadId.make("thread:heron-branch");
871 const linked = ThreadId.make("thread:heron-linked");
872 yield* Effect.forEach(
873 [
874 thread(branch, project, {
875 title: "Heron",
876 settledAt: at(10),
877 branchPullRequest: pullRequest(4101),
878 }),
879 thread(linked, project, {
880 title: "Heron",
881 settledAt: at(10),
882 linkedPullRequest: pullRequest(4202),
883 }),
884 ],
885 projections.apply,
886 { discard: true },
887 );
888 const find = (query: string) =>
889 search.searchOlderSettled({
890 query,
891 before: DateTime.formatIso(at(30)),
892 messageThreadIds: [],
893 });
894 assert.deepEqual(yield* find("#4101"), [branch]);
895 assert.deepEqual(yield* find("acme/heron#4202"), [linked]);
896 }),
897 );
898});
899​
900it.layer(layerTest)("ThreadSearch.searchThreadsWithOlderSettledRows", (it) => {
901 it.effect("adds older settled rows to message hits, or alone for titles only", () =>
902 Effect.gen(function* () {
903 const projections = yield* ProjectionStore.ProjectionStoreV2;
904 const search = yield* ThreadSearch.ThreadSearch;
905 const sql = yield* SqlClient.SqlClient;
906 const project = ProjectId.make("project:plover");
907 yield* createProject(project);
908 const old = ThreadId.make("thread:plover-old");
909 const recent = ThreadId.make("thread:plover-recent");
910 yield* Effect.forEach(
911 [
912 thread(old, project, { title: "Plover nest", settledAt: at(10) }),
913 thread(recent, project, { title: "Plover nest", settledAt: at(50) }),
914 message(recent, "plover-note", "user", "a plover note", { minute: 2 }),
915 ],
916 projections.apply,
917 { discard: true },
918 );
919 const run = (request: { readonly titlesOnly?: boolean }) =>
920 ThreadSearch.searchThreadsWithOlderSettledRows({
921 request: { query: "plover", olderSettledBefore: DateTime.formatIso(at(30)), ...request },
922 search: search.search,
923 searchOlderSettled: search.searchOlderSettled,
924 sql,
925 readThreads: (threadIds) =>
926 projections.readShellSnapshot({ location: "active", threadIds }),
927 latestSequence: Effect.succeed(7),
928 });
929 const withMessages = yield* run({});
930 assert.deepEqual(
931 withMessages.matches.map((match) => match.threadId),
932 [recent],
933 );
934 assert.equal(withMessages.snapshotSequence, 7);
935 assert.deepEqual(
936 withMessages.threads?.map((row) => row.id),
937 [old],
938 );
939 const titles = yield* run({ titlesOnly: true });
940 assert.deepEqual(titles.matches, []);
941 assert.deepEqual(
942 titles.threads?.map((row) => row.id),
943 [old],
944 );
945 // Without the cut it is the plain message search.
946 assert.isUndefined(
947 (yield* ThreadSearch.searchThreadsWithOlderSettledRows({
948 request: { query: "plover" },
949 search: search.search,
950 searchOlderSettled: search.searchOlderSettled,
951 sql,
952 readThreads: (threadIds) =>
953 projections.readShellSnapshot({ location: "active", threadIds }),
954 latestSequence: Effect.succeed(7),
955 })).threads,
956 );
957 }),
958 );
959});
960​
961it.layer(layerTest)("ThreadSearch.searchThreads", (it) => {
962 it.effect("keeps room for a message-only thread behind many titled ones", () =>
963 Effect.gen(function* () {
964 const projections = yield* ProjectionStore.ProjectionStoreV2;
965 const search = yield* ThreadSearch.ThreadSearch;
966 const project = ProjectId.make("project:petrel");
967 yield* createProject(project);
968 const messageOnly = ThreadId.make("thread:petrel-message");
969 yield* Effect.forEach(
970 [
971 thread(messageOnly, project),
972 // The oldest message, so a cut taken before titles drop would lose it.
973 message(messageOnly, "petrel-old", "user", "a petrel note", { minute: 1 }),
974 ...Array.from({ length: 50 }, (_, index) => {
975 const id = ThreadId.make(`thread:petrel-${index}`);
976 return [
977 thread(id, project, { title: `Petrel ${index}` }),
978 message(id, `petrel-${index}`, "user", "petrel again", { minute: 2 }),
979 ];
980 }).flat(),
981 ],
982 projections.apply,
983 { discard: true },
984 );
985 const { matches } = yield* search.searchThreads({ query: "petrel", limit: 5 });
986 assert.include(
987 matches.map((match) => match.threadId),
988 messageOnly,
989 );
990 }),
991 );
992​
993 it.effect("leaves titled threads out before the hit limit", () =>
994 Effect.gen(function* () {
995 const projections = yield* ProjectionStore.ProjectionStoreV2;
996 const search = yield* ThreadSearch.ThreadSearch;
997 const sql = yield* SqlClient.SqlClient;
998 const project = ProjectId.make("project:hit-limit");
999 const messageOnly = ThreadId.make("thread:grebe-message");
1000 const titled = ThreadId.make("thread:grebe-titled");
1001 yield* createProject(project);
1002 yield* Effect.forEach(
1004 thread(messageOnly, project, { title: "Unrelated" }),
1005 message(messageOnly, "grebe-old", "user", "a grebe note", { minute: 1 }),
1006 thread(titled, project, { title: "Grebe" }),
1007 ],
1008 projections.apply,
1009 { discard: true },
1010 );
1011 // Newer hits than one read holds, all in the titled thread.
1012 yield* sql`
1013 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
1014 INSERT INTO orchestration_v2_projection_messages
1015 (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
1016 SELECT 'grebe-titled-' || i, ${titled}, 'assistant', 0, ${DateTime.formatIso(at(5))},
1017 ${DateTime.formatIso(at(5))}, json_object('text', 'grebe again')
1018 FROM n
1019 `;
1020 const { matches } = yield* search.searchThreads({ query: "grebe", limit: 5 });
1021 assert.include(
1022 matches.map((match) => match.threadId),
1023 messageOnly,
1024 );
1025 }),
1026 );
1027​
1028 it.effect("ranks title matches like the palette, then message matches, within one project", () =>
1029 Effect.gen(function* () {
1030 const projections = yield* ProjectionStore.ProjectionStoreV2;
1031 const search = yield* ThreadSearch.ThreadSearch;
1032 const project = ProjectId.make("project:titles");
1033 const otherProject = ProjectId.make("project:titles-other");
1034 yield* createProject(project);
1035 yield* createProject(otherProject);
1036 const wordStart = ThreadId.make("thread:word-start");
1037 const midWord = ThreadId.make("thread:mid-word");
1038 const messageOnly = ThreadId.make("thread:message-only");
1039 const elsewhere = ThreadId.make("thread:elsewhere");
1040 yield* Effect.forEach(
1042 thread(midWord, project, { title: "Fix oauth redirect" }),
1043 thread(wordStart, project, { title: "Clean up auth tokens" }),
1044 thread(messageOnly, project, { title: "Unrelated" }),
1045 message(messageOnly, "message-only", "user", "the auth flow broke again"),
1046 thread(elsewhere, otherProject, { title: "Auth everywhere" }),
1047 ],
1048 projections.apply,
1049 { discard: true },
1050 );
1051​
1052 // Stronger message hits in another project must not use up this project's limit.
1053 yield* Effect.forEach(
1054 Array.from({ length: 55 }, (_, index) => {
1055 const busy = ThreadId.make(`thread:elsewhere-${index}`);
1056 return [
1057 thread(busy, otherProject),
1058 message(busy, `elsewhere-${index}`, "user", "auth auth auth"),
1059 ];
1060 }).flat(),
1061 projections.apply,
1062 { discard: true },
1063 );
1064 const result = yield* search.searchThreads({ query: "auth", projectId: project, limit: 3 });
1065 assert.deepEqual(
1066 result.matches.map((match) => [match.threadId, match.source]),
1068 [wordStart, "title"],
1069 [midWord, "title"],
1070 [messageOnly, "user"],
1071 ],
1072 );
1073 // With one slot, an exact title keeps it.
1074 assert.deepEqual(
1075 (yield* search.searchThreads({ query: "auth", projectId: project, limit: 1 })).matches.map(
1076 (match) => match.threadId,
1077 ),
1078 [wordStart],
1079 );
1080 // Exact matching finds nothing, so one typo is forgiven.
1081 assert.deepEqual(
1082 (yield* search.searchThreads({ query: "tokesn", projectId: project })).matches.map(
1083 (match) => match.title,
1084 ),
1085 ["Clean up auth tokens"],
1086 );
1087 }),
1088 );
1089});
1090​
1091it.effect("starts snippets a few words before the match so one line shows it", () =>
1092 Effect.sync(() => {
1093 const snippet = (text: string, word: string) =>
1094 ThreadSearch.buildSearchSnippet(text, text.indexOf(word));
1095 const long = `${"lead ".repeat(60)}the NEEDLE sits here ${"tail ".repeat(60)}`;
1096 const cut = snippet(long, "NEEDLE");
1097 assert.isAtMost(cut.length, 240);
1098 assert.match(cut, /^…(lead ){2,4}the NEEDLE sits here/);
1099 assert.isTrue(cut.endsWith("…"));
1100 // Whitespace collapses only in the shown part, so the offset still lands.
1101 assert.match(snippet(`${"word\n\n ".repeat(60)}un café`, "café"), /un café$/);
1102 // A cut never splits an emoji's surrogate pair.
1103 assert.notMatch(
1104 snippet(`x${"🚀".repeat(200)}needle`, "needle"),
1105 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,
1106 );
1107 // Emphasis and code marks go, as the thread shows the text.
1108 assert.equal(
1109 ThreadSearch.buildSearchSnippet("Use **bold** and `code` here", 0),
1110 "Use bold and code here",
1111 );
1112 assert.equal(ThreadSearch.buildSearchSnippet("Call __init__ first", 0), "Call __init__ first");
1113 // Short text still moves a late match into view.
1114 assert.equal(snippet(`${"word ".repeat(20)}needle`, "needle"), "…word word word word needle");
1115 }),
1117​
1118it.effect("searches on the reader worker while the writer is busy", () =>
1119 Effect.gen(function* () {
1120 const fileSystem = yield* FileSystem.FileSystem;
1121 const path = yield* Path.Path;
1122 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-search-" });
1123 const layerFile = Layer.mergeAll(
1124 ThreadSearch.layer,
1125 ProjectionStore.layer,
1126 ProjectStore.layer,
1127 ).pipe(
1128 Layer.provideMerge(SqlitePersistence.layerFromPath(path.join(directory, "state.sqlite"))),
1129 Layer.provide(NodeServices.layer),
1130 );
1131​
1132 yield* Effect.gen(function* () {
1133 const projections = yield* ProjectionStore.ProjectionStoreV2;
1134 const search = yield* ThreadSearch.ThreadSearch;
1135 const sql = yield* SqlClient.SqlClient;
1136 const project = ProjectId.make("project:search-reader");
1137 const threadId = ThreadId.make("thread:reader");
1138 yield* createProject(project);
1139 yield* Effect.forEach(
1140 [thread(threadId, project), message(threadId, "reader", "user", "needle on the reader")],
1141 projections.apply,
1142 { discard: true },
1143 );
1144​
1145 const writerHeld = yield* Deferred.make<void>();
1146 const releaseWriter = yield* Deferred.make<void>();
1147 const writer = yield* Effect.forkChild(
1148 sql.withTransaction(
1149 Deferred.succeed(writerHeld, undefined).pipe(
1150 Effect.andThen(Deferred.await(releaseWriter)),
1151 ),
1152 ),
1153 );
1154 yield* Deferred.await(writerHeld);
1155 const result = yield* search.search({ query: "needle" });
1156 yield* Deferred.succeed(releaseWriter, undefined);
1157 yield* Fiber.join(writer);
1158​
1159 assert.deepEqual(
1160 result.matches.map((match) => match.threadId),
1161 [threadId],
1162 );
1163 }).pipe(Effect.provide(layerFile));
1164 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),