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

ThreadFind.ts

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