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