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// The newest messages that hold every token, from active, non-subagent
152// threads. Every palette and sidebar hides subagent threads, so their
153// messages would only use up the hit limit; filters apply before it, so
154// hidden threads never crowd out a visible match. Word starts and ranking
155// happen in JS, with the rules titles use.
156//
157// Without the index (an SQLite build without FTS5 trigrams, see migration
158// 69) or for two-character CJK words, the same query scans the newest
159// messages migration 69 would index. That scan is weaker than the index: it
160// ignores case for ASCII only and does not fold accents ("cafe" misses
161// "café"). Exported so a test can check the query plan.
162export const messageHitsQuery = (
163 sql: SqlClient.SqlClient,
164 { match, substrings, projectId, excludedThreadIds }: typeof SearchRequest.Encoded,
165) => sql`
166 WITH eligible AS MATERIALIZED (
167 SELECT threads.thread_id, threads.project_id
168 FROM orchestration_v2_projection_threads AS threads
169 INNER JOIN projection_projects AS projects
170 ON projects.project_id = threads.project_id
171 WHERE threads.deleted_at IS NULL
172 AND threads.archived_at IS NULL
173 AND projects.deleted_at IS NULL
174 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
175 AND threads.thread_id NOT IN (SELECT value FROM json_each(${excludedThreadIds}))
176 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
177 IS NOT 'subagent'
178 )
179 ${
180 match === null
181 ? sql`
182 SELECT
183 messages.rowid AS "messageRowid",
184 messages.message_id AS "messageId",
185 messages.thread_id AS "threadId",
186 eligible.project_id AS "projectId",
187 messages.role AS source,
188 json_extract(messages.payload_json, '$.text') AS text,
189 messages.created_at AS "messageCreatedAt"
190 FROM orchestration_v2_projection_messages AS messages
191 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
192 WHERE ${indexedMessageCondition(sql)}
193 -- A scan reads every message it passes, so it stops at the newest ones.
194 AND messages.rowid > (
195 SELECT coalesce(max(rowid), 0) FROM orchestration_v2_projection_messages
196 ) - ${MESSAGE_SCAN_LIMIT}
197 `
198 : sql`
199 SELECT
200 orchestration_v2_message_search.rowid AS "messageRowid",
201 messages.message_id AS "messageId",
202 messages.thread_id AS "threadId",
203 eligible.project_id AS "projectId",
204 messages.role AS source,
205 json_extract(messages.payload_json, '$.text') AS text,
206 messages.created_at AS "messageCreatedAt"
207 FROM orchestration_v2_message_search
208 INNER JOIN orchestration_v2_projection_messages AS messages
209 ON messages.rowid = orchestration_v2_message_search.rowid
210 INNER JOIN eligible ON eligible.thread_id = messages.thread_id
211 WHERE orchestration_v2_message_search MATCH ${match}
212 AND orchestration_v2_message_search.rowid >= coalesce((
213 SELECT rowid FROM orchestration_v2_message_search
214 WHERE orchestration_v2_message_search MATCH ${match}
215 ORDER BY rowid DESC
216 LIMIT 1 OFFSET ${MESSAGE_CANDIDATE_LIMIT - 1}
217 ), 0)
218 `
219 }
220 -- Answers to an agent's question show inside its question card, where
221 -- neither find nor a jump can reach them.
222 AND messages.message_id NOT LIKE 'async-answer:%'
223 AND NOT EXISTS (
224 SELECT 1 FROM json_each(${substrings}) AS token
225 WHERE instr(lower(json_extract(messages.payload_json, '$.text')), token.value) = 0
226 )
227 -- The index's own rowid, so FTS5 returns hits newest first and stops at
228 -- the limit; ordering by the messages table's rowid sorts every hit.
229 ORDER BY "messageRowid" DESC
230 LIMIT ${MESSAGE_HIT_LIMIT}
231 `;
232
233const TitleCandidateRow = Schema.Struct({
234 thread: Schema.fromJsonString(OrchestrationV2AppThreadJson),
235 projectTitle: Schema.String,
236 latestUserMessageAt: Schema.NullOr(IsoDateTime),
237});
238
239export interface ThreadSearchHit {
240 readonly threadId: ThreadId;
241 readonly projectId: ProjectId;
242 readonly title: string;
243 readonly source: "title" | OrchestrationThreadSearchSource;
244 readonly snippet?: string;
245 readonly messageCreatedAt?: string | null;
246}
247
248export class ThreadSearch extends Context.Service<
249 ThreadSearch,
250 {
251 /** Message text matches, for clients that rank their own thread list. */
252 readonly search: (
253 input: OrchestrationSearchThreadsInput,
254 ) => Effect.Effect<OrchestrationSearchThreadsResult, ThreadSearchError>;
255 /**
256 * Title, branch, pull request, and project matches ranked as the command
257 * palette ranks them, then message matches for the remaining threads.
258 */
259 readonly searchThreads: (
260 input: OrchestrationSearchThreadsInput & { readonly projectId?: ProjectId | undefined },
261 ) => Effect.Effect<{ readonly matches: ReadonlyArray<ThreadSearchHit> }, ThreadSearchError>;
262 }
263>()("t3/orchestration-v2/ThreadSearch") {}
264
265/** @public Service construction is part of the canonical Effect module API. */
266export const make = Effect.gen(function* () {
267 const sql = yield* SqlClient.SqlClient;
268
269 const searchRows = SqlSchema.findAll({
270 Request: SearchRequest,
271 Result: SearchRow,
272 execute: (request) => messageHitsQuery(sql, request),
273 });
274
275 const threadOpens = SqlSchema.findAll({
276 Request: Schema.Struct({ threadIds: TokenList }),
277 Result: ThreadOpensRow,
278 execute: ({ threadIds }) => sql`
279 SELECT
280 threads.thread_id AS "threadId",
281 json_extract(threads.payload_json, '$.opens') AS opens,
282 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
283 FROM orchestration_v2_projection_threads AS threads
284 WHERE threads.thread_id IN (SELECT value FROM json_each(${threadIds}))
285 `,
286 });
287
288 const titleCandidates = SqlSchema.findAll({
289 Request: Schema.Struct({ projectId: Schema.NullOr(ProjectId) }),
290 Result: TitleCandidateRow,
291 execute: ({ projectId }) => sql`
292 SELECT
293 threads.payload_json AS thread,
294 projects.title AS "projectTitle",
295 ${latestUserMessageAt(sql)} AS "latestUserMessageAt"
296 FROM orchestration_v2_projection_threads AS threads
297 INNER JOIN projection_projects AS projects
298 ON projects.project_id = threads.project_id
299 WHERE threads.deleted_at IS NULL
300 AND threads.archived_at IS NULL
301 AND projects.deleted_at IS NULL
302 AND json_extract(threads.payload_json, '$.lineage.relationshipToParent')
303 IS NOT 'subagent'
304 AND (${projectId} IS NULL OR threads.project_id = ${projectId})
305 `,
306 });
307
308 const read = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
309 sql.withTransaction(effect).pipe(
310 NodeSqliteClient.readOnly,
311 Effect.mapError(
312 (cause) =>
313 new ThreadSearchError({
314 operation: Schema.isSchemaError(cause) ? "decode" : "query",
315 cause,
316 }),
317 ),
318 );
319
320 // A project scope applies before ranking, so other projects' stronger hits
321 // cannot use up the limit.
322 const searchMessages = Effect.fn("ThreadSearch.search")(function* (
323 input: OrchestrationSearchThreadsInput & {
324 readonly projectId: ProjectId | null;
325 /** Threads the caller already lists, which must not use up the limit. */
326 readonly excludedThreadIds?: ReadonlySet<ThreadId>;
327 /** Off for an agent's search, which has no use for the user's picks. */
328 readonly picks?: boolean;
329 },
330 ) {
331 // One message per thread: the best word match, then what the user wrote,
332 // since that is what they remember asking, then the newest by when it was
333 // written. Row order is not age: imported histories arrive in one batch.
334 // Text relevance (bm25) would cost a pass over every hit in history.
335 type Hit = {
336 readonly row: typeof SearchRow.Type;
337 /** The message as it reads, links as their text. */
338 readonly text: string;
339 readonly quality: number;
340 readonly offset: number;
341 };
342 const newer = (left: Hit, right: Hit) =>
343 (right.row.messageCreatedAt ?? "").localeCompare(left.row.messageCreatedAt ?? "");
344 const compareHits = (left: Hit, right: Hit) =>
345 right.quality - left.quality ||
346 Number(left.row.source !== "user") - Number(right.row.source !== "user") ||
347 newer(left, right);
348 const rows = yield* read(
349 Effect.gen(function* () {
350 const index = yield* sql`
351 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
352 `;
353 const messageSearch = buildMessageSearch(input.query, index.length > 0);
354 return messageSearch === null
355 ? []
356 : yield* searchRows({
357 ...messageSearch,
358 projectId: input.projectId,
359 excludedThreadIds: [...(input.excludedThreadIds ?? [])],
360 });
361 }),
362 );
363 const best = new Map<ThreadId, Hit>();
364 // Matching messages per thread at its best quality: a thread that keeps
365 // using the word ranks above a passing mention, and weaker hits ("Trust"
366 // for "rust") never add to a whole word's count.
367 const hitCounts = new Map<ThreadId, number>();
368 const hitCount = (threadId: ThreadId) => hitCounts.get(threadId) ?? 1;
369 const matchMessage = messageMatcher(input.query);
370 for (const row of rows) {
371 const text = row.text.replace(MARKDOWN_LINK, "$1");
372 const match = matchMessage(text);
373 if (match === null) continue;
374 const hit = { row, text, ...match };
375 const current = best.get(row.threadId);
376 if (current === undefined || hit.quality > current.quality) {
377 hitCounts.set(row.threadId, 1);
378 } else if (hit.quality === current.quality) {
379 hitCounts.set(row.threadId, hitCount(row.threadId) + 1);
380 }
381 if (current === undefined || compareHits(hit, current) < 0) best.set(row.threadId, hit);
382 }
383 // Ranked as clients rank them, with picks and use, before the limit cuts:
384 // a thread picked for this query must come back even when it only
385 // matches in a few old messages.
386 const opens = best.size === 0 ? [] : yield* read(threadOpens({ threadIds: [...best.keys()] }));
387 const subjectById = new Map(
388 opens.map((row) => [
389 row.threadId,
390 {
391 title: "",
392 activityAt: row.latestUserMessageAt === null ? null : Date.parse(row.latestUserMessageAt),
393 opens: Option.getOrNull(decodeThreadOpens(row.opens)),
394 },
395 ]),
396 );
397 const now = DateTime.toEpochMillis(yield* DateTime.now);
398 const ranked = rankMessageMatches(
399 [...best.values()].map((hit) => ({
400 ...hit,
401 hits: hitCount(hit.row.threadId),
402 messageCreatedAt: hit.row.messageCreatedAt,
403 })),
404 (hit) => subjectById.get(hit.row.threadId),
405 foldSearchQuery(input.query),
406 now,
407 { picks: input.picks ?? true },
408 );
409 return {
410 matches: ranked.slice(0, input.limit ?? 50).map(({ row, text, quality, offset }) => ({
411 hits: hitCount(row.threadId),
412 threadId: row.threadId,
413 messageId: row.messageId,
414 projectId: row.projectId,
415 source: row.source,
416 snippet: buildSearchSnippet(text, offset),
417 messageCreatedAt: row.messageCreatedAt,
418 quality,
419 })),
420 };
421 });
422
423 const search: ThreadSearch["Service"]["search"] = (input) =>
424 searchMessages({ ...input, projectId: null });
425
426 const searchThreads: ThreadSearch["Service"]["searchThreads"] = Effect.fn(
427 "ThreadSearch.searchThreads",
428 )(function* (input) {
429 const limit = input.limit ?? 50;
430 const normalizedQuery = foldSearchQuery(input.query);
431 const now = DateTime.toEpochMillis(yield* DateTime.now);
432 // Agents call this rarely, and a project has hundreds of threads, not
433 // millions, so ranking every active thread in memory stays cheap.
434 const candidates = yield* read(titleCandidates({ projectId: input.projectId ?? null }));
435 const subjectById = new Map(
436 candidates.map((row): [ThreadId, ThreadSearchSubject] => [
437 row.thread.id,
438 {
439 id: row.thread.id,
440 title: row.thread.title,
441 branch: row.thread.branch,
442 projectTitle: row.projectTitle,
443 pullRequests: threadSearchPullRequests(row.thread),
444 // Like the clients: what the user last wrote, else when the thread began.
445 activityAt: Date.parse(
446 row.latestUserMessageAt ?? DateTime.formatIso(row.thread.createdAt),
447 ),
448 opens: row.thread.opens ?? null,
449 },
450 ]),
451 );
452 const titleHits: ThreadSearchHit[] = rankSearchItems(candidates, (row, options) =>
453 // An agent's search has no use for the user's palette picks.
454 scoreThreadSearch(normalizedQuery, subjectById.get(row.thread.id)!, now, {
455 ...options,
456 picks: false,
457 }),
458 )
459 .slice(0, limit)
460 .map(({ item }) => ({
461 threadId: item.thread.id,
462 projectId: item.thread.projectId,
463 title: item.thread.title,
464 source: "title",
465 }));
466 const shown = new Set(titleHits.map((hit) => hit.threadId));
467 const { matches } = yield* searchMessages({
468 query: input.query,
469 limit: 50,
470 projectId: input.projectId ?? null,
471 excludedThreadIds: shown,
472 picks: false,
473 });
474 const messageHits = matches
475 .filter((match) => subjectById.has(match.threadId))
476 .map(({ quality: _quality, hits: _hits, messageId: _messageId, ...match }) => ({
477 ...match,
478 title: subjectById.get(match.threadId)!.title,
479 }));
480 // Titles come first, but a fifth of the slots stay for message matches,
481 // as the palette keeps its "In messages" section.
482 const messageSlots = Math.min(messageHits.length, Math.floor(limit / 5));
483 return {
484 matches: [...titleHits.slice(0, limit - messageSlots), ...messageHits].slice(0, limit),
485 };
486 });
487
488 return ThreadSearch.of({ search, searchThreads });
489});
490
491export const layer = Layer.effect(ThreadSearch, make);