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

ThreadFind.ts

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