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";
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: "[]", shortSpellings: "[]", 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.effect.each([true, false])(
736 "ThreadSearch narrows short words outside ASCII before the hit limit (indexed: %s)",
737 (indexed) =>
738 Effect.gen(function* () {
739 const projections = yield* ProjectionStore.ProjectionStoreV2;
740 const search = yield* ThreadSearch.ThreadSearch;
741 const sql = yield* SqlClient.SqlClient;
742 const project = ProjectId.make("project:short-limit");
743 const older = ThreadId.make("thread:short-older");
744 const newer = ThreadId.make("thread:short-newer");
745 yield* createProject(project);
746 yield* Effect.forEach(
747 [
748 thread(older, project),
749 message(older, "older", "user", "В логах ошибка"),
750 thread(newer, project),
751 ],
752 projections.apply,
753 { discard: true },
754 );
755 if (!indexed) {
756 yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`;
757 yield* sql`DROP TRIGGER orchestration_v2_message_search_update`;
758 yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`;
759 yield* sql`DROP TABLE orchestration_v2_message_search`;
760 }
761 // More newer hits for the long word than one read holds, none with the short one.
762 yield* sql`
763 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
764 INSERT INTO orchestration_v2_projection_messages
765 (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
766 SELECT 'short-newer-' || i, ${newer}, 'assistant', 0, ${DateTime.formatIso(at(5))},
767 ${DateTime.formatIso(at(5))}, json_object('text', 'ошибка здесь')
768 FROM n
769 `;
770 const { matches } = yield* search.search({ query: "ошибка в" });
771 assert.deepEqual(
772 matches.map((match) => match.threadId),
773 [older],
774 );
775 }).pipe(Effect.provide(layerTest)),
776);
777
778it.layer(layerTest)("ThreadSearch short words outside ASCII", (it) => {
779 it.effect("finds them in any case or accent, with or without the index", () =>
780 Effect.gen(function* () {
781 const projections = yield* ProjectionStore.ProjectionStoreV2;
782 const search = yield* ThreadSearch.ThreadSearch;
783 const sql = yield* SqlClient.SqlClient;
784 const project = ProjectId.make("project:short-non-ascii");
785 const russian = ThreadId.make("thread:short-russian");
786 const french = ThreadId.make("thread:short-french");
787 yield* createProject(project);
788 yield* Effect.forEach(
789 [
790 thread(russian, project),
791 message(russian, "russian", "user", "В логах ошибка"),
792 thread(french, project),
793 message(french, "french", "user", "École fermée à Lyon"),
794 ],
795 projections.apply,
796 { discard: true },
797 );
798 const threadIds = (query: string) =>
799 search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
800
801 const assertMatches = Effect.gen(function* () {
802 assert.deepEqual(yield* threadIds("ошибка в"), [russian]);
803 assert.deepEqual(yield* threadIds("fermée éc"), [french]);
804 // They still narrow: a word the message lacks rules it out.
805 assert.deepEqual(yield* threadIds("ошибка я"), []);
806 });
807 yield* assertMatches;
808 yield* sql`DROP TABLE orchestration_v2_message_search`;
809 yield* assertMatches;
810 }),
811 );
812});
813
814it.layer(layerTest)("ThreadSearch across scripts and without the index", (it) => {
815 it.effect(
816 "matches Korean, Japanese, and two-character Chinese words, and whole short words",
817 () =>
818 Effect.gen(function* () {
819 const projections = yield* ProjectionStore.ProjectionStoreV2;
820 const search = yield* ThreadSearch.ThreadSearch;
821 const sql = yield* SqlClient.SqlClient;
822 const project = ProjectId.make("project:scripts");
823 const threadId = ThreadId.make("thread:scripts");
824 const drafts = ThreadId.make("thread:drafts");
825 const addresses = ThreadId.make("thread:addresses");
826 yield* createProject(project);
827 yield* Effect.forEach(
828 [
829 thread(threadId, project),
830 message(threadId, "korean", "user", "검색 기능을 고쳐 주세요"),
831 message(threadId, "japanese", "user", "がんばって検索します"),
832 message(threadId, "chinese", "user", "明天部署到生产环境"),
833 message(threadId, "fts", "assistant", "the FTS index is ready"),
834 thread(drafts, project),
835 message(drafts, "drafts", "assistant", "saved two drafts and shifts"),
836 message(threadId, "camel", "assistant", "Configure enableFTS today"),
837 message(threadId, "accented", "user", "Review Résumé indexing"),
838 thread(addresses, project),
839 message(addresses, "addresses", "user", "This addresses Résumé indexing"),
840 ],
841 projections.apply,
842 { discard: true },
843 );
844 const threadIds = (query: string) =>
845 search
846 .search({ query })
847 .pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId)));
848
849 // Short words must start a word, which camelCase and accented words do.
850 for (const query of ["검색 기능", "がんばって", "部署", "fts", "enable"]) {
851 assert.deepEqual(yield* threadIds(query), [threadId], query);
852 }
853 // "res" inside "addresses" does not hide the accented word after it.
854 assert.sameMembers(yield* threadIds("res"), [threadId, addresses]);
855 // A word beats the same letters inside a longer word, even in an older message.
856 const trust = ThreadId.make("thread:trust");
857 const rust = ThreadId.make("thread:rust");
858 yield* Effect.forEach(
859 [
860 thread(rust, project),
861 message(rust, "rust", "assistant", "Rust rewrite notes"),
862 thread(trust, project),
863 message(trust, "trust", "user", "We trust the build"),
864 ],
865 projections.apply,
866 { discard: true },
867 );
868 const { matches } = yield* search.search({ query: "rust" });
869 assert.deepEqual(
870 matches.map((match) => [match.threadId, (match.quality ?? 1) <= 0.3]),
871 [
872 [rust, false],
873 [trust, true],
874 ],
875 );
876 // Without the index (an SQLite build without FTS5 trigrams) search scans instead.
877 yield* sql`DROP TABLE orchestration_v2_message_search`;
878 assert.deepEqual(yield* threadIds("検索"), [threadId]);
879 assert.deepEqual(yield* threadIds("fts"), [threadId]);
880 }),
881 );
882});
883
884it.layer(layerTest)("ThreadSearch.searchOlderSettled", (it) => {
885 it.effect("returns older settled title matches in scope, then older message hits", () =>
886 Effect.gen(function* () {
887 const projections = yield* ProjectionStore.ProjectionStoreV2;
888 const search = yield* ThreadSearch.ThreadSearch;
889 const project = ProjectId.make("project:kestrel");
890 const other = ProjectId.make("project:kestrel-other");
891 yield* createProject(project);
892 yield* createProject(other);
893 const id = (name: string) => ThreadId.make(`thread:kestrel-${name}`);
894 const old = at(10);
895 yield* Effect.forEach(
896 [
897 thread(id("old"), project, { title: "Kestrel nest", settledAt: old }),
898 thread(id("recent"), project, { title: "Kestrel nest", settledAt: at(50) }),
899 thread(id("open"), project, { title: "Kestrel nest" }),
900 thread(id("child"), project, { title: "Kestrel nest", subagentOf: id("old") }),
901 thread(id("elsewhere"), other, { title: "Kestrel nest", settledAt: old }),
902 thread(id("note"), project, { title: "Unrelated", settledAt: old }),
903 thread(id("new-note"), project, { title: "Unrelated", settledAt: at(50) }),
904 ],
905 projections.apply,
906 { discard: true },
907 );
908 const before = DateTime.formatIso(at(30));
909 const messageThreadIds = [id("new-note"), id("note"), id("old")];
910 assert.sameMembers(
911 [...(yield* search.searchOlderSettled({ query: "kestrel", before, messageThreadIds }))],
912 [id("old"), id("elsewhere"), id("note")],
913 );
914 // The scope applies to titles and message hits; message hits follow the titles in order.
915 assert.deepEqual(
916 yield* search.searchOlderSettled({
917 query: "kestrel",
918 before,
919 projectIds: [project],
920 messageThreadIds: [id("elsewhere"), ...messageThreadIds],
921 }),
922 [id("old"), id("note")],
923 );
924 // A palette also matches the environment's name.
925 assert.include(
926 yield* search.searchOlderSettled({
927 query: "laptop unrelated",
928 before,
929 environmentLabel: "Laptop",
930 messageThreadIds: [],
931 }),
932 id("note"),
933 );
934 }),
935 );
936
937 it.effect("matches the branch and linked pull requests, like the palette", () =>
938 Effect.gen(function* () {
939 const projections = yield* ProjectionStore.ProjectionStoreV2;
940 const search = yield* ThreadSearch.ThreadSearch;
941 const project = ProjectId.make("project:heron");
942 yield* createProject(project);
943 const pullRequest = (number: number): ThreadLinkedPullRequest => ({
944 projectId: project,
945 repository: "acme/heron",
946 number,
947 url: `https://github.com/acme/heron/pull/${number}`,
948 });
949 const branch = ThreadId.make("thread:heron-branch");
950 const linked = ThreadId.make("thread:heron-linked");
951 yield* Effect.forEach(
952 [
953 thread(branch, project, {
954 title: "Heron",
955 settledAt: at(10),
956 branchPullRequest: pullRequest(4101),
957 }),
958 thread(linked, project, {
959 title: "Heron",
960 settledAt: at(10),
961 linkedPullRequest: pullRequest(4202),
962 }),
963 ],
964 projections.apply,
965 { discard: true },
966 );
967 const find = (query: string) =>
968 search.searchOlderSettled({
969 query,
970 before: DateTime.formatIso(at(30)),
971 messageThreadIds: [],
972 });
973 assert.deepEqual(yield* find("#4101"), [branch]);
974 assert.deepEqual(yield* find("acme/heron#4202"), [linked]);
975 }),
976 );
977});
978
979it.layer(layerTest)("ThreadSearch.searchThreadsWithOlderSettledRows", (it) => {
980 it.effect("adds older settled rows to message hits, or alone for titles only", () =>
981 Effect.gen(function* () {
982 const projections = yield* ProjectionStore.ProjectionStoreV2;
983 const search = yield* ThreadSearch.ThreadSearch;
984 const sql = yield* SqlClient.SqlClient;
985 const project = ProjectId.make("project:plover");
986 yield* createProject(project);
987 const old = ThreadId.make("thread:plover-old");
988 const recent = ThreadId.make("thread:plover-recent");
989 yield* Effect.forEach(
990 [
991 thread(old, project, { title: "Plover nest", settledAt: at(10) }),
992 thread(recent, project, { title: "Plover nest", settledAt: at(50) }),
993 message(recent, "plover-note", "user", "a plover note", { minute: 2 }),
994 ],
995 projections.apply,
996 { discard: true },
997 );
998 const run = (request: { readonly titlesOnly?: boolean }) =>
999 ThreadSearch.searchThreadsWithOlderSettledRows({
1000 request: { query: "plover", olderSettledBefore: DateTime.formatIso(at(30)), ...request },
1001 search: search.search,
1002 searchOlderSettled: search.searchOlderSettled,
1003 sql,
1004 readThreads: (threadIds) =>
1005 projections.readShellSnapshot({ location: "active", threadIds }),
1006 latestSequence: Effect.succeed(7),
1007 });
1008 const withMessages = yield* run({});
1009 assert.deepEqual(
1010 withMessages.matches.map((match) => match.threadId),
1011 [recent],
1012 );
1013 assert.equal(withMessages.snapshotSequence, 7);
1014 assert.deepEqual(
1015 withMessages.threads?.map((row) => row.id),
1016 [old],
1017 );
1018 const titles = yield* run({ titlesOnly: true });
1019 assert.deepEqual(titles.matches, []);
1020 assert.deepEqual(
1021 titles.threads?.map((row) => row.id),
1022 [old],
1023 );
1024 // Without the cut it is the plain message search.
1025 assert.isUndefined(
1026 (yield* ThreadSearch.searchThreadsWithOlderSettledRows({
1027 request: { query: "plover" },
1028 search: search.search,
1029 searchOlderSettled: search.searchOlderSettled,
1030 sql,
1031 readThreads: (threadIds) =>
1032 projections.readShellSnapshot({ location: "active", threadIds }),
1033 latestSequence: Effect.succeed(7),
1034 })).threads,
1035 );
1036 }),
1037 );
1038});
1039
1040it.layer(layerTest)("ThreadSearch.searchThreads", (it) => {
1041 it.effect("keeps room for a message-only thread behind many titled ones", () =>
1042 Effect.gen(function* () {
1043 const projections = yield* ProjectionStore.ProjectionStoreV2;
1044 const search = yield* ThreadSearch.ThreadSearch;
1045 const project = ProjectId.make("project:petrel");
1046 yield* createProject(project);
1047 const messageOnly = ThreadId.make("thread:petrel-message");
1048 yield* Effect.forEach(
1049 [
1050 thread(messageOnly, project),
1051 // The oldest message, so a cut taken before titles drop would lose it.
1052 message(messageOnly, "petrel-old", "user", "a petrel note", { minute: 1 }),
1053 ...Array.from({ length: 50 }, (_, index) => {
1054 const id = ThreadId.make(`thread:petrel-${index}`);
1055 return [
1056 thread(id, project, { title: `Petrel ${index}` }),
1057 message(id, `petrel-${index}`, "user", "petrel again", { minute: 2 }),
1058 ];
1059 }).flat(),
1060 ],
1061 projections.apply,
1062 { discard: true },
1063 );
1064 const { matches } = yield* search.searchThreads({ query: "petrel", limit: 5 });
1065 assert.include(
1066 matches.map((match) => match.threadId),
1067 messageOnly,
1068 );
1069 }),
1070 );
1071
1072 it.effect("leaves titled threads out before the hit limit", () =>
1073 Effect.gen(function* () {
1074 const projections = yield* ProjectionStore.ProjectionStoreV2;
1075 const search = yield* ThreadSearch.ThreadSearch;
1076 const sql = yield* SqlClient.SqlClient;
1077 const project = ProjectId.make("project:hit-limit");
1078 const messageOnly = ThreadId.make("thread:grebe-message");
1079 const titled = ThreadId.make("thread:grebe-titled");
1080 yield* createProject(project);
1081 yield* Effect.forEach(
1082 [
1083 thread(messageOnly, project, { title: "Unrelated" }),
1084 message(messageOnly, "grebe-old", "user", "a grebe note", { minute: 1 }),
1085 thread(titled, project, { title: "Grebe" }),
1086 ],
1087 projections.apply,
1088 { discard: true },
1089 );
1090 // Newer hits than one read holds, all in the titled thread.
1091 yield* sql`
1092 WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 2000)
1093 INSERT INTO orchestration_v2_projection_messages
1094 (message_id, thread_id, role, streaming, created_at, updated_at, payload_json)
1095 SELECT 'grebe-titled-' || i, ${titled}, 'assistant', 0, ${DateTime.formatIso(at(5))},
1096 ${DateTime.formatIso(at(5))}, json_object('text', 'grebe again')
1097 FROM n
1098 `;
1099 const { matches } = yield* search.searchThreads({ query: "grebe", limit: 5 });
1100 assert.include(
1101 matches.map((match) => match.threadId),
1102 messageOnly,
1103 );
1104 }),
1105 );
1106
1107 it.effect("ranks title matches like the palette, then message matches, within one project", () =>
1108 Effect.gen(function* () {
1109 const projections = yield* ProjectionStore.ProjectionStoreV2;
1110 const search = yield* ThreadSearch.ThreadSearch;
1111 const project = ProjectId.make("project:titles");
1112 const otherProject = ProjectId.make("project:titles-other");
1113 yield* createProject(project);
1114 yield* createProject(otherProject);
1115 const wordStart = ThreadId.make("thread:word-start");
1116 const midWord = ThreadId.make("thread:mid-word");
1117 const messageOnly = ThreadId.make("thread:message-only");
1118 const elsewhere = ThreadId.make("thread:elsewhere");
1119 yield* Effect.forEach(
1120 [
1121 thread(midWord, project, { title: "Fix oauth redirect" }),
1122 thread(wordStart, project, { title: "Clean up auth tokens" }),
1123 thread(messageOnly, project, { title: "Unrelated" }),
1124 message(messageOnly, "message-only", "user", "the auth flow broke again"),
1125 thread(elsewhere, otherProject, { title: "Auth everywhere" }),
1126 ],
1127 projections.apply,
1128 { discard: true },
1129 );
1130
1131 // Stronger message hits in another project must not use up this project's limit.
1132 yield* Effect.forEach(
1133 Array.from({ length: 55 }, (_, index) => {
1134 const busy = ThreadId.make(`thread:elsewhere-${index}`);
1135 return [
1136 thread(busy, otherProject),
1137 message(busy, `elsewhere-${index}`, "user", "auth auth auth"),
1138 ];
1139 }).flat(),
1140 projections.apply,
1141 { discard: true },
1142 );
1143 const result = yield* search.searchThreads({ query: "auth", projectId: project, limit: 3 });
1144 assert.deepEqual(
1145 result.matches.map((match) => [match.threadId, match.source]),
1146 [
1147 [wordStart, "title"],
1148 [midWord, "title"],
1149 [messageOnly, "user"],
1150 ],
1151 );
1152 // With one slot, an exact title keeps it.
1153 assert.deepEqual(
1154 (yield* search.searchThreads({ query: "auth", projectId: project, limit: 1 })).matches.map(
1155 (match) => match.threadId,
1156 ),
1157 [wordStart],
1158 );
1159 // Exact matching finds nothing, so one typo is forgiven.
1160 assert.deepEqual(
1161 (yield* search.searchThreads({ query: "tokesn", projectId: project })).matches.map(
1162 (match) => match.title,
1163 ),
1164 ["Clean up auth tokens"],
1165 );
1166 }),
1167 );
1168});
1169
1170it.effect("starts snippets a few words before the match so one line shows it", () =>
1171 Effect.sync(() => {
1172 const snippet = (text: string, word: string) =>
1173 ThreadSearch.buildSearchSnippet(text, text.indexOf(word));
1174 const long = `${"lead ".repeat(60)}the NEEDLE sits here ${"tail ".repeat(60)}`;
1175 const cut = snippet(long, "NEEDLE");
1176 assert.isAtMost(cut.length, 240);
1177 assert.match(cut, /^…(lead ){2,4}the NEEDLE sits here/);
1178 assert.isTrue(cut.endsWith("…"));
1179 // Whitespace collapses only in the shown part, so the offset still lands.
1180 assert.match(snippet(`${"word\n\n ".repeat(60)}un café`, "café"), /un café$/);
1181 // A cut never splits an emoji's surrogate pair.
1182 assert.notMatch(
1183 snippet(`x${"🚀".repeat(200)}needle`, "needle"),
1184 /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,
1185 );
1186 // Emphasis and code marks go, as the thread shows the text.
1187 assert.equal(
1188 ThreadSearch.buildSearchSnippet("Use **bold** and `code` here", 0),
1189 "Use bold and code here",
1190 );
1191 assert.equal(ThreadSearch.buildSearchSnippet("Call __init__ first", 0), "Call __init__ first");
1192 // Short text still moves a late match into view.
1193 assert.equal(snippet(`${"word ".repeat(20)}needle`, "needle"), "…word word word word needle");
1194 }),
1195);
1196
1197it.effect("searches on the reader worker while the writer is busy", () =>
1198 Effect.gen(function* () {
1199 const fileSystem = yield* FileSystem.FileSystem;
1200 const path = yield* Path.Path;
1201 const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-search-" });
1202 const layerFile = Layer.mergeAll(
1203 ThreadSearch.layer,
1204 ProjectionStore.layer,
1205 ProjectStore.layer,
1206 ).pipe(
1207 Layer.provideMerge(SqlitePersistence.layerFromPath(path.join(directory, "state.sqlite"))),
1208 Layer.provide(NodeServices.layer),
1209 );
1210
1211 yield* Effect.gen(function* () {
1212 const projections = yield* ProjectionStore.ProjectionStoreV2;
1213 const search = yield* ThreadSearch.ThreadSearch;
1214 const sql = yield* SqlClient.SqlClient;
1215 const project = ProjectId.make("project:search-reader");
1216 const threadId = ThreadId.make("thread:reader");
1217 yield* createProject(project);
1218 yield* Effect.forEach(
1219 [thread(threadId, project), message(threadId, "reader", "user", "needle on the reader")],
1220 projections.apply,
1221 { discard: true },
1222 );
1223
1224 const writerHeld = yield* Deferred.make<void>();
1225 const releaseWriter = yield* Deferred.make<void>();
1226 const writer = yield* Effect.forkChild(
1227 sql.withTransaction(
1228 Deferred.succeed(writerHeld, undefined).pipe(
1229 Effect.andThen(Deferred.await(releaseWriter)),
1230 ),
1231 ),
1232 );
1233 yield* Deferred.await(writerHeld);
1234 const result = yield* search.search({ query: "needle" });
1235 yield* Deferred.succeed(releaseWriter, undefined);
1236 yield* Fiber.join(writer);
1237
1238 assert.deepEqual(
1239 result.matches.map((match) => match.threadId),
1240 [threadId],
1241 );
1242 }).pipe(Effect.provide(layerFile));
1243 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1244);