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

ThreadFind.ts

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