Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadSearch.ts

846 lines35.7 KB

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 }
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)];
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))),
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("")}*`;
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 };
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));
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 ? "…" : ""}`;
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 ${foldedMessageSearchText(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 json_each(${shortSpellings}) AS token
395 WHERE NOT EXISTS (
396 SELECT 1 FROM json_each(token.value) AS spelling
397 WHERE instr(${foldedMessageSearchText(sql)}, spelling.value) > 0
398 )
399 )
400 -- The index's own rowid, so FTS5 returns hits newest first and stops at
401 -- the limit; ordering by the messages table's rowid sorts every hit.
402 ORDER BY "messageRowid" DESC
403 LIMIT ${hitLimit}
404 `;
405​
406const TitleCandidateRow = Schema.Struct({
407 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
408 projectTitle: Schema.String,
409 latestUserMessageAt: Schema.NullOr(IsoDateTime),
410});
411​
412export interface ThreadSearchHit {
413 readonly threadId: ThreadId;
414 readonly projectId: ProjectId;
415 readonly title: string;
416 readonly source: "title" | OrchestrationThreadSearchSource;
417 readonly snippet?: string;
418 readonly messageCreatedAt?: string | null;
420​
421export class ThreadSearch extends Context.Service<
422 ThreadSearch,
423 {
424 /** Message text matches, for clients that rank their own thread list. */
425 readonly search: (
426 input: OrchestrationSearchThreadsInput &
427 Pick<OrchestrationV2SearchThreadsInput, "projectIds">,
428 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
429 /**
430 * Title, branch, pull request, and project matches ranked as the command
431 * palette ranks them, then message matches for the remaining threads.
432 */
433 readonly searchThreads: (
434 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
435 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
436 /**
437 * The settled threads before `before` that clients omitting older settled threads should
438 * receive for a query: the best title, branch, pull request and project matches, ranked as
439 * the palette ranks them, then the older ones among `messageThreadIds`, in their order.
440 */
441 readonly searchOlderSettled: (input: {
442 readonly query: string;
443 readonly before: string;
444 readonly projectIds?: ReadonlyArray<ProjectId> | undefined;
445 /** The caller's name for this environment, which its palette also matches. */
446 readonly environmentLabel?: string | undefined;
447 readonly messageThreadIds: ReadonlyArray<ThreadId>;
448 }) => Effect.Effect<ReadonlyArray<ThreadId>, ThreadSearchError>;
449 }
450>()("t3/orchestration-v2/ThreadSearch") {}
451​
452// Title rows a client gets per search: the best ones, since a common word can match every thread.
453// Each message hit gets its row: lists show every hit, and the search already caps the hits.
454const OLDER_SETTLED_TITLE_ROWS = 15;
455​
456// Only the fields the palette scorer reads, so an interactive search does not decode payloads.
457const OlderSettledTitleRow = Schema.Struct({
458 id: ThreadId,
459 title: Schema.String,
460 branch: Schema.NullOr(Schema.String),
461 pullRequests: Schema.NullOr(Schema.fromJsonString(Schema.Array(ThreadPullRequestLink))),
462 linkedPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
463 branchPullRequest: Schema.NullOr(Schema.fromJsonString(ThreadLinkedPullRequest)),
464 opens: Schema.NullOr(Schema.String),
465 createdAt: IsoDateTime,
466 projectTitle: Schema.String,
467 latestUserMessageAt: Schema.NullOr(IsoDateTime),
468});
469​
470/** @public */
471export const make = Effect.gen(function* () {
472 const sql = yield* SqlClient.SqlClient;
473​
474 const searchRows = SqlSchema.findAll({
475 Request: SearchRequest,
476 Result: SearchRow,
477 execute: (request) => messageHitsQuery(sql, request),
478 });
479​
480 const threadOpens = SqlSchema.findAll({
481 Request: Schema.Struct({ threadIds: TokenList }),
482 Result: ThreadOpensRow,
483 execute: ({ threadIds }) => sql`
484 SELECT
485 threads.thread_id AS "threadId",
486 json_extract(threads.payload_json, '$.opens') AS opens,
487 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
488 FROM orchestration_v2_projection_threads AS threads
489 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
490 `,
491 });
492​
493 const titleCandidates = SqlSchema.findAll({
494 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
495 Result: TitleCandidateRow,
496 execute: ({ projectId }) => sql`
497 SELECT
498 threads.payload_json AS thread,
499 projects.title AS "projectTitle",
500 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
501 FROM orchestration_v2_projection_threads AS threads
502 INNER JOIN projection_projects AS projects
503 ON projects.project_id = threads.project_id
504 WHERE threads.deleted_at IS NULL
505 AND threads.archived_at IS NULL
506 AND projects.deleted_at IS NULL
507 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
508 IS NOT 'subagent'
509 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
510 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
511 `,
512 });
513​
514 const olderSettledTitleCandidates = SqlSchema.findAll({
515 Request: Schema.Struct({
516 before: Schema.String,
517 projectIds: Schema.NullOr(TokenList),
518 }),
519 Result: OlderSettledTitleRow,
520 execute: ({ before, projectIds }) => sql`
521 SELECT
522 threads.thread_id AS id,
523 json_extract(threads.payload_json, '$.title') AS title,
524 json_extract(threads.payload_json, '$.branch') AS branch,
525 json_extract(threads.payload_json, '$.pullRequests') AS "pullRequests",
526 json_extract(threads.payload_json, '$.linkedPullRequest') AS "linkedPullRequest",
527 json_extract(threads.payload_json, '$.branchPullRequest') AS "branchPullRequest",
528 json_extract(threads.payload_json, '$.opens') AS opens,
529 json_extract(threads.payload_json, '$.createdAt') AS "createdAt",
530 projects.title AS "projectTitle",
531 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
532 FROM orchestration_v2_projection_threads AS threads
533 INNER JOIN projection_projects AS projects
534 ON projects.project_id = threads.project_id
535 WHERE threads.deleted_at IS NULL
536 AND threads.archived_at IS NULL
537 AND projects.deleted_at IS NULL
538 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
539 IS NOT 'subagent'
540 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
541 AND json_type(threads.payload_json, '$.delegatedFrom') IS NOT 'object'
542 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
543 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
544 AND (${projectIds} IS NULL
545 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
546 `,
547 });
548​
549 const olderSettledIds = SqlSchema.findAll({
550 Request: Schema.Struct({
551 before: Schema.String,
552 threadIds: TokenList,
553 projectIds: Schema.NullOr(TokenList),
554 }),
555 Result: Schema.Struct({ id: ThreadId }),
556 execute: ({ before, threadIds, projectIds }) => sql`
557 SELECT threads.thread_id AS id
558 FROM orchestration_v2_projection_threads AS threads
559 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
560 AND threads.deleted_at IS NULL
561 AND threads.archived_at IS NULL
562 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
563 IS NOT 'subagent'
564 AND json_extract(threads.payload_json, '$.lineage.sideChat') IS NOT 1
565 AND json_type(threads.payload_json, '$.delegatedFrom') IS NOT 'object'
566 AND json_extract(threads.payload_json, '$.settledOverride') = 'settled'
567 AND json_extract(threads.payload_json, '$.settledAt') < ${before}
568 AND (${projectIds} IS NULL
569 OR threads.project_id IN (SELECT value FROM json_each(${projectIds})))
570 `,
571 });
572​
573 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
574 sql.withTransaction(effect).pipe(
575 NodeSqliteClient.readOnly,
576 Effect.mapError(
577 (cause) =>
578 new ThreadSearchError({
579 operation: Schema.isSchemaError(cause) ? "decode" : "query",
580 cause,
581 }),
582 ),
583 );
584​
585 // A project scope applies before ranking, so other projects' stronger hits
586 // cannot use up the limit.
587 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
588 input: OrchestrationSearchThreadsInput & {
589 readonly projectIds: ReadonlyArray<ProjectId> | null;
590 /** Threads the caller already lists, which must not use up the limit. */
591 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
592 /** Off for an agent's search, which has no use for the user's picks. */
593 readonly picks?: boolean;
594 },
595 ) {
596 // One message per thread: the best word match, then what the user wrote,
597 // since that is what they remember asking, then the newest by when it was
598 // written. Row order is not age: imported histories arrive in one batch.
599 // Text relevance (bm25) would cost a pass over every hit in history.
600 type Hit = {
601 readonly row: typeof SearchRow.Type;
602 /** The message as it reads, links as their text. */
603 readonly text: string;
604 readonly quality: number;
605 readonly offset: number;
606 };
607 const newer = (left: Hit, right: Hit) =>
608 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
609 const compareHits = (left: Hit, right: Hit) =>
610 right.quality - left.quality ||
611 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
612 newer(left, right);
613 const rows = yield* read(
614 Effect.gen(function* () {
615 const index = yield* sql`
616 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
617 `;
618 const messageSearch = buildMessageSearch(input.query, index.length > 0);
619 return messageSearch === null
620 ? []
621 : yield* searchRows({
622 ...messageSearch,
623 projectIds: input.projectIds,
624 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
625 });
626 }),
627 );
628 const best = new Map<ThreadId, Hit>();
629 // Matching messages per thread at its best quality: a thread that keeps
630 // using the word ranks above a passing mention, and weaker hits ("Trust"
631 // for "rust") never add to a whole word's count.
632 const hitCounts = new Map<ThreadId, number>();
633 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
634 const matchMessage = messageMatcher(input.query);
635 for (const row of rows) {
636 // A thread shows a link as its text, so messages are matched as they read. Webhook URL
637 // tokens are withheld before matching, so a snippet cut inside the URL has none.
638 const text = withoutWebhookUrlToken(row.text.replace(MARKDOWN_LINK, "$2"));
639 const match = matchMessage(text);
640 if (match === null) continue;
641 const hit = { row, text, ...match };
642 const current = best.get(row.threadId);
643 if (current === undefined || hit.quality > current.quality) {
644 hitCounts.set(row.threadId, 1);
645 } else if (hit.quality === current.quality) {
646 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
647 }
648 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
649 }
650 // Ranked as clients rank them, with picks and use, before the limit cuts:
651 // a thread picked for this query must come back even when it only
652 // matches in a few old messages.
653 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
654 const subjectById = new Map(
655 opens.map((row) => [
656 row.threadId,
657 {
658 title: "",
659 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
660 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
661 },
662 ]),
663 );
664 const now = DateTime.toEpochMillis(yield* DateTime.now);
665 const ranked = rankMessageMatches(
666 [...best.values()].map((hit) => ({
667 ...hit,
668 hits: hitCount(hit.row.threadId),
669 messageCreatedAt: hit.row.messageCreatedAt,
670 })),
671 (hit) => subjectById.get(hit.row.threadId),
672 foldSearchQuery(input.query),
673 now,
674 { picks: input.picks ?? true },
675 );
676 return {
677 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
678 hits: hitCount(row.threadId),
679 threadId: row.threadId,
680 messageId: row.messageId,
681 projectId: row.projectId,
682 source: row.source,
683 snippet: buildSearchSnippet(text, offset),
684 messageCreatedAt: row.messageCreatedAt,
685 quality,
686 })),
687 };
688 });
689​
690 const search: ThreadSearch["Service"]["search"] = (input) =>
691 searchMessages({ ...input, projectIds: input.projectIds ?? null });
692​
693 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
694 "ThreadSearch.searchThreads",
695 )(function* (input) {
696 const limit = input.limit ?? 50;
697 const normalizedQuery = foldSearchQuery(input.query);
698 const now = DateTime.toEpochMillis(yield* DateTime.now);
699 // Agents call this rarely, and a project has hundreds of threads, not
700 // millions, so ranking every active thread in memory stays cheap.
701 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
702 const subjectById = new Map(
703 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
704 row.thread.id,
705 {
706 id: row.thread.id,
707 title: row.thread.title,
708 branch: row.thread.branch,
709 projectTitle: row.projectTitle,
710 pullRequests: threadSearchPullRequests(row.thread),
711 // Like the clients: what the user last wrote, else when the thread began.
712 activityAt: Date.parse(
713 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
714 ),
715 opens: row.thread.opens ?? null,
716 },
717 ]),
718 );
719 const titleRanked = rankSearchItems(candidates, (row, options) =>
720 // An agent's search has no use for the user's palette picks.
721 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
722 ...options,
723 picks: false,
724 }),
725 );
726 const titleHits: ThreadSearchHit[] = titleRanked.slice(0, limit).map(({ item }) => ({
727 threadId: item.thread.id,
728 projectId: item.thread.projectId,
729 title: item.thread.title,
730 source: "title",
731 }));
732 // The message slots are for threads the titles miss: a weaker title match
733 // found again by its messages would push out a better one.
734 const shown = new Set(titleRanked.map(({ item }) => item.thread.id));
735 const { matches } = yield* searchMessages({
736 query: input.query,
737 limit: 50,
738 projectIds: input.projectId === undefined ? null : [input.projectId],
739 excludedThreadIds: shown,
740 picks: false,
741 });
742 const messageHits = matches
743 .filter((match) => subjectById.has(match.threadId))
744 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
745 ...match,
746 title: subjectById.get(match.threadId)!.title,
747 }));
748 // Titles come first, but a fifth of the slots stay for message matches,
749 // as the palette keeps its "In messages" section.
750 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
751 return {
752 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
753 };
754 });
755​
756 const searchOlderSettled: ThreadSearch["Service"]["searchOlderSettled"] = Effect.fn(
757 "ThreadSearch.searchOlderSettled",
758 )(function* ({ query, before, projectIds, environmentLabel, messageThreadIds }) {
759 const normalizedQuery = foldSearchQuery(query);
760 const now = DateTime.toEpochMillis(yield* DateTime.now);
761 const candidates = yield* read(
762 olderSettledTitleCandidates({ before, projectIds: projectIds ?? null }),
763 );
764 const subjectOf = (row: typeof OlderSettledTitleRow.Type): ThreadSearchSubject => ({
765 id: row.id,
766 title: row.title,
767 branch: row.branch,
768 projectTitle: row.projectTitle,
769 environmentLabel: environmentLabel ?? null,
770 pullRequests: threadSearchPullRequests({
771 pullRequests: row.pullRequests ?? undefined,
772 linkedPullRequest: row.linkedPullRequest,
773 branchPullRequest: row.branchPullRequest,
774 }),
775 // Like the clients: what the user last wrote, else when the thread began.
776 activityAt: Date.parse(row.latestUserMessageAt ?? row.createdAt),
777 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
778 });
779 // Picks on, as in the command palette: a thread picked for this query must make the cut.
780 const titleIds = rankSearchItems(candidates, (row, options) =>
781 scoreThreadSearch(normalizedQuery, subjectOf(row), now, { ...options, picks: true }),
782 )
783 .slice(0, OLDER_SETTLED_TITLE_ROWS)
784 .map(({ item }) => item.id);
785 const shown = new Set(titleIds);
786 const messageCandidates = [...new Set(messageThreadIds)].filter((id) => !shown.has(id));
787 const older =
788 messageCandidates.length === 0
789 ? new Set<ThreadId>()
790 : new Set(
791 (yield* read(
792 olderSettledIds({
793 before,
794 threadIds: messageCandidates,
795 projectIds: projectIds ?? null,
796 }),
797 )).map((row) => row.id),
798 );
799 return [...titleIds, ...messageCandidates.filter((id) => older.has(id))];
800 });
801​
802 return ThreadSearch.of({ search, searchThreads, searchOlderSettled });
803});
804​
805export const layer = Layer.effect(ThreadSearch, make);
806​
807/**
808 * The client search: message hits, and with `olderSettledBefore`, the rows of the best older
809 * settled matches, which shells that omit them do not hold.
810 */
811export const searchThreadsWithOlderSettledRows = Effect.fn(
812 "ThreadSearch.searchThreadsWithOlderSettledRows",
813)(function* <E1, E2, E3, E4, E5>(input: {
814 readonly request: OrchestrationV2SearchThreadsInput;
815 readonly search: (
816 input: Parameters<ThreadSearch["Service"]["search"]>[0],
817 ) => Effect.Effect<OrchestrationSearchThreadsResult, E1>;
818 readonly searchOlderSettled: (
819 input: Parameters<ThreadSearch["Service"]["searchOlderSettled"]>[0],
820 ) => Effect.Effect<ReadonlyArray<ThreadId>, E2>;
821 readonly sql: SqlClient.SqlClient;
822 readonly readThreads: (
823 threadIds: ReadonlyArray<ThreadId>,
824 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E4>, E3>;
825 readonly latestSequence: Effect.Effect<number, E5>;
826}) {
827 const { olderSettledBefore, environmentLabel, titlesOnly, ...request } = input.request;
828 const messages: OrchestrationV2SearchThreadsResult =
829 titlesOnly === true ? { matches: [] } : yield* input.search(request);
830 if (olderSettledBefore === undefined) return messages;
831 // Ranked before the rows' transaction, so scoring never holds the shared reader.
832 const threadIds = yield* input.searchOlderSettled({
833 query: request.query,
834 before: olderSettledBefore,
835 projectIds: request.projectIds,
836 environmentLabel,
837 messageThreadIds: messages.matches.map((match) => match.threadId),
838 });
839 const older = yield* loadOlderSettledThreadsPage({
840 sql: input.sql,
841 listThreads: Effect.succeed({ threadIds, counts: [] }),
842 readThreads: input.readThreads,
843 latestSequence: input.latestSequence,
844 });
845 return { ...messages, snapshotSequence: older.snapshotSequence, threads: older.threads };
846});