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 projectIds: Schema.NullOr(TokenList),
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, "projectIds" | "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// Marks, joiners, presentation selectors and skin tones draw on the character before them.
205const ATTACHED = /^[\p{Mark}\p{Emoji_Modifier}\u200d]/u;
206
207/**
208 * Up to 240 characters starting a few words before the match at `matchStart`,
209 * whitespace collapsed, with ellipses where the text was cut. The client finds
210 * the highlights again in the result.
211 */
212export function buildSearchSnippet(text: string, matchStart: number): string {
213 let start = Math.max(0, matchStart - SNIPPET_LEAD);
214 const wordStart = text.slice(start, matchStart).search(/\s/);
215 if (start > 0 && wordStart !== -1) start += wordStart + 1;
216 // Cut between characters, not inside an emoji's surrogate pair or before a detached mark.
217 while (
218 start < matchStart &&
219 (isLowSurrogate(text.charCodeAt(start)) || ATTACHED.test(text.slice(start, start + 2)))
220 )
221 start++;
222 // Collapsing whitespace shortens the text, so read more of it.
223 let rawEnd = Math.min(text.length, start + SNIPPET_LENGTH * 2);
224 if (isLowSurrogate(text.charCodeAt(rawEnd))) rawEnd++;
225 // Emphasis and code marks do not show in a thread either.
226 const shown = text
227 .slice(start, rawEnd)
228 .replace(/\*\*|`+/g, "")
229 .replace(/\s+/g, " ")
230 .trim();
231 let end = Math.min(shown.length, SNIPPET_LENGTH - 2);
232 if (isLowSurrogate(shown.charCodeAt(end))) end--;
233 const cut = end < shown.length || rawEnd < text.length;
234 return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;
235}
236
237// Filter hidden subagents and side chats before the hit limit; JS checks word starts and ranking.
238// Both paths narrow ASCII tokens with Latin-1 and Extended-A/B/Additional accent variants.
239// Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages;
240// accented queries and non-Latin case can still miss: "fermée"/"fermee", "ОШИБКА"/"ошибка".
241export const messageHitsQuery = (
242 sql: SqlClient.SqlClient,
243 {
244 match,
245 substrings,
246 shortSpellings,
247 hitLimit,
248 projectIds,
249 excludedThreadIds,
250 }: typeof SearchRequest.Encoded,
251) => sql`
252 WITH eligible AS MATERIALIZED (
253 SELECT threads.thread_id, threads.project_id
254 FROM orchestration_v2_projection_threads AS threads
255 INNER JOIN projection_projects AS projects
256 ON projects.project_id = threads.project_id
257 WHERE threads.deleted_at IS NULL
258 AND threads.archived_at IS NULL
259 AND projects.deleted_at IS NULL
260 AND (${projectIds} IS NULL
261 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
262 AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
263 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
264 IS NOT 'subagent'
265 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
266 )
267 ${
268 match === null
269 ? sql`
270 SELECT
271 messages.rowid AS "messageRowid",
272 messages.message_id AS "messageId",
273 messages.thread_id AS "threadId",
274 eligible.project_id AS "projectId",
275 messages.role AS source,
276 ${messageSearchText(sql)} AS text,
277 messages.created_at AS "messageCreatedAt"
278 FROM orchestration_v2_projection_messages AS messages
279 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
280 WHERE ${indexedMessageCondition(sql)}
281 -- A scan reads every message it passes, so it stops at the newest ones.
282 AND messages.rowid > (
283 SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages
284 ) - ${MESSAGE_SCAN_LIMIT}
285 `
286 : sql`
287 SELECT
288 orchestration_v2_message_search.rowid AS "messageRowid",
289 messages.message_id AS "messageId",
290 messages.thread_id AS "threadId",
291 eligible.project_id AS "projectId",
292 messages.role AS source,
293 ${messageSearchText(sql)} AS text,
294 messages.created_at AS "messageCreatedAt"
295 FROM orchestration_v2_message_search
296 INNER JOIN orchestration_v2_projection_messages AS messages
297 ON messages.rowid = orchestration_v2_message_search.rowid
298 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
299 WHERE orchestration_v2_message_search MATCH ${match}
300 AND orchestration_v2_message_search.rowid >= coalesce((
301 SELECT orchestration_v2_message_search.rowid FROM orchestration_v2_message_search
302 WHERE orchestration_v2_message_search MATCH ${match}
303 ORDER BY orchestration_v2_message_search.rowid DESC
304 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
305 ), 0)
306 AND ${nonPlaceholderMessageCondition(sql)}
307 `
308 }
309 -- Answers to an agent's question show inside its question card, where
310 -- neither find nor a jump can reach them.
311 AND messages.message_id NOT LIKE 'async-answer:%'
312 -- Nor can they reach a rolled-back turn, or a message of a stopped turn
313 -- that no shown item carries, such as a queued prompt that never ran.
314 AND NOT EXISTS (
315 SELECT 1 FROM orchestration_v2_projection_runs AS runs
316 WHERE runs.run_id = messages.run_id
317 AND (
318 runs.status = 'rolled_back'
319 OR (
320 runs.status = 'cancelled'
321 AND NOT EXISTS (
322 SELECT 1 FROM orchestration_v2_projection_turn_items AS items
323 -- Seeks migration 94's message index rather than reading every item of
324 -- the run; + drops the column's affinity, which would stop the seek.
325 WHERE items.thread_id = messages.thread_id
326 AND items.type IN ('user_message', 'assistant_message')
327 AND json_valid(items.payload_json)
328 AND json_extract(items.payload_json, '$.messageId') = +messages.message_id
329 AND items.run_id = runs.run_id
330 AND (
331 json_extract(items.payload_json, '$.inputIntent') IS NOT 'queued_turn'
332 OR json_extract(runs.payload_json, '$.startedAt') IS NOT NULL
333 )
334 )
335 )
336 )
337 )
338 AND NOT EXISTS (
339 -- The text read once, not once per check.
340 SELECT 1 FROM (SELECT ${foldedMessageSearchText(sql)} AS text) AS message,
341 json_each(${substrings}) AS substring
342 WHERE instr(lower(message.text), json_extract(substring.value, '$.token')) = 0
343 AND NOT (
344 (${sql.literal(MESSAGE_HOLDS_ACCENTED_LATIN)})
345 AND message.text GLOB json_extract(substring.value, '$.accentInsensitive')
346 )
347 )
348 AND NOT EXISTS (
349 SELECT 1 FROM json_each(${shortSpellings}) AS token
350 WHERE NOT EXISTS (
351 SELECT 1 FROM json_each(token.value) AS spelling
352 WHERE instr(${foldedMessageSearchText(sql)}, spelling.value) > 0
353 )
354 )
355 -- The index's own rowid, so FTS5 returns hits newest first and stops at
356 -- the limit; ordering by the messages table's rowid sorts every hit.
357 ORDER BY "messageRowid" DESC
358 LIMIT ${hitLimit}
359 `;
360
361const TitleCandidateRow = Schema.Struct({
362 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
363 projectTitle: Schema.String,
364 latestUserMessageAt: Schema.NullOr(IsoDateTime),
365});
366
367export interface ThreadSearchHit {
368 readonly threadId: ThreadId;
369 readonly projectId: ProjectId;
370 readonly title: string;
371 readonly source: "title" | OrchestrationThreadSearchSource;
372 readonly snippet?: string;
373 readonly messageCreatedAt?: string | null;
374}
375
376export class ThreadSearch extends Context.Service<
377 ThreadSearch,
378 {
379 /** Message text matches, for clients that rank their own thread list. */
380 readonly search: (
381 input: OrchestrationSearchThreadsInput &
382 Pick<OrchestrationV2SearchThreadsInput, "projectIds">,
383 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
384 /**
385 * Title, branch, pull request, and project matches ranked as the command
386 * palette ranks them, then message matches for the remaining threads.
387 */
388 readonly searchThreads: (
389 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
390 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
391 /**
392 * The settled threads before `before` that clients omitting older settled threads should
393 * receive for a query: the best title, branch, pull request and project matches, ranked as
394 * the palette ranks them, then the older ones among `messageThreadIds`, in their order.
395 */
396 readonly searchOlderSettled: (input: {
397 readonly query: string;
398 readonly before: string;
399 readonly projectIds?: ReadonlyArray<ProjectId> | undefined;
400 /** The caller's name for this environment, which its palette also matches. */
401 readonly environmentLabel?: string | undefined;
402 readonly messageThreadIds: ReadonlyArray<ThreadId>;
403 }) => Effect.Effect<ReadonlyArray<ThreadId>, ThreadSearchError>;
404 }
405>()("t3/orchestration-v2/ThreadSearch") {}
406
407// Rows a client gets per search: enough for the shown results without sending every match.
408const OLDER_SETTLED_TITLE_ROWS = 15;
409const OLDER_SETTLED_MESSAGE_ROWS = 5;
410
411// Only the fields the palette scorer reads, so an interactive search does not decode payloads.
412const OlderSettledTitleRow = Schema.Struct({
413 id: ThreadId,
414 title: Schema.String,
415 branch: Schema.NullOr(Schema.String),
416 pullRequests: Schema.NullOr(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink))),
417 linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
418 branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
419 opens: Schema.NullOr(Schema.String),
420 createdAt: IsoDateTime,
421 projectTitle: Schema.String,
422 latestUserMessageAt: Schema.NullOr(IsoDateTime),
423});
424
425/** @public */
426export const make = Effect.gen(function* () {
427 const sql = yield* SqlClient.SqlClient;
428
429 const searchRows = SqlSchema.findAll({
430 Request: SearchRequest,
431 Result: SearchRow,
432 execute: (request) => messageHitsQuery(sql, request),
433 });
434
435 const threadOpens = SqlSchema.findAll({
436 Request: Schema.Struct({ threadIds: TokenList }),
437 Result: ThreadOpensRow,
438 execute: ({ threadIds }) => sql`
439 SELECT
440 threads.thread_id AS "threadId",
441 json_extract(threads.payload_json, '$.opens') AS opens,
442 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
443 FROM orchestration_v2_projection_threads AS threads
444 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
445 `,
446 });
447
448 const titleCandidates = SqlSchema.findAll({
449 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
450 Result: TitleCandidateRow,
451 execute: ({ projectId }) => sql`
452 SELECT
453 threads.payload_json AS thread,
454 projects.title AS "projectTitle",
455 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
456 FROM orchestration_v2_projection_threads AS threads
457 INNER JOIN projection_projects AS projects
458 ON projects.project_id = threads.project_id
459 WHERE threads.deleted_at IS NULL
460 AND threads.archived_at IS NULL
461 AND projects.deleted_at IS NULL
462 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
463 IS NOT 'subagent'
464 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
465 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
466 `,
467 });
468
469 const olderSettledTitleCandidates = SqlSchema.findAll({
470 Request: Schema.Struct({
471 before: Schema.String,
472 projectIds: Schema.NullOr(TokenList),
473 }),
474 Result: OlderSettledTitleRow,
475 execute: ({ before, projectIds }) => sql`
476 SELECT
477 threads.thread_id AS id,
478 json_extract(threads.payload_json, '$.title') AS title,
479 json_extract(threads.payload_json, '$.branch') AS branch,
480 json_extract(threads.payload_json, '$.pullRequests') AS "pullRequests",
481 json_extract(threads.payload_json, '$.linkedPullRequest') AS "linkedPullRequest",
482 json_extract(threads.payload_json, '$.branchPullRequest') AS "branchPullRequest",
483 json_extract(threads.payload_json, '$.opens') AS opens,
484 json_extract(threads.payload_json, '$.createdAt') AS "createdAt",
485 projects.title AS "projectTitle",
486 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
487 FROM orchestration_v2_projection_threads AS threads
488 INNER JOIN projection_projects AS projects
489 ON projects.project_id = threads.project_id
490 WHERE threads.deleted_at IS NULL
491 AND threads.archived_at IS NULL
492 AND projects.deleted_at IS NULL
493 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
494 IS NOT 'subagent'
495 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
496 AND json_type(threads.payload_json, '$.delegatedFrom') IS NOT 'object'
497 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
498 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
499 AND (${projectIds} IS NULL
500 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
501 `,
502 });
503
504 const olderSettledIds = SqlSchema.findAll({
505 Request: Schema.Struct({
506 before: Schema.String,
507 threadIds: TokenList,
508 projectIds: Schema.NullOr(TokenList),
509 }),
510 Result: Schema.Struct({ id: ThreadId }),
511 execute: ({ before, threadIds, projectIds }) => sql`
512 SELECT threads.thread_id AS id
513 FROM orchestration_v2_projection_threads AS threads
514 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
515 AND threads.deleted_at IS NULL
516 AND threads.archived_at IS NULL
517 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
518 IS NOT 'subagent'
519 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
520 AND json_type(threads.payload_json, '$.delegatedFrom') IS NOT 'object'
521 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
522 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
523 AND (${projectIds} IS NULL
524 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
525 `,
526 });
527
528 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
529 sql.withTransaction(effect).pipe(
530 NodeSqliteClient.readOnly,
531 Effect.mapError(
532 (cause) =>
533 new ThreadSearchError({
534 operation: Schema.isSchemaError(cause) ? "decode" : "query",
535 cause,
536 }),
537 ),
538 );
539
540 // A project scope applies before ranking, so other projects' stronger hits
541 // cannot use up the limit.
542 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
543 input: OrchestrationSearchThreadsInput & {
544 readonly projectIds: ReadonlyArray<ProjectId> | null;
545 /** Threads the caller already lists, which must not use up the limit. */
546 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
547 /** Off for an agent's search, which has no use for the user's picks. */
548 readonly picks?: boolean;
549 },
550 ) {
551 // One message per thread: the best word match, then what the user wrote,
552 // since that is what they remember asking, then the newest by when it was
553 // written. Row order is not age: imported histories arrive in one batch.
554 // Text relevance (bm25) would cost a pass over every hit in history.
555 type Hit = {
556 readonly row: typeof SearchRow.Type;
557 /** The message as it reads, links as their text. */
558 readonly text: string;
559 readonly quality: number;
560 readonly offset: number;
561 };
562 const newer = (left: Hit, right: Hit) =>
563 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
564 const compareHits = (left: Hit, right: Hit) =>
565 right.quality - left.quality ||
566 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
567 newer(left, right);
568 const rows = yield* read(
569 Effect.gen(function* () {
570 const index = yield* sql`
571 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
572 `;
573 const messageSearch = buildMessageSearch(input.query, index.length > 0);
574 return messageSearch === null
575 ? []
576 : yield* searchRows({
577 ...messageSearch,
578 projectIds: input.projectIds,
579 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
580 });
581 }),
582 );
583 const best = new Map<ThreadId, Hit>();
584 // Matching messages per thread at its best quality: a thread that keeps
585 // using the word ranks above a passing mention, and weaker hits ("Trust"
586 // for "rust") never add to a whole word's count.
587 const hitCounts = new Map<ThreadId, number>();
588 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
589 const matchMessage = messageMatcher(input.query);
590 for (const row of rows) {
591 // Webhook URL tokens are withheld before matching, so a snippet cut inside the URL has none.
592 const text = withoutWebhookUrlToken(row.text.replace(MARKDOWN_LINK, "$1"));
593 const match = matchMessage(text);
594 if (match === null) continue;
595 const hit = { row, text, ...match };
596 const current = best.get(row.threadId);
597 if (current === undefined || hit.quality > current.quality) {
598 hitCounts.set(row.threadId, 1);
599 } else if (hit.quality === current.quality) {
600 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
601 }
602 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
603 }
604 // Ranked as clients rank them, with picks and use, before the limit cuts:
605 // a thread picked for this query must come back even when it only
606 // matches in a few old messages.
607 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
608 const subjectById = new Map(
609 opens.map((row) => [
610 row.threadId,
611 {
612 title: "",
613 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
614 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
615 },
616 ]),
617 );
618 const now = DateTime.toEpochMillis(yield* DateTime.now);
619 const ranked = rankMessageMatches(
620 [...best.values()].map((hit) => ({
621 ...hit,
622 hits: hitCount(hit.row.threadId),
623 messageCreatedAt: hit.row.messageCreatedAt,
624 })),
625 (hit) => subjectById.get(hit.row.threadId),
626 foldSearchQuery(input.query),
627 now,
628 { picks: input.picks ?? true },
629 );
630 return {
631 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
632 hits: hitCount(row.threadId),
633 threadId: row.threadId,
634 messageId: row.messageId,
635 projectId: row.projectId,
636 source: row.source,
637 snippet: buildSearchSnippet(text, offset),
638 messageCreatedAt: row.messageCreatedAt,
639 quality,
640 })),
641 };
642 });
643
644 const search: ThreadSearch["Service"]["search"] = (input) =>
645 searchMessages({ ...input, projectIds: input.projectIds ?? null });
646
647 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
648 "ThreadSearch.searchThreads",
649 )(function* (input) {
650 const limit = input.limit ?? 50;
651 const normalizedQuery = foldSearchQuery(input.query);
652 const now = DateTime.toEpochMillis(yield* DateTime.now);
653 // Agents call this rarely, and a project has hundreds of threads, not
654 // millions, so ranking every active thread in memory stays cheap.
655 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
656 const subjectById = new Map(
657 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
658 row.thread.id,
659 {
660 id: row.thread.id,
661 title: row.thread.title,
662 branch: row.thread.branch,
663 projectTitle: row.projectTitle,
664 pullRequests: threadSearchPullRequests(row.thread),
665 // Like the clients: what the user last wrote, else when the thread began.
666 activityAt: Date.parse(
667 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
668 ),
669 opens: row.thread.opens ?? null,
670 },
671 ]),
672 );
673 const titleRanked = rankSearchItems(candidates, (row, options) =>
674 // An agent's search has no use for the user's palette picks.
675 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
676 ...options,
677 picks: false,
678 }),
679 );
680 const titleHits: ThreadSearchHit[] = titleRanked.slice(0, limit).map(({ item }) => ({
681 threadId: item.thread.id,
682 projectId: item.thread.projectId,
683 title: item.thread.title,
684 source: "title",
685 }));
686 // The message slots are for threads the titles miss: a weaker title match
687 // found again by its messages would push out a better one.
688 const shown = new Set(titleRanked.map(({ item }) => item.thread.id));
689 const { matches } = yield* searchMessages({
690 query: input.query,
691 limit: 50,
692 projectIds: input.projectId === undefined ? null : [input.projectId],
693 excludedThreadIds: shown,
694 picks: false,
695 });
696 const messageHits = matches
697 .filter((match) => subjectById.has(match.threadId))
698 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
699 ...match,
700 title: subjectById.get(match.threadId)!.title,
701 }));
702 // Titles come first, but a fifth of the slots stay for message matches,
703 // as the palette keeps its "In messages" section.
704 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
705 return {
706 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
707 };
708 });
709
710 const searchOlderSettled: ThreadSearch["Service"]["searchOlderSettled"] = Effect.fn(
711 "ThreadSearch.searchOlderSettled",
712 )(function* ({ query, before, projectIds, environmentLabel, messageThreadIds }) {
713 const normalizedQuery = foldSearchQuery(query);
714 const now = DateTime.toEpochMillis(yield* DateTime.now);
715 const candidates = yield* read(
716 olderSettledTitleCandidates({ before, projectIds: projectIds ?? null }),
717 );
718 const subjectOf = (row: typeof OlderSettledTitleRow.Type): ThreadSearchSubject => ({
719 id: row.id,
720 title: row.title,
721 branch: row.branch,
722 projectTitle: row.projectTitle,
723 environmentLabel: environmentLabel ?? null,
724 pullRequests: threadSearchPullRequests({
725 pullRequests: row.pullRequests ?? undefined,
726 linkedPullRequest: row.linkedPullRequest,
727 branchPullRequest: row.branchPullRequest,
728 }),
729 // Like the clients: what the user last wrote, else when the thread began.
730 activityAt: Date.parse(row.latestUserMessageAt ?? row.createdAt),
731 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
732 });
733 // Picks on, as in the command palette: a thread picked for this query must make the cut.
734 const titleIds = rankSearchItems(candidates, (row, options) =>
735 scoreThreadSearch(normalizedQuery, subjectOf(row), now, { ...options, picks: true }),
736 )
737 .slice(0, OLDER_SETTLED_TITLE_ROWS)
738 .map(({ item }) => item.id);
739 const shown = new Set(titleIds);
740 const messageCandidates = [...new Set(messageThreadIds)].filter((id) => !shown.has(id));
741 const older =
742 messageCandidates.length === 0
743 ? new Set<ThreadId>()
744 : new Set(
745 (yield* read(
746 olderSettledIds({
747 before,
748 threadIds: messageCandidates,
749 projectIds: projectIds ?? null,
750 }),
751 )).map((row) => row.id),
752 );
753 return [
754 ...titleIds,
755 ...messageCandidates.filter((id) => older.has(id)).slice(0, OLDER_SETTLED_MESSAGE_ROWS),
756 ];
757 });
758
759 return ThreadSearch.of({ search, searchThreads, searchOlderSettled });
760});
761
762export const layer = Layer.effect(ThreadSearch, make);
763
764/**
765 * The client search: message hits, and with `olderSettledBefore`, the rows of the best older
766 * settled matches, which shells that omit them do not hold.
767 */
768export const searchThreadsWithOlderSettledRows = Effect.fn(
769 "ThreadSearch.searchThreadsWithOlderSettledRows",
770)(function* <E1, E2, E3, E4, E5>(input: {
771 readonly request: OrchestrationV2SearchThreadsInput;
772 readonly search: (
773 input: Parameters<ThreadSearch["Service"]["search"]>[0],
774 ) => Effect.Effect<OrchestrationSearchThreadsResult, E1>;
775 readonly searchOlderSettled: (
776 input: Parameters<ThreadSearch["Service"]["searchOlderSettled"]>[0],
777 ) => Effect.Effect<ReadonlyArray<ThreadId>, E2>;
778 readonly sql: SqlClient.SqlClient;
779 readonly readThreads: (
780 threadIds: ReadonlyArray<ThreadId>,
781 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E4>, E3>;
782 readonly latestSequence: Effect.Effect<number, E5>;
783}) {
784 const { olderSettledBefore, environmentLabel, titlesOnly, ...request } = input.request;
785 const messages: OrchestrationV2SearchThreadsResult =
786 titlesOnly === true ? { matches: [] } : yield* input.search(request);
787 if (olderSettledBefore === undefined) return messages;
788 // Ranked before the rows' transaction, so scoring never holds the shared reader.
789 const threadIds = yield* input.searchOlderSettled({
790 query: request.query,
791 before: olderSettledBefore,
792 projectIds: request.projectIds,
793 environmentLabel,
794 messageThreadIds: messages.matches.map((match) => match.threadId),
795 });
796 const older = yield* loadOlderSettledThreadsPage({
797 sql: input.sql,
798 listThreads: Effect.succeed({ threadIds, counts: [] }),
799 readThreads: input.readThreads,
800 latestSequence: input.latestSequence,
801 });
802 return { ...messages, snapshotSequence: older.snapshotSequence, threads: older.threads };
803});