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

ThreadFind.ts

447 lines16.9 KB

1import {
2 OrchestrationV2TurnItemJson,
3 type OrchestrationV2ProjectedTurnItem,
4 OrchestrationV2SearchThreadInput,
5 type OrchestrationV2SearchThreadResult,
6 type OrchestrationV2TurnItem,
7 ThreadId,
8 TurnItemId,
9} from "@t3tools/contracts";
10import { searchableMessageSegments, searchablePlanSegments } from "@t3tools/shared/threadFindText";
11import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
12import * as Cache from "effect/Cache";
13import * as Data from "effect/Data";
14import * as Effect from "effect/Effect";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import * as SqlClient from "effect/sql/SqlClient";
18import {
19 ProjectionStoreReadError,
20 ProjectionStoreThreadNotFoundError,
21 type ProjectionStoreV2Error,
22} from "./ProjectionStore.ts";
23​
24interface FindRow {
25 readonly position: number;
26 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
27 readonly sourceThreadId: ThreadId;
28 readonly sourceItemId: TurnItemId;
30interface FindPayload extends FindRow {
31 readonly payload: string;
32 readonly entryId: string;
33 readonly type: OrchestrationV2TurnItem["type"];
35interface FindDocument extends FindRow {
36 readonly entryId: string;
37 readonly runId: OrchestrationV2TurnItem["runId"];
38 readonly count: number;
40class TextKey extends Data.Class<{
41 text: string;
42 role: "user" | "assistant" | "plan";
43 streaming: boolean;
44 hasContext: boolean;
45 cwd: string | undefined;
46 skills: NonNullable<OrchestrationV2SearchThreadInput["skills"]>;
47}> {}
48​
49function textKey(
50 item: OrchestrationV2TurnItem,
51 cwd: string | undefined,
52 skills: TextKey["skills"],
53) {
54 return new TextKey({
55 text:
56 item.type === "proposed_plan"
57 ? item.markdown
58 : item.type === "user_message" || item.type === "assistant_message"
59 ? item.text
60 : "",
61 role:
62 item.type === "proposed_plan" ? "plan" : item.type === "user_message" ? "user" : "assistant",
63 streaming: item.type === "assistant_message" && item.streaming,
64 hasContext: item.type === "user_message" && item.context !== undefined,
65 cwd,
66 skills,
67 });
69​
70function parseText(key: TextKey): readonly string[] {
71 return key.role === "plan"
72 ? searchablePlanSegments(key.text, key.cwd)
73 : (searchableMessageSegments(
74 {
75 role: key.role,
76 text: key.text,
77 streaming: key.streaming,
78 context: key.hasContext ? { version: 1, records: [] } : undefined,
79 },
80 key.cwd,
81 key.skills,
82 ) ?? []);
84​
85function searchableRows(items: readonly OrchestrationV2ProjectedTurnItem[]) {
86 const foldedAnswers = new Set(
87 items.flatMap(({ item }) =>
88 item.type === "user_input_request" && item.questionAnswer
89 ? [`async-answer:${item.questionAnswer.requestId}`]
90 : [],
91 ),
92 );
93 return items.filter(
94 ({ item }) =>
95 ["user_message", "assistant_message", "proposed_plan"].includes(item.type) &&
96 !(item.type === "user_message" && foldedAnswers.has(item.messageId)),
97 );
99​
100function documentFor(row: OrchestrationV2ProjectedTurnItem, count: number): FindDocument {
101 return {
102 position: row.position,
103 visibility: row.visibility,
104 sourceThreadId: row.sourceThreadId,
105 sourceItemId: row.sourceItemId,
106 entryId:
107 row.item.type === "user_message" || row.item.type === "assistant_message"
108 ? row.item.messageId
109 : row.item.id,
110 runId: row.item.runId,
111 count,
112 };
114​
115function countSegments(segments: readonly string[], query: string) {
116 return segments.reduce((sum, text) => sum + countThreadSearchOccurrences(text, query), 0);
118​
119function selectMatch(
120 documents: readonly FindDocument[],
121 input: Pick<OrchestrationV2SearchThreadInput, "index" | "start" | "offset">,
122) {
123 const totalMatches = documents.reduce((sum, doc) => sum + doc.count, 0);
124 let requestedIndex = input.index ?? 0;
125 if (input.index === undefined && input.start) {
126 const startIndex = documents.findIndex((doc) => doc.entryId === input.start?.entryId);
127 if (startIndex >= 0) {
128 requestedIndex =
129 documents.slice(0, startIndex).reduce((sum, doc) => sum + doc.count, 0) +
130 Math.min(input.start.occurrence, documents[startIndex]!.count);
131 if (requestedIndex >= totalMatches) requestedIndex = 0;
132 }
133 }
134 const activeIndex =
135 input.index === undefined && totalMatches > 0
136 ? (((requestedIndex + (input.offset ?? 0)) % totalMatches) + totalMatches) % totalMatches
137 : Math.min(requestedIndex, Math.max(0, totalMatches - 1));
138 let occurrence = activeIndex;
139 for (const document of documents) {
140 if (occurrence < document.count) return { totalMatches, activeIndex, document, occurrence };
141 occurrence -= document.count;
142 }
143 return { totalMatches, activeIndex, document: null, occurrence: 0 };
145​
146/** The memory projection uses the same match ordering as SQLite. */
147export function findProjectedThreadItems(
148 items: readonly OrchestrationV2ProjectedTurnItem[],
149 input: OrchestrationV2SearchThreadInput,
150 snapshotSequence: number,
151 cwd?: string,
152): OrchestrationV2SearchThreadResult {
153 const rows = searchableRows(items);
154 const docs = rows.map((row) =>
155 documentFor(
156 row,
157 countSegments(parseText(textKey(row.item, cwd, input.skills ?? [])), input.query),
158 ),
159 );
160 return resultForSelection(selectMatch(docs, input), docs, snapshotSequence);
162​
163function resultForSelection(
164 selected: ReturnType<typeof selectMatch>,
165 documents: readonly FindDocument[],
166 snapshotSequence: number,
167): OrchestrationV2SearchThreadResult {
168 let startIndex = 0;
169 const entries = documents.flatMap(({ entryId, runId, count }) => {
170 const entry = { entryId, runId, count, startIndex };
171 startIndex += count;
172 return count > 0 ? [entry] : [];
173 });
174 const selectedEntry = entries.findIndex((entry) => entry.entryId === selected.document?.entryId);
175 const navigation =
176 entries.length <= 17
177 ? entries
178 : Array.from(
179 { length: 17 },
180 (_, i) => entries[(selectedEntry + i - 8 + entries.length) % entries.length]!,
181 );
182 return {
183 snapshotSequence,
184 totalMatches: selected.totalMatches,
185 activeIndex: selected.activeIndex,
186 navigation,
187 match:
188 selected.document === null
189 ? null
190 : {
191 entryId: selected.document.entryId,
192 runId: selected.document.runId,
193 occurrence: selected.occurrence,
194 },
195 };
197​
198export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
199 readIndex: (threadId: ThreadId) => Effect.Effect<
200 readonly (Omit<FindRow, "position"> & {
201 readonly item: Pick<OrchestrationV2TurnItem, "type">;
202 })[],
203 ProjectionStoreV2Error
204 >,
205) {
206 const sql = yield* SqlClient.SqlClient;
207 const encodeCacheKey = Schema.encodeEffect(
208 Schema.fromJsonString(
209 Schema.Struct({
210 threadId: ThreadId,
211 cwd: Schema.optional(Schema.String),
212 query: Schema.String,
213 skills: OrchestrationV2SearchThreadInput.fields.skills,
214 }),
215 ),
216 );
217 const encodeThreadIds = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(ThreadId)));
218 const encodeSources = Schema.encodeEffect(
219 Schema.fromJsonString(Schema.Array(Schema.Struct({ threadId: ThreadId, id: TurnItemId }))),
220 );
221 const decodeItem = Schema.decodeUnknownEffect(Schema.fromJsonString(OrchestrationV2TurnItemJson));
222 const isSnapshotError = Schema.is(
223 Schema.Union([ProjectionStoreReadError, ProjectionStoreThreadNotFoundError]),
224 );
225 const load = Effect.fn("ThreadFind.load")(function* (
226 threadId: ThreadId,
227 rows: readonly FindRow[],
228 ) {
229 if (rows.length === 0) return [];
230 const sources = yield* encodeSources(
231 rows.map((row) => ({ threadId: row.sourceThreadId, id: row.sourceItemId })),
232 ).pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
233 const payloads = yield* sql<{
234 thread_id: string;
235 turn_item_id: string;
236 payload_json: string;
237 entry_id: string;
238 item_type: OrchestrationV2TurnItem["type"];
239 }>`
240 SELECT item.thread_id, item.turn_item_id, item.payload_json,
241 COALESCE(json_extract(item.payload_json, '$.messageId'), item.turn_item_id) AS entry_id,
242 json_extract(item.payload_json, '$.type') AS item_type
243 FROM orchestration_v2_projection_turn_items AS item
244 JOIN json_each(${sources}) AS wanted
245 ON item.thread_id = json_extract(wanted.value, '$.threadId')
246 AND item.turn_item_id = json_extract(wanted.value, '$.id')
247 `.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })));
248 const byThread = new Map<string, Map<string, (typeof payloads)[number]>>();
249 for (const row of payloads) {
250 let items = byThread.get(row.thread_id);
251 if (!items) byThread.set(row.thread_id, (items = new Map()));
252 items.set(row.turn_item_id, row);
253 }
254 return yield* Effect.forEach(rows, (row) => {
255 const payload = byThread.get(row.sourceThreadId)?.get(row.sourceItemId);
256 return payload === undefined
257 ? Effect.fail(new ProjectionStoreReadError({ threadId }))
258 : Effect.succeed({
259 ...row,
260 payload: payload.payload_json,
261 entryId: payload.entry_id,
262 type: payload.item_type,
263 });
264 });
265 });
266 // Each scan visits every message, so a cache smaller than the thread is cycled through and
267 // never hits. Real threads reach a few thousand messages of a few hundred characters.
268 const textCache = yield* Cache.make({
269 capacity: 8192,
270 timeToLive: "1 minute",
271 lookup: (key: TextKey) => Effect.sync(() => parseText(key)),
272 });
273 // Bounded separately because each entry can hold a large body; typing reuses the parse.
274 const largeTextCache = yield* Cache.make({
275 capacity: 32,
276 timeToLive: "1 minute",
277 lookup: (key: TextKey) => Effect.sync(() => parseText(key)),
278 });
279 const scans = new Map<
280 string,
281 {
282 sequence: number;
283 documents: readonly FindDocument[];
284 sourceThreadIds: readonly ThreadId[];
285 }
286 >();
287 const readRevision = Effect.fn("ThreadFind.readRevision")(function* (
288 threadIds: readonly ThreadId[],
289 ) {
290 const sources = yield* encodeThreadIds(threadIds);
291 const revision = yield* sql<{ sequence: number }>`
292 WITH RECURSIVE source_threads(thread_id) AS (
293 SELECT value FROM json_each(${sources})
294 UNION
295 SELECT json_extract(t.payload_json, '$.forkedFrom.threadId')
296 FROM orchestration_v2_projection_threads t
297 JOIN source_threads s ON s.thread_id = t.thread_id
298 WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
299 )
300 SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events
301 -- The planner otherwise walks every V2 event backwards from the newest,
302 -- which takes seconds for a thread that has been idle a long time.
303 INDEXED BY idx_orch_events_stream_sequence
304 WHERE application_event_version = 2 AND aggregate_kind = 'thread'
305 AND stream_id IN (SELECT thread_id FROM source_threads)
306 `;
307 return revision[0]?.sequence ?? 0;
308 });
309 const snapshot = Effect.fn("ThreadFind.snapshot")(
310 function* (input: OrchestrationV2SearchThreadInput) {
311 const { threadId } = input;
312 const active = yield* sql<{ cwd: string | null }>`
313 SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd
314 FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id
315 WHERE t.thread_id = ${threadId} AND t.deleted_at IS NULL AND p.deleted_at IS NULL
316 `;
317 if (!active[0]) return yield* new ProjectionStoreThreadNotFoundError({ threadId });
318 const cwd = active[0].cwd ?? undefined;
319 const cacheKey = yield* encodeCacheKey({
320 threadId,
321 cwd,
322 query: input.query,
323 skills: input.skills ?? [],
324 });
325 const cached = scans.get(cacheKey);
326 if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {
327 const selected = selectMatch(cached.documents, input);
328 scans.delete(cacheKey);
329 scans.set(cacheKey, cached);
330 return { result: resultForSelection(selected, cached.documents, cached.sequence) };
331 }
332 const index = yield* readIndex(threadId);
333 const sourceThreadIds = [...new Set([threadId, ...index.map((row) => row.sourceThreadId)])];
334 const sequence = yield* readRevision(sourceThreadIds);
335 const candidates = index
336 .map((row, position) => ({ ...row, position }))
337 .filter((row) =>
338 ["user_message", "assistant_message", "proposed_plan", "user_input_request"].includes(
339 row.item.type,
340 ),
341 );
342 const payloads: FindPayload[] = [];
343 for (let start = 0; start < candidates.length; start += 128) {
344 payloads.push(...(yield* load(threadId, candidates.slice(start, start + 128))));
345 }
346 return { payloads, cwd, sequence, cacheKey, sourceThreadIds };
347 },
348 sql.withTransaction,
349 (effect, input) =>
350 effect.pipe(
351 Effect.mapError((cause) =>
352 isSnapshotError(cause)
353 ? cause
354 : new ProjectionStoreReadError({ threadId: input.threadId, cause }),
355 ),
356 ),
357 );
358 const searchThreadStream = (input: OrchestrationV2SearchThreadInput) =>
359 Stream.unwrap(
360 Effect.gen(function* () {
361 // Release SQLite before decoding and parsing. Both frames describe one snapshot.
362 const data = yield* snapshot(input);
363 if (data.result) return Stream.succeed(data.result);
364 const { payloads, cwd, sequence, cacheKey, sourceThreadIds } = data;
365 const decode = (row: FindPayload) =>
366 decodeItem(row.payload).pipe(
367 Effect.map((item) => ({ ...row, item })),
368 Effect.mapError(
369 (cause) => new ProjectionStoreReadError({ threadId: input.threadId, cause }),
370 ),
371 );
372 // Answers rendered inside question cards must not appear as separate matches.
373 const foldedAnswers = new Set<string>();
374 for (const payload of payloads) {
375 if (payload.type !== "user_input_request") continue;
376 const { item } = yield* decode(payload);
377 if (item.type === "user_input_request" && item.questionAnswer)
378 foldedAnswers.add(`async-answer:${item.questionAnswer.requestId}`);
379 }
380 const rows = payloads.filter(
381 (row) =>
382 row.type !== "user_input_request" &&
383 !(row.type === "user_message" && foldedAnswers.has(row.entryId)),
384 );
385 const documents = new Map<number, FindDocument>();
386 const count = Effect.fnUntraced(function* (row: FindPayload) {
387 const cached = documents.get(row.position);
388 if (cached) return cached;
389 const decoded = yield* decode(row);
390 const key = textKey(decoded.item, cwd, input.skills ?? []);
391 const segments = yield* Cache.get(
392 key.text.length <= 32_768 ? textCache : largeTextCache,
393 key,
394 );
395 const document = documentFor(decoded, countSegments(segments, input.query));
396 documents.set(row.position, document);
397 yield* Effect.yieldNow;
398 return document;
399 });
400 const finish = Effect.gen(function* () {
401 for (const row of rows) yield* count(row);
402 const ordered = rows.map((row) => documents.get(row.position)!);
403 scans.delete(cacheKey);
404 scans.set(cacheKey, { sequence, documents: ordered, sourceThreadIds });
405 if (scans.size > 8) {
406 const oldest = scans.keys().next().value;
407 if (oldest !== undefined) scans.delete(oldest);
408 }
409 return resultForSelection(selectMatch(ordered, input), ordered, sequence);
410 });
411 if (input.index !== undefined || (input.offset ?? 0) !== 0)
412 return Stream.fromEffect(finish);
413 const anchor = Math.max(
414 0,
415 rows.findIndex((row) => row.entryId === input.start?.entryId),
416 );
417 for (let step = 0; step <= rows.length; step++) {
418 const index = (anchor + step) % rows.length;
419 const row = rows[index];
420 if (!row) break;
421 const document = yield* count(row);
422 const occurrence =
423 step === 0 && row.entryId === input.start?.entryId
424 ? Math.min(input.start.occurrence, document.count)
425 : 0;
426 if (occurrence >= document.count) continue;
427 const first: OrchestrationV2SearchThreadResult = {
428 complete: false,
429 snapshotSequence: sequence,
430 totalMatches: 1,
431 activeIndex: 0,
432 match: { entryId: document.entryId, runId: document.runId, occurrence },
433 };
434 return Stream.concat(Stream.succeed(first), Stream.fromEffect(finish));
435 }
436 return Stream.fromEffect(finish);
437 }),
438 );
439 return {
440 searchThreadStream,
441 searchThread: (input: OrchestrationV2SearchThreadInput) =>
442 searchThreadStream(input).pipe(
443 Stream.runCollect,
444 Effect.map((results) => results[results.length - 1]!),
445 ),
446 };
447});