From 8479e5427703418f11ffe2b66b90eee327340225 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:24 -0800 Subject: [PATCH 01/14] search: a message search reads a trigram index instead of every message, about 70x faster on 50,000 messages Searching all chats ran lower(text) LIKE '%needle%' over every row: 78 ms p95 in bench:persistence (50,000 messages), blocking the server for that long unless the worker ran it. A contentless FTS5 trigram index (detail=none) of each text message's text and each activity's tool name now narrows a needle of three or more characters to the rows that hold all of its trigrams; the same LIKE still decides every match, so results do not change. A property test checks that against a brute-force reading for any messages, edits, deletions and needle. bench:persistence, search p95: 76-81 ms -> 0.43-0.62 ms; event loop max with searches: 82-87 ms -> 3-15 ms. Costs: a message write's p95 0.12 -> 0.20 ms; the index adds about 15% to messages.db; the first start after the update builds it once (about 0.6 s per 50,000 messages). A needle found in most messages, or under three characters, still reads every candidate row. --- package.json | 1 + pnpm-lock.yaml | 16 ++++++ server/message-db.ts | 3 +- server/message-search-query.test.ts | 83 ++++++++++++++++++++++++++--- server/message-search-query.ts | 56 +++++++++++++++++-- 5 files changed, 147 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index bc777d8e1b..ca84e7595e 100644 --- a/package.json +++ b/package.json @@ -201,6 +201,7 @@ "electron": "^43.8.1", "electron-builder": "^26.15.3", "esbuild": "^0.28.2", + "fast-check": "^4.11.0", "happy-dom": "^21.0.4", "lucide-react": "^0.539.0", "oxlint": "1.80.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca21eaacc5..81f1f7ef12 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -298,6 +298,9 @@ importers: esbuild: specifier: ^0.28.2 version: 0.28.2 + fast-check: + specifier: ^4.11.0 + version: 4.11.0 happy-dom: specifier: ^21.0.4 version: 21.0.4 @@ -3416,6 +3419,10 @@ packages: extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} + fast-check@4.11.0: + resolution: {integrity: sha512-V4Uc238rhQOdQlc+Gz7JG6SGBtrWnWL8d/6RyiBeCMcNKMhF6DZ0KkAVHJSyNV5r4lA0PmIpZ6iRpTVoz4qjoA==} + engines: {node: '>=12.17.0'} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -4545,6 +4552,9 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} + pure-rand@8.4.2: + resolution: {integrity: sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==} + pvtsutils@1.3.6: resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==} @@ -8379,6 +8389,10 @@ snapshots: extend@3.0.2: {} + fast-check@4.11.0: + dependencies: + pure-rand: 8.4.2 + fast-deep-equal@3.1.3: {} fast-equals@5.4.6: {} @@ -9828,6 +9842,8 @@ snapshots: punycode@2.3.1: {} + pure-rand@8.4.2: {} + pvtsutils@1.3.6: dependencies: tslib: 2.8.1 diff --git a/server/message-db.ts b/server/message-db.ts index 77a523c816..b36adc21ee 100644 --- a/server/message-db.ts +++ b/server/message-db.ts @@ -11,7 +11,7 @@ import type { UsageTrigger } from "./usage-ledger.ts"; import { ensureFactStore, ensureMemoryIndex } from "./message-db-memory-index.ts"; import { MessageSearchWorker } from "./message-search-worker.ts"; import { rowToMessage, threadPreviewRows, threadRowsBefore, type ThreadRows, type ThreadTailRows } from "./message-db-rows.ts"; -import { searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts"; +import { ensureMessageSearchIndex, searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts"; import { rollbackKeeping } from "./sqlite-rollback.ts"; import type { Notification, NotificationLogEntry } from "../shared/notification.ts"; export type { SearchHit } from "./message-search-query.ts"; @@ -103,6 +103,7 @@ function open(): DatabaseSync { const notificationColumns = db.prepare("PRAGMA table_info(notification_log)").all() as Array<{ name: string }>; if (!notificationColumns.some((column) => column.name === "for_person")) db.exec("ALTER TABLE notification_log ADD COLUMN for_person TEXT"); ensureRecallIndex(db); + ensureMessageSearchIndex(db); ensureMemoryIndex(db); ensureFactStore(db); return db; diff --git a/server/message-search-query.test.ts b/server/message-search-query.test.ts index ce0b3c9dc8..49f70323da 100644 --- a/server/message-search-query.test.ts +++ b/server/message-search-query.test.ts @@ -1,19 +1,88 @@ import { DatabaseSync } from "node:sqlite"; +import fc from "fast-check"; import { expect, it } from "vitest"; -import { searchMessagesInDatabase } from "./message-search-query.ts"; +import { ensureMessageSearchIndex, searchMessagesInDatabase } from "./message-search-query.ts"; -function database() { +function emptyDatabase() { const db = new DatabaseSync(":memory:"); db.exec("CREATE TABLE messages (thread_id TEXT, id TEXT, at INTEGER, role TEXT, kind TEXT, text TEXT, json TEXT)"); - const add = (id: string, kind: string, text: string | null, tool?: string) => - db.prepare("INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?, ?)").run("t", id, 1, "bot", kind, text, JSON.stringify(tool ? { tool: { name: tool } } : {})); - add("note", "activity", null, "recovery: New session started"); - add("tool", "activity", null, "Searched the session list"); - add("said", "text", "the session notes"); + return db; +} + +function addMessage(db: DatabaseSync, id: string, at: number, kind: string, text: string | null, tool?: string) { + db.prepare("INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?, ?)") + .run("t", id, at, "bot", kind, text, JSON.stringify(tool === undefined ? {} : { tool: { name: tool } })); +} + +function database() { + const db = emptyDatabase(); + ensureMessageSearchIndex(db); + addMessage(db, "note", 1, "activity", null, "recovery: New session started"); + addMessage(db, "tool", 1, "activity", null, "Searched the session list"); + addMessage(db, "said", 1, "text", "the session notes"); return db; } it("finds what was said and the tools that ran, never the app's own recovery notes", () => { expect(searchMessagesInDatabase(database(), "session").map((hit) => hit.messageId).sort()).toEqual(["said", "tool"]); }); + +it("finds a message whose text changed after it was indexed, and forgets a deleted one", () => { + const db = database(); + db.prepare("UPDATE messages SET text = ? WHERE id = ?").run("renamed to quokka", "said"); + db.prepare("DELETE FROM messages WHERE id = ?").run("tool"); + expect(searchMessagesInDatabase(db, "quokka").map((hit) => hit.messageId)).toEqual(["said"]); + expect(searchMessagesInDatabase(db, "session").map((hit) => hit.messageId)).toEqual([]); +}); + +// SQLite's lower() and LIKE fold ASCII letters only; anything else must match exactly. +const asciiLower = (value: string) => value.replace(/[A-Z]/g, (letter) => letter.toLowerCase()); + +const searchCharacter = fc.constantFrom(...Array.from("aAbBcC%_\\\"'ÉéßİıfiΣσς😀: "), "recovery:"); +const searchText = fc.array(searchCharacter, { maxLength: 12 }).map((parts) => parts.join("")); +const message = fc.record({ + kind: fc.constantFrom("text", "activity", "digest"), + text: fc.option(searchText, { nil: null }), + tool: fc.option(searchText, { nil: undefined }), +}); + +it("the trigram index never changes which messages a search finds", () => { + fc.assert( + fc.property( + fc.array(message, { maxLength: 12 }), + fc.array(message, { maxLength: 12 }), + fc.array(fc.nat({ max: 23 }), { maxLength: 6 }), + searchText, + fc.record({ row: fc.nat(), start: fc.nat(), length: fc.integer({ min: 1, max: 8 }), upper: fc.boolean(), own: fc.boolean() }), + (before, after, deletions, randomQuery, pick) => { + const db = emptyDatabase(); + const all = [...before, ...after]; + const source = all.length ? Array.from(all[pick.row % all.length].text ?? all[pick.row % all.length].tool ?? "") : []; + const slice = source.slice(pick.start % (source.length || 1)).slice(0, pick.length).join(""); + const query = pick.own && slice ? (pick.upper ? slice.toUpperCase() : slice) : randomQuery; + all.forEach((row, index) => { + if (index === before.length) ensureMessageSearchIndex(db); + addMessage(db, `m${index}`, index, row.kind, row.text, row.tool); + }); + if (all.length === before.length) ensureMessageSearchIndex(db); + const deleted = new Set(deletions.filter((index) => index < all.length)); + for (const index of deleted) db.prepare("DELETE FROM messages WHERE id = ?").run(`m${index}`); + + const needle = query.trim().toLowerCase(); + const expected = needle + ? all.flatMap((row, index) => { + if (deleted.has(index)) return []; + const textHit = row.kind === "text" && row.text !== null && asciiLower(row.text).includes(needle); + const toolHit = row.kind === "activity" && row.tool !== undefined && + !asciiLower(row.tool).startsWith("recovery:") && asciiLower(row.tool).includes(needle); + return textHit || toolHit ? [`m${index}`] : []; + }) + : []; + const found = searchMessagesInDatabase(db, query, 1000).map((hit) => hit.messageId); + expect(found.sort()).toEqual(expected.sort()); + }, + ), + { numRuns: 400 }, + ); +}); diff --git a/server/message-search-query.ts b/server/message-search-query.ts index 67d3916b63..d114221a03 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -13,20 +13,68 @@ export interface SearchHit { from?: string; } +const searchableText = (row: "new" | "old" | "messages") => + `CASE ${row}.kind WHEN 'text' THEN ${row}.text WHEN 'activity' THEN json_extract(${row}.json, '$.tool.name') END`; + +/** + * A trigram index of what search can match: a text message's text and an activity's tool name. It is contentless + * with detail=none, so it stores only which rows hold each trigram (about 15% of the text's size) and narrows a + * search to candidate rows; the LIKE in the search query still decides every match. + */ +export function ensureMessageSearchIndex(database: DatabaseSync): void { + const existed = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_search'").get(); + if (existed) return; + database.exec("BEGIN IMMEDIATE"); + try { + database.exec(` + CREATE VIRTUAL TABLE messages_search USING fts5( + body, content='', contentless_delete=1, tokenize='trigram case_sensitive 0', detail=none + ); + CREATE TRIGGER messages_search_ai AFTER INSERT ON messages BEGIN + INSERT INTO messages_search(rowid, body) SELECT new.rowid, ${searchableText("new")} WHERE ${searchableText("new")} IS NOT NULL; + END; + CREATE TRIGGER messages_search_ad AFTER DELETE ON messages BEGIN + DELETE FROM messages_search WHERE rowid = old.rowid; + END; + CREATE TRIGGER messages_search_au AFTER UPDATE ON messages BEGIN + DELETE FROM messages_search WHERE rowid = old.rowid; + INSERT INTO messages_search(rowid, body) SELECT new.rowid, ${searchableText("new")} WHERE ${searchableText("new")} IS NOT NULL; + END; + INSERT INTO messages_search(rowid, body) + SELECT rowid, ${searchableText("messages")} FROM messages WHERE ${searchableText("messages")} IS NOT NULL; + `); + database.exec("COMMIT"); + } catch (error) { + database.exec("ROLLBACK"); + throw error; + } +} + +/** Every three-character window of the needle as one quoted FTS5 term, all required; null when the needle is shorter. */ +export function trigramMatchQuery(needle: string): string | null { + const characters = Array.from(needle); + const terms = new Set(); + for (let start = 0; start + 3 <= characters.length; start++) { + terms.add(`"${characters.slice(start, start + 3).join("").replaceAll('"', '""')}"`); + } + return terms.size ? [...terms].join(" ") : null; +} + export function searchMessagesInDatabase(database: DatabaseSync, query: string, limit = 40, threadId?: string): SearchHit[] { const needle = query.trim().toLowerCase(); if (!needle) return []; const pattern = `%${needle.replace(/([\\%_])/g, "\\$1")}%`; + const trigrams = trigramMatchQuery(needle); const scope = threadId ? "thread_id = ? AND " : ""; + const candidates = trigrams ? "rowid IN (SELECT rowid FROM messages_search WHERE messages_search MATCH ?) AND " : ""; const statement = database.prepare( "SELECT thread_id, id, at, role, kind, text, json_extract(json, '$.tool.name') AS tool_name, json_extract(json, '$.from.name') AS from_name FROM messages " + - `WHERE ${scope}((kind = 'text' AND text IS NOT NULL AND lower(text) LIKE ? ESCAPE '\\') ` + + `WHERE ${scope}${candidates}((kind = 'text' AND text IS NOT NULL AND lower(text) LIKE ? ESCAPE '\\') ` + " OR (kind = 'activity' AND tool_name IS NOT NULL AND tool_name NOT LIKE 'recovery:%' AND lower(tool_name) LIKE ? ESCAPE '\\')) " + "ORDER BY at DESC LIMIT ?", ); - const rows = (threadId - ? statement.all(threadId, pattern, pattern, limit) - : statement.all(pattern, pattern, limit)) as Array<{ + const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), pattern, pattern, limit]; + const rows = statement.all(...parameters) as Array<{ thread_id: string; id: string; at: number; From 239cfa2ec2581023048caae6716d9063af188f64 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:24 -0800 Subject: [PATCH 02/14] =?UTF-8?q?search:=20a=20word=20with=20capital=20let?= =?UTF-8?q?ters=20outside=20A-Z=20finds=20its=20messages=20(=D0=9F=D1=80?= =?UTF-8?q?=D0=B8=D0=B2=D0=B5=D1=82,=20=C3=89cole,=20=C3=9Cber)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SQLite's lower() and LIKE fold ASCII letters only, while the query is lowercased in JavaScript, so a search for "Привет" never found a message saying "Привет": the needle became "привет" and the row kept its capital П. Rows are now lowercased by the same toLowerCase() as the query (a deterministic SQL function on the search's connection) and matched with instr. The trigram index folds case itself, so it still narrows a search; a needle holding U+0307 (from "İ", which lowercases to i + U+0307) reads every row, since no indexed text holds that pair. The property test now uses an alphabet with Cyrillic, Greek sigmas, İ/ı, ß/ẞ, DŽ/Dž/dž, the Kelvin and Ångström signs and a ligature, against toLowerCase().includes. A needle under three characters, or found in most messages, still reads every candidate: that path now costs 17-34% more (35 -> 47 ms for a two-letter needle on 50,000 messages). --- server/message-search-query.test.ts | 19 ++++++++++++++----- server/message-search-query.ts | 12 +++++++----- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/server/message-search-query.test.ts b/server/message-search-query.test.ts index 49f70323da..d08a55d433 100644 --- a/server/message-search-query.test.ts +++ b/server/message-search-query.test.ts @@ -36,10 +36,19 @@ it("finds a message whose text changed after it was indexed, and forgets a delet expect(searchMessagesInDatabase(db, "session").map((hit) => hit.messageId)).toEqual([]); }); -// SQLite's lower() and LIKE fold ASCII letters only; anything else must match exactly. const asciiLower = (value: string) => value.replace(/[A-Z]/g, (letter) => letter.toLowerCase()); -const searchCharacter = fc.constantFrom(...Array.from("aAbBcC%_\\\"'ÉéßİıfiΣσς😀: "), "recovery:"); +it("finds a word in any alphabet whatever its letters' case", () => { + const db = emptyDatabase(); + ensureMessageSearchIndex(db); + addMessage(db, "ru", 1, "text", "Привет, команда"); + addMessage(db, "fr", 2, "text", "école ouverte"); + for (const [query, found] of [["Привет", "ru"], ["привет", "ru"], ["ПРИВЕТ", "ru"], ["École", "fr"]] as const) { + expect(searchMessagesInDatabase(db, query).map((hit) => hit.messageId)).toEqual([found]); + } +}); + +const searchCharacter = fc.constantFrom(...Array.from("aAbBcCkK%_\\\"'ÉéПпßẞİıΣσςDŽDždžfiKÅΩ😀: "), "recovery:"); const searchText = fc.array(searchCharacter, { maxLength: 12 }).map((parts) => parts.join("")); const message = fc.record({ kind: fc.constantFrom("text", "activity", "digest"), @@ -47,7 +56,7 @@ const message = fc.record({ tool: fc.option(searchText, { nil: undefined }), }); -it("the trigram index never changes which messages a search finds", () => { +it("finds exactly the messages whose lowercased text holds the lowercased query, through the trigram index or without it", () => { fc.assert( fc.property( fc.array(message, { maxLength: 12 }), @@ -73,9 +82,9 @@ it("the trigram index never changes which messages a search finds", () => { const expected = needle ? all.flatMap((row, index) => { if (deleted.has(index)) return []; - const textHit = row.kind === "text" && row.text !== null && asciiLower(row.text).includes(needle); + const textHit = row.kind === "text" && row.text !== null && row.text.toLowerCase().includes(needle); const toolHit = row.kind === "activity" && row.tool !== undefined && - !asciiLower(row.tool).startsWith("recovery:") && asciiLower(row.tool).includes(needle); + !asciiLower(row.tool).startsWith("recovery:") && row.tool.toLowerCase().includes(needle); return textHit || toolHit ? [`m${index}`] : []; }) : []; diff --git a/server/message-search-query.ts b/server/message-search-query.ts index d114221a03..f62e768eb4 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -63,17 +63,19 @@ export function trigramMatchQuery(needle: string): string | null { export function searchMessagesInDatabase(database: DatabaseSync, query: string, limit = 40, threadId?: string): SearchHit[] { const needle = query.trim().toLowerCase(); if (!needle) return []; - const pattern = `%${needle.replace(/([\\%_])/g, "\\$1")}%`; - const trigrams = trigramMatchQuery(needle); + // SQLite's own lower() and LIKE fold ASCII letters only, so "Привет" would never find "Привет". + database.function("dusk_lower", { deterministic: true }, (value) => (typeof value === "string" ? value.toLowerCase() : null)); + // "İ".toLowerCase() is "i" + U+0307, a pair no indexed text holds, so such a needle reads every row. + const trigrams = needle.includes("̇") ? null : trigramMatchQuery(needle); const scope = threadId ? "thread_id = ? AND " : ""; const candidates = trigrams ? "rowid IN (SELECT rowid FROM messages_search WHERE messages_search MATCH ?) AND " : ""; const statement = database.prepare( "SELECT thread_id, id, at, role, kind, text, json_extract(json, '$.tool.name') AS tool_name, json_extract(json, '$.from.name') AS from_name FROM messages " + - `WHERE ${scope}${candidates}((kind = 'text' AND text IS NOT NULL AND lower(text) LIKE ? ESCAPE '\\') ` + - " OR (kind = 'activity' AND tool_name IS NOT NULL AND tool_name NOT LIKE 'recovery:%' AND lower(tool_name) LIKE ? ESCAPE '\\')) " + + `WHERE ${scope}${candidates}((kind = 'text' AND text IS NOT NULL AND instr(dusk_lower(text), ?) > 0) ` + + " OR (kind = 'activity' AND tool_name IS NOT NULL AND tool_name NOT LIKE 'recovery:%' AND instr(dusk_lower(tool_name), ?) > 0)) " + "ORDER BY at DESC LIMIT ?", ); - const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), pattern, pattern, limit]; + const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), needle, needle, limit]; const rows = statement.all(...parameters) as Array<{ thread_id: string; id: string; From 27dff4b98c3291da5f222889b9e453b8531dd076 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:24 -0800 Subject: [PATCH 03/14] search: the index is asked for each trigram in every way it can be written, checked for every cased letter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SQLite's FTS5 case folding is older than JavaScript's toLowerCase(): it has no pairs for Cherokee, Georgian Mtavruli, Adlam, Osage and the Greek and Cyrillic letters added since Unicode 7, and keeps İ apart from i, so a needle folded by one could miss rows folded by the other (1,395 of 9,234 checks missed). A search now asks the index for each three-character window written any way that lowercases to it (İ standing for an i that ends a window, Σ for ς), so the index only has to apply the same tokenizer to both sides. A test runs every letter Unicode gives a lower case at each place in a window. The index triggers read a tool name only from valid JSON, so one damaged row cannot stop the database from opening. --- server/message-search-query.test.ts | 20 +++++++++ server/message-search-query.ts | 69 ++++++++++++++++++++++++----- 2 files changed, 77 insertions(+), 12 deletions(-) diff --git a/server/message-search-query.test.ts b/server/message-search-query.test.ts index d08a55d433..1aec62a976 100644 --- a/server/message-search-query.test.ts +++ b/server/message-search-query.test.ts @@ -48,6 +48,26 @@ it("finds a word in any alphabet whatever its letters' case", () => { } }); +it("finds every letter Unicode gives a lower case, at each place in a three-letter window, through the index", () => { + const db = emptyDatabase(); + ensureMessageSearchIndex(db); + const texts: string[] = ["abİ"]; + for (let code = 0; code <= 0x10ffff; code++) { + if (code === 0xd800) code = 0xe000; + const letter = String.fromCodePoint(code); + if (letter.toLowerCase() !== letter) texts.push(`q${letter}z`, `${letter}qz`, `qz${letter}`); + } + db.exec("BEGIN"); + texts.forEach((text, i) => addMessage(db, `m${i}`, i, "text", text)); + db.exec("COMMIT"); + const missed = texts.filter((text, i) => { + const query = text === "abİ" ? "abi" : text; + return !searchMessagesInDatabase(db, query, 10_000).some((hit) => hit.messageId === `m${i}`); + }); + expect(texts.length).toBeGreaterThan(4_000); + expect(missed).toEqual([]); +}); + const searchCharacter = fc.constantFrom(...Array.from("aAbBcCkK%_\\\"'ÉéПпßẞİıΣσςDŽDždžfiKÅΩ😀: "), "recovery:"); const searchText = fc.array(searchCharacter, { maxLength: 12 }).map((parts) => parts.join("")); const message = fc.record({ diff --git a/server/message-search-query.ts b/server/message-search-query.ts index f62e768eb4..1a8832bfdf 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -13,19 +13,23 @@ export interface SearchHit { from?: string; } -const searchableText = (row: "new" | "old" | "messages") => - `CASE ${row}.kind WHEN 'text' THEN ${row}.text WHEN 'activity' THEN json_extract(${row}.json, '$.tool.name') END`; +const searchableText = (row: "new" | "messages") => + `CASE WHEN ${row}.kind = 'text' THEN ${row}.text ` + + `WHEN ${row}.kind = 'activity' AND json_valid(${row}.json) THEN json_extract(${row}.json, '$.tool.name') END`; /** * A trigram index of what search can match: a text message's text and an activity's tool name. It is contentless - * with detail=none, so it stores only which rows hold each trigram (about 15% of the text's size) and narrows a - * search to candidate rows; the LIKE in the search query still decides every match. + * with detail=none, so it stores only which rows hold each trigram, and it only narrows a search to candidate rows: + * the search query's own comparison decides every match. SQLite's case folding is older than JavaScript's, so a + * search names each trigram as it can be written rather than relying on it. The triggers use SQLite built-ins only, so + * an older dusk bot can still write to a database this one opened. */ export function ensureMessageSearchIndex(database: DatabaseSync): void { const existed = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_search'").get(); if (existed) return; database.exec("BEGIN IMMEDIATE"); try { + dropMessageSearchIndex(database); database.exec(` CREATE VIRTUAL TABLE messages_search USING fts5( body, content='', contentless_delete=1, tokenize='trigram case_sensitive 0', detail=none @@ -50,14 +54,56 @@ export function ensureMessageSearchIndex(database: DatabaseSync): void { } } -/** Every three-character window of the needle as one quoted FTS5 term, all required; null when the needle is shorter. */ +/** Security: a deleted row's trigrams stay in a contentless index until its segments merge, so a copy that must not + * hold removed messages' words drops the index; ensureMessageSearchIndex builds it again from the rows left. */ +export function dropMessageSearchIndex(database: DatabaseSync): void { + database.exec(` + DROP TRIGGER IF EXISTS messages_search_ai; + DROP TRIGGER IF EXISTS messages_search_ad; + DROP TRIGGER IF EXISTS messages_search_au; + DROP TABLE IF EXISTS messages_search; + `); +} + +let writtenForms: Map | null = null; + +/** Every character whose toLowerCase() is the key, the key included. toLowerCase() also lowers "İ" to "i" + U+0307, + * so "İ" stands for an "i" that ends a window, and lowers "Σ" to "ς" at the end of a word. */ +function formsThatLowerTo(character: string): readonly string[] { + if (!writtenForms) { + writtenForms = new Map([["i", ["i", "İ"]], ["ς", ["ς", "Σ"]]]); + for (let code = 0; code <= 0x10ffff; code++) { + if (code === 0xd800) code = 0xe000; + const written = String.fromCodePoint(code), lowered = written.toLowerCase(); + if (lowered === written || Array.from(lowered).length !== 1) continue; + const forms = writtenForms.get(lowered) ?? [lowered]; + writtenForms.set(lowered, [...forms, written]); + } + } + return writtenForms.get(character) ?? [character]; +} + +const MAX_WINDOWS = 8; + +/** + * The FTS5 query a row must answer to hold the lowercased needle: for each of up to eight three-character windows, + * any way those characters can be written. Null when the needle is under three characters or holds U+0307, which + * "İ" lowers into across two characters, so no single written trigram stands for it. + */ export function trigramMatchQuery(needle: string): string | null { const characters = Array.from(needle); - const terms = new Set(); - for (let start = 0; start + 3 <= characters.length; start++) { - terms.add(`"${characters.slice(start, start + 3).join("").replaceAll('"', '""')}"`); - } - return terms.size ? [...terms].join(" ") : null; + const windows = characters.length - 2; + if (windows < 1 || needle.includes("̇")) return null; + const starts = new Set(Array.from({ length: Math.min(windows, MAX_WINDOWS) }, (_, i) => + windows <= MAX_WINDOWS ? i : Math.round((i * (windows - 1)) / (MAX_WINDOWS - 1)))); + const groups = [...starts].map((start) => { + let written = [""]; + for (const character of characters.slice(start, start + 3)) { + written = written.flatMap((head) => formsThatLowerTo(character).map((form) => head + form)); + } + return `(${written.map((trigram) => `"${trigram.replaceAll('"', '""')}"`).join(" OR ")})`; + }); + return groups.join(" AND "); } export function searchMessagesInDatabase(database: DatabaseSync, query: string, limit = 40, threadId?: string): SearchHit[] { @@ -65,8 +111,7 @@ export function searchMessagesInDatabase(database: DatabaseSync, query: string, if (!needle) return []; // SQLite's own lower() and LIKE fold ASCII letters only, so "Привет" would never find "Привет". database.function("dusk_lower", { deterministic: true }, (value) => (typeof value === "string" ? value.toLowerCase() : null)); - // "İ".toLowerCase() is "i" + U+0307, a pair no indexed text holds, so such a needle reads every row. - const trigrams = needle.includes("̇") ? null : trigramMatchQuery(needle); + const trigrams = trigramMatchQuery(needle); const scope = threadId ? "thread_id = ? AND " : ""; const candidates = trigrams ? "rowid IN (SELECT rowid FROM messages_search WHERE messages_search MATCH ?) AND " : ""; const statement = database.prepare( From bf54dadd3d5175a81e8669b2563d78d336e9bad2 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:24 -0800 Subject: [PATCH 04/14] team backups: a snapshot drops the message search index, so it keeps no trigram of a private conversation A contentless FTS5 index keeps a deleted row's trigrams until its segments merge, and VACUUM does not merge them, so a Team Cloud export that removed a member's private conversations still held trigrams of their words. The snapshot now drops the index and its triggers; the database builds it again from the rows left when it next opens. --- server/workspace-backup-team-private.test.ts | 8 ++++++++ server/workspace-backup-team-private.ts | 2 ++ 2 files changed, 10 insertions(+) diff --git a/server/workspace-backup-team-private.test.ts b/server/workspace-backup-team-private.test.ts index c596a2dfdc..26a9b8324f 100644 --- a/server/workspace-backup-team-private.test.ts +++ b/server/workspace-backup-team-private.test.ts @@ -9,6 +9,7 @@ import { openRuntimeStore } from "./runtime/store.ts"; import type { Assignment } from "./runtime/types.ts"; import { createWorkspaceBackupSnapshot, stagedWorkspaceData, stageWorkspaceBackup } from "./workspace-backup.ts"; import { ensureMemoryIndex } from "./message-db-memory-index.ts"; +import { ensureMessageSearchIndex, searchMessagesInDatabase } from "./message-search-query.ts"; import { omittedAsTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts"; const BOB = "p_bobbobbobbobbobbobbob1"; @@ -51,6 +52,7 @@ function teamData(root: string): void { + " CREATE TABLE chat_followups(id TEXT PRIMARY KEY, kind TEXT, owner_id TEXT, thread_id TEXT, send_id TEXT, status TEXT, payload TEXT);" + " CREATE TABLE notification_log(id TEXT PRIMARY KEY, at INTEGER, kind TEXT, bot_id TEXT, bot_name TEXT, thread_id TEXT, group_id TEXT, title TEXT, body TEXT, avatar_url TEXT, for_person TEXT, read INTEGER);"); ensureMemoryIndex(db); + ensureMessageSearchIndex(db); db.exec("CREATE TABLE command_receipts(kind TEXT, key TEXT, at INTEGER, result TEXT, PRIMARY KEY (kind, key))"); db.prepare("INSERT INTO command_receipts VALUES ('memory', 'k', 1, ?)").run("Bob's receipted secret"); for (const [bot, text] of [["bot", "team notes"], [`bot--member-${BOB}`, "Bob's noted secret"], ["bobs-own", "Bob's own noted secret"]]) { @@ -121,6 +123,12 @@ describe("what a Team Cloud's export leaves out (the private sentence: not the O expect(table(messages, "SELECT bot_id AS id FROM memory_files").map((row) => row.id)).toEqual(["bot"]); expect(textOf(messages).toLowerCase()).not.toContain("secret"); expect(textOf(messages)).toContain("team question"); + expect(table(messages, "SELECT name AS id FROM sqlite_master WHERE name LIKE 'messages_search%'")).toEqual([]); + const restored = new DatabaseSync(messages); + ensureMessageSearchIndex(restored); + expect(searchMessagesInDatabase(restored, "question").map((hit) => hit.threadId)).toEqual(["main"]); + expect(searchMessagesInDatabase(restored, "secret")).toEqual([]); + restored.close(); }); it("on a Team Cloud the export carries the team's things and nothing of Bob's alone; off a team everything stays", async () => { diff --git a/server/workspace-backup-team-private.ts b/server/workspace-backup-team-private.ts index 3f4b65ddcf..1b7f626936 100644 --- a/server/workspace-backup-team-private.ts +++ b/server/workspace-backup-team-private.ts @@ -6,6 +6,7 @@ import { DatabaseSync } from "node:sqlite"; import { isLayerId, layerAudience } from "./audience.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; +import { dropMessageSearchIndex } from "./message-search-query.ts"; const PERSON = /^p_[\w-]{22}$/; const MARKERS: ReadonlySet = new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]); @@ -107,6 +108,7 @@ function strip(file: string, remove: (db: DatabaseSync) => void): void { try { db.exec("BEGIN"); try { remove(db); db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } + dropMessageSearchIndex(db); for (const index of ["messages_fts", "memory_fts"]) if (hasTable(db, index)) db.exec(`INSERT INTO ${index}(${index}) VALUES('rebuild')`); db.exec("VACUUM"); } finally { From df4495a29383a5fd610d143e8f99b419e9275208 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:24 -0800 Subject: [PATCH 05/14] search: one conversation's search reads its rows by thread, and ASCII text is lowercased by SQLite A search in one conversation asked the trigram index for every conversation's candidates first: 1 ms became 20-44 ms for words most messages hold. It reads the conversation's rows by thread again. SQLite's lower() agrees with toLowerCase() on ASCII text, so only a value with other characters calls the JavaScript lowercase. --- server/message-search-query.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/server/message-search-query.ts b/server/message-search-query.ts index 1a8832bfdf..c77be94f59 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -93,7 +93,7 @@ const MAX_WINDOWS = 8; export function trigramMatchQuery(needle: string): string | null { const characters = Array.from(needle); const windows = characters.length - 2; - if (windows < 1 || needle.includes("̇")) return null; + if (windows < 1 || needle.includes("\u0307")) return null; const starts = new Set(Array.from({ length: Math.min(windows, MAX_WINDOWS) }, (_, i) => windows <= MAX_WINDOWS ? i : Math.round((i * (windows - 1)) / (MAX_WINDOWS - 1)))); const groups = [...starts].map((start) => { @@ -106,21 +106,29 @@ export function trigramMatchQuery(needle: string): string | null { return groups.join(" AND "); } +/** + * Whether a column, lowercased by JavaScript's toLowerCase() as the needle is, holds the needle. SQLite's own lower() + * folds A-Z only, so "Привет" would never find "Привет" with it alone; it agrees with toLowerCase() on ASCII text, so + * only a value with other characters (its byte length differs from its character length) pays for the JavaScript call. + */ +const holdsNeedle = (column: string) => + `(instr(lower(${column}), ?) > 0 OR (length(CAST(${column} AS BLOB)) <> length(${column}) AND instr(dusk_lower(${column}), ?) > 0))`; + export function searchMessagesInDatabase(database: DatabaseSync, query: string, limit = 40, threadId?: string): SearchHit[] { const needle = query.trim().toLowerCase(); if (!needle) return []; - // SQLite's own lower() and LIKE fold ASCII letters only, so "Привет" would never find "Привет". database.function("dusk_lower", { deterministic: true }, (value) => (typeof value === "string" ? value.toLowerCase() : null)); - const trigrams = trigramMatchQuery(needle); + // One conversation's rows are few and indexed by thread already; asking the trigram index first only adds its work. + const trigrams = threadId ? null : trigramMatchQuery(needle); const scope = threadId ? "thread_id = ? AND " : ""; const candidates = trigrams ? "rowid IN (SELECT rowid FROM messages_search WHERE messages_search MATCH ?) AND " : ""; const statement = database.prepare( "SELECT thread_id, id, at, role, kind, text, json_extract(json, '$.tool.name') AS tool_name, json_extract(json, '$.from.name') AS from_name FROM messages " + - `WHERE ${scope}${candidates}((kind = 'text' AND text IS NOT NULL AND instr(dusk_lower(text), ?) > 0) ` + - " OR (kind = 'activity' AND tool_name IS NOT NULL AND tool_name NOT LIKE 'recovery:%' AND instr(dusk_lower(tool_name), ?) > 0)) " + + `WHERE ${scope}${candidates}((kind = 'text' AND text IS NOT NULL AND ${holdsNeedle("text")}) ` + + ` OR (kind = 'activity' AND tool_name IS NOT NULL AND tool_name NOT LIKE 'recovery:%' AND ${holdsNeedle("tool_name")})) ` + "ORDER BY at DESC LIMIT ?", ); - const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), needle, needle, limit]; + const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), needle, needle, needle, needle, limit]; const rows = statement.all(...parameters) as Array<{ thread_id: string; id: string; From d398eac9654a974c3cd3f6e2109396d9d16e946a Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:07:24 -0800 Subject: [PATCH 06/14] messages: the recall and search indexes of messages.db live in message-text-index.ts message-db.ts is at its size ratchet; the FTS5 setup moves out unchanged. --- server/message-db.test.ts | 3 +- server/message-db.ts | 40 +-------- server/message-search-query.test.ts | 3 +- server/message-search-query.ts | 52 ----------- server/message-text-index.ts | 90 ++++++++++++++++++++ server/workspace-backup-team-private.test.ts | 3 +- server/workspace-backup-team-private.ts | 2 +- 7 files changed, 99 insertions(+), 94 deletions(-) create mode 100644 server/message-text-index.ts diff --git a/server/message-db.test.ts b/server/message-db.test.ts index 96e63af364..ca31eb1fe4 100644 --- a/server/message-db.test.ts +++ b/server/message-db.test.ts @@ -28,7 +28,8 @@ import { closeMessageDb, recallMessages, searchMessages, setActiveLeaf, - updateMessage, describeMissingFts5 } from "./message-db.ts"; + updateMessage } from "./message-db.ts"; +import { describeMissingFts5 } from "./message-text-index.ts"; import type { NotificationLogEntry } from "../shared/notification.ts"; import { withPeerProvenance } from "./peer-provenance.ts"; import { Store, type Message } from "./store.ts"; diff --git a/server/message-db.ts b/server/message-db.ts index b36adc21ee..c933d56c9e 100644 --- a/server/message-db.ts +++ b/server/message-db.ts @@ -11,7 +11,8 @@ import type { UsageTrigger } from "./usage-ledger.ts"; import { ensureFactStore, ensureMemoryIndex } from "./message-db-memory-index.ts"; import { MessageSearchWorker } from "./message-search-worker.ts"; import { rowToMessage, threadPreviewRows, threadRowsBefore, type ThreadRows, type ThreadTailRows } from "./message-db-rows.ts"; -import { ensureMessageSearchIndex, searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts"; +import { searchMessagesInDatabase, type SearchHit } from "./message-search-query.ts"; +import { ensureMessageSearchIndex, ensureRecallIndex } from "./message-text-index.ts"; import { rollbackKeeping } from "./sqlite-rollback.ts"; import type { Notification, NotificationLogEntry } from "../shared/notification.ts"; export type { SearchHit } from "./message-search-query.ts"; @@ -109,43 +110,6 @@ function open(): DatabaseSync { return db; } -export function describeMissingFts5(error: unknown): Error | null { - const message = error instanceof Error ? error.message : String(error); - if (!/no such module:\s*fts5/i.test(message)) return null; - return new Error( - `dusk bot needs SQLite with FTS5, which is built into Node 24 and newer (and into the app). ` + - `This Node (${process.version}) has none: install Node 24 or newer. (${message})`, - ); -} - -function ensureRecallIndex(db: DatabaseSync): void { - const existed = db - .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'") - .get(); - try { - db.exec(` - CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5( - text, content='messages', content_rowid='rowid', tokenize='unicode61' - ); - `); - } catch (error) { - throw describeMissingFts5(error) ?? error; - } - db.exec(` - CREATE TRIGGER IF NOT EXISTS messages_fts_ai AFTER INSERT ON messages BEGIN - INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text); - END; - CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN - INSERT INTO messages_fts(messages_fts, rowid, text) VALUES ('delete', old.rowid, old.text); - END; - CREATE TRIGGER IF NOT EXISTS messages_fts_au AFTER UPDATE ON messages BEGIN - INSERT INTO messages_fts(messages_fts, rowid, text) VALUES ('delete', old.rowid, old.text); - INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text); - END; - `); - if (!existed) db.exec("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')"); -} - // INSERT OR REPLACE skips the delete trigger (SQLite fires it only with recursive triggers on), so upsert to keep FTS in step. const UPSERT_MESSAGE = "INSERT INTO messages (thread_id, id, at, role, kind, text, json) VALUES (?, ?, ?, ?, ?, ?, ?) " + diff --git a/server/message-search-query.test.ts b/server/message-search-query.test.ts index 1aec62a976..4bdaf7f121 100644 --- a/server/message-search-query.test.ts +++ b/server/message-search-query.test.ts @@ -2,7 +2,8 @@ import { DatabaseSync } from "node:sqlite"; import fc from "fast-check"; import { expect, it } from "vitest"; -import { ensureMessageSearchIndex, searchMessagesInDatabase } from "./message-search-query.ts"; +import { searchMessagesInDatabase } from "./message-search-query.ts"; +import { ensureMessageSearchIndex } from "./message-text-index.ts"; function emptyDatabase() { const db = new DatabaseSync(":memory:"); diff --git a/server/message-search-query.ts b/server/message-search-query.ts index c77be94f59..bb00b8f8e7 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -13,58 +13,6 @@ export interface SearchHit { from?: string; } -const searchableText = (row: "new" | "messages") => - `CASE WHEN ${row}.kind = 'text' THEN ${row}.text ` + - `WHEN ${row}.kind = 'activity' AND json_valid(${row}.json) THEN json_extract(${row}.json, '$.tool.name') END`; - -/** - * A trigram index of what search can match: a text message's text and an activity's tool name. It is contentless - * with detail=none, so it stores only which rows hold each trigram, and it only narrows a search to candidate rows: - * the search query's own comparison decides every match. SQLite's case folding is older than JavaScript's, so a - * search names each trigram as it can be written rather than relying on it. The triggers use SQLite built-ins only, so - * an older dusk bot can still write to a database this one opened. - */ -export function ensureMessageSearchIndex(database: DatabaseSync): void { - const existed = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_search'").get(); - if (existed) return; - database.exec("BEGIN IMMEDIATE"); - try { - dropMessageSearchIndex(database); - database.exec(` - CREATE VIRTUAL TABLE messages_search USING fts5( - body, content='', contentless_delete=1, tokenize='trigram case_sensitive 0', detail=none - ); - CREATE TRIGGER messages_search_ai AFTER INSERT ON messages BEGIN - INSERT INTO messages_search(rowid, body) SELECT new.rowid, ${searchableText("new")} WHERE ${searchableText("new")} IS NOT NULL; - END; - CREATE TRIGGER messages_search_ad AFTER DELETE ON messages BEGIN - DELETE FROM messages_search WHERE rowid = old.rowid; - END; - CREATE TRIGGER messages_search_au AFTER UPDATE ON messages BEGIN - DELETE FROM messages_search WHERE rowid = old.rowid; - INSERT INTO messages_search(rowid, body) SELECT new.rowid, ${searchableText("new")} WHERE ${searchableText("new")} IS NOT NULL; - END; - INSERT INTO messages_search(rowid, body) - SELECT rowid, ${searchableText("messages")} FROM messages WHERE ${searchableText("messages")} IS NOT NULL; - `); - database.exec("COMMIT"); - } catch (error) { - database.exec("ROLLBACK"); - throw error; - } -} - -/** Security: a deleted row's trigrams stay in a contentless index until its segments merge, so a copy that must not - * hold removed messages' words drops the index; ensureMessageSearchIndex builds it again from the rows left. */ -export function dropMessageSearchIndex(database: DatabaseSync): void { - database.exec(` - DROP TRIGGER IF EXISTS messages_search_ai; - DROP TRIGGER IF EXISTS messages_search_ad; - DROP TRIGGER IF EXISTS messages_search_au; - DROP TABLE IF EXISTS messages_search; - `); -} - let writtenForms: Map | null = null; /** Every character whose toLowerCase() is the key, the key included. toLowerCase() also lowers "İ" to "i" + U+0307, diff --git a/server/message-text-index.ts b/server/message-text-index.ts new file mode 100644 index 0000000000..41da89de36 --- /dev/null +++ b/server/message-text-index.ts @@ -0,0 +1,90 @@ +import type { DatabaseSync } from "node:sqlite"; + +export function describeMissingFts5(error: unknown): Error | null { + const message = error instanceof Error ? error.message : String(error); + if (!/no such module:\s*fts5/i.test(message)) return null; + return new Error( + `dusk bot needs SQLite with FTS5, which is built into Node 24 and newer (and into the app). ` + + `This Node (${process.version}) has none: install Node 24 or newer. (${message})`, + ); +} + +export function ensureRecallIndex(db: DatabaseSync): void { + const existed = db + .prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'") + .get(); + try { + db.exec(` + CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5( + text, content='messages', content_rowid='rowid', tokenize='unicode61' + ); + `); + } catch (error) { + throw describeMissingFts5(error) ?? error; + } + db.exec(` + CREATE TRIGGER IF NOT EXISTS messages_fts_ai AFTER INSERT ON messages BEGIN + INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text); + END; + CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN + INSERT INTO messages_fts(messages_fts, rowid, text) VALUES ('delete', old.rowid, old.text); + END; + CREATE TRIGGER IF NOT EXISTS messages_fts_au AFTER UPDATE ON messages BEGIN + INSERT INTO messages_fts(messages_fts, rowid, text) VALUES ('delete', old.rowid, old.text); + INSERT INTO messages_fts(rowid, text) VALUES (new.rowid, new.text); + END; + `); + if (!existed) db.exec("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')"); +} + +const searchableText = (row: "new" | "messages") => + `CASE WHEN ${row}.kind = 'text' THEN ${row}.text ` + + `WHEN ${row}.kind = 'activity' AND json_valid(${row}.json) THEN json_extract(${row}.json, '$.tool.name') END`; + +/** + * A trigram index of what search can match: a text message's text and an activity's tool name. It is contentless + * with detail=none, so it stores only which rows hold each trigram, and it only narrows a search to candidate rows: + * the search query's own comparison decides every match. SQLite's case folding is older than JavaScript's, so a + * search names each trigram as it can be written rather than relying on it. The triggers use SQLite built-ins only, so + * an older dusk bot can still write to a database this one opened. + */ +export function ensureMessageSearchIndex(database: DatabaseSync): void { + const existed = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_search'").get(); + if (existed) return; + database.exec("BEGIN IMMEDIATE"); + try { + dropMessageSearchIndex(database); + database.exec(` + CREATE VIRTUAL TABLE messages_search USING fts5( + body, content='', contentless_delete=1, tokenize='trigram case_sensitive 0', detail=none + ); + CREATE TRIGGER messages_search_ai AFTER INSERT ON messages BEGIN + INSERT INTO messages_search(rowid, body) SELECT new.rowid, ${searchableText("new")} WHERE ${searchableText("new")} IS NOT NULL; + END; + CREATE TRIGGER messages_search_ad AFTER DELETE ON messages BEGIN + DELETE FROM messages_search WHERE rowid = old.rowid; + END; + CREATE TRIGGER messages_search_au AFTER UPDATE ON messages BEGIN + DELETE FROM messages_search WHERE rowid = old.rowid; + INSERT INTO messages_search(rowid, body) SELECT new.rowid, ${searchableText("new")} WHERE ${searchableText("new")} IS NOT NULL; + END; + INSERT INTO messages_search(rowid, body) + SELECT rowid, ${searchableText("messages")} FROM messages WHERE ${searchableText("messages")} IS NOT NULL; + `); + database.exec("COMMIT"); + } catch (error) { + database.exec("ROLLBACK"); + throw error; + } +} + +/** Security: a deleted row's trigrams stay in a contentless index until its segments merge, so a copy that must not + * hold removed messages' words drops the index; ensureMessageSearchIndex builds it again from the rows left. */ +export function dropMessageSearchIndex(database: DatabaseSync): void { + database.exec(` + DROP TRIGGER IF EXISTS messages_search_ai; + DROP TRIGGER IF EXISTS messages_search_ad; + DROP TRIGGER IF EXISTS messages_search_au; + DROP TABLE IF EXISTS messages_search; + `); +} diff --git a/server/workspace-backup-team-private.test.ts b/server/workspace-backup-team-private.test.ts index 26a9b8324f..0f6c8660d4 100644 --- a/server/workspace-backup-team-private.test.ts +++ b/server/workspace-backup-team-private.test.ts @@ -9,7 +9,8 @@ import { openRuntimeStore } from "./runtime/store.ts"; import type { Assignment } from "./runtime/types.ts"; import { createWorkspaceBackupSnapshot, stagedWorkspaceData, stageWorkspaceBackup } from "./workspace-backup.ts"; import { ensureMemoryIndex } from "./message-db-memory-index.ts"; -import { ensureMessageSearchIndex, searchMessagesInDatabase } from "./message-search-query.ts"; +import { searchMessagesInDatabase } from "./message-search-query.ts"; +import { ensureMessageSearchIndex } from "./message-text-index.ts"; import { omittedAsTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts"; const BOB = "p_bobbobbobbobbobbobbob1"; diff --git a/server/workspace-backup-team-private.ts b/server/workspace-backup-team-private.ts index 1b7f626936..271caa790b 100644 --- a/server/workspace-backup-team-private.ts +++ b/server/workspace-backup-team-private.ts @@ -6,7 +6,7 @@ import { DatabaseSync } from "node:sqlite"; import { isLayerId, layerAudience } from "./audience.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; -import { dropMessageSearchIndex } from "./message-search-query.ts"; +import { dropMessageSearchIndex } from "./message-text-index.ts"; const PERSON = /^p_[\w-]{22}$/; const MARKERS: ReadonlySet = new Set([CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY]); From 1bfd3da708e8076c37b722ba8aa8d640c527d1b4 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:00:33 -0800 Subject: [PATCH 07/14] search: the case table reads the first two Unicode planes only, 4 ms instead of 30 ms on the first search No letter past U+1FFFF has a lower case (the last is U+1E921); a test fails if a later Unicode adds one. --- server/message-search-query.test.ts | 11 ++++++++++- server/message-search-query.ts | 4 +++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/server/message-search-query.test.ts b/server/message-search-query.test.ts index 4bdaf7f121..255fd19a7e 100644 --- a/server/message-search-query.test.ts +++ b/server/message-search-query.test.ts @@ -2,9 +2,18 @@ import { DatabaseSync } from "node:sqlite"; import fc from "fast-check"; import { expect, it } from "vitest"; -import { searchMessagesInDatabase } from "./message-search-query.ts"; +import { LAST_CASED_CODE_POINT, searchMessagesInDatabase } from "./message-search-query.ts"; import { ensureMessageSearchIndex } from "./message-text-index.ts"; +it("has no letter with a lower case past the last code point the case table reads", () => { + const cased: string[] = []; + for (let code = LAST_CASED_CODE_POINT + 1; code <= 0x10ffff; code++) { + const letter = String.fromCodePoint(code); + if (letter.toLowerCase() !== letter) cased.push(`U+${code.toString(16).toUpperCase()}`); + } + expect(cased).toEqual([]); +}); + function emptyDatabase() { const db = new DatabaseSync(":memory:"); db.exec("CREATE TABLE messages (thread_id TEXT, id TEXT, at INTEGER, role TEXT, kind TEXT, text TEXT, json TEXT)"); diff --git a/server/message-search-query.ts b/server/message-search-query.ts index bb00b8f8e7..b89453ce21 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -14,13 +14,15 @@ export interface SearchHit { } let writtenForms: Map | null = null; +/** No letter past the first two Unicode planes has a lower case (the last is U+1E921, Adlam); a test holds this. */ +export const LAST_CASED_CODE_POINT = 0x1ffff; /** Every character whose toLowerCase() is the key, the key included. toLowerCase() also lowers "İ" to "i" + U+0307, * so "İ" stands for an "i" that ends a window, and lowers "Σ" to "ς" at the end of a word. */ function formsThatLowerTo(character: string): readonly string[] { if (!writtenForms) { writtenForms = new Map([["i", ["i", "İ"]], ["ς", ["ς", "Σ"]]]); - for (let code = 0; code <= 0x10ffff; code++) { + for (let code = 0; code <= LAST_CASED_CODE_POINT; code++) { if (code === 0xd800) code = 0xe000; const written = String.fromCodePoint(code), lowered = written.toLowerCase(); if (lowered === written || Array.from(lowered).length !== 1) continue; From 02d6e381255e856d695bef0022c84941f2683249 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:03:15 -0800 Subject: [PATCH 08/14] search: ASCII text is matched with lower() LIKE, as before, which SQLite runs faster than instr --- server/message-search-query.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/server/message-search-query.ts b/server/message-search-query.ts index b89453ce21..4adb1708c0 100644 --- a/server/message-search-query.ts +++ b/server/message-search-query.ts @@ -62,7 +62,7 @@ export function trigramMatchQuery(needle: string): string | null { * only a value with other characters (its byte length differs from its character length) pays for the JavaScript call. */ const holdsNeedle = (column: string) => - `(instr(lower(${column}), ?) > 0 OR (length(CAST(${column} AS BLOB)) <> length(${column}) AND instr(dusk_lower(${column}), ?) > 0))`; + `(lower(${column}) LIKE ? ESCAPE '\\' OR (length(CAST(${column} AS BLOB)) <> length(${column}) AND instr(dusk_lower(${column}), ?) > 0))`; export function searchMessagesInDatabase(database: DatabaseSync, query: string, limit = 40, threadId?: string): SearchHit[] { const needle = query.trim().toLowerCase(); @@ -78,7 +78,8 @@ export function searchMessagesInDatabase(database: DatabaseSync, query: string, ` OR (kind = 'activity' AND tool_name IS NOT NULL AND tool_name NOT LIKE 'recovery:%' AND ${holdsNeedle("tool_name")})) ` + "ORDER BY at DESC LIMIT ?", ); - const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), needle, needle, needle, needle, limit]; + const pattern = `%${needle.replace(/([\\%_])/g, "\\$1")}%`; + const parameters = [...(threadId ? [threadId] : []), ...(trigrams ? [trigrams] : []), pattern, needle, pattern, needle, limit]; const rows = statement.all(...parameters) as Array<{ thread_id: string; id: string; From 6635778a01439946fd7089374154c7820f5faeff Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 03:32:37 -0800 Subject: [PATCH 09/14] tests: find_tool ranks skill_manage first again for a reusable skill, and the guest skill card test stages four kinds of work bacb5320b left two tests red on dev. Its new skill_manage description dropped the word reusable, so find_tool ranked skills_list first for "save this procedure as a reusable skill"; the description says reusable SKILL.md again (a skill is recurring work, which that change keeps). Its duplicate check turns away a create that covers an existing skill, and the guest skill card test staged four skills with one description, the same as an earlier test's: each now has its own kind of work. (cherry picked from commit 78889fccca4dacac387ef69c68b5c41c3ebc3f1d) --- server/cloud-personal.e2e.test.ts | 9 ++++- .../full.tools-list.json | 2 +- .../agents-catalog-goldens/profiles.json | 40 +++++++++---------- server/drivers/agents-catalog.ts | 2 +- 4 files changed, 30 insertions(+), 23 deletions(-) diff --git a/server/cloud-personal.e2e.test.ts b/server/cloud-personal.e2e.test.ts index 73081ca1f2..781e7d3415 100644 --- a/server/cloud-personal.e2e.test.ts +++ b/server/cloud-personal.e2e.test.ts @@ -678,7 +678,14 @@ it("a guest's skill card enables only the exact text the owner reviewed, holds a const owner = await adminPairing(); await settleAll(owner); const botId = before.roomBot.id; - const skillMd = (name: string, body: string) => `---\nname: ${name}\ndescription: Checks the site for broken links.\n---\n\n# ${name}\n\n${body}\n`; + // kinds of work none of this file's other skills covers: a create that covers a skill already there is turned away + const work: Record = { + "reviewed-links": "Reviews pull requests for missing tests.", + "denied-links": "Drafts the weekly status email for the team.", + "lost-links": "Files expense receipts in the company portal.", + "deleted-links": "Renames vacation photos by the date taken.", + }; + const skillMd = (name: string, body: string) => `---\nname: ${name}\ndescription: ${work[name]}\n---\n\n# ${name}\n\n${body}\n`; const cards = async () => ((await api("GET", `/api/threads/${before.theirs}/messages`, { token: owner })).body.messages as any[]) .map((message) => message.card).filter((card) => card?.skillRequest); const respond = (route: "bot" | "thread", body: Record) => route === "bot" diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json index 338d8ca056..6ebfb58711 100644 --- a/server/drivers/agents-catalog-goldens/full.tools-list.json +++ b/server/drivers/agents-catalog-goldens/full.tools-list.json @@ -2611,7 +2611,7 @@ }, { "name": "skill_manage", - "description": "Submit a new or updated SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged. Read the result: it applies immediately at every access level, and the person sees it with an Undo where possible. If applied, continue the work without another confirmation. Only a pending result (a Cloud conversation its owner did not drive) means ending the turn to wait for the owner. Never claim success without an applied result; report failures honestly. This does not elevate another bot's execution permissions.", + "description": "Submit a new or updated reusable SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged. Read the result: it applies immediately at every access level, and the person sees it with an Undo where possible. If applied, continue the work without another confirmation. Only a pending result (a Cloud conversation its owner did not drive) means ending the turn to wait for the owner. Never claim success without an applied result; report failures honestly. This does not elevate another bot's execution permissions.", "inputSchema": { "type": "object", "additionalProperties": false, diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json index 232389816e..8da9b6b072 100644 --- a/server/drivers/agents-catalog-goldens/profiles.json +++ b/server/drivers/agents-catalog-goldens/profiles.json @@ -125,8 +125,8 @@ ] }, "skills": { - "bytes": 79704, - "sha256": "ab31ffbd342b3eff3b99849f6722cdc5002514b372e398e499d8bffcd9d5e3da", + "bytes": 79713, + "sha256": "a3ea87f686b9fc624c9aa68eaca93d2fa3d239d377854a7e788870336e8e944a", "tools": [ "set_status", "send_message", @@ -189,8 +189,8 @@ ] }, "skills+voice": { - "bytes": 80482, - "sha256": "72656e98d9324abd4a0a6fe99a0b5fd2d1cb6648b8a8789e50e7ee175bcff5c5", + "bytes": 80491, + "sha256": "5845b1830e6d0546c3f2c9ecbf0329faadd9e82c36769afad6148aa61b374b9a", "tools": [ "set_status", "send_message", @@ -369,8 +369,8 @@ ] }, "skills+non-chief": { - "bytes": 71686, - "sha256": "e033162122142bb14c5991c22b21fb182a049e75efe36f4452890496631c3e55", + "bytes": 71695, + "sha256": "0a31ffd3ed3a5803db43c317b810595a014d9f4d993e119a8b168ac620b6cceb", "tools": [ "set_status", "send_message", @@ -428,8 +428,8 @@ ] }, "skills+voice+non-chief": { - "bytes": 72464, - "sha256": "630045d61d6bdc00fd94bec0327599b38772069a9c2d6b7f982ce176d4bdbaba", + "bytes": 72473, + "sha256": "feacf12ae6edd3eb48ca5b9bc74241682851c3708e8f9a42954575c99523ed4f", "tools": [ "set_status", "send_message", @@ -488,8 +488,8 @@ ] }, "skills+voice+cloud-home": { - "bytes": 79458, - "sha256": "87046e3f1680cb3688a81e68c736e25fe4cc822a7c5c43848d57f732613d509f", + "bytes": 79467, + "sha256": "f19672a959c94ce7073ae118ce9d62172c4af6b88593191de7996a4fccb83165", "tools": [ "set_status", "send_message", @@ -552,8 +552,8 @@ ] }, "skills+voice+non-chief+cloud-home": { - "bytes": 71440, - "sha256": "158fe4d01fbb73b6f4c4a468868e7fe7dd4cd30bb92c6500fe448b0c8a8b542f", + "bytes": 71449, + "sha256": "c3be064722efa48c326150acf7529cf16993760a56bc6c3726915758b63b2e3e", "tools": [ "set_status", "send_message", @@ -611,8 +611,8 @@ ] }, "skills+voice+x": { - "bytes": 87140, - "sha256": "a57e0b4afbfa031a592ced1ab097100ec2a12f6c59535a7b2f2127e0fd3e3303", + "bytes": 87149, + "sha256": "62498a24d47f510cca1314d99605d4be581dab3c2763825ef2ecd5d0d09d79fa", "tools": [ "set_status", "send_message", @@ -684,8 +684,8 @@ ] }, "skills+voice+x+team": { - "bytes": 87556, - "sha256": "efd173cb43a931be63700ee55cf3798c55578d6603495d5353fa0391140ddf21", + "bytes": 87565, + "sha256": "e253321813dbe8fa0ea457f40401f68e92853fa5dacc5fd3f90f3323d2542563", "tools": [ "set_status", "send_message", @@ -758,8 +758,8 @@ ] }, "skills+skill-reader": { - "bytes": 80120, - "sha256": "e562baae663c0b9d238fc65d9a557019eae0e3a10c7cd986d42bec9227b9fcc9", + "bytes": 80129, + "sha256": "db617a90d6dec8a458a5678034198026d7bf2e69afd665d3bf122b4d4322cf99", "tools": [ "set_status", "send_message", @@ -949,8 +949,8 @@ ] }, "skills+voice+dusk": { - "bytes": 81133, - "sha256": "aecee531cd5dd67546525416ac925ec36db52b978777bbbb997718b51da4af69", + "bytes": 81142, + "sha256": "e48dad639cff9c24f7b605f54f443aa54c09d1081519d403df93be26de903f87", "tools": [ "set_status", "send_message", diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.ts index 324a261bec..4f0077619e 100644 --- a/server/drivers/agents-catalog.ts +++ b/server/drivers/agents-catalog.ts @@ -808,7 +808,7 @@ const TOOL_DEFINITIONS = [ { name: "skill_manage", description: - "Submit a new or updated SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged." + APPLIES_OUTCOME, + "Submit a new or updated reusable SKILL.md for one kind of work. Update a learned skill when the person corrected how that work is done, asked you to revise it, or it misled you; never one the person wrote or imported unless they asked for that named skill. Create one only for recurring work with rules you'd get wrong without it, never for an automation, a one-off or a preference; omit what any model knows. If the result is pending, a create stays inactive and an update leaves the current version unchanged." + APPLIES_OUTCOME, inputSchema: { type: "object", additionalProperties: false, From 7119c2236d75f580b87131d1a2d2c0d226461494 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:37:50 -0800 Subject: [PATCH 10/14] ci: the tests that failed at random in Dec 1's CI runs get the flaky list's two retries Fifteen tests failed in CI on Dec 1 in runs of main, a release and PRs #477-#483 whose changes do not reach them, a different set each run, and pass locally. Each entry names the runs it failed in. vps-routing's 'reuses the existing VPS with $settings' failed too (PR #477, run 46623618361) but is left out: its name is made per case, and the list matches names written in the file. (cherry picked from commit 54f5c514dc9dc2315d41cb8c7d82f00b8472fd44) --- scripts/testing/ci-retry-list.json | 105 +++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/scripts/testing/ci-retry-list.json b/scripts/testing/ci-retry-list.json index 070a6c47a0..3498b1c38a 100644 --- a/scripts/testing/ci-retry-list.json +++ b/scripts/testing/ci-retry-list.json @@ -70,6 +70,111 @@ "owner": "siddharth", "reason": "Failed once in the 0.2.33 release CI (run 45993068105, ubuntu shard 5 or parallel-threads, a different test each attempt); passes locally on a quiet machine.", "since": "2026-11-27" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "a setting changed in any one place reaches the others, and the last change wins", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "what belongs to one computer stays there", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "keys travel only over the person's own links, and a Team Cloud keeps no person's settings", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "the move to My Cloud and the way home keep settings level", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/settings-sync.e2e.test.ts", + "test": "a computer whose bots moved to My Cloud is left as it was, with nothing failing, until they come back", + "owner": "Yabuku-xD", + "reason": "Failed on Dec 1 in CI of PRs #479 (run 46726301408, all five), #481 (run 46636209589) and #483 (run 46637592516): a loopback request with no forwarding header was answered 403 'this request came through a proxy'. Passed in the other PR runs that day; passes locally (macOS, Node 26) alone, as four copies at once and in its full ubuntu shard 7/8 with 4 workers.", + "since": "2026-12-01" + }, + { + "file": "server/steer-e2e.test.ts", + "test": "mid-turn steering e2e > a steer the CLI runs as its next native turn keeps the turn, its busy state and its internal tool pass until that reply lands", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #477 (run 46623618361, ubuntu shard 8/8) and of the diag/connector-issues branch on Dec 1; passes locally on dev and on #477.", + "since": "2026-12-01" + }, + { + "file": "server/drivers/antigravity.test.ts", + "test": "starting Google sign-in again > hands back the same link while it is live, so a code from the first page still completes", + "owner": "Yabuku-xD", + "reason": "Failed in CI of main (run 46580994542), a release (run 46616055192) and PR #478 (run 46623629685) on Dec 1; failed 1 of 3 local runs on one commit.", + "since": "2026-12-01" + }, + { + "file": "server/connected-app-tools.e2e.test.ts", + "test": "a bot given Gmail by its app switch reaches gmail.search_emails by name on Claude and on an ACP engine alike", + "owner": "Yabuku-xD", + "reason": "Failed in CI of main (run 46615872847) and PR #478 (run 46623629685) on Dec 1; passes locally on dev.", + "since": "2026-12-01" + }, + { + "file": "server/direct-coordination.e2e.test.ts", + "test": "runs the owed direct follow-up while the same bot works in another thread", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #478 (run 46623629685) and of fix-app-trigger-restore-enabled (run 46370208019); passed 3 of 3 local runs.", + "since": "2026-12-01" + }, + { + "file": "server/index.test.ts", + "test": "harness HTTP API > reports a failed routine once, not twice", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PRs #480 (run 46636190164) and #481 (run 46636209589) on Dec 1, at about 10.7 s; passes locally on dev.", + "since": "2026-12-01" + }, + { + "file": "server/setup-connect-card.e2e.test.ts", + "test": "/setup connects an app through a Connect card, against the real server > names the switch, and mounts nothing to call, when the bot's connected apps are off", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46636167463) on Dec 1; passes locally on dev, twice.", + "since": "2026-12-01" + }, + { + "file": "server/host-lazy-claim.e2e.test.ts", + "test": "lazy host claim and pin on use (issue #1650) > a No is an answer, not a failure: the screen stays untouched and the bot is told to finish another way", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #482 (run 46636235332, windows shard 5/8, 'Fixture wait expired') on Dec 1; that PR changes only electron/main.mjs.", + "since": "2026-12-01" + }, + { + "file": "server/copilot-engine.e2e.test.ts", + "test": "creates and updates a routine through Copilot's launcher-owned tools", + "owner": "Yabuku-xD", + "reason": "Failed in CI of main (run 46615872847) on Dec 1.", + "since": "2026-12-01" + }, + { + "file": "server/usage-trace/recorder.test.ts", + "test": "trace recorder > records 2,000 tool calls in one turn without holding up the event loop", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46726301408, ubuntu shard 7/8) on Dec 1 at 53 ms against its 50 ms bound; that PR changes only src/lib/live-events.ts.", + "since": "2026-12-01" + }, + { + "file": "server/teammate-follow-ups.e2e.test.ts", + "test": "F4 keeps a second assignment Clive hands Mira in the same turn its own job, though the first is already running", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46726301408, ubuntu shard 7/8) on Dec 1 ('the first was running when the second was sent'); that PR changes only src/lib/live-events.ts.", + "since": "2026-12-01" } ] } From 2e037f18578eabc328b52a3e5420295aa0aaacb0 Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:50:37 -0800 Subject: [PATCH 11/14] link chaos: the run ends once its results are written, and the storm's 60 servers link from their own addresses Every link chaos run since the per-address limit on new links (adc99d770, Nov 14) was cancelled at CI's 60-minute limit, on main pushes, the weekly run and every PR that touches the link service: the scenarios finished in about five minutes and printed their table, but a socket or timer a scenario left open held the process. The run now exits once its results are written. The storm's 60 servers set up their links over one connection, so the node's front gave them one address, which the limit refused after 30 (Too many new links from here); each now uses its own connection, as 60 machines would. Locally, --quick passes all 12 scenarios and exits in 5.6 minutes. (cherry picked from commit 83ab615c36ac0c5452b417071d977ad702fdf35b) --- apps/link-service/chaos/run.mjs | 3 ++- apps/link-service/chaos/scenarios.mjs | 14 ++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/apps/link-service/chaos/run.mjs b/apps/link-service/chaos/run.mjs index 08e9a00082..f4e235fc99 100644 --- a/apps/link-service/chaos/run.mjs +++ b/apps/link-service/chaos/run.mjs @@ -336,5 +336,6 @@ if (!process.env.DUSK_CHAOS_DIR) { } else { process.env.DUSK_CHAOS_PARENT = String(process.pid); for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => process.exit(130)); - main().catch((error) => { console.error(error); process.exit(2); }); + // the results are written by then; a socket or timer some scenario left open would otherwise hold the run until CI's job limit + main().then(() => process.exit(process.exitCode ?? 0), (error) => { console.error(error); process.exit(2); }); } diff --git a/apps/link-service/chaos/scenarios.mjs b/apps/link-service/chaos/scenarios.mjs index bf64921b90..db2f680e87 100644 --- a/apps/link-service/chaos/scenarios.mjs +++ b/apps/link-service/chaos/scenarios.mjs @@ -3,6 +3,7 @@ import { createHash } from "node:crypto"; import { chmodSync } from "node:fs"; import { join } from "node:path"; +import { Agent, fetch as undiciFetch } from "undici"; import { createTunnelAgent } from "../agent.mjs"; import { createRelayClient, createTunnelProxy, newLinkKeys, seal, sha256hex, vpsTokenOf } from "../../../electron/vps-link-protocol.mjs"; @@ -27,17 +28,22 @@ async function failover(world, { kill = true } = {}) { return { pass: moved !== home && moved !== null, note: `moved ${home} -> ${moved} in ${Math.round((workedAt - started) / 1000)} s`, clearedAt: started }; } -/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each */ +/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each. Each + * sets up its link over its own connection, so the node's front gives it its own address, as `count` machines would have: + * on one connection they would be one address, over the node's limit on new links an address may make in a minute. */ async function crowd(world, count) { - const base = world.url("contabo"), relay = createRelayClient({ base }), out = []; + const base = world.url("contabo"), out = []; for (let i = 0; i < count; i += 1) { + const own = new Agent(); + const ownFetch = (url, init) => undiciFetch(url, { ...init, dispatcher: own }); const keys = newLinkKeys(); - const made = await relay.create({ verifier: keys.verifier, appPub: keys.pub }); + const made = await createRelayClient({ base, fetch: ownFetch }).create({ verifier: keys.verifier, appPub: keys.pub }); const vps = vpsTokenOf(keys.secret); - const post = (path, body) => fetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) }); + const post = (path, body) => ownFetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) }); await post("claim", {}); const tunnel = { key: randomBytes(32).toString("base64url"), vps: randomBytes(32).toString("base64url"), app: randomBytes(32).toString("base64url") }; const done = await post("result", { sealed: seal(Buffer.alloc(32), made.id, Buffer.from("{}")), vpsPub: keys.pub, tunnel: { vps: sha256hex(tunnel.vps), app: sha256hex(tunnel.app) } }); + await own.close(); if (!done.ok) throw new Error(`crowd link ${i} answered ${done.status}`); const agent = createTunnelAgent({ base, id: made.id, key: tunnel.key, token: tunnel.vps, server: { host: "127.0.0.1", port: world.bot.port }, log: () => {} }); const running = agent.run(); From 12fcecd92fc93ac2103827c287d2568489feae1b Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:50:37 -0800 Subject: [PATCH 12/14] ci: three more tests that failed at random in Dec 1's CI get the flaky list's retries chat-mcp-tools' shutdown verdict, memory-order and the encrypted workspace restore failed in PR #479's run 46740020170, whose change does not reach them, and pass locally. (cherry picked from commit c47197f8d57186c25b8e8b9682681bdd48248486) --- scripts/testing/ci-retry-list.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/scripts/testing/ci-retry-list.json b/scripts/testing/ci-retry-list.json index 3498b1c38a..90b819f616 100644 --- a/scripts/testing/ci-retry-list.json +++ b/scripts/testing/ci-retry-list.json @@ -175,6 +175,27 @@ "owner": "Yabuku-xD", "reason": "Failed in CI of PR #479 (run 46726301408, ubuntu shard 7/8) on Dec 1 ('the first was running when the second was sent'); that PR changes only src/lib/live-events.ts.", "since": "2026-12-01" + }, + { + "file": "server/drivers/chat-mcp-tools.test.ts", + "test": "Chat MCP shutdown verdict > an unconfirmed shutdown still fails close when a call was in flight", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46740020170, ubuntu shard 3/8) on Dec 1 ('Unexpected end of JSON input'); that PR changes only src/lib/live-events.ts. Passes locally.", + "since": "2026-12-01" + }, + { + "file": "server/memory-order.e2e.test.ts", + "test": "starts the person's own line ahead of a hand-off that was already waiting for memory, and the hand-off right after", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46740020170, ubuntu shard 5/8) on Dec 1; that PR changes only src/lib/live-events.ts. Passes locally.", + "since": "2026-12-01" + }, + { + "file": "server/workspace-backup-workflow.test.ts", + "test": "restores an encrypted workspace through the real server and continues its original chat", + "owner": "Yabuku-xD", + "reason": "Failed in CI of PR #479 (run 46740020170, windows shard 5/8) on Dec 1; that PR changes only src/lib/live-events.ts. Passes locally.", + "since": "2026-12-01" } ] } From ed07b70b0ffdee1fccfab5988037e4411ab6459d Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:08:10 -0800 Subject: [PATCH 13/14] link chaos: the crowd's own connections use node:https, since the chaos job installs no packages The job runs `node apps/link-service/chaos/run.mjs` straight after checkout, so the undici import failed with ERR_MODULE_NOT_FOUND before any scenario ran. --- apps/link-service/chaos/scenarios.mjs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/apps/link-service/chaos/scenarios.mjs b/apps/link-service/chaos/scenarios.mjs index db2f680e87..4d70cf6fa9 100644 --- a/apps/link-service/chaos/scenarios.mjs +++ b/apps/link-service/chaos/scenarios.mjs @@ -2,8 +2,8 @@ // things route around it) and answers { clearedAt, pass, note, sees }. run.mjs measures the rest. import { createHash } from "node:crypto"; import { chmodSync } from "node:fs"; +import { Agent as HttpsAgent, request as httpsRequest } from "node:https"; import { join } from "node:path"; -import { Agent, fetch as undiciFetch } from "undici"; import { createTunnelAgent } from "../agent.mjs"; import { createRelayClient, createTunnelProxy, newLinkKeys, seal, sha256hex, vpsTokenOf } from "../../../electron/vps-link-protocol.mjs"; @@ -28,14 +28,35 @@ async function failover(world, { kill = true } = {}) { return { pass: moved !== home && moved !== null, note: `moved ${home} -> ${moved} in ${Math.round((workedAt - started) / 1000)} s`, clearedAt: started }; } +/** a fetch that keeps to one connection of its own. Node's built-in fetch shares one pool for the whole process, and the + * chaos workflow runs without installing packages, so this uses node:https. `close()` ends the connection. */ +function fetchOverOwnConnection() { + const agent = new HttpsAgent({ keepAlive: true, maxSockets: 1 }); + const ownFetch = (url, { method = "GET", headers = {}, body, signal } = {}) => new Promise((resolve, reject) => { + const request = httpsRequest(url, { method, headers, agent, signal }, (answer) => { + const chunks = []; + answer.on("data", (chunk) => chunks.push(chunk)); + answer.on("error", reject); + answer.on("end", () => { + const noBody = [204, 205, 304].includes(answer.statusCode); + const answerHeaders = Object.entries(answer.headers).flatMap(([name, value]) => (Array.isArray(value) ? value.map((one) => [name, one]) : [[name, value]])); + resolve(new Response(noBody ? null : Buffer.concat(chunks), { status: answer.statusCode, headers: answerHeaders })); + }); + }); + request.on("error", reject); + request.end(body); + }); + return { fetch: ownFetch, close: () => agent.destroy() }; +} + /** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each. Each * sets up its link over its own connection, so the node's front gives it its own address, as `count` machines would have: * on one connection they would be one address, over the node's limit on new links an address may make in a minute. */ async function crowd(world, count) { const base = world.url("contabo"), out = []; for (let i = 0; i < count; i += 1) { - const own = new Agent(); - const ownFetch = (url, init) => undiciFetch(url, { ...init, dispatcher: own }); + const own = fetchOverOwnConnection(); + const ownFetch = own.fetch; const keys = newLinkKeys(); const made = await createRelayClient({ base, fetch: ownFetch }).create({ verifier: keys.verifier, appPub: keys.pub }); const vps = vpsTokenOf(keys.secret); From d292b6c140d8095ca3dcdf86d8669fd2577b303a Mon Sep 17 00:00:00 2001 From: Yabuku-xD <78594762+Yabuku-xD@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:26:57 -0800 Subject: [PATCH 14/14] link chaos: the probe dials its live stream again when a new dial sends nothing for 8 s, as the app does src/lib/live-events.ts gives up on a dial that sends nothing in LIVE_EVENTS_OPEN_MS (8 s) and dials again. The probe dropped a quiet stream only after it had sent something, so one silent dial after node-5xx's 502s held it down until the relay closed it, about 90 s, and failed the scenario in CI on five of seven runs. --- apps/link-service/chaos/run.mjs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/link-service/chaos/run.mjs b/apps/link-service/chaos/run.mjs index f4e235fc99..b9c6e09c15 100644 --- a/apps/link-service/chaos/run.mjs +++ b/apps/link-service/chaos/run.mjs @@ -136,7 +136,7 @@ async function bringUp() { */ function createProbe(world) { const pings = [], gaps = []; - let live = null, lastEventAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null; + let live = null, lastEventAt = 0, openedAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null; const port = () => Number(new URL(world.app.origin()).port); const host = () => world.app.host(); function call(path, { method = "GET", body = null, timeoutMs = 8000, port: at = port(), host: name = host() } = {}) { @@ -180,6 +180,7 @@ function createProbe(world) { res.on("close", () => closed("closed")); }); liveReq = req; + openedAt = Date.now(); let done = false; function closed() { if (done) return; @@ -198,7 +199,10 @@ function createProbe(world) { const up = now - lastEventAt < 5000; if (!up && downSince === null) downSince = Math.max(lastEventAt, now - 5000); if (up && downSince !== null) { gaps.push({ from: downSince, to: now }); downSince = null; } - if (liveReq && now - lastEventAt > 20_000 && live) { liveReq.destroy(); } + // as the app does (src/lib/live-events.ts): a dial that sends nothing in LIVE_EVENTS_OPEN_MS (8 s) is dialled again, + // and a stream that went quiet after it sent something is dialled again after 20 s + const quietFor = now - Math.max(lastEventAt, openedAt); + if (liveReq && quietFor > (live ? 20_000 : 8_000)) { liveReq.destroy(); } }, 250); return { start() { timer = setInterval(tick, 500); openLive(); },