Open History to see the last commit
1import * as Effect from "effect/Effect";
2import type * as SqlClient from "effect/sql/SqlClient";
3
4/**
5 * Exclude generated notices and subagent threads: search hides them, and ACP subagents rewrite
6 * their finished answer on every streamed chunk.
7 * Migration triggers, backfill, rebuild and scans share this predicate; `row` may be `new`.
8 */
9export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "messages") =>
10 sql.literal(`
11 ${row}.streaming = 0
12 AND (
13 ${row}.role = 'assistant'
14 OR (
15 ${row}.role = 'user'
16 AND COALESCE(json_extract(${row}.payload_json, '$.createdBy'), 'user') = 'user'
17 )
18 )
19 AND NOT EXISTS (
20 SELECT 1 FROM orchestration_v2_projection_threads AS subagent_threads
21 WHERE subagent_threads.thread_id = ${row}.thread_id
22 AND json_extract(subagent_threads.payload_json, '$.lineage.relationshipToParent') = 'subagent'
23 )
24`);
25
26/**
27 * What the index stores for a message: its text with curly apostrophes
28 * straight, as search folds a query, since iOS keyboards type "’" and others
29 * type "'". Migration 69's triggers use it too. `payload` is the message's
30 * JSON column.
31 */
32export const indexedMessageText = (sql: SqlClient.SqlClient, payload: string) =>
33 sql.literal(`replace(replace(json_extract(${payload}, '$.text'), '’', ''''), '‘', '''')`);
34
35/**
36 * Refills the search index from the messages table. The index is keyed by
37 * message rowid, so anything that may renumber or copy rows (VACUUM, a dev
38 * database copy) rebuilds it instead of trusting it. Databases from before
39 * migration 69, or on an SQLite without FTS5 trigrams, have no index.
40 */
41export const rebuildMessageSearch = Effect.fn("MessageSearchIndex.rebuild")(function* (
42 sql: SqlClient.SqlClient,
43) {
44 const index = yield* sql`
45 SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search'
46 `;
47 if (index.length === 0) return;
48 // One transaction: an interrupt between clear and refill would leave an
49 // empty index that nothing repairs, since search only checks the table exists.
50 yield* sql.withTransaction(
51 Effect.gen(function* () {
52 yield* sql`
53 INSERT INTO orchestration_v2_message_search (orchestration_v2_message_search)
54 VALUES ('delete-all')
55 `;
56 yield* sql`
57 INSERT INTO orchestration_v2_message_search (rowid, text)
58 SELECT messages.rowid, ${indexedMessageText(sql, "messages.payload_json")}
59 FROM orchestration_v2_projection_messages AS messages
60 WHERE ${indexedMessageCondition(sql)}
61 AND json_extract(messages.payload_json, '$.text') IS NOT NULL
62 `;
63 }),
64 );
65});