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