Open History to see the last commit
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;
29}
30interface FindPayload extends FindRow {
31 readonly payload: string;
32 readonly entryId: string;
33 readonly type: OrchestrationV2TurnItem["type"];
34}
35interface FindDocument extends FindRow {
36 readonly entryId: string;
37 readonly runId: OrchestrationV2TurnItem["runId"];
38 readonly count: number;
39}
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 });
68}
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 ) ?? []);
83}
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 );
98}
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 };
113}
114
115function countSegments(segments: readonly string[], query: string) {
116 return segments.reduce((sum, text) => sum + countThreadSearchOccurrences(text, query), 0);
117}
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 };
144}
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);
161}
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 };
196}
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 const textCache = yield* Cache.make({
267 capacity: 512,
268 timeToLive: "1 minute",
269 lookup: (key: TextKey) => Effect.sync(() => parseText(key)),
270 });
271 // Bounded separately because each entry can hold a large body; typing reuses the parse.
272 const largeTextCache = yield* Cache.make({
273 capacity: 32,
274 timeToLive: "1 minute",
275 lookup: (key: TextKey) => Effect.sync(() => parseText(key)),
276 });
277 const scans = new Map<
278 string,
279 {
280 sequence: number;
281 documents: readonly FindDocument[];
282 sourceThreadIds: readonly ThreadId[];
283 }
284 >();
285 const readRevision = Effect.fn("ThreadFind.readRevision")(function* (
286 threadIds: readonly ThreadId[],
287 ) {
288 const sources = yield* encodeThreadIds(threadIds);
289 const revision = yield* sql<{ sequence: number }>`
290 WITH RECURSIVE source_threads(thread_id) AS (
291 SELECT value FROM json_each(${sources})
292 UNION
293 SELECT json_extract(t.payload_json, '$.forkedFrom.threadId')
294 FROM orchestration_v2_projection_threads t
295 JOIN source_threads s ON s.thread_id = t.thread_id
296 WHERE json_extract(t.payload_json, '$.forkedFrom.type') = 'run'
297 )
298 SELECT COALESCE(MAX(sequence), 0) AS sequence FROM orchestration_events
299 WHERE application_event_version = 2 AND aggregate_kind = 'thread'
300 AND stream_id IN (SELECT thread_id FROM source_threads)
301 `;
302 return revision[0]?.sequence ?? 0;
303 });
304 const snapshot = Effect.fn("ThreadFind.snapshot")(
305 function* (input: OrchestrationV2SearchThreadInput) {
306 const { threadId } = input;
307 const active = yield* sql<{ cwd: string | null }>`
308 SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd
309 FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id
310 WHERE t.thread_id = ${threadId} AND t.deleted_at IS NULL AND p.deleted_at IS NULL
311 `;
312 if (!active[0]) return yield* new ProjectionStoreThreadNotFoundError({ threadId });
313 const cwd = active[0].cwd ?? undefined;
314 const cacheKey = yield* encodeCacheKey({
315 threadId,
316 cwd,
317 query: input.query,
318 skills: input.skills ?? [],
319 });
320 const cached = scans.get(cacheKey);
321 if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {
322 const selected = selectMatch(cached.documents, input);
323 scans.delete(cacheKey);
324 scans.set(cacheKey, cached);
325 return { result: resultForSelection(selected, cached.documents, cached.sequence) };
326 }
327 const index = yield* readIndex(threadId);
328 const sourceThreadIds = [...new Set([threadId, ...index.map((row) => row.sourceThreadId)])];
329 const sequence = yield* readRevision(sourceThreadIds);
330 const candidates = index
331 .map((row, position) => ({ ...row, position }))
332 .filter((row) =>
333 ["user_message", "assistant_message", "proposed_plan", "user_input_request"].includes(
334 row.item.type,
335 ),
336 );
337 const payloads: FindPayload[] = [];
338 for (let start = 0; start < candidates.length; start += 128) {
339 payloads.push(...(yield* load(threadId, candidates.slice(start, start + 128))));
340 }
341 return { payloads, cwd, sequence, cacheKey, sourceThreadIds };
342 },
343 sql.withTransaction,
344 (effect, input) =>
345 effect.pipe(
346 Effect.mapError((cause) =>
347 isSnapshotError(cause)
348 ? cause
349 : new ProjectionStoreReadError({ threadId: input.threadId, cause }),
350 ),
351 ),
352 );
353 const searchThreadStream = (input: OrchestrationV2SearchThreadInput) =>
354 Stream.unwrap(
355 Effect.gen(function* () {
356 // Release SQLite before decoding and parsing. Both frames describe one snapshot.
357 const data = yield* snapshot(input);
358 if (data.result) return Stream.succeed(data.result);
359 const { payloads, cwd, sequence, cacheKey, sourceThreadIds } = data;
360 const decode = (row: FindPayload) =>
361 decodeItem(row.payload).pipe(
362 Effect.map((item) => ({ ...row, item })),
363 Effect.mapError(
364 (cause) => new ProjectionStoreReadError({ threadId: input.threadId, cause }),
365 ),
366 );
367 // Answers rendered inside question cards must not appear as separate matches.
368 const foldedAnswers = new Set<string>();
369 for (const payload of payloads) {
370 if (payload.type !== "user_input_request") continue;
371 const { item } = yield* decode(payload);
372 if (item.type === "user_input_request" && item.questionAnswer)
373 foldedAnswers.add(`async-answer:${item.questionAnswer.requestId}`);
374 }
375 const rows = payloads.filter(
376 (row) =>
377 row.type !== "user_input_request" &&
378 !(row.type === "user_message" && foldedAnswers.has(row.entryId)),
379 );
380 const documents = new Map<number, FindDocument>();
381 const count = Effect.fnUntraced(function* (row: FindPayload) {
382 const cached = documents.get(row.position);
383 if (cached) return cached;
384 const decoded = yield* decode(row);
385 const key = textKey(decoded.item, cwd, input.skills ?? []);
386 const segments = yield* Cache.get(
387 key.text.length <= 32_768 ? textCache : largeTextCache,
388 key,
389 );
390 const document = documentFor(decoded, countSegments(segments, input.query));
391 documents.set(row.position, document);
392 yield* Effect.yieldNow;
393 return document;
394 });
395 const finish = Effect.gen(function* () {
396 for (const row of rows) yield* count(row);
397 const ordered = rows.map((row) => documents.get(row.position)!);
398 scans.delete(cacheKey);
399 scans.set(cacheKey, { sequence, documents: ordered, sourceThreadIds });
400 if (scans.size > 8) {
401 const oldest = scans.keys().next().value;
402 if (oldest !== undefined) scans.delete(oldest);
403 }
404 return resultForSelection(selectMatch(ordered, input), ordered, sequence);
405 });
406 if (input.index !== undefined || (input.offset ?? 0) !== 0)
407 return Stream.fromEffect(finish);
408 const anchor = Math.max(
409 0,
410 rows.findIndex((row) => row.entryId === input.start?.entryId),
411 );
412 for (let step = 0; step <= rows.length; step++) {
413 const index = (anchor + step) % rows.length;
414 const row = rows[index];
415 if (!row) break;
416 const document = yield* count(row);
417 const occurrence =
418 step === 0 && row.entryId === input.start?.entryId
419 ? Math.min(input.start.occurrence, document.count)
420 : 0;
421 if (occurrence >= document.count) continue;
422 const first: OrchestrationV2SearchThreadResult = {
423 complete: false,
424 snapshotSequence: sequence,
425 totalMatches: 1,
426 activeIndex: 0,
427 match: { entryId: document.entryId, runId: document.runId, occurrence },
428 };
429 return Stream.concat(Stream.succeed(first), Stream.fromEffect(finish));
430 }
431 return Stream.fromEffect(finish);
432 }),
433 );
434 return {
435 searchThreadStream,
436 searchThread: (input: OrchestrationV2SearchThreadInput) =>
437 searchThreadStream(input).pipe(
438 Stream.runCollect,
439 Effect.map((results) => results[results.length - 1]!),
440 ),
441 };
442});