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