From 743d83a5eb90a74a4b663130cf2bd9131719e958 Mon Sep 17 00:00:00 2001 From: Santino Fuentes Date: Sat, 28 Nov 2026 11:52:45 -0600 Subject: [PATCH 1/2] test(copy): check every TaintSource kind has taintFrom copy in both locales Signed-off-by: Santino Fuentes --- packages/copy/test/copy.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/copy/test/copy.test.ts b/packages/copy/test/copy.test.ts index 4a9c55f..07dcbdc 100644 --- a/packages/copy/test/copy.test.ts +++ b/packages/copy/test/copy.test.ts @@ -27,6 +27,20 @@ describe("locale files (CT-10)", () => { } }); + test("every TaintSource kind has HM-APPR-01.taintFrom copy in both locales", () => { + const types = readFileSync(new URL("../../core/src/types.ts", import.meta.url), "utf8"); + const kinds = /interface TaintSource \{\s*kind: ([^;]+);/ + .exec(types)![1]! + .split("|") + .map((k) => k.trim().replace(/"/g, "")); + expect(kinds.length).toBeGreaterThanOrEqual(6); + for (const kind of kinds) { + const key = `HM-APPR-01.taintFrom.${kind}`; + expect(en[key], key).toBeTruthy(); + expect(es[key], key).toBeTruthy(); + } + }); + test("no em or en dashes in copy (house style)", () => { for (const [k, v] of [...Object.entries(en), ...Object.entries(es)]) expect(v, k).not.toMatch(/[–—]/); }); From 6b37497aff6727a6d0788e44f152335ded2096f7 Mon Sep 17 00:00:00 2001 From: Santino Fuentes Date: Sat, 28 Nov 2026 10:27:33 -0600 Subject: [PATCH 2/2] fix(runtime): refuse turns and sessions while a bot is clearing (#108) Signed-off-by: Santino Fuentes --- packages/copy/locales/en.json | 1 + packages/copy/locales/es-419.json | 1 + packages/runtime/src/bots.ts | 21 ++-- packages/runtime/src/hermit.ts | 37 ++++++- packages/runtime/test/bots.test.ts | 155 +++++++++++++++++++++++++++++ 5 files changed, 204 insertions(+), 11 deletions(-) diff --git a/packages/copy/locales/en.json b/packages/copy/locales/en.json index 4e3cc2b..9235ab0 100644 --- a/packages/copy/locales/en.json +++ b/packages/copy/locales/en.json @@ -1431,6 +1431,7 @@ "HM-BOT-02.olderTitle": "Older chats", "HM-BOT-02.newFailed": "Couldn't start a new chat.", "HM-BOT-02.olderFailed": "Couldn't open that chat.", + "HM-BOT-02.clearing": "This conversation is being cleared. Write again in a moment.", "HM-BOT-03.title": "New bot", "HM-BOT-03.templatesIntro": "Start from a template or from scratch. You adjust everything after.", "HM-BOT-03.blank": "Start from scratch", diff --git a/packages/copy/locales/es-419.json b/packages/copy/locales/es-419.json index 8dde6dd..7cb902d 100644 --- a/packages/copy/locales/es-419.json +++ b/packages/copy/locales/es-419.json @@ -1431,6 +1431,7 @@ "HM-BOT-02.olderTitle": "Chats anteriores", "HM-BOT-02.newFailed": "No se pudo empezar un chat nuevo.", "HM-BOT-02.olderFailed": "No se pudo abrir ese chat.", + "HM-BOT-02.clearing": "Se está borrando esta conversación. Escribe de nuevo en un momento.", "HM-BOT-03.title": "Bot nuevo", "HM-BOT-03.templatesIntro": "Empieza con una plantilla o desde cero. Después ajustas todo.", "HM-BOT-03.blank": "Empezar desde cero", diff --git a/packages/runtime/src/bots.ts b/packages/runtime/src/bots.ts index aa63bb0..fb3e698 100644 --- a/packages/runtime/src/bots.ts +++ b/packages/runtime/src/bots.ts @@ -34,6 +34,8 @@ export interface BotsApiDeps { clear(botId: string): Promise; /** A turn of that bot is running (Review Focus 1). */ busy(botId: string): boolean; + /** Marks a bot as clearing while its chats or row are being deleted (#108). */ + setClearing?(botId: string, active: boolean): void; /** The fingerprint. Without it, every change that needs one is declined. */ confirm?: BotPorts["confirm"]; /** A copy key in the app's language, for the fingerprint's prompt; English without it. */ @@ -333,15 +335,20 @@ export function createBotsApi(deps: BotsApiDeps): { bots: HermitBots; modes: Her if (bot.primary) return refused("primary"); // Review Focus 1: never under a running turn, whose late writes would leave chats or notes for a bot that is gone. if (deps.busy(id)) return refused("busy"); + deps.setClearing?.(id, true); try { - await store.remove(id); - } catch (err) { - return storeRefusal(err); + try { + await store.remove(id); + } catch (err) { + return storeRefusal(err); + } + // The store deleted its chats, notes, grants and sources; this also drops its sessions kept in memory. + await deps.sessions.clear(id); + await log(id, "bot.deleted"); + return done(bot); + } finally { + deps.setClearing?.(id, false); } - // The store deleted its chats, notes, grants and sources; this also drops its sessions kept in memory. - await deps.sessions.clear(id); - await log(id, "bot.deleted"); - return done(bot); }, async notes(id, opts = {}) { diff --git a/packages/runtime/src/hermit.ts b/packages/runtime/src/hermit.ts index 5356784..0be05e6 100644 --- a/packages/runtime/src/hermit.ts +++ b/packages/runtime/src/hermit.ts @@ -481,6 +481,10 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit store, sessions, memory, settings: table, audit, clear: (botId) => api.clearConversation(botId), busy: (botId) => running.has(botId), + setClearing: (botId, active) => { + if (active) clearing.add(botId); + else clearing.delete(botId); + }, ...(ports.bots ? { confirm: (prompt: string) => ports.bots!.confirm(prompt) } : {}), ...(ports.copy ? { say: (key: string) => ports.copy!(ports.language(), key) } : {}), proposals, @@ -887,7 +891,16 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit * send already sees it. */ const running = new Map(); + const clearing = new Set(); const botOf = new Map(); + class ClearingError extends Error { + constructor() { + super("This conversation is being cleared."); + this.name = "ClearingError"; + } + } + const clearingReply = (): string => + ports.copy ? ports.copy(ports.language(), "HM-BOT-02.clearing") : "This conversation is being cleared. Write again in a moment."; const markRunning = (botId: string, sessionId: string): (() => void) => { running.set(botId, [...(running.get(botId) ?? []), sessionId]); let ended = false; @@ -907,14 +920,16 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit * so lower-priority work waits for the whole turn, not just its current call (spec 6.6), and its bot is marked running. */ const inTurn = (sessionId: string, priority: RunPriority, run: (session: SessionState, botId: string) => Promise): Promise => { - const release = queue.hold(priority); const handedOut = botOf.get(sessionId); + if (handedOut !== undefined && clearing.has(handedOut)) return Promise.reject(new ClearingError()); + const release = queue.hold(priority); let unmark = handedOut !== undefined ? markRunning(handedOut, sessionId) : undefined; return (async () => { try { const session = await sessions.load(sessionId); if (!session) throw new Error(`No session ${sessionId}.`); const botId = session.botId ?? HERMIT_BOT_ID; + if (clearing.has(botId)) throw new ClearingError(); botOf.set(sessionId, botId); unmark ??= markRunning(botId, sessionId); return await run(session, botId); @@ -1111,6 +1126,7 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit }, async startSession(opts = {}) { const botId = opts.botId ?? HERMIT_BOT_ID; + if (clearing.has(botId)) throw new ClearingError(); // Only for a bot that exists (Hermit's row is the migration's own): a session of no bot could never run a turn. if (botId !== HERMIT_BOT_ID && !(await store.get(botId))) throw new Error(`No bot ${botId}.`); const id = ports.newId(); @@ -1120,6 +1136,7 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit return id; }, async resumeSession(botId = HERMIT_BOT_ID) { + if (clearing.has(botId)) throw new ClearingError(); const last = await sessions.latest(botId); if (!last) return api.startSession({ botId }); botOf.set(last, botId); @@ -1137,7 +1154,12 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit // F-M14: while a turn of that bot runs nothing is cleared, so its late writes never land in a chat that is gone. const runningIn = running.get(botId)?.at(-1); if (runningIn !== undefined) return runningIn; - await sessions.clear(botId); + clearing.add(botId); + try { + await sessions.clear(botId); + } finally { + clearing.delete(botId); + } return api.startSession({ botId }); }, memories: { @@ -1154,7 +1176,9 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit }, }, // The user's own turn, run as the session's bot (spec 6.6): its values are this turn's, built for that bot. - send: (sessionId, text, live = {}) => inTurn(sessionId, "user", async (session, botId) => { + send: async (sessionId, text, live = {}) => { + try { + return await inTurn(sessionId, "user", async (session, botId) => { const turn = await turnFor(botId); // Security review 00:40: what the prompt's notes were read from, this session has read too, before any model call. addReads(session, turn.profileReads); @@ -1307,7 +1331,12 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit }, }); return view; - }), + }); + } catch (err) { + if (err instanceof ClearingError) return { kind: "reply", text: clearingReply() }; + throw err; + } + }, // Seguir, a reply the user is waiting for: it holds that priority, as the session's bot, with the bot's cache key (a // long reply's Seguir reads under the bot's own long key). continueReply: (sessionId, live = {}) => inTurn(sessionId, "reply", async (session, botId) => { diff --git a/packages/runtime/test/bots.test.ts b/packages/runtime/test/bots.test.ts index ff88436..117e4e9 100644 --- a/packages/runtime/test/bots.test.ts +++ b/packages/runtime/test/bots.test.ts @@ -483,3 +483,158 @@ describe("a proposal's offer (F-M15)", () => { expect(p.used).toEqual(["o1"]); }); }); + +describe("refuse turns, startSession and resumeSession while a bot is being cleared (#108)", () => { + function defer() { + let open = () => {}; + const promise = new Promise((resolve) => { + open = resolve; + }); + return { promise, open }; + } + + /** Wraps a SqlPort so the first write matching `match` waits on a deferred gate. */ + function holdSqlOn(match: RegExp) { + const base = nodeSql(); + const gate = defer(); + const entered = defer(); + let held = false; + const sql: typeof base = { + exec: async (q, params) => { + if (!held && match.test(q)) { + held = true; + entered.open(); + await gate.promise; + } + return base.exec(q, params); + }, + query: (q, params) => base.query(q, params), + transaction: (fn) => base.transaction((tx) => fn({ + ...tx, + exec: async (q, params) => { + if (!held && match.test(q)) { + held = true; + entered.open(); + await gate.promise; + } + return tx.exec(q, params); + }, + })), + close: () => base.close(), + }; + return { sql, entered: entered.promise, release: gate.open }; + } + + test("bots.reset refuses a concurrent send, startSession, and resumeSession without orphan chat_turns", async () => { + const h = holdSqlOn(/DELETE FROM sessions WHERE bot_id = \?/i); + const { createHermit } = await import("../src/hermit.ts"); + const { PROFILE } = await import("./bot-harness.ts"); + const store = createBotsStore(h.sql, () => NOW); + await migrate(h.sql); + await store.create({ id: "b1", name: "Viajes", role: "Planeas viajes.", grants: ["notes"], sources: none, mode: null }); + let n = 0; + const hermit = createHermit({ + sql: h.sql, + signer: ed25519Signer(new Uint8Array(32).fill(8)), + notifier: { schedule: async () => "n", cancel: async () => {} }, + calendar: { list: async () => [], add: async () => {}, calendars: async () => [] }, + replySender: { send: async () => "sent" }, + engine: { complete: async () => ({ text: '{"choice":"respond"}', toolCalls: [] }) }, + approvals: { request: async () => ({ kind: "denied" }) }, + now: () => NOW, + timeZone: () => "America/Costa_Rica", + language: () => "es-419", + newId: () => `id${++n}`, + copy, + }, PROFILE); + + const oldSession = await hermit.resumeSession("b1"); + const resetting = hermit.bots.reset("b1"); + await h.entered; + + const refused = await hermit.send(oldSession, "hola durante reset"); + expect(refused).toEqual({ kind: "reply", text: copy("es-419", "HM-BOT-02.clearing") }); + await expect(hermit.startSession({ botId: "b1" })).rejects.toThrow(); + await expect(hermit.resumeSession("b1")).rejects.toThrow(); + + h.release(); + const res = await resetting; + expect(res.kind).toBe("done"); + const orphans = await h.sql.query("SELECT id FROM chat_turns WHERE session_id NOT IN (SELECT id FROM sessions)"); + expect(orphans).toEqual([]); + }); + + test("bots.remove refuses a concurrent send, startSession, and resumeSession without orphan chat_turns", async () => { + const h = holdSqlOn(/DELETE FROM bots WHERE id = \?/i); + const { createHermit } = await import("../src/hermit.ts"); + const { PROFILE } = await import("./bot-harness.ts"); + await migrate(h.sql); + const store = createBotsStore(h.sql, () => NOW); + await store.create({ id: "b1", name: "Viajes", role: "Planeas viajes.", grants: ["notes"], sources: none, mode: null }); + let n = 0; + const hermit = createHermit({ + sql: h.sql, + signer: ed25519Signer(new Uint8Array(32).fill(8)), + notifier: { schedule: async () => "n", cancel: async () => {} }, + calendar: { list: async () => [], add: async () => {}, calendars: async () => [] }, + replySender: { send: async () => "sent" }, + engine: { complete: async () => ({ text: '{"choice":"respond"}', toolCalls: [] }) }, + approvals: { request: async () => ({ kind: "denied" }) }, + now: () => NOW, + timeZone: () => "America/Costa_Rica", + language: () => "en", + newId: () => `id${++n}`, + copy, + }, PROFILE); + + const oldSession = await hermit.resumeSession("b1"); + const removing = hermit.bots.remove("b1"); + await h.entered; + + const refused = await hermit.send(oldSession, "hello during remove"); + expect(refused).toEqual({ kind: "reply", text: copy("en", "HM-BOT-02.clearing") }); + await expect(hermit.startSession({ botId: "b1" })).rejects.toThrow(); + await expect(hermit.resumeSession("b1")).rejects.toThrow(); + + h.release(); + const res = await removing; + expect(res.kind).toBe("done"); + const orphans = await h.sql.query("SELECT id FROM chat_turns WHERE session_id NOT IN (SELECT id FROM sessions)"); + expect(orphans).toEqual([]); + }); + + test("clearConversation refuses a concurrent send without orphan chat_turns", async () => { + const h = holdSqlOn(/DELETE FROM sessions WHERE bot_id = \?/i); + const { createHermit } = await import("../src/hermit.ts"); + const { PROFILE } = await import("./bot-harness.ts"); + await migrate(h.sql); + let n = 0; + const hermit = createHermit({ + sql: h.sql, + signer: ed25519Signer(new Uint8Array(32).fill(8)), + notifier: { schedule: async () => "n", cancel: async () => {} }, + calendar: { list: async () => [], add: async () => {}, calendars: async () => [] }, + replySender: { send: async () => "sent" }, + engine: { complete: async () => ({ text: '{"choice":"respond"}', toolCalls: [] }) }, + approvals: { request: async () => ({ kind: "denied" }) }, + now: () => NOW, + timeZone: () => "America/Costa_Rica", + language: () => "es-419", + newId: () => `id${++n}`, + copy, + }, PROFILE); + + const oldSession = await hermit.resumeSession(); + const clearing = hermit.clearConversation(); + await h.entered; + + const refused = await hermit.send(oldSession, "hola durante clear"); + expect(refused).toEqual({ kind: "reply", text: copy("es-419", "HM-BOT-02.clearing") }); + + h.release(); + const fresh = await clearing; + expect(fresh).toBeTruthy(); + const orphans = await h.sql.query("SELECT id FROM chat_turns WHERE session_id NOT IN (SELECT id FROM sessions)"); + expect(orphans).toEqual([]); + }); +});