Open History to see the last commit
1import {
2 IsoDateTime,
3 MessageId,
4 OrchestrationThreadSearchSource,
5 OrchestrationV2AppThreadJson,
6 OrchestrationV2ThreadOpens,
7 ThreadLinkedPullRequest,
8 ThreadPullRequestLink,
9 type OrchestrationSearchThreadsInput,
10 type OrchestrationSearchThreadsResult,
11 type OrchestrationV2SearchThreadsInput,
12 type OrchestrationV2SearchThreadsResult,
13 type OrchestrationV2ThreadShellSnapshot,
14 ProjectId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Context from "effect/Context";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Schema from "effect/Schema";
23import * as SqlClient from "effect/sql/SqlClient";
24import * as SqlSchema from "effect/sql/SqlSchema";
25import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
26import {
27 EXACT_PHRASE_GAP,
28 messageSearchTokens,
29 foldSearchQuery,
30 rankMessageMatches,
31 rankSearchItems,
32 messageMatcher,
33 scoreThreadSearch,
34 type ThreadSearchSubject,
35} from "@t3tools/shared/paletteSearch";
36import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
37import {
38 foldedMessageSearchText,
39 indexedMessageCondition,
40 messageSearchText,
41 nonPlaceholderMessageCondition,
42} from "./messageSearchIndex.ts";
43import { loadOlderSettledThreadsPage } from "./ShellStream.ts";
44import { withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts";
45
46// When the user last wrote in the thread aliased `threads`, as the clients
47// rank recency; agent notices in the user role do not count.
48const latestUserMessageAt = (sql: SqlClient.SqlClient) => sql`(
49 SELECT messages.updated_at
50 FROM orchestration_v2_projection_messages AS messages
51 WHERE messages.thread_id = threads.thread_id
52 AND messages.role = 'user'
53 AND COALESCE(json_extract(messages.payload_json, '$.createdBy'), 'user') = 'user'
54 ORDER BY messages.updated_at DESC, messages.message_id DESC
55 LIMIT 1
56)`;
57
58export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
59 "ThreadSearchError",
60 {
61 operation: Schema.Literals(["query", "decode"]),
62 cause: Schema.Defect(),
63 },
64) {
65 override get message(): string {
66 return `Thread search ${this.operation} failed.`;
67 }
68}
69
70// Token lists bind as JSON arrays, so any number of them is one parameter.
71const TokenList = Schema.fromJsonString(Schema.Array(Schema.String));
72const SearchRequest = Schema.Struct({
73 /** The FTS5 query, or null to scan messages instead. */
74 match: Schema.NullOr(Schema.String),
75 /** Tokens every hit must contain, as typed or as their GLOB folding case and Latin accents. */
76 substrings: Schema.fromJsonString(
77 Schema.Array(Schema.Struct({ token: Schema.String, accentInsensitive: Schema.String })),
78 ),
79 /** For each short word outside ASCII, the spellings a hit must contain one of. */
80 shortSpellings: Schema.fromJsonString(Schema.Array(Schema.Array(Schema.String))),
81 /** How many of the newest hits to read. */
82 hitLimit: Schema.Number,
83 projectId: Schema.NullOr(ProjectId),
84 /** Threads the caller already lists, left out before the hit limit. */
85 excludedThreadIds: TokenList,
86});
87const SearchRow = Schema.Struct({
88 messageRowid: Schema.Number,
89 messageId: MessageId,
90 threadId: ThreadId,
91 projectId: ProjectId,
92 source: OrchestrationThreadSearchSource,
93 text: Schema.String,
94 messageCreatedAt: Schema.NullOr(IsoDateTime),
95});
96
97const ThreadOpensRow = Schema.Struct({
98 threadId: ThreadId,
99 opens: Schema.NullOr(Schema.String),
100 latestUserMessageAt: Schema.NullOr(IsoDateTime),
101});
102const decodeThreadOpens = Schema.decodeUnknownOption(
103 Schema.fromJsonString(OrchestrationV2ThreadOpens),
104);
105
106const SNIPPET_LENGTH = 240;
107// The newest hits read per query. A common word stops here instead of reading
108// every message, so time stays flat as history grows.
109const MESSAGE_HIT_LIMIT = 2000;
110// How many of the newest index hits the filters may pass over to fill that
111// limit: a rare short word or hidden threads would otherwise read every hit.
112const MESSAGE_CANDIDATE_LIMIT = 10_000;
113// Without the index, how many of the newest messages a search scans.
114const MESSAGE_SCAN_LIMIT = 20_000;
115const NON_ASCII = /[\u0080-\uffff]/;
116
117/** SQLite's lower() folds ASCII only, so a short word is checked as each spelling it can match. */
118function shortTokenSpellings(token: string): ReadonlyArray<string> {
119 const forms = (char: string) => {
120 const plain = char.normalize("NFD").replace(/\p{M}/gu, "");
121 return [char, char.toUpperCase(), plain, plain.toUpperCase()];
122 };
123 const spellings = Array.from(token).reduce<ReadonlyArray<string>>(
124 (prefixes, char) => prefixes.flatMap((prefix) => forms(char).map((form) => prefix + form)),
125 [""],
126 );
127 return [...new Set(spellings)];
128}
129
130// Latin-1 Supplement and Extended-A/B/Additional letters that fold to ASCII,
131// including Romanian and Vietnamese letters SQLite's lower() leaves alone.
132const accentedForms = Map.groupBy(
133 [
134 ...Array.from({ length: 0x250 - 0xc0 }, (_, offset) => String.fromCharCode(0xc0 + offset)),
135 ...Array.from({ length: 0x1f00 - 0x1e00 }, (_, offset) => String.fromCharCode(0x1e00 + offset)),
136 ].filter((char) => /^[a-z]$/.test(foldSearchQuery(char))),
137 (char) => foldSearchQuery(char),
138);
139// Only text that may hold one of those letters (by UTF-8 lead byte) needs the GLOB:
140// lower() already folds ASCII case.
141const MESSAGE_HOLDS_ACCENTED_LATIN = [
142 ...new Set(
143 [...accentedForms.values()].flat().map((char) => Buffer.from(char).toString("hex", 0, 1)),
144 ),
145]
146 .map((lead) => `instr(CAST(message.text AS BLOB), x'${lead}') > 0`)
147 .join(" OR ");
148
149/** A GLOB pattern for `token` anywhere, in any case and with or without Latin accents. */
150function accentInsensitiveGlob(token: string): string {
151 const pattern = Array.from(token, (char) => {
152 const letter = foldSearchQuery(char);
153 if (/^[a-z]$/.test(letter)) {
154 return `[${letter}${letter.toUpperCase()}${accentedForms.get(letter)?.join("") ?? ""}]`;
155 }
156 return /[*?[]/.test(char) ? `[${char}]` : char;
157 });
158 return `*${pattern.join("")}*`;
159}
160
161/**
162 * The SQL inputs for a message search, or null when the query has no token
163 * long enough to search. Tokens of three or more characters go to the
164 * trigram index as quoted phrases; shorter ones, and every token when the
165 * index cannot serve the query, are checked as substrings of the hits.
166 */
167function buildMessageSearch(
168 query: string,
169 hasIndex: boolean,
170): Omit<typeof SearchRequest.Type, "projectId" | "excludedThreadIds"> | null {
171 const { long, short, words, exact } = messageSearchTokens(query);
172 if (long.length === 0) return null;
173 // Two-character CJK words are too short for trigrams.
174 const indexed = hasIndex && long.every((token) => Array.from(token).length >= 3);
175 const narrowing = short.filter((token) => !NON_ASCII.test(token));
176 const phrases = long.map((token) => `"${token.replaceAll('"', '""')}"`).join(" ");
177 // An exact query's words sit together, so the index reads only hits that hold them that
178 // close. The distance covers the widest phrase the matcher accepts, so it never drops a match.
179 const near =
180 exact && long.length > 1
181 ? words.join(" ").length + (words.length - 1) * EXACT_PHRASE_GAP
182 : null;
183 return {
184 match: !indexed ? null : near === null ? phrases : `NEAR(${phrases}, ${near})`,
185 // The matcher drops most hits that hold a phrase's words but not together, so a
186 // phrase reads every candidate: the newest ones would otherwise hide an older match.
187 hitLimit: exact && words.length > 1 ? MESSAGE_CANDIDATE_LIMIT : MESSAGE_HIT_LIMIT,
188 substrings: (indexed ? narrowing : [...long, ...narrowing]).map((token) => ({
189 token,
190 accentInsensitive: accentInsensitiveGlob(token),
191 })),
192 shortSpellings: short.filter((token) => NON_ASCII.test(token)).map(shortTokenSpellings),
193 };
194}
195
196// A thread shows a link as its text, so in-thread find cannot reach a match
197// in the address; messages are matched as they read.
198const MARKDOWN_LINK = /!?\[([^\]\n]*)\]\([^)\s]*\)/g;
199
200// Result rows show one line, so the match must sit near the start to be seen.
201const SNIPPET_LEAD = 24;
202
203const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
204
205/**
206 * Up to 240 characters starting a few words before the match at `matchStart`,
207 * whitespace collapsed, with ellipses where the text was cut. The client finds
208 * the highlights again in the result.
209 */
210export function buildSearchSnippet(text: string, matchStart: number): string {
211 let start = Math.max(0, matchStart - SNIPPET_LEAD);
212 const wordStart = text.slice(start, matchStart).search(/\s/);
213 if (start > 0 && wordStart !== -1) start += wordStart + 1;
214 // Cut between characters, not inside an emoji's surrogate pair.
215 if (isLowSurrogate(text.charCodeAt(start))) start++;
216 // Collapsing whitespace shortens the text, so read more of it.
217 let rawEnd = Math.min(text.length, start + SNIPPET_LENGTH * 2);
218 if (isLowSurrogate(text.charCodeAt(rawEnd))) rawEnd++;
219 // Emphasis and code marks do not show in a thread either.
220 const shown = text
221 .slice(start, rawEnd)
222 .replace(/\*\*|`+/g, "")
223 .replace(/\s+/g, " ")
224 .trim();
225 let end = Math.min(shown.length, SNIPPET_LENGTH - 2);
226 if (isLowSurrogate(shown.charCodeAt(end))) end--;
227 const cut = end < shown.length || rawEnd < text.length;
228 return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;
229}
230
231// Filter hidden subagents and side chats before the hit limit; JS checks word starts and ranking.
232// Both paths narrow ASCII tokens with Latin-1 and Extended-A/B/Additional accent variants.
233// Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages;
234// accented queries and non-Latin case can still miss: "fermée"/"fermee", "ОШИБКА"/"ошибка".
235export const messageHitsQuery = (
236 sql: SqlClient.SqlClient,
237 {
238 match,
239 substrings,
240 shortSpellings,
241 hitLimit,
242 projectId,
243 excludedThreadIds,
244 }: typeof SearchRequest.Encoded,
245) => sql`
246 WITH eligible AS MATERIALIZED (
247 SELECT threads.thread_id, threads.project_id
248 FROM orchestration_v2_projection_threads AS threads
249 INNER JOIN projection_projects AS projects
250 ON projects.project_id = threads.project_id
251 WHERE threads.deleted_at IS NULL
252 AND threads.archived_at IS NULL
253 AND projects.deleted_at IS NULL
254 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
255 AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
256 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
257 IS NOT 'subagent'
258 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
259 )
260 ${
261 match === null
262 ? sql`
263 SELECT
264 messages.rowid AS "messageRowid",
265 messages.message_id AS "messageId",
266 messages.thread_id AS "threadId",
267 eligible.project_id AS "projectId",
268 messages.role AS source,
269 ${messageSearchText(sql)} AS text,
270 messages.created_at AS "messageCreatedAt"
271 FROM orchestration_v2_projection_messages AS messages
272 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
273 WHERE ${indexedMessageCondition(sql)}
274 -- A scan reads every message it passes, so it stops at the newest ones.
275 AND messages.rowid > (
276 SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages
277 ) - ${MESSAGE_SCAN_LIMIT}
278 `
279 : sql`
280 SELECT
281 orchestration_v2_message_search.rowid AS "messageRowid",
282 messages.message_id AS "messageId",
283 messages.thread_id AS "threadId",
284 eligible.project_id AS "projectId",
285 messages.role AS source,
286 ${messageSearchText(sql)} AS text,
287 messages.created_at AS "messageCreatedAt"
288 FROM orchestration_v2_message_search
289 INNER JOIN orchestration_v2_projection_messages AS messages
290 ON messages.rowid = orchestration_v2_message_search.rowid
291 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
292 WHERE orchestration_v2_message_search MATCH ${match}
293 AND orchestration_v2_message_search.rowid >= coalesce((
294 SELECT orchestration_v2_message_search.rowid FROM orchestration_v2_message_search
295 WHERE orchestration_v2_message_search MATCH ${match}
296 ORDER BY orchestration_v2_message_search.rowid DESC
297 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
298 ), 0)
299 AND ${nonPlaceholderMessageCondition(sql)}
300 `
301 }
302 -- Answers to an agent's question show inside its question card, where
303 -- neither find nor a jump can reach them.
304 AND messages.message_id NOT LIKE 'async-answer:%'
305 -- Nor can they reach a rolled-back turn, or a message of a stopped turn
306 -- that no shown item carries, such as a queued prompt that never ran.
307 AND NOT EXISTS (
308 SELECT 1 FROM orchestration_v2_projection_runs AS runs
309 WHERE runs.run_id = messages.run_id
310 AND (
311 runs.status = 'rolled_back'
312 OR (
313 runs.status = 'cancelled'
314 AND NOT EXISTS (
315 SELECT 1 FROM orchestration_v2_projection_turn_items AS items
316 -- Seeks migration 94's message index rather than reading every item of
317 -- the run; + drops the column's affinity, which would stop the seek.
318 WHERE items.thread_id = messages.thread_id
319 AND items.type IN ('user_message', 'assistant_message')
320 AND json_valid(items.payload_json)
321 AND json_extract(items.payload_json, '$.messageId') = +messages.message_id
322 AND items.run_id = runs.run_id
323 AND (
324 json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn'
325 OR json_extract(runs.payload_json, '$.startedAt') IS NOT NULL
326 )
327 )
328 )
329 )
330 )
331 AND NOT EXISTS (
332 -- The text read once, not once per check.
333 SELECT 1 FROM (SELECT ${foldedMessageSearchText(sql)} AS text) AS message,
334 json_each(${substrings}) AS substring
335 WHERE instr(lower(message.text), json_extract(substring.value, '$.token')) = 0
336 AND NOT (
337 (${sql.literal(MESSAGE_HOLDS_ACCENTED_LATIN)})
338 AND message.text GLOB json_extract(substring.value, '$.accentInsensitive')
339 )
340 )
341 AND NOT EXISTS (
342 SELECT 1 FROM json_each(${shortSpellings}) AS token
343 WHERE NOT EXISTS (
344 SELECT 1 FROM json_each(token.value) AS spelling
345 WHERE instr(${foldedMessageSearchText(sql)}, spelling.value) > 0
346 )
347 )
348 -- The index's own rowid, so FTS5 returns hits newest first and stops at
349 -- the limit; ordering by the messages table's rowid sorts every hit.
350 ORDER BY "messageRowid" DESC
351 LIMIT ${hitLimit}
352 `;
353
354const TitleCandidateRow = Schema.Struct({
355 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
356 projectTitle: Schema.String,
357 latestUserMessageAt: Schema.NullOr(IsoDateTime),
358});
359
360export interface ThreadSearchHit {
361 readonly threadId: ThreadId;
362 readonly projectId: ProjectId;
363 readonly title: string;
364 readonly source: "title" | OrchestrationThreadSearchSource;
365 readonly snippet?: string;
366 readonly messageCreatedAt?: string | null;
367}
368
369export class ThreadSearch extends Context.Service<
370 ThreadSearch,
371 {
372 /** Message text matches, for clients that rank their own thread list. */
373 readonly search: (
374 input: OrchestrationSearchThreadsInput,
375 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
376 /**
377 * Title, branch, pull request, and project matches ranked as the command
378 * palette ranks them, then message matches for the remaining threads.
379 */
380 readonly searchThreads: (
381 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
382 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
383 /**
384 * The settled threads before `before` that clients omitting older settled threads should
385 * receive for a query: the best title, branch, pull request and project matches, ranked as
386 * the palette ranks them, then the older ones among `messageThreadIds`, in their order.
387 */
388 readonly searchOlderSettled: (input: {
389 readonly query: string;
390 readonly before: string;
391 readonly projectIds?: ReadonlyArray<ProjectId> | undefined;
392 /** The caller's name for this environment, which its palette also matches. */
393 readonly environmentLabel?: string | undefined;
394 readonly messageThreadIds: ReadonlyArray<ThreadId>;
395 }) => Effect.Effect<ReadonlyArray<ThreadId>, ThreadSearchError>;
396 }
397>()("t3/orchestration-v2/ThreadSearch") {}
398
399// Rows a client gets per search: enough for the shown results without sending every match.
400const OLDER_SETTLED_TITLE_ROWS = 15;
401const OLDER_SETTLED_MESSAGE_ROWS = 5;
402
403// Only the fields the palette scorer reads, so an interactive search does not decode payloads.
404const OlderSettledTitleRow = Schema.Struct({
405 id: ThreadId,
406 title: Schema.String,
407 branch: Schema.NullOr(Schema.String),
408 pullRequests: Schema.NullOr(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink))),
409 linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
410 branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
411 opens: Schema.NullOr(Schema.String),
412 createdAt: IsoDateTime,
413 projectTitle: Schema.String,
414 latestUserMessageAt: Schema.NullOr(IsoDateTime),
415});
416
417/** @public */
418export const make = Effect.gen(function* () {
419 const sql = yield* SqlClient.SqlClient;
420
421 const searchRows = SqlSchema.findAll({
422 Request: SearchRequest,
423 Result: SearchRow,
424 execute: (request) => messageHitsQuery(sql, request),
425 });
426
427 const threadOpens = SqlSchema.findAll({
428 Request: Schema.Struct({ threadIds: TokenList }),
429 Result: ThreadOpensRow,
430 execute: ({ threadIds }) => sql`
431 SELECT
432 threads.thread_id AS "threadId",
433 json_extract(threads.payload_json, '$.opens') AS opens,
434 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
435 FROM orchestration_v2_projection_threads AS threads
436 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
437 `,
438 });
439
440 const titleCandidates = SqlSchema.findAll({
441 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
442 Result: TitleCandidateRow,
443 execute: ({ projectId }) => sql`
444 SELECT
445 threads.payload_json AS thread,
446 projects.title AS "projectTitle",
447 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
448 FROM orchestration_v2_projection_threads AS threads
449 INNER JOIN projection_projects AS projects
450 ON projects.project_id = threads.project_id
451 WHERE threads.deleted_at IS NULL
452 AND threads.archived_at IS NULL
453 AND projects.deleted_at IS NULL
454 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
455 IS NOT 'subagent'
456 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
457 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
458 `,
459 });
460
461 const olderSettledTitleCandidates = SqlSchema.findAll({
462 Request: Schema.Struct({
463 before: Schema.String,
464 projectIds: Schema.NullOr(TokenList),
465 }),
466 Result: OlderSettledTitleRow,
467 execute: ({ before, projectIds }) => sql`
468 SELECT
469 threads.thread_id AS id,
470 json_extract(threads.payload_json, '$.title') AS title,
471 json_extract(threads.payload_json, '$.branch') AS branch,
472 json_extract(threads.payload_json, '$.pullRequests') AS "pullRequests",
473 json_extract(threads.payload_json, '$.linkedPullRequest') AS "linkedPullRequest",
474 json_extract(threads.payload_json, '$.branchPullRequest') AS "branchPullRequest",
475 json_extract(threads.payload_json, '$.opens') AS opens,
476 json_extract(threads.payload_json, '$.createdAt') AS "createdAt",
477 projects.title AS "projectTitle",
478 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
479 FROM orchestration_v2_projection_threads AS threads
480 INNER JOIN projection_projects AS projects
481 ON projects.project_id = threads.project_id
482 WHERE threads.deleted_at IS NULL
483 AND threads.archived_at IS NULL
484 AND projects.deleted_at IS NULL
485 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
486 IS NOT 'subagent'
487 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
488 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
489 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
490 AND (${projectIds} IS NULL
491 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
492 `,
493 });
494
495 const olderSettledIds = SqlSchema.findAll({
496 Request: Schema.Struct({
497 before: Schema.String,
498 threadIds: TokenList,
499 projectIds: Schema.NullOr(TokenList),
500 }),
501 Result: Schema.Struct({ id: ThreadId }),
502 execute: ({ before, threadIds, projectIds }) => sql`
503 SELECT threads.thread_id AS id
504 FROM orchestration_v2_projection_threads AS threads
505 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
506 AND threads.deleted_at IS NULL
507 AND threads.archived_at IS NULL
508 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
509 IS NOT 'subagent'
510 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
511 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
512 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
513 AND (${projectIds} IS NULL
514 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
515 `,
516 });
517
518 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
519 sql.withTransaction(effect).pipe(
520 NodeSqliteClient.readOnly,
521 Effect.mapError(
522 (cause) =>
523 new ThreadSearchError({
524 operation: Schema.isSchemaError(cause) ? "decode" : "query",
525 cause,
526 }),
527 ),
528 );
529
530 // A project scope applies before ranking, so other projects' stronger hits
531 // cannot use up the limit.
532 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
533 input: OrchestrationSearchThreadsInput & {
534 readonly projectId: ProjectId | null;
535 /** Threads the caller already lists, which must not use up the limit. */
536 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
537 /** Off for an agent's search, which has no use for the user's picks. */
538 readonly picks?: boolean;
539 },
540 ) {
541 // One message per thread: the best word match, then what the user wrote,
542 // since that is what they remember asking, then the newest by when it was
543 // written. Row order is not age: imported histories arrive in one batch.
544 // Text relevance (bm25) would cost a pass over every hit in history.
545 type Hit = {
546 readonly row: typeof SearchRow.Type;
547 /** The message as it reads, links as their text. */
548 readonly text: string;
549 readonly quality: number;
550 readonly offset: number;
551 };
552 const newer = (left: Hit, right: Hit) =>
553 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
554 const compareHits = (left: Hit, right: Hit) =>
555 right.quality - left.quality ||
556 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
557 newer(left, right);
558 const rows = yield* read(
559 Effect.gen(function* () {
560 const index = yield* sql`
561 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
562 `;
563 const messageSearch = buildMessageSearch(input.query, index.length > 0);
564 return messageSearch === null
565 ? []
566 : yield* searchRows({
567 ...messageSearch,
568 projectId: input.projectId,
569 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
570 });
571 }),
572 );
573 const best = new Map<ThreadId, Hit>();
574 // Matching messages per thread at its best quality: a thread that keeps
575 // using the word ranks above a passing mention, and weaker hits ("Trust"
576 // for "rust") never add to a whole word's count.
577 const hitCounts = new Map<ThreadId, number>();
578 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
579 const matchMessage = messageMatcher(input.query);
580 for (const row of rows) {
581 // Webhook URL tokens are withheld before matching, so a snippet cut inside the URL has none.
582 const text = withoutWebhookUrlToken(row.text.replace(MARKDOWN_LINK, "$1"));
583 const match = matchMessage(text);
584 if (match === null) continue;
585 const hit = { row, text, ...match };
586 const current = best.get(row.threadId);
587 if (current === undefined || hit.quality > current.quality) {
588 hitCounts.set(row.threadId, 1);
589 } else if (hit.quality === current.quality) {
590 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
591 }
592 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
593 }
594 // Ranked as clients rank them, with picks and use, before the limit cuts:
595 // a thread picked for this query must come back even when it only
596 // matches in a few old messages.
597 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
598 const subjectById = new Map(
599 opens.map((row) => [
600 row.threadId,
601 {
602 title: "",
603 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
604 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
605 },
606 ]),
607 );
608 const now = DateTime.toEpochMillis(yield* DateTime.now);
609 const ranked = rankMessageMatches(
610 [...best.values()].map((hit) => ({
611 ...hit,
612 hits: hitCount(hit.row.threadId),
613 messageCreatedAt: hit.row.messageCreatedAt,
614 })),
615 (hit) => subjectById.get(hit.row.threadId),
616 foldSearchQuery(input.query),
617 now,
618 { picks: input.picks ?? true },
619 );
620 return {
621 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
622 hits: hitCount(row.threadId),
623 threadId: row.threadId,
624 messageId: row.messageId,
625 projectId: row.projectId,
626 source: row.source,
627 snippet: buildSearchSnippet(text, offset),
628 messageCreatedAt: row.messageCreatedAt,
629 quality,
630 })),
631 };
632 });
633
634 const search: ThreadSearch["Service"]["search"] = (input) =>
635 searchMessages({ ...input, projectId: null });
636
637 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
638 "ThreadSearch.searchThreads",
639 )(function* (input) {
640 const limit = input.limit ?? 50;
641 const normalizedQuery = foldSearchQuery(input.query);
642 const now = DateTime.toEpochMillis(yield* DateTime.now);
643 // Agents call this rarely, and a project has hundreds of threads, not
644 // millions, so ranking every active thread in memory stays cheap.
645 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
646 const subjectById = new Map(
647 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
648 row.thread.id,
649 {
650 id: row.thread.id,
651 title: row.thread.title,
652 branch: row.thread.branch,
653 projectTitle: row.projectTitle,
654 pullRequests: threadSearchPullRequests(row.thread),
655 // Like the clients: what the user last wrote, else when the thread began.
656 activityAt: Date.parse(
657 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
658 ),
659 opens: row.thread.opens ?? null,
660 },
661 ]),
662 );
663 const titleRanked = rankSearchItems(candidates, (row, options) =>
664 // An agent's search has no use for the user's palette picks.
665 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
666 ...options,
667 picks: false,
668 }),
669 );
670 const titleHits: ThreadSearchHit[] = titleRanked.slice(0, limit).map(({ item }) => ({
671 threadId: item.thread.id,
672 projectId: item.thread.projectId,
673 title: item.thread.title,
674 source: "title",
675 }));
676 // The message slots are for threads the titles miss: a weaker title match
677 // found again by its messages would push out a better one.
678 const shown = new Set(titleRanked.map(({ item }) => item.thread.id));
679 const { matches } = yield* searchMessages({
680 query: input.query,
681 limit: 50,
682 projectId: input.projectId ?? null,
683 excludedThreadIds: shown,
684 picks: false,
685 });
686 const messageHits = matches
687 .filter((match) => subjectById.has(match.threadId))
688 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
689 ...match,
690 title: subjectById.get(match.threadId)!.title,
691 }));
692 // Titles come first, but a fifth of the slots stay for message matches,
693 // as the palette keeps its "In messages" section.
694 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
695 return {
696 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
697 };
698 });
699
700 const searchOlderSettled: ThreadSearch["Service"]["searchOlderSettled"] = Effect.fn(
701 "ThreadSearch.searchOlderSettled",
702 )(function* ({ query, before, projectIds, environmentLabel, messageThreadIds }) {
703 const normalizedQuery = foldSearchQuery(query);
704 const now = DateTime.toEpochMillis(yield* DateTime.now);
705 const candidates = yield* read(
706 olderSettledTitleCandidates({ before, projectIds: projectIds ?? null }),
707 );
708 const subjectOf = (row: typeof OlderSettledTitleRow.Type): ThreadSearchSubject => ({
709 id: row.id,
710 title: row.title,
711 branch: row.branch,
712 projectTitle: row.projectTitle,
713 environmentLabel: environmentLabel ?? null,
714 pullRequests: threadSearchPullRequests({
715 pullRequests: row.pullRequests ?? undefined,
716 linkedPullRequest: row.linkedPullRequest,
717 branchPullRequest: row.branchPullRequest,
718 }),
719 // Like the clients: what the user last wrote, else when the thread began.
720 activityAt: Date.parse(row.latestUserMessageAt ?? row.createdAt),
721 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
722 });
723 // Picks on, as in the command palette: a thread picked for this query must make the cut.
724 const titleIds = rankSearchItems(candidates, (row, options) =>
725 scoreThreadSearch(normalizedQuery, subjectOf(row), now, { ...options, picks: true }),
726 )
727 .slice(0, OLDER_SETTLED_TITLE_ROWS)
728 .map(({ item }) => item.id);
729 const shown = new Set(titleIds);
730 const messageCandidates = [...new Set(messageThreadIds)].filter((id) => !shown.has(id));
731 const older =
732 messageCandidates.length === 0
733 ? new Set<ThreadId>()
734 : new Set(
735 (yield* read(
736 olderSettledIds({
737 before,
738 threadIds: messageCandidates,
739 projectIds: projectIds ?? null,
740 }),
741 )).map((row) => row.id),
742 );
743 return [
744 ...titleIds,
745 ...messageCandidates.filter((id) => older.has(id)).slice(0, OLDER_SETTLED_MESSAGE_ROWS),
746 ];
747 });
748
749 return ThreadSearch.of({ search, searchThreads, searchOlderSettled });
750});
751
752export const layer = Layer.effect(ThreadSearch, make);
753
754/**
755 * The client search: message hits, and with `olderSettledBefore`, the rows of the best older
756 * settled matches, which shells that omit them do not hold.
757 */
758export const searchThreadsWithOlderSettledRows = Effect.fn(
759 "ThreadSearch.searchThreadsWithOlderSettledRows",
760)(function* <E1, E2, E3, E4, E5>(input: {
761 readonly request: OrchestrationV2SearchThreadsInput;
762 readonly search: (
763 input: OrchestrationSearchThreadsInput,
764 ) => Effect.Effect<OrchestrationSearchThreadsResult, E1>;
765 readonly searchOlderSettled: (
766 input: Parameters<ThreadSearch["Service"]["searchOlderSettled"]>[0],
767 ) => Effect.Effect<ReadonlyArray<ThreadId>, E2>;
768 readonly sql: SqlClient.SqlClient;
769 readonly readThreads: (
770 threadIds: ReadonlyArray<ThreadId>,
771 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E4>, E3>;
772 readonly latestSequence: Effect.Effect<number, E5>;
773}) {
774 const { olderSettledBefore, projectIds, environmentLabel, titlesOnly, ...request } =
775 input.request;
776 const messages: OrchestrationV2SearchThreadsResult =
777 titlesOnly === true ? { matches: [] } : yield* input.search(request);
778 if (olderSettledBefore === undefined) return messages;
779 // Ranked before the rows' transaction, so scoring never holds the shared reader.
780 const threadIds = yield* input.searchOlderSettled({
781 query: request.query,
782 before: olderSettledBefore,
783 projectIds,
784 environmentLabel,
785 messageThreadIds: messages.matches.map((match) => match.threadId),
786 });
787 const older = yield* loadOlderSettledThreadsPage({
788 sql: input.sql,
789 listThreads: Effect.succeed({ threadIds, counts: [] }),
790 readThreads: input.readThreads,
791 latestSequence: input.latestSequence,
792 });
793 return { ...messages, snapshotSequence: older.snapshotSequence, threads: older.threads };
794});