Open History to see the last commit
1import {
2 IsoDateTime,
3 MessageId,
4 OrchestrationThreadSearchSource,
5 OrchestrationV2AppThreadJson,
6 OrchestrationV2ThreadOpens,
7 type OrchestrationSearchThreadsInput,
8 type OrchestrationSearchThreadsResult,
9 ProjectId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as DateTime from "effect/DateTime";
13import * as Context from "effect/Context";
14import * as Effect from "effect/Effect";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18import * as SqlClient from "effect/sql/SqlClient";
19import * as SqlSchema from "effect/sql/SqlSchema";
20import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
21import {
22 messageSearchTokens,
23 foldSearchQuery,
24 rankMessageMatches,
25 rankSearchItems,
26 messageMatcher,
27 scoreThreadSearch,
28 type ThreadSearchSubject,
29} from "@t3tools/shared/paletteSearch";
30import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests";
31import { indexedMessageCondition } from "./messageSearchIndex.ts";
32
33// When the user last wrote in the thread aliased `threads`, as the clients
34// rank recency; agent notices in the user role do not count.
35const latestUserMessageAt = (sql: SqlClient.SqlClient) => sql`(
36 SELECT messages.updated_at
37 FROM orchestration_v2_projection_messages AS messages
38 WHERE messages.thread_id = threads.thread_id
39 AND messages.role = 'user'
40 AND COALESCE(json_extract(messages.payload_json, '$.createdBy'), 'user') = 'user'
41 ORDER BY messages.updated_at DESC, messages.message_id DESC
42 LIMIT 1
43)`;
44
45export class ThreadSearchError extends Schema.TaggedError<ThreadSearchError>()(
46 "ThreadSearchError",
47 {
48 operation: Schema.Literals(["query", "decode"]),
49 cause: Schema.Defect(),
50 },
51) {
52 override get message(): string {
53 return `Thread search ${this.operation} failed.`;
54 }
55}
56
57// Token lists bind as JSON arrays, so any number of them is one parameter.
58const TokenList = Schema.fromJsonString(Schema.Array(Schema.String));
59const SearchRequest = Schema.Struct({
60 /** The FTS5 query, or null to scan messages instead. */
61 match: Schema.NullOr(Schema.String),
62 /** Tokens every hit must contain, checked on the text. */
63 substrings: TokenList,
64 projectId: Schema.NullOr(ProjectId),
65 /** Threads the caller already lists, left out before the hit limit. */
66 excludedThreadIds: TokenList,
67});
68const SearchRow = Schema.Struct({
69 messageRowid: Schema.Number,
70 messageId: MessageId,
71 threadId: ThreadId,
72 projectId: ProjectId,
73 source: OrchestrationThreadSearchSource,
74 text: Schema.String,
75 messageCreatedAt: Schema.NullOr(IsoDateTime),
76});
77
78const ThreadOpensRow = Schema.Struct({
79 threadId: ThreadId,
80 opens: Schema.NullOr(Schema.String),
81 latestUserMessageAt: Schema.NullOr(IsoDateTime),
82});
83const decodeThreadOpens = Schema.decodeUnknownOption(
84 Schema.fromJsonString(OrchestrationV2ThreadOpens),
85);
86
87const SNIPPET_LENGTH = 240;
88// The newest hits read per query. A common word stops here instead of reading
89// every message, so time stays flat as history grows.
90const MESSAGE_HIT_LIMIT = 2000;
91// How many of the newest index hits the filters may pass over to fill that
92// limit: a rare short word or hidden threads would otherwise read every hit.
93const MESSAGE_CANDIDATE_LIMIT = 10_000;
94// Without the index, how many of the newest messages a search scans.
95const MESSAGE_SCAN_LIMIT = 20_000;
96
97/**
98 * The SQL inputs for a message search, or null when the query has no token
99 * long enough to search. Tokens of three or more characters go to the
100 * trigram index as quoted phrases; shorter ones, and every token when the
101 * index cannot serve the query, are checked as substrings of the hits.
102 */
103function buildMessageSearch(
104 query: string,
105 hasIndex: boolean,
106): Omit<typeof SearchRequest.Type, "projectId" | "excludedThreadIds"> | null {
107 const { long, short } = messageSearchTokens(query);
108 if (long.length === 0) return null;
109 // Two-character CJK words are too short for trigrams.
110 const indexed = hasIndex && long.every((token) => Array.from(token).length >= 3);
111 return {
112 match: indexed ? long.map((token) => `"${token.replaceAll('"', '""')}"`).join(" ") : null,
113 substrings: indexed ? short : [...long, ...short],
114 };
115}
116
117// A thread shows a link as its text, so in-thread find cannot reach a match
118// in the address; messages are matched as they read.
119const MARKDOWN_LINK = /!?\[([^\]\n]*)\]\([^)\s]*\)/g;
120
121// Result rows show one line, so the match must sit near the start to be seen.
122const SNIPPET_LEAD = 24;
123
124const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
125
126/**
127 * Up to 240 characters starting a few words before the match at `matchStart`,
128 * whitespace collapsed, with ellipses where the text was cut. The client finds
129 * the highlights again in the result.
130 */
131export function buildSearchSnippet(text: string, matchStart: number): string {
132 let start = Math.max(0, matchStart - SNIPPET_LEAD);
133 const wordStart = text.slice(start, matchStart).search(/\s/);
134 if (start > 0 && wordStart !== -1) start += wordStart + 1;
135 // Cut between characters, not inside an emoji's surrogate pair.
136 if (isLowSurrogate(text.charCodeAt(start))) start++;
137 // Collapsing whitespace shortens the text, so read more of it.
138 const rawEnd = Math.min(text.length, start + SNIPPET_LENGTH * 2);
139 // Emphasis and code marks do not show in a thread either.
140 const shown = text
141 .slice(start, rawEnd)
142 .replace(/\*\*|`+/g, "")
143 .replace(/\s+/g, " ")
144 .trim();
145 let end = Math.min(shown.length, SNIPPET_LENGTH - 2);
146 if (isLowSurrogate(shown.charCodeAt(end))) end--;
147 const cut = end < shown.length || rawEnd < text.length;
148 return `${start > 0 ? "…" : ""}${shown.slice(0, end)}${cut ? "…" : ""}`;
149}
150
151// Hidden subagent threads must be filtered before the hit limit so visible matches aren't lost.
152// Word starts and ranking follow the title rules in JS.
153// Without FTS5 trigrams, or for two-character CJK words, scan the same eligible messages.
154// The scan folds ASCII case only, so accent variants and non-ASCII case variants may not match.
155export const messageHitsQuery = (
156 sql: SqlClient.SqlClient,
157 { match, substrings, projectId, excludedThreadIds }: typeof SearchRequest.Encoded,
158) => sql`
159 WITH eligible AS MATERIALIZED (
160 SELECT threads.thread_id, threads.project_id
161 FROM orchestration_v2_projection_threads AS threads
162 INNER JOIN projection_projects AS projects
163 ON projects.project_id = threads.project_id
164 WHERE threads.deleted_at IS NULL
165 AND threads.archived_at IS NULL
166 AND projects.deleted_at IS NULL
167 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
168 AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
169 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
170 IS NOT 'subagent'
171 )
172 ${
173 match === null
174 ? sql`
175 SELECT
176 messages.rowid AS "messageRowid",
177 messages.message_id AS "messageId",
178 messages.thread_id AS "threadId",
179 eligible.project_id AS "projectId",
180 messages.role AS source,
181 json_extract(messages.payload_json, '$.text') AS text,
182 messages.created_at AS "messageCreatedAt"
183 FROM orchestration_v2_projection_messages AS messages
184 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
185 WHERE ${indexedMessageCondition(sql)}
186 -- A scan reads every message it passes, so it stops at the newest ones.
187 AND messages.rowid > (
188 SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages
189 ) - ${MESSAGE_SCAN_LIMIT}
190 `
191 : sql`
192 SELECT
193 orchestration_v2_message_search.rowid AS "messageRowid",
194 messages.message_id AS "messageId",
195 messages.thread_id AS "threadId",
196 eligible.project_id AS "projectId",
197 messages.role AS source,
198 json_extract(messages.payload_json, '$.text') AS text,
199 messages.created_at AS "messageCreatedAt"
200 FROM orchestration_v2_message_search
201 INNER JOIN orchestration_v2_projection_messages AS messages
202 ON messages.rowid = orchestration_v2_message_search.rowid
203 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
204 WHERE orchestration_v2_message_search MATCH ${match}
205 AND orchestration_v2_message_search.rowid >= coalesce((
206 SELECT rowid FROM orchestration_v2_message_search
207 WHERE orchestration_v2_message_search MATCH ${match}
208 ORDER BY rowid DESC
209 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
210 ), 0)
211 `
212 }
213 -- Answers to an agent's question show inside its question card, where
214 -- neither find nor a jump can reach them.
215 AND messages.message_id NOT LIKE 'async-answer:%'
216 AND NOT EXISTS (
217 SELECT 1 FROM json_each(${substrings}) AS token
218 WHERE instr(lower(json_extract(messages.payload_json, '$.text')), token.value) = 0
219 )
220 -- The index's own rowid, so FTS5 returns hits newest first and stops at
221 -- the limit; ordering by the messages table's rowid sorts every hit.
222 ORDER BY "messageRowid" DESC
223 LIMIT ${MESSAGE_HIT_LIMIT}
224 `;
225
226const TitleCandidateRow = Schema.Struct({
227 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
228 projectTitle: Schema.String,
229 latestUserMessageAt: Schema.NullOr(IsoDateTime),
230});
231
232export interface ThreadSearchHit {
233 readonly threadId: ThreadId;
234 readonly projectId: ProjectId;
235 readonly title: string;
236 readonly source: "title" | OrchestrationThreadSearchSource;
237 readonly snippet?: string;
238 readonly messageCreatedAt?: string | null;
239}
240
241export class ThreadSearch extends Context.Service<
242 ThreadSearch,
243 {
244 /** Message text matches, for clients that rank their own thread list. */
245 readonly search: (
246 input: OrchestrationSearchThreadsInput,
247 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
248 /**
249 * Title, branch, pull request, and project matches ranked as the command
250 * palette ranks them, then message matches for the remaining threads.
251 */
252 readonly searchThreads: (
253 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
254 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
255 }
256>()("t3/orchestration-v2/ThreadSearch") {}
257
258/** @public */
259export const make = Effect.gen(function* () {
260 const sql = yield* SqlClient.SqlClient;
261
262 const searchRows = SqlSchema.findAll({
263 Request: SearchRequest,
264 Result: SearchRow,
265 execute: (request) => messageHitsQuery(sql, request),
266 });
267
268 const threadOpens = SqlSchema.findAll({
269 Request: Schema.Struct({ threadIds: TokenList }),
270 Result: ThreadOpensRow,
271 execute: ({ threadIds }) => sql`
272 SELECT
273 threads.thread_id AS "threadId",
274 json_extract(threads.payload_json, '$.opens') AS opens,
275 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
276 FROM orchestration_v2_projection_threads AS threads
277 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
278 `,
279 });
280
281 const titleCandidates = SqlSchema.findAll({
282 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
283 Result: TitleCandidateRow,
284 execute: ({ projectId }) => sql`
285 SELECT
286 threads.payload_json AS thread,
287 projects.title AS "projectTitle",
288 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
289 FROM orchestration_v2_projection_threads AS threads
290 INNER JOIN projection_projects AS projects
291 ON projects.project_id = threads.project_id
292 WHERE threads.deleted_at IS NULL
293 AND threads.archived_at IS NULL
294 AND projects.deleted_at IS NULL
295 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
296 IS NOT 'subagent'
297 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
298 `,
299 });
300
301 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
302 sql.withTransaction(effect).pipe(
303 NodeSqliteClient.readOnly,
304 Effect.mapError(
305 (cause) =>
306 new ThreadSearchError({
307 operation: Schema.isSchemaError(cause) ? "decode" : "query",
308 cause,
309 }),
310 ),
311 );
312
313 // A project scope applies before ranking, so other projects' stronger hits
314 // cannot use up the limit.
315 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
316 input: OrchestrationSearchThreadsInput & {
317 readonly projectId: ProjectId | null;
318 /** Threads the caller already lists, which must not use up the limit. */
319 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
320 /** Off for an agent's search, which has no use for the user's picks. */
321 readonly picks?: boolean;
322 },
323 ) {
324 // One message per thread: the best word match, then what the user wrote,
325 // since that is what they remember asking, then the newest by when it was
326 // written. Row order is not age: imported histories arrive in one batch.
327 // Text relevance (bm25) would cost a pass over every hit in history.
328 type Hit = {
329 readonly row: typeof SearchRow.Type;
330 /** The message as it reads, links as their text. */
331 readonly text: string;
332 readonly quality: number;
333 readonly offset: number;
334 };
335 const newer = (left: Hit, right: Hit) =>
336 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
337 const compareHits = (left: Hit, right: Hit) =>
338 right.quality - left.quality ||
339 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
340 newer(left, right);
341 const rows = yield* read(
342 Effect.gen(function* () {
343 const index = yield* sql`
344 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
345 `;
346 const messageSearch = buildMessageSearch(input.query, index.length > 0);
347 return messageSearch === null
348 ? []
349 : yield* searchRows({
350 ...messageSearch,
351 projectId: input.projectId,
352 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
353 });
354 }),
355 );
356 const best = new Map<ThreadId, Hit>();
357 // Matching messages per thread at its best quality: a thread that keeps
358 // using the word ranks above a passing mention, and weaker hits ("Trust"
359 // for "rust") never add to a whole word's count.
360 const hitCounts = new Map<ThreadId, number>();
361 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
362 const matchMessage = messageMatcher(input.query);
363 for (const row of rows) {
364 const text = row.text.replace(MARKDOWN_LINK, "$1");
365 const match = matchMessage(text);
366 if (match === null) continue;
367 const hit = { row, text, ...match };
368 const current = best.get(row.threadId);
369 if (current === undefined || hit.quality > current.quality) {
370 hitCounts.set(row.threadId, 1);
371 } else if (hit.quality === current.quality) {
372 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
373 }
374 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
375 }
376 // Ranked as clients rank them, with picks and use, before the limit cuts:
377 // a thread picked for this query must come back even when it only
378 // matches in a few old messages.
379 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
380 const subjectById = new Map(
381 opens.map((row) => [
382 row.threadId,
383 {
384 title: "",
385 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
386 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
387 },
388 ]),
389 );
390 const now = DateTime.toEpochMillis(yield* DateTime.now);
391 const ranked = rankMessageMatches(
392 [...best.values()].map((hit) => ({
393 ...hit,
394 hits: hitCount(hit.row.threadId),
395 messageCreatedAt: hit.row.messageCreatedAt,
396 })),
397 (hit) => subjectById.get(hit.row.threadId),
398 foldSearchQuery(input.query),
399 now,
400 { picks: input.picks ?? true },
401 );
402 return {
403 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
404 hits: hitCount(row.threadId),
405 threadId: row.threadId,
406 messageId: row.messageId,
407 projectId: row.projectId,
408 source: row.source,
409 snippet: buildSearchSnippet(text, offset),
410 messageCreatedAt: row.messageCreatedAt,
411 quality,
412 })),
413 };
414 });
415
416 const search: ThreadSearch["Service"]["search"] = (input) =>
417 searchMessages({ ...input, projectId: null });
418
419 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
420 "ThreadSearch.searchThreads",
421 )(function* (input) {
422 const limit = input.limit ?? 50;
423 const normalizedQuery = foldSearchQuery(input.query);
424 const now = DateTime.toEpochMillis(yield* DateTime.now);
425 // Agents call this rarely, and a project has hundreds of threads, not
426 // millions, so ranking every active thread in memory stays cheap.
427 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
428 const subjectById = new Map(
429 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
430 row.thread.id,
431 {
432 id: row.thread.id,
433 title: row.thread.title,
434 branch: row.thread.branch,
435 projectTitle: row.projectTitle,
436 pullRequests: threadSearchPullRequests(row.thread),
437 // Like the clients: what the user last wrote, else when the thread began.
438 activityAt: Date.parse(
439 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
440 ),
441 opens: row.thread.opens ?? null,
442 },
443 ]),
444 );
445 const titleHits: ThreadSearchHit[] = rankSearchItems(candidates, (row, options) =>
446 // An agent's search has no use for the user's palette picks.
447 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
448 ...options,
449 picks: false,
450 }),
451 )
452 .slice(0, limit)
453 .map(({ item }) => ({
454 threadId: item.thread.id,
455 projectId: item.thread.projectId,
456 title: item.thread.title,
457 source: "title",
458 }));
459 const shown = new Set(titleHits.map((hit) => hit.threadId));
460 const { matches } = yield* searchMessages({
461 query: input.query,
462 limit: 50,
463 projectId: input.projectId ?? null,
464 excludedThreadIds: shown,
465 picks: false,
466 });
467 const messageHits = matches
468 .filter((match) => subjectById.has(match.threadId))
469 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
470 ...match,
471 title: subjectById.get(match.threadId)!.title,
472 }));
473 // Titles come first, but a fifth of the slots stay for message matches,
474 // as the palette keeps its "In messages" section.
475 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
476 return {
477 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
478 };
479 });
480
481 return ThreadSearch.of({ search, searchThreads });
482});
483
484export const layer = Layer.effect(ThreadSearch, make);