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