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