diff --git a/.changeset/full-journal-receipt-safety.md b/.changeset/full-journal-receipt-safety.md new file mode 100644 index 0000000000..71a283124f --- /dev/null +++ b/.changeset/full-journal-receipt-safety.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +Clear ended turns from active journal attribution before finish writes can fail, and mark a refused finish record partial. Admit checkout receipt tables only when capturing a checkout so upgrading a nearly full journal preserves ordinary writes. Keep history, retention and operational backups usable before those tables exist. diff --git a/.changeset/quiet-workspace-inspection.md b/.changeset/quiet-workspace-inspection.md index 81bb3a16b9..9f9bb3451a 100644 --- a/.changeset/quiet-workspace-inspection.md +++ b/.changeset/quiet-workspace-inspection.md @@ -8,7 +8,7 @@ Restrict workspace access in default governed and strict turns to read-only inspection. These turns no longer scan writable workspace aliases, read checkout ignore policy, retain workspace change rows or charge workspace bytes. Existing retained history remains readable. -Add an authenticated per-session (and draft) code-changes preference API. Enabling it takes effect at the next admission and preserves the previous writable mounts, alias scan and per-file journal. The worker learns its mode through append-only turn context; read-only guidance names the session switch and managed worktree alternatives for edits, installs and builds. +Add an authenticated per-session (and draft) code-changes preference API. Enabling it takes effect at the next admission and preserves the previous writable mounts and alias scan. Ordinary workspace files keep per-file journaling; covered Git checkouts retain one endpoint receipt per checkout, with ignored files and intermediate versions no longer retained. The worker learns its mode through append-only turn context; read-only guidance names the session switch and managed worktree alternatives for edits, installs and builds. Keep governed note writes live when the optional workspace is absent, retaining and charging newly created content until the next default admission seals it. Skip mounted checkout metadata traversal in inspection turns, preserve handoff prompts through actual preparation, and return actionable install refusals without denying checkout reads. diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 7ad88a675a..f4806b7d57 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -444,8 +444,9 @@ an inspection turn usable. The authenticated code-changes preference survives resume and applies at the next admission. Changing it cannot change a running worker's mounts. Enabling -it retains the existing alias scan and per-file journaling; the Git receipt -transition is separate work. The worker's sandbox note names the mode and both +it retains the existing alias scan. Ordinary workspace files keep per-file +journaling; covered Git checkouts retain one endpoint receipt per checkout +under the [history contract](../integration-contract/http.md#checkout-change-receipts-4297). The worker's sandbox note names the mode and both ways to obtain writable checkout access: the session's code-changes switch or a managed worktree. Arbitrary tools still return the kernel's read-only error; failed tool results carrying `EROFS` or a read-only diagnostic receive the diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index ccf8097141..bb57912aa9 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -471,7 +471,9 @@ write verified scratch/workspace copies through the aliases below. worker's note names both alternatives. The preference is per session, survives resume and applies at the next admission, leaving a running worker unchanged. When enabled, the existing real directory gets the - previous writable mount, alias scan, per-file journal and byte accounting: + previous writable mount, alias scan and byte bounds. Ordinary workspace files + keep per-file journaling; covered Git checkouts retain one endpoint receipt + per checkout (see the [history contract](../integration-contract/http.md#checkout-change-receipts-4297)): governed uses its canonical path; strict uses a private copy at `/tmp/brain-worker-areas/workspaces` with validated publication after exit. Writable qualification still refuses outside hard links, mount points, diff --git a/docs/http-api.md b/docs/http-api.md index 528540084c..08756a813c 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -2468,7 +2468,9 @@ They use the same authenticated identity and principal-scoped draft binding as profile preferences. PUT accepts exactly `{ enabled: boolean }`; all replies are `Cache-Control: no-store`. Existing sessions default to false. Saves survive resume and apply only to the next admission; enabled sessions retain -the existing writable-workspace protections and per-file journal. +the existing writable-workspace protections. Ordinary workspace files keep +per-file journaling; covered Git checkouts retain one endpoint receipt per +checkout, as defined by the [history contract](integration-contract/http.md#checkout-change-receipts-4297). ### Combined selected-trigger and future-source review diff --git a/packages/ui-server/migrations/096_code_change_receipts.journal.sql b/packages/ui-server/migrations/096_code_change_receipts.journal.sql index e114b2e674..333733e31e 100644 --- a/packages/ui-server/migrations/096_code_change_receipts.journal.sql +++ b/packages/ui-server/migrations/096_code_change_receipts.journal.sql @@ -1,27 +1,3 @@ --- Host-owned endpoint packs share journal CAS accounting and turn lifetime pins. -CREATE TABLE journal.turn_journal_code_receipts ( - turn_id TEXT NOT NULL REFERENCES turn_journal_turns(turn_id) ON DELETE CASCADE, - checkout TEXT NOT NULL, - receipt TEXT NOT NULL, - pack_hash TEXT NOT NULL REFERENCES turn_journal_objects(hash), - PRIMARY KEY (turn_id, checkout) -); +-- Checkout receipt tables are created on demand through admitted journal accounting. -CREATE TABLE journal.turn_journal_code_reverts ( - id TEXT PRIMARY KEY, - principal_id TEXT NOT NULL, - session_id TEXT NOT NULL, - turn_id TEXT NOT NULL REFERENCES turn_journal_turns(turn_id) ON DELETE CASCADE, - checkout TEXT NOT NULL, - state TEXT NOT NULL CHECK (state IN ('applying','complete','unknown','failed')), - result TEXT, - pid INTEGER NOT NULL, - pid_start TEXT NOT NULL -); - -CREATE TABLE journal.turn_journal_code_failures ( - turn_id TEXT NOT NULL REFERENCES turn_journal_turns(turn_id) ON DELETE CASCADE, - checkout TEXT NOT NULL, - cause TEXT NOT NULL, - PRIMARY KEY (turn_id, checkout) -); +SELECT 1; diff --git a/packages/ui-server/src/brain/code-change-history.ts b/packages/ui-server/src/brain/code-change-history.ts index 00f52d7b0c..b02a55cec3 100644 --- a/packages/ui-server/src/brain/code-change-history.ts +++ b/packages/ui-server/src/brain/code-change-history.ts @@ -1,4 +1,5 @@ /** Owner-confirmed checkout restoration; one durable identity, never a blind retry. */ +import { codeReceiptTablesExist } from "../db/journal-database.js"; import type { Database } from "bun:sqlite"; import type { CodeChangeReceipt } from "@schlessera/brain-ui-sdk/protocol"; import { runMaintenanceWorker, prepareNativeWorkerStartupView, type MaintenanceHost, type createNativeBrainManagerClient } from "@schlessera/brain-ui-sdk/internal"; @@ -23,6 +24,7 @@ export function createCodeChangeHistory(db: Database, options: { const { journal } = options; const pending = new Map>(); function read(id: string, principalId: string, sessionId: string, turnId: string): Result | null { + if (!codeReceiptTablesExist(db)) return null; const row = db.query("SELECT * FROM turn_journal_code_reverts WHERE id=? AND principal_id=? AND session_id=? AND turn_id=?").get(id, principalId, sessionId, turnId) as Row | null; if (!row) return null; if (row.result) return JSON.parse(row.result) as Result; @@ -30,7 +32,7 @@ export function createCodeChangeHistory(db: Database, options: { } async function revert(id: string, principalId: string, sessionId: string, turnId: string, checkout: string): Promise { if (pending.has(id)) { await pending.get(id); return revert(id, principalId, sessionId, turnId, checkout); } - const existing = db.query("SELECT * FROM turn_journal_code_reverts WHERE id=?").get(id) as Row | null; + const existing = codeReceiptTablesExist(db) ? db.query("SELECT * FROM turn_journal_code_reverts WHERE id=?").get(id) as Row | null : null; if (existing) { if (existing.principal_id !== principalId || existing.session_id !== sessionId || existing.turn_id !== turnId || existing.checkout !== checkout) throw Error("History operation identity belongs to another selection"); return pending.get(id) ?? read(id, principalId, sessionId, turnId)!; diff --git a/packages/ui-server/src/brain/journal-accounting.ts b/packages/ui-server/src/brain/journal-accounting.ts index 01077ba520..6d5f2f69bd 100644 --- a/packages/ui-server/src/brain/journal-accounting.ts +++ b/packages/ui-server/src/brain/journal-accounting.ts @@ -2,7 +2,7 @@ import type { JournalRecoveryStatus } from "@schlessera/brain-ui-sdk/protocol"; import type { Database } from "bun:sqlite"; import { realpathSync, statSync } from "node:fs"; import { resolve } from "node:path"; -import { attachJournalDatabase, JOURNAL_CHANGE_PATH_INDEX, JOURNAL_CONFLICT_TABLES, JOURNAL_CONFLICT_GUARDS, JOURNAL_MIGRATIONS_TABLE, JOURNAL_OBJECT_REFS_INDEX, JOURNAL_SCRUB_QUARANTINE, JOURNAL_SCRUB_GUARDS, JOURNAL_SCHEMA, journalDatabasePath } from "../db/journal-database.js"; +import { attachJournalDatabase, codeReceiptTablesExist, JOURNAL_CODE_TABLES, JOURNAL_CODE_GUARDS, JOURNAL_CHANGE_PATH_INDEX, JOURNAL_CONFLICT_TABLES, JOURNAL_CONFLICT_GUARDS, JOURNAL_MIGRATIONS_TABLE, JOURNAL_OBJECT_REFS_INDEX, JOURNAL_SCRUB_QUARANTINE, JOURNAL_SCRUB_GUARDS, JOURNAL_SCHEMA, journalDatabasePath } from "../db/journal-database.js"; import { JournalCapacityError, type JournalObjectAccounting } from "./journal-objects.js"; import { processAlive, SELF } from "./writer-gate.js"; @@ -45,6 +45,7 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { /** Admitted, retryable schema upgrade; false leaves integrity-checked collection usable. */ ensureObjectRefIndex(): boolean; ensureScrubQuarantine(): boolean; + ensureCodeReceiptTables(): boolean; ensureChangePathIndex(): boolean; ensureConflictTables(): boolean; openRead(hash: string, assertOwner?: () => void): string; @@ -250,6 +251,32 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { return false; } } + /** Like scrub DDL, receipt tables cannot consume an upgrade's unadmitted + * pages. Sixteen pages cover the three tables, primary keys and schema; + * reserve their FULL WAL and measure the actual extent before commit. + */ + const codeSchemaReady = () => codeReceiptTablesExist(db) && + (db.query("SELECT count(*) AS n FROM journal.sqlite_schema WHERE type='trigger' AND name IN (SELECT value FROM json_each(?))").get(JSON.stringify(JOURNAL_CODE_GUARDS.map(guard => guard.name))) as { n: number }).n === JOURNAL_CODE_GUARDS.length; + function ensureCodeReceiptTables(): boolean { + if (codeSchemaReady()) return true; + try { + write(() => { + if (codeSchemaReady()) return; + const pages = 16, before = measure(), projected = measure(pages), debt = wal(); + if (projected.bytes + debt > cap) { if (debt > 0) throw new WalDebt(); throw new JournalCapacityError(); } + for (const table of JOURNAL_CODE_TABLES) if (!db.query("SELECT 1 FROM journal.sqlite_schema WHERE type='table' AND name=?").get(table.name)) + db.exec(table.sql.replace("CREATE TABLE ", "CREATE TABLE journal.")); + for (const guard of JOURNAL_CODE_GUARDS) if (!db.query("SELECT 1 FROM journal.sqlite_schema WHERE type='trigger' AND name=?").get(guard.name)) + db.exec(guard.sql.replace("CREATE TRIGGER ", "CREATE TRIGGER journal.")); + installEscapeGuard(db); + if (measure().pages > before.pages + pages) throw new JournalCapacityError("The checkout receipt schema exceeded its admitted page allowance."); + }); + return true; + } catch (error) { + if (!(error instanceof JournalCapacityError || error instanceof JournalStorageUnavailable)) throw error; + return false; + } + } // While the server starts, truncate and return the pages released before // the last stop to the file system, as one admitted FULL write. A pinned // WAL or an over-cap store leaves this to the first write, which refuses @@ -260,7 +287,7 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { if (!memory) db.query(`PRAGMA ${JOURNAL_SCHEMA}.wal_checkpoint(TRUNCATE)`).get(); } catch (error) { if (!(error instanceof JournalStorageUnavailable || error instanceof JournalCapacityError)) throw error; } return { - write, usage, ensureScrubQuarantine, + write, usage, ensureScrubQuarantine, ensureCodeReceiptTables, ensureConflictTables() { const row = db.query("SELECT count(*) AS n FROM journal.sqlite_schema WHERE type='table' AND name IN ('turn_journal_path_peers','turn_journal_path_conflicts')").get() as { n: number }; const guards = db.query("SELECT count(*) AS n FROM journal.sqlite_schema WHERE type='trigger' AND name IN (SELECT value FROM json_each(?))").get(JSON.stringify(JOURNAL_CONFLICT_GUARDS.map(guard => guard.name))) as { n: number }; @@ -369,7 +396,7 @@ export function createJournalAccounting(db: Database, dbPath: string, options: { const owners = db.query("SELECT t.turn_id,t.missing FROM turn_journal_turns t JOIN turn_journal_object_refs r ON r.turn_id=t.turn_id WHERE r.hash=?").all(row.hash) as {turn_id:string;missing:string}[]; for (const owner of owners) { const paths = db.query(`SELECT path FROM turn_journal_changes WHERE turn_id=?1 AND (json_extract(before_json,'$.hash')=?2 OR json_extract(after_json,'$.hash')=?2) - UNION SELECT checkout AS path FROM turn_journal_code_receipts WHERE turn_id=?1 AND pack_hash=?2 + ${codeReceiptTablesExist(db) ? "UNION SELECT checkout AS path FROM turn_journal_code_receipts WHERE turn_id=?1 AND pack_hash=?2" : ""} UNION SELECT path FROM turn_journal_claude_memory WHERE turn_id=?1 AND (json_extract(before_json,'$.hash')=?2 OR json_extract(after_json,'$.hash')=?2) UNION SELECT p.path FROM turn_journal_revert_paths p JOIN turn_journal_revert_operations o ON o.id=p.operation_id WHERE o.journal_turn_id=?1 AND (json_extract(p.before_json,'$.hash')=?2 OR json_extract(p.after_json,'$.hash')=?2)`) .all(owner.turn_id, row.hash) as {path:string}[]; diff --git a/packages/ui-server/src/brain/journal-reference-cleanup.ts b/packages/ui-server/src/brain/journal-reference-cleanup.ts index 1fb6428de9..a297ce2e34 100644 --- a/packages/ui-server/src/brain/journal-reference-cleanup.ts +++ b/packages/ui-server/src/brain/journal-reference-cleanup.ts @@ -13,3 +13,6 @@ WHERE turn_id = ?1 AND hash NOT IN ( SELECT json_extract(after_json, '$.hash') FROM turn_journal_claude_memory WHERE turn_id = ?1 AND state != 'saved' ) WHERE h IS NOT NULL )`; + +/** Older or near-cap stores can finish notes without admitting receipt tables. */ +export const FINISH_REFERENCE_CLEANUP_WITHOUT_CODE = FINISH_REFERENCE_CLEANUP.replace(" SELECT pack_hash AS h FROM turn_journal_code_receipts WHERE turn_id = ?1\n UNION ALL\n", ""); diff --git a/packages/ui-server/src/brain/journal-store.ts b/packages/ui-server/src/brain/journal-store.ts index 9fbea4ed16..2d17f210f3 100644 --- a/packages/ui-server/src/brain/journal-store.ts +++ b/packages/ui-server/src/brain/journal-store.ts @@ -1,3 +1,4 @@ +import { codeReceiptTablesExist } from "../db/journal-database.js"; import { createJournalScrub } from "./journal-scrub.js"; /** * The turn journal's writes, run on the write worker's connection (#2814). @@ -72,8 +73,8 @@ const indexPins = ["before_json", "after_json"].flatMap(column => [ * external memory note, and an attachment removal's retained original, which * its Undo restores through the removal turn's pin. */ -const namedHashes = `${hashes("turn_journal_changes")} UNION ALL ${hashes("turn_journal_revert_paths")} UNION ALL ${hashes("turn_journal_claude_memory")} - UNION ALL SELECT pack_hash FROM turn_journal_code_receipts +const namedHashes = (codeReceipts: boolean) => `${hashes("turn_journal_changes")} UNION ALL ${hashes("turn_journal_revert_paths")} UNION ALL ${hashes("turn_journal_claude_memory")} + ${codeReceipts ? "UNION ALL SELECT pack_hash FROM turn_journal_code_receipts" : ""} UNION ALL SELECT json_extract(file.value,'$.retained.hash') FROM turn_journal_storage_operations s, json_each(s.private_versions) file`; type TurnRow = { session_id: string | null; actor: "interactive" | "voice" | "user"; kind: "turn" | "revert"; model: string | null; profile: "strict" | "governed"; steering_inventory_missing: string; configuration_set: string | null; missing: string }; @@ -162,6 +163,7 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur return db.query(statement.sql).run(...(statement.params ?? [])).changes; }); return { + ensureCodeReceiptTables: () => accounting.ensureCodeReceiptTables(), /** Statements in order, as one accounted transaction; the changes each made. */ statements(list: JournalStatement[]): number[] { return accounting.write(() => runStatements(list)); @@ -223,7 +225,7 @@ export function setup(db: Database, options: JournalStoreOptions): WriteProcedur for (const table of ["turn_journal_changes", "turn_journal_revert_paths"]) versions += db.query(`UPDATE ${table} SET before_json=${metadataOnly("before_json")},after_json=${metadataOnly("after_json")} WHERE ${INDEX_PATH} AND (${legacy("before_json")} OR ${legacy("after_json")})`).run(family, INDEX_PUBLICATION_COPY).changes; // Index versions name no hash any more: whatever still does is another record's content. - db.exec(`DELETE FROM temp.journal_index_purge WHERE hash IN (${namedHashes})`); + db.exec(`DELETE FROM temp.journal_index_purge WHERE hash IN (${namedHashes(codeReceiptTablesExist(db))})`); // Only the pin of the turn that recorded the index version: a pin // any other turn holds, for whatever reason, keeps its object. const pins = db.query(`DELETE FROM turn_journal_object_refs WHERE (turn_id,hash) IN (SELECT turn_id,hash FROM temp.journal_index_purge) diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 5a48ac668c..cfd183f2b4 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -1,6 +1,6 @@ import { startCronSpan } from "../cron/activity.js"; import type { JournalScrubResult } from "./journal-scrub.js"; -import { FINISH_REFERENCE_CLEANUP } from "./journal-reference-cleanup.js"; +import { FINISH_REFERENCE_CLEANUP, FINISH_REFERENCE_CLEANUP_WITHOUT_CODE } from "./journal-reference-cleanup.js"; import type { ActivityTurnHold } from "@schlessera/brain-ui-sdk/protocol"; /** Concrete host journal: observations, durable ownership and completed-turn collection. */ import type { CodeChangeReceipt, JournalRecoveryStatus } from "@schlessera/brain-ui-sdk/protocol"; @@ -15,7 +15,7 @@ import type { MaintenanceHost, WorkerStartupView } from "@schlessera/brain-ui-sd import { randomUUID } from "node:crypto"; import { recordedConfigurationSet } from "./journal-configuration-sets.js"; import { openSqliteWriter, type SqliteWriter } from "../db/write-worker.js"; -import { JOURNAL_SCHEMA, journalDatabasePath } from "../db/journal-database.js"; +import { codeReceiptTablesExist, JOURNAL_SCHEMA, journalDatabasePath } from "../db/journal-database.js"; import { installEscapeGuard, JournalObjectQuarantined, JournalStorageUnavailable } from "./journal-accounting.js"; import { createGovernanceWrites } from "../governance/event-writes.js"; import { createJournalObjects, JournalCapacityError } from "./journal-objects.js"; @@ -172,8 +172,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const interrupted = (db.query("SELECT turn_id,pid,pid_start,missing FROM turn_journal_turns WHERE ended_at IS NULL").all() as { turn_id: string; pid: number; pid_start: string; missing: string }[]) .filter(row => !processAlive(row.pid, row.pid_start)); for (const row of interrupted) await recoverAtOpen("interrupted_turn", () => ledger.call("statements", [statement("UPDATE turn_journal_turns SET state='partial',ended_at=?,missing=? WHERE turn_id=?", now(), JSON.stringify([...JSON.parse(row.missing), { path: ".", reason: "interrupted_observation" }]), row.turn_id)]), { turnId: row.turn_id }); - const invalidReceipts = db.query(`SELECT c.turn_id,c.checkout FROM turn_journal_code_receipts c JOIN turn_journal_turns t USING(turn_id) - WHERE t.ended_at IS NOT NULL AND NOT (${USABLE_CODE_RECEIPT}) ORDER BY c.turn_id,c.checkout`).all() as { turn_id: string; checkout: string }[]; + const invalidReceipts = codeReceiptTablesExist(db) ? db.query(`SELECT c.turn_id,c.checkout FROM turn_journal_code_receipts c JOIN turn_journal_turns t USING(turn_id) + WHERE t.ended_at IS NOT NULL AND NOT (${USABLE_CODE_RECEIPT}) ORDER BY c.turn_id,c.checkout`).all() as { turn_id: string; checkout: string }[] : []; if (invalidReceipts.length) { // Each quarantine atomically replaces the unusable endpoint with its // durable checkout-specific cause; no later reader sees damaged JSON. @@ -193,10 +193,10 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { } const recordingReceipt = `CASE WHEN (${USABLE_CODE_RECEIPT}) THEN json_extract(receipt,'$.state') END='recording' AND turn_id IN (SELECT turn_id FROM turn_journal_turns WHERE ended_at IS NOT NULL)`; - if (db.query(`SELECT 1 FROM turn_journal_code_receipts WHERE ${recordingReceipt} LIMIT 1`).get()) { + if (codeReceiptTablesExist(db) && db.query(`SELECT 1 FROM turn_journal_code_receipts WHERE ${recordingReceipt} LIMIT 1`).get()) { await recoverAtOpen("recording_receipts", () => ledger.call("statements", [statement(`UPDATE turn_journal_code_receipts SET receipt=json_set(receipt,'$.state','partial') WHERE ${recordingReceipt}`)])); } - for (const row of db.query("SELECT id,turn_id,pid,pid_start FROM turn_journal_code_reverts WHERE state='applying'").all() as { id: string; turn_id: string; pid: number; pid_start: string }[]) { + for (const row of codeReceiptTablesExist(db) ? db.query("SELECT id,turn_id,pid,pid_start FROM turn_journal_code_reverts WHERE state='applying'").all() as { id: string; turn_id: string; pid: number; pid_start: string }[] : []) { if (processAlive(row.pid, row.pid_start)) continue; await recoverAtOpen("interrupted_code_revert", () => ledger.call("statements", [statement("UPDATE turn_journal_code_reverts SET state='unknown',result=? WHERE id=? AND state='applying'", JSON.stringify({ id: row.id, status: "unknown", error: "Interrupted checkout restoration; review partial work before another action.", at: now(), callSite: "turn-journal.recover" }), row.id)]), { turnId: row.turn_id }); } @@ -328,14 +328,16 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const codeScopeFacts = new Map; sizes: Map }>(); async function captureCheckout(turnId: string, checkout: string, manager: NativeJournalManager, relative: string, signal?: AbortSignal, final = false): Promise { const key = checkoutKey(turnId, checkout), held = checkouts.get(key); - const previous = held ?? (db.query(`SELECT c.receipt,c.pack_hash FROM turn_journal_code_receipts c JOIN turn_journal_turns t USING(turn_id) - WHERE checkout=? AND json_extract(c.receipt,'$.state')='complete' ORDER BY t.started_at DESC LIMIT 1`).get(checkout) as { receipt: string; pack_hash: string } | null); - const earlier = previous ? typeof previous.receipt === "string" ? JSON.parse(previous.receipt) as CodeChangeReceipt : previous.receipt : undefined; - const previousHash = previous ? "hash" in previous ? previous.hash : previous.pack_hash : undefined; const checkpointId = randomUUID(); const maximum = relative ? CODE_CHECKOUT_BYTES : (db.query("SELECT allowance FROM reference_worktrees WHERE id=?").get(checkout.split("/")[2]!) as { allowance: number } | null)?.allowance ?? CODE_CHECKOUT_BYTES; - let packLease: string | undefined, previousBody: ReadableStream | undefined; + let packLease: string | undefined, previousBody: ReadableStream | undefined, checkpointAttempted = false; try { + if (!await call("ensureCodeReceiptTables")) throw new JournalStorageUnavailable("checkout_receipt_schema_not_admitted"); + const previous = held ?? (db.query(`SELECT c.receipt,c.pack_hash FROM turn_journal_code_receipts c JOIN turn_journal_turns t USING(turn_id) + WHERE checkout=? AND json_extract(c.receipt,'$.state')='complete' ORDER BY t.started_at DESC LIMIT 1`).get(checkout) as { receipt: string; pack_hash: string } | null); + const earlier = previous ? typeof previous.receipt === "string" ? JSON.parse(previous.receipt) as CodeChangeReceipt : previous.receipt : undefined; + const previousHash = previous ? "hash" in previous ? previous.hash : previous.pack_hash : undefined; + checkpointAttempted = true; const checkpoint = await manager.checkpoint(checkpointId, signal); const directory = await checkedCodeDirectory(checkpoint.path, relative); if (previousHash) { @@ -363,12 +365,15 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { } catch (error) { const cause = { checkout, at: now(), callSite: "captureCheckout", errorClass: error instanceof Error ? error.name : "UnknownError", message: String(error).slice(0, 2000) }; diagnostic(() => options.log?.emit({ severityText: "ERROR", body: "Checkout receipt capture failed", attributes: { "turn.id": turnId, "checkout": checkout, "error.type": cause.errorClass } })); - try { await write([ + if (!codeReceiptTablesExist(db)) { + await createSettingsWrites(db, writer).setSetting("journal.cleanup.lastFailure", { kind: "code_capture_failed", scope: "checkout", turnId, ...cause, cause: cause.message, retrying: true }); + } + try { if (codeReceiptTablesExist(db)) await write([ statement("INSERT INTO turn_journal_code_failures VALUES (?,?,?) ON CONFLICT(turn_id,checkout) DO UPDATE SET cause=excluded.cause", turnId, checkout, JSON.stringify(cause)), statement("UPDATE turn_journal_code_receipts SET receipt=json_set(receipt,'$.state','partial') WHERE turn_id=? AND checkout=?", turnId, checkout), ]); } catch { /* The preallocated turn failure slot remains authoritative. */ } throw error; - } finally { await previousBody?.cancel().catch(() => {}); if (packLease) await releaseRead(packLease); await releaseCodeCheckpoint(checkpointId, manager); } + } finally { await previousBody?.cancel().catch(() => {}); if (packLease) await releaseRead(packLease); if (checkpointAttempted) await releaseCodeCheckpoint(checkpointId, manager); } } async function attachBrainCheckouts(turnId: string, signal?: AbortSignal): Promise { const id = randomUUID(); @@ -547,7 +552,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const counts = { ...((active.has(turnId) ? advanceCounters(turnId).counts : undefined) ?? db.query(`SELECT count(DISTINCT path) AS changedFiles,count(DISTINCT CASE WHEN class='steering' THEN path END) AS steeringFiles, count(DISTINCT CASE WHEN ${KEPT_CHANGE} THEN path END) AS keptFiles,max(overlaps!='[]') AS sharedAttribution FROM turn_journal_changes WHERE turn_id=?`) .get(DISPOSABLE_INDEX_PATHS, INDEX_PUBLICATION_COPY, turnId) as { changedFiles: number; steeringFiles: number; keptFiles: number; sharedAttribution: number }) }; - const codeCount = (db.query("SELECT coalesce(sum(json_array_length(receipt,'$.paths')),0) AS n FROM turn_journal_code_receipts WHERE turn_id=?").get(turnId) as { n: number }).n; + const codeCount = codeReceiptTablesExist(db) ? (db.query("SELECT coalesce(sum(json_array_length(receipt,'$.paths')),0) AS n FROM turn_journal_code_receipts WHERE turn_id=?").get(turnId) as { n: number }).n : 0; counts.changedFiles += codeCount; counts.keptFiles += codeCount; const cost = db.query("SELECT effective_cost_usd,pricing_estimate FROM activity_run_rollups WHERE run_id=?").get(turnId) as { effective_cost_usd: number | null; pricing_estimate: number | null } | null; const partial = row.state !== "expired" && (failures.has(turnId) || row.failure.trim() || row.state === "partial"); @@ -574,12 +579,12 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { async function expire(turnId: string, removeSummary = false) { // A drained owner effect keeps its source and idempotency receipt until // completion; a dead owner is marked unknown by startup recovery above. - if (db.query("SELECT 1 FROM turn_journal_code_reverts WHERE turn_id=? AND state='applying'").get(turnId)) return; + if (codeReceiptTablesExist(db) && db.query("SELECT 1 FROM turn_journal_code_reverts WHERE turn_id=? AND state='applying'").get(turnId)) return; // Retention deletes the whole turn and does not need to parse its raw receipts. const before = removeSummary ? undefined : summary(turnId); await write([ - statement("DELETE FROM turn_journal_code_failures WHERE turn_id=?", turnId), - statement("DELETE FROM turn_journal_code_receipts WHERE turn_id=?", turnId), + ...(codeReceiptTablesExist(db) ? [statement("DELETE FROM turn_journal_code_failures WHERE turn_id=?", turnId), + statement("DELETE FROM turn_journal_code_receipts WHERE turn_id=?", turnId)] : []), ...(db.query("SELECT 1 FROM journal.sqlite_schema WHERE name='turn_journal_path_peers'").get() ? [statement("DELETE FROM turn_journal_path_peers WHERE turn_id=?", turnId), statement("DELETE FROM turn_journal_path_conflicts WHERE turn_id=?", turnId)] : []), statement("DELETE FROM turn_journal_changes WHERE turn_id=?", turnId), statement("DELETE FROM turn_journal_claude_memory WHERE turn_id=?", turnId), @@ -650,7 +655,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, () => {}); } async function collectOne(): Promise { - const row = db.query("SELECT turn_id,state FROM turn_journal_turns t WHERE ended_at IS NOT NULL AND NOT EXISTS (SELECT 1 FROM turn_journal_code_reverts r WHERE r.turn_id=t.turn_id AND r.state='applying') ORDER BY (state='expired'),ended_at LIMIT 1").get() as { turn_id: string; state: string } | null; + const row = db.query(`SELECT turn_id,state FROM turn_journal_turns t WHERE ended_at IS NOT NULL ${codeReceiptTablesExist(db) ? "AND NOT EXISTS (SELECT 1 FROM turn_journal_code_reverts r WHERE r.turn_id=t.turn_id AND r.state='applying')" : ""} ORDER BY (state='expired'),ended_at LIMIT 1`).get() as { turn_id: string; state: string } | null; if (!row) return false; await expire(row.turn_id, row.state === "expired"); return true; } @@ -659,7 +664,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { // The preallocated terminal slot shrinks more than ended_at grows. // A refused worker made no changes, so initial-only CAS pins are unneeded. statement("UPDATE turn_journal_turns SET state='partial',failure=?,ended_at=? WHERE turn_id=?", failures.get(turnId) ?? "journal_unavailable", now(), turnId), - statement("DELETE FROM turn_journal_code_receipts WHERE turn_id=?", turnId), + ...(codeReceiptTablesExist(db) ? [statement("DELETE FROM turn_journal_code_receipts WHERE turn_id=?", turnId)] : []), statement("DELETE FROM turn_journal_manifests WHERE turn_id=?", turnId), statement("DELETE FROM turn_journal_object_refs WHERE turn_id=?", turnId), ])); @@ -746,7 +751,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { codeScopeFacts.set(turnId, code); facts.observedBytes += [...code.sizes.values()].reduce((sum, bytes) => sum + bytes, 0); const paths = new Set(code.paths); - const codeFacts = db.query("SELECT checkout,json_extract(receipt,'$.paths') AS paths FROM turn_journal_code_receipts WHERE turn_id=?").all(turnId) as { checkout: string; paths: string }[]; + const codeFacts = codeReceiptTablesExist(db) ? db.query("SELECT checkout,json_extract(receipt,'$.paths') AS paths FROM turn_journal_code_receipts WHERE turn_id=?").all(turnId) as { checkout: string; paths: string }[] : []; for (const receipt of codeFacts) for (const item of JSON.parse(receipt.paths) as { path: string }[]) paths.add(`${receipt.checkout.replace(/\/$/, "")}/${item.path}`); facts.changedPaths += paths.size; facts.workspacePaths += [...paths].filter(path => isWithin(BRAIN_WORKSPACES_DIR, path)).length; @@ -1022,7 +1027,6 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { catch (error) { await fail(turnId, error); throw error; } finally { for (const [key, root] of checkouts) if (root.turnId === turnId) checkouts.delete(key); - await write([statement("UPDATE turn_journal_code_receipts SET receipt=json_set(receipt,'$.state','partial') WHERE turn_id=? AND json_extract(receipt,'$.state')='recording'", turnId)]); active.delete(turnId); counters.delete(turnId); codeScopeFacts.delete(turnId); lasting.delete(turnId); for (const [key, call] of calls) if (call.turnId === turnId) calls.delete(key); let step = [...worktrees.values()].some(root => root.turnId === turnId) ? timing?.("finish_worktrees") : undefined; @@ -1030,11 +1034,12 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { if (!active.size) { clearInterval(scopeTimer); scopeTimer = undefined; } step = timing?.("finish_record"); await write([ + ...(codeReceiptTablesExist(db) ? [statement("UPDATE turn_journal_code_receipts SET receipt=json_set(receipt,'$.state','partial') WHERE turn_id=? AND json_extract(receipt,'$.state')='recording'", turnId)] : []), ...(failures.has(turnId) ? [statement("UPDATE turn_journal_turns SET state='partial',failure=? WHERE turn_id=?", failures.get(turnId)!.padEnd(64), turnId)] : []), statement("UPDATE turn_journal_turns SET ended_at=?,failure=trim(failure),state=CASE WHEN state='partial' OR missing!='[]' THEN 'partial' ELSE 'complete' END WHERE turn_id=?", now(), turnId), statement("DELETE FROM turn_journal_manifests WHERE turn_id=?", turnId), - statement(FINISH_REFERENCE_CLEANUP, turnId), - ]); + statement(codeReceiptTablesExist(db) ? FINISH_REFERENCE_CLEANUP : FINISH_REFERENCE_CLEANUP_WITHOUT_CODE, turnId), + ]).catch(async error => { await fail(turnId, error); throw error; }); step?.(); step = timing?.("finish_collect"); await collectObjects(); step?.(); step = timing?.("finish_publish"); @@ -1160,6 +1165,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { /** Host history only; the pack is leased for the entire isolated operation. */ async withCodeEvidence(sessionId: string, turnId: string, checkout: string, operation: (receipt: CodeChangeReceipt, pack: string) => Promise): Promise { if (!this.details(sessionId, turnId) || ["unknown", "expired"].includes(summary(turnId).state)) throw new JournalStorageUnavailable("checkout receipt unavailable"); + if (!codeReceiptTablesExist(db)) throw new JournalStorageUnavailable("checkout receipt unavailable"); const row = db.query("SELECT receipt,pack_hash FROM turn_journal_code_receipts WHERE turn_id=? AND checkout=?").get(turnId, checkout) as { receipt: string; pack_hash: string } | null; if (!row) throw new JournalStorageUnavailable("checkout receipt unavailable"); const lease = await call("openRead", row.pack_hash, turnId); @@ -1212,8 +1218,8 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const outwardActions: JournalOutwardAction[] = outward.slice(0, 1000).map(event => ({ id: event.id, at: event.at, tool: String(event.payload.tool), action: event.payload.action as JournalOutwardAction["action"], target: event.payload.target as string | null, decision: event.payload.decision as JournalOutwardAction["decision"], historyRewrite: event.payload.historyRewrite === true, revertible: false })); - const codeChanges = (db.query("SELECT receipt FROM turn_journal_code_receipts WHERE turn_id=? ORDER BY checkout").all(turnId) as { receipt: string }[]).map(item => JSON.parse(item.receipt) as CodeChangeReceipt); - return { turnId, sessionId, summary: summary(turnId), changes, ...(codeChanges.length ? { codeChanges } : {}), ...(outwardActions.length ? { outwardActions, outwardActionsTruncated: outward.length > 1000 } : {}), missing: [...(db.query("SELECT checkout,cause FROM turn_journal_code_failures WHERE turn_id=?").all(turnId) as { checkout: string; cause: string }[]).map(item => { + const codeChanges = (codeReceiptTablesExist(db) ? db.query("SELECT receipt FROM turn_journal_code_receipts WHERE turn_id=? ORDER BY checkout").all(turnId) as { receipt: string }[] : []).map(item => JSON.parse(item.receipt) as CodeChangeReceipt); + return { turnId, sessionId, summary: summary(turnId), changes, ...(codeChanges.length ? { codeChanges } : {}), ...(outwardActions.length ? { outwardActions, outwardActionsTruncated: outward.length > 1000 } : {}), missing: [...(codeReceiptTablesExist(db) ? db.query("SELECT checkout,cause FROM turn_journal_code_failures WHERE turn_id=?").all(turnId) as { checkout: string; cause: string }[] : []).map(item => { const cause = diagnostic(() => JSON.parse(item.cause) as { message?: unknown } | null); return { path: item.checkout, reason: `code_capture_failed: ${typeof cause?.message === "string" ? cause.message : "Retained checkout failure cause is unavailable."}` }; }), ...JSON.parse(row.missing), ...(db.query("SELECT path FROM turn_journal_claude_memory WHERE turn_id=? AND state!='saved'").all(turnId) as {path:string}[]).filter(item => !(JSON.parse(row.missing) as {path:string}[]).some(missing => missing.path === item.path)).map(item => ({path:item.path,reason:"memory_persistence_unconfirmed"})), ...configurationOf(row).paths.map(path => ({ path, reason: "configuration_inputs_not_fully_identified" })), ...(failure ? [{ path: ".", reason: failure }] : [])] }; diff --git a/packages/ui-server/src/db/journal-database.ts b/packages/ui-server/src/db/journal-database.ts index 3321621c42..28bf713c85 100644 --- a/packages/ui-server/src/db/journal-database.ts +++ b/packages/ui-server/src/db/journal-database.ts @@ -151,3 +151,44 @@ export const JOURNAL_SCRUB_GUARDS = ["INSERT", "UPDATE", "DELETE"].map(event => WHEN (SELECT writing FROM turn_journal_allocation WHERE id=1) IS NOT 1 BEGIN SELECT RAISE(ABORT, 'journal storage write outside capacity accounting'); END`, })); + +/** Receipt state is installed atomically through capacity admission, only when needed. */ +export const JOURNAL_CODE_TABLES = [ + { name: "turn_journal_code_receipts", sql: `CREATE TABLE turn_journal_code_receipts ( + turn_id TEXT NOT NULL REFERENCES turn_journal_turns(turn_id) ON DELETE CASCADE, + checkout TEXT NOT NULL, + receipt TEXT NOT NULL, + pack_hash TEXT NOT NULL REFERENCES turn_journal_objects(hash), + PRIMARY KEY (turn_id, checkout) +)` }, + { name: "turn_journal_code_reverts", sql: `CREATE TABLE turn_journal_code_reverts ( + id TEXT PRIMARY KEY, + principal_id TEXT NOT NULL, + session_id TEXT NOT NULL, + turn_id TEXT NOT NULL REFERENCES turn_journal_turns(turn_id) ON DELETE CASCADE, + checkout TEXT NOT NULL, + state TEXT NOT NULL CHECK (state IN ('applying','complete','unknown','failed')), + result TEXT, + pid INTEGER NOT NULL, + pid_start TEXT NOT NULL +)` }, + { name: "turn_journal_code_failures", sql: `CREATE TABLE turn_journal_code_failures ( + turn_id TEXT NOT NULL REFERENCES turn_journal_turns(turn_id) ON DELETE CASCADE, + checkout TEXT NOT NULL, + cause TEXT NOT NULL, + PRIMARY KEY (turn_id, checkout) +)` }, +] as const; + +/** Permanent capacity guards also cover connections opened before the tables exist. */ +export const JOURNAL_CODE_GUARDS = JOURNAL_CODE_TABLES.flatMap(table => ["INSERT", "UPDATE", "DELETE"].map(event => ({ + name: `${table.name}_capacity_${event.toLowerCase()}`, + sql: `CREATE TRIGGER ${table.name}_capacity_${event.toLowerCase()} BEFORE ${event} ON ${table.name} + WHEN (SELECT writing FROM turn_journal_allocation WHERE id=1) IS NOT 1 + BEGIN SELECT RAISE(ABORT, 'journal storage write outside capacity accounting'); END`, +}))); + +/** Do not cache absence: another connection can admit the tables at runtime. */ +export function codeReceiptTablesExist(db: Database): boolean { + return Boolean(db.query("SELECT 1 FROM journal.sqlite_schema WHERE type='table' AND name='turn_journal_code_receipts'").get()); +} diff --git a/packages/ui-server/src/inbox/snapshot.ts b/packages/ui-server/src/inbox/snapshot.ts index 8dde087033..5ce130384e 100644 --- a/packages/ui-server/src/inbox/snapshot.ts +++ b/packages/ui-server/src/inbox/snapshot.ts @@ -9,7 +9,7 @@ import { z } from "zod"; import { brainApplicationInput } from "@schlessera/brain-ui-sdk/server"; import { COMPLETE_SHARE_INPUT_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; -import { JOURNAL_CHANGE_PATH_INDEX, JOURNAL_CONFLICT_TABLES, JOURNAL_CONFLICT_GUARDS, JOURNAL_OBJECT_REFS_INDEX, JOURNAL_SCRUB_QUARANTINE, JOURNAL_SCRUB_GUARDS, JOURNAL_SCHEMA, journalDatabasePath } from "../db/journal-database.js"; +import { JOURNAL_CODE_TABLES, JOURNAL_CODE_GUARDS, JOURNAL_CHANGE_PATH_INDEX, JOURNAL_CONFLICT_TABLES, JOURNAL_CONFLICT_GUARDS, JOURNAL_OBJECT_REFS_INDEX, JOURNAL_SCRUB_QUARANTINE, JOURNAL_SCRUB_GUARDS, JOURNAL_SCHEMA, journalDatabasePath } from "../db/journal-database.js"; import type { InboxQueueItem } from "@schlessera/brain-ui-sdk/protocol"; import { pauseRestoredSchedules, validateScheduleRelations } from "../schedules/recovery.js"; import { invalidateRestoredStorage, parseStoredHistory } from "../storage/history-store.js"; @@ -112,6 +112,12 @@ function validateDatabase(db: Database): void { const guards = JOURNAL_CONFLICT_GUARDS.filter(guard => actual.some(row => row.type === "trigger" && row.name === guard.name)); if (guards.length && (admitted.length !== JOURNAL_CONFLICT_TABLES.length || guards.length !== JOURNAL_CONFLICT_GUARDS.length)) throw new Error("inbox_snapshot_schema"); for (const guard of guards) expected.exec(guard.sql.replace("CREATE TRIGGER ", "CREATE TRIGGER journal.")); + const codeTables = JOURNAL_CODE_TABLES.filter(table => actual.some(row => row.type === "table" && row.name === table.name)); + if (codeTables.length && codeTables.length !== JOURNAL_CODE_TABLES.length) throw new Error("inbox_snapshot_schema"); + for (const table of codeTables) expected.exec(table.sql.replace("CREATE TABLE ", "CREATE TABLE journal.")); + const codeGuards = JOURNAL_CODE_GUARDS.filter(guard => actual.some(row => row.type === "trigger" && row.name === guard.name)); + if (codeGuards.length && (codeTables.length !== JOURNAL_CODE_TABLES.length || codeGuards.length !== JOURNAL_CODE_GUARDS.length)) throw new Error("inbox_snapshot_schema"); + for (const guard of codeGuards) expected.exec(guard.sql.replace("CREATE TRIGGER ", "CREATE TRIGGER journal.")); const scrub=actual.some(row=>row.type==="table"&&row.name===JOURNAL_SCRUB_QUARANTINE.name); if(scrub)expected.exec(JOURNAL_SCRUB_QUARANTINE.sql); const scrubGuards=JOURNAL_SCRUB_GUARDS.filter(guard=>actual.some(row=>row.type==="trigger"&&row.name===guard.name)); diff --git a/packages/ui-server/tests/code-change-receipt.test.ts b/packages/ui-server/tests/code-change-receipt.test.ts index 425184da77..152a69748c 100644 --- a/packages/ui-server/tests/code-change-receipt.test.ts +++ b/packages/ui-server/tests/code-change-receipt.test.ts @@ -231,7 +231,7 @@ test("inspection-only turns invoke no checkout maintenance and write no receipt" await journal.begin("inspect", { sessionId: "ithaca", actor: "interactive", model: null, profile: "governed", policyHash: null, workspaceReadOnly: true }, () => {}); await journal.finish("inspect"); expect(calls, "NO_WRITABLE_CHECKOUT_RUNS_NO_GIT").toBe(0); - expect(db.query("SELECT count(*) AS n FROM turn_journal_code_receipts").get()).toEqual({ n: 0 }); + expect(db.query("SELECT name FROM journal.sqlite_schema WHERE type='table' AND name GLOB 'turn_journal_code_*'").all(), "INSPECTION_NEVER_ALLOCATES_RECEIPT_TABLES").toEqual([]); } finally { await journal.close(); await native.close(); db.close(); f.close(); } }); diff --git a/packages/ui-server/tests/journal-code-receipt-upgrade.test.ts b/packages/ui-server/tests/journal-code-receipt-upgrade.test.ts new file mode 100644 index 0000000000..d95bb275bb --- /dev/null +++ b/packages/ui-server/tests/journal-code-receipt-upgrade.test.ts @@ -0,0 +1,109 @@ +import { expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { createUiDb } from "../src/db/client.js"; +import { JOURNAL_SCHEMA, journalDatabasePath } from "../src/db/journal-database.js"; +import { createJournalAccounting } from "../src/brain/journal-accounting.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { createTurnJournal } from "../src/brain/turn-journal.js"; +import { SELF } from "../src/brain/writer-gate.js"; +import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; +import { createFixtureMaintenanceHost } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture.js"; + +const tables = ["turn_journal_code_receipts", "turn_journal_code_reverts", "turn_journal_code_failures"]; +test("upgrading a near-cap journal preserves writes and admits receipt tables only for a checkout with room", async () => { + const root = mkdtempSync("/var/tmp/odysseus-code-upgrade-"), path = join(root, "ui.db"), brain = join(root, "brain"), objects = join(root, "objects"); + mkdirSync(brain); + let db = createUiDb(path), journal: ReturnType | undefined, other: ReturnType | undefined; + const native = createNativeJournalFixture(brain, root), maintenance = createFixtureMaintenanceHost(brain); + let externalWriter: ReturnType | undefined; + try { + for (const table of tables) db.exec(`DROP TABLE IF EXISTS journal.${table}`); + db.query("DELETE FROM journal.turn_journal_migrations WHERE filename='096_code_change_receipts.journal.sql'").run(); + const id = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", reserved = 1024 * 1024; + db.query("INSERT INTO turn_journal_reservations(id,bytes,pid,pid_start,created_at,hash,kind) VALUES (?,?,?,?,0,NULL,'temporary')").run(id, reserved, SELF.pid, SELF.start); + db.exec("VACUUM journal"); db.exec("PRAGMA journal.wal_checkpoint(TRUNCATE)"); + const pageSize = (db.query("PRAGMA journal.page_size").get() as { page_size: number }).page_size, pages = statSync(journalDatabasePath(path)).size / pageSize; + const standingWal = 32 + (pages + Math.ceil(pages / (pageSize / 4 - 2))) * (pageSize + 24), cap = pages * pageSize + standingWal + reserved + 4096; + db.close(); db = createUiDb(path); + const accounting = createJournalAccounting(db, path, { capBytes: cap }); + expect(() => accounting.write(() => db.query("UPDATE turn_journal_allocation SET index_purge=1 WHERE id=1").run()), "NEAR_CAP_RECEIPT_UPGRADE_WRITES_REMAIN_USABLE").not.toThrow(); + expect(accounting.ensureCodeReceiptTables(), "NEAR_CAP_RECEIPT_SCHEMA_IS_REFUSED").toBe(false); + expect(() => accounting.write(() => {}), "RECEIPT_SCHEMA_REFUSAL_LEAVES_WRITES_USABLE").not.toThrow(); + const schema = () => db.query("SELECT name FROM journal.sqlite_schema WHERE type='table' AND name GLOB 'turn_journal_code_*' ORDER BY name").all(); + expect(schema(), "UNUSED_RECEIPT_SCHEMA_STAYS_ABSENT").toEqual([]); + journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: objects, capBytes: cap, codeChanges: { maintenance } }); + await journal.ready; + expect(journal.details("ithaca", "missing")).toBeNull(); + expect(journal.summary("missing").state).toBe("unknown"); + expect(schema(), "STARTUP_NEVER_ADMITS_UNUSED_RECEIPT_SCHEMA").toEqual([]); + await expect(journal.withCodeEvidence("ithaca", "missing", "workspaces/argo", async () => {})).rejects.toThrow("checkout receipt unavailable"); + accounting.write(() => db.query("DELETE FROM turn_journal_reservations WHERE id=?").run(id)); + const checkout = join(brain, "workspaces/argo"); mkdirSync(checkout, { recursive: true }); + const git = (...args: string[]) => { + const result = Bun.spawnSync(["git", "-C", checkout, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@ithaca.example", ...args], { env: { PATH: "/usr/bin:/bin", HOME: "/nonexistent", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" } }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + }; + git("init", "-q", "-b", "main"); writeFileSync(join(checkout, "chart.md"), "Ithaca\n"); git("add", "."); git("commit", "-qm", "Set sail"); + // Refuse only the schema admission on the first real checkout capture. + // The next turn retries without a restart; unrelated note history stays usable. + await journal.close(); + const writer = openSqliteWriter(db, { attach: [{ schema: JOURNAL_SCHEMA, path: journalDatabasePath(path) }] }); + let refused = false; + journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: path, objectsRoot: objects, capBytes: cap, codeChanges: { maintenance }, + writer: { ...writer, channel(module, options, revive) { + const channel = writer.channel(module, options, revive); + return { ...channel, call(name: string, ...args: unknown[]): Promise { + if (name === "ensureCodeReceiptTables" && !refused) { refused = true; return Promise.resolve(false as T); } + return channel.call(name, ...args); + } }; + } }, + }); + // This writer is externally owned, so the final teardown closes it too. + externalWriter = writer; + const metadata = { sessionId: "ithaca", actor: "interactive", profile: "governed", model: null, policyHash: null } as const; + await expect(journal.begin("refused", { ...metadata, workspaceReadOnly: false, workspacesWritable: true }, () => {}), "SCHEMA_REFUSAL_NAMES_ONLY_FAILED_CHECKOUT_CAPTURE").rejects.toThrow("checkout_receipt_schema_not_admitted"); + expect(journal.cleanupStatus().lastFailure).toMatchObject({ kind: "code_capture_failed", scope: "checkout", turnId: "refused", checkout: "workspaces/argo", cause: expect.stringContaining("checkout_receipt_schema_not_admitted") }); + expect(schema()).toEqual([]); + expect(journal.details("ithaca", "refused")!.missing, "SCHEMA_ADMISSION_REFUSAL_DOES_NOT_INVENT_A_CAPACITY_CAUSE").toContainEqual({ path: ".", reason: "journal_unavailable" }); + await journal.begin("notes", { ...metadata, workspaceReadOnly: true }, () => {}); + writeFileSync(join(brain, "penelope.md"), "Penelope returns\n"); await journal.observe(); await journal.finish("notes"); + expect(journal.details("ithaca", "notes")!.changes.map(row => row.path), "REFUSED_CHECKOUT_LEAVES_NOTE_HISTORY_USABLE").toEqual(["penelope.md"]); + other = createUiDb(path); createJournalAccounting(other, path, { capBytes: cap }); + await journal.begin("sail", { sessionId: "ithaca", actor: "interactive", profile: "governed", model: null, policyHash: null, workspaceReadOnly: false, workspacesWritable: true }, () => {}); + expect(schema(), "CHECKOUT_RETRIES_SCHEMA_AFTER_CAPACITY_IS_FREED").toEqual(tables.toSorted().map(name => ({ name }))); + await journal.finish("sail"); + expect(journal.details("ithaca", "sail")!.codeChanges).toMatchObject([{ checkout: "workspaces/argo", state: "complete" }]); + expect(() => other!.query("DELETE FROM turn_journal_code_receipts").run(), "LATE_RECEIPT_SCHEMA_PROTECTS_OLDER_CONNECTIONS").toThrow("outside capacity accounting"); + expect(accounting.usage()).toBeLessThanOrEqual(cap); + } finally { other?.close(); await journal?.close(); await externalWriter?.close(); maintenance.cleanup(); await native.close(); db.close(); rmSync(root, { recursive: true, force: true }); } +}); + +for (const admitted of [false, true, "legacy"] as const) test(`backups preserve ${admitted === "legacy" ? "legacy" : admitted ? "admitted" : "absent"} receipt tables`, async () => { + const { exportInboxSnapshot, restoreInboxSnapshot } = await import("../src/inbox/snapshot.js"); + const root = mkdtempSync("/var/tmp/odysseus-code-backup-"), source = join(root, "source"), target = join(root, "target"); + mkdirSync(source); mkdirSync(target); + const path = join(source, "ui.db"), db = createUiDb(path), accounting = createJournalAccounting(db, path); + let restored: ReturnType | undefined; + try { + if (admitted) { + expect(accounting.ensureCodeReceiptTables()).toBe(true); + accounting.write(() => { + db.query("INSERT INTO turn_journal_turns(turn_id,actor,profile,started_at,state) VALUES ('sail','interactive','governed',0,'partial')").run(); + db.query("INSERT INTO turn_journal_code_failures VALUES ('sail','workspaces/argo',?)").run(JSON.stringify({ message: "Odysseus capture refused" })); + }); + if (admitted === "legacy") { + const { JOURNAL_CODE_GUARDS } = await import("../src/db/journal-database.js"); + for (const guard of JOURNAL_CODE_GUARDS) db.exec(`DROP TRIGGER journal.${guard.name}`); + } + } + const snapshot = await exportInboxSnapshot(db, source); + await expect(restoreInboxSnapshot(snapshot, join(target, "ui.db"), target), "BACKUP_ACCEPTS_OPTIONAL_RECEIPT_SCHEMA").resolves.toMatchObject({ resumed: false }); + restored = createUiDb(join(target, "ui.db")); + expect(restored.query("SELECT name FROM journal.sqlite_schema WHERE type='table' AND name GLOB 'turn_journal_code_*' ORDER BY name").all(), "BACKUP_PRESERVES_RECEIPT_SCHEMA_PRESENCE").toEqual(admitted ? tables.toSorted().map(name => ({ name })) : []); + if (admitted) { + expect(restored.query("SELECT checkout,cause FROM turn_journal_code_failures").all()).toEqual([{ checkout: "workspaces/argo", cause: JSON.stringify({ message: "Odysseus capture refused" }) }]); + if (admitted === true) expect(() => restored!.query("DELETE FROM turn_journal_code_failures").run(), "RESTORED_RECEIPT_GUARDS_REMAIN_ACTIVE").toThrow("outside capacity accounting"); + } + } finally { restored?.close(); db.close(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/packages/ui-server/tests/turn-journal.test.ts b/packages/ui-server/tests/turn-journal.test.ts index 2b80e9d239..444a6fb6a7 100644 --- a/packages/ui-server/tests/turn-journal.test.ts +++ b/packages/ui-server/tests/turn-journal.test.ts @@ -13,8 +13,9 @@ import { createNativeJournalCapture } from "../src/brain/native-journal-capture. import { createTurnJournal } from "../src/brain/turn-journal.js"; import { openSqliteWriter, type SqliteWriter } from "../src/db/write-worker.js"; import { JOURNAL_SCHEMA, journalDatabasePath } from "../src/db/journal-database.js"; -import { FINISH_REFERENCE_CLEANUP } from "../src/brain/journal-reference-cleanup.js"; +import { FINISH_REFERENCE_CLEANUP_WITHOUT_CODE } from "../src/brain/journal-reference-cleanup.js"; import { journalStatement, type JournalStatement } from "../src/brain/journal-store.js"; +import { JournalCapacityError } from "../src/brain/journal-objects.js"; import { configurationSet } from "../src/brain/journal-configuration-sets.js"; import { recordGovernanceEvent, queryGovernanceEvents } from "../src/governance/events.js"; import { createStatusRoutes } from "../src/routes/health.js"; @@ -851,17 +852,46 @@ test("idle checkpoint cleanup records its cause durably before any turn exists a } finally { f.native.manager.release = release; await f.close(); } }); +test("a refused finish write removes the ended turn before the next note observation", async () => { + let refuse = false, injected = 0, idleScrubs = 0; + const f = fixture(undefined, writer => ({ ...writer, channel(module, options, revive) { + const channel = writer.channel(module, options, revive); + return { ...channel, call(name, ...args) { + if (name === "scrubObjects") idleScrubs++; + if (refuse && name === "statements") { + refuse = false; injected++; + return Promise.reject(new JournalCapacityError()); + } + return channel.call(name, ...args); + } }; + } })); + try { + await f.begin("ended"); refuse = true; + await expect(f.journal.finish("ended")).rejects.toThrow(); + expect(injected).toBe(1); + await f.begin("later"); + writeFileSync(join(f.brain, "notes/penelope.md"), "Penelope returns to Ithaca.\n"); + await f.journal.observe(); + expect(f.db.query("SELECT DISTINCT turn_id FROM turn_journal_changes WHERE path='notes/penelope.md' ORDER BY turn_id").all(), "NEXT_NOTE_BELONGS_ONLY_TO_LATER_TURN").toEqual([{ turn_id: "later" }]); + expect(f.journal.summary("ended").state, "REFUSED_FINISH_NEVER_READS_RECORDING").toBe("partial"); + await f.journal.finish("later"); + expect(f.journal.isHeld(), "FINISH_RELEASES_HOLD").toBe(false); + await f.journal.maintain(); + expect(idleScrubs, "ENDED_TURN_DOES_NOT_BLOCK_IDLE_MAINTENANCE").toBe(1); + } finally { await f.close(); } +}); + test("actual finish rolls back its terminal record when reference cleanup refuses",async()=>{ let injected=0; const f=fixture(undefined,writer=>({...writer,channel(module,options,revive){ const channel=writer.channel(module,options,revive); return {...channel,call(name,...args){ - if(name==="statements" && (args[0] as JournalStatement[]).some(row=>"sql" in row && row.sql===FINISH_REFERENCE_CLEANUP)) { + if(name==="statements" && (args[0] as JournalStatement[]).some(row=>"sql" in row && row.sql===FINISH_REFERENCE_CLEANUP_WITHOUT_CODE)) { injected++; // Refuse at the actual cleanup statement through the production writer // and accounted transaction. Splitting finish into two writes exposes a // committed terminal record and fails the rollback assertions below. - args[0]=(args[0] as JournalStatement[]).map(row=>"sql" in row && row.sql===FINISH_REFERENCE_CLEANUP + args[0]=(args[0] as JournalStatement[]).map(row=>"sql" in row && row.sql===FINISH_REFERENCE_CLEANUP_WITHOUT_CODE ? {check:"SELECT 1 WHERE 0",refusal:"actual finish cleanup interrupted"}:row); } return channel.call(name,...args); @@ -872,7 +902,7 @@ test("actual finish rolls back its terminal record when reference cleanup refuse const refs=f.db.query("SELECT count(*) AS n FROM turn_journal_object_refs WHERE turn_id='finish-atomic'").get(); await expect(f.journal.finish("finish-atomic"),"ACTUAL_FINISH_CLEANUP_FAULT").rejects.toThrow("actual finish cleanup interrupted"); expect(injected,"ACTUAL_FINISH_FAULT_EXECUTED").toBe(1); - expect(f.db.query("SELECT ended_at,state FROM turn_journal_turns WHERE turn_id='finish-atomic'").get(),"ACTUAL_FINISH_RECORD_ROLLS_BACK_WITH_REFS").toEqual({ended_at:null,state:"recording"}); + expect(f.db.query("SELECT ended_at,state FROM turn_journal_turns WHERE turn_id='finish-atomic'").get(),"ACTUAL_FINISH_RECORD_ROLLS_BACK_WITH_REFS").toEqual({ended_at:null,state:"partial"}); expect(f.db.query("SELECT count(*) AS n FROM turn_journal_object_refs WHERE turn_id='finish-atomic'").get()).toEqual(refs); }finally{await f.close();} }); @@ -896,7 +926,7 @@ test("successful actual finish binds cleanup to its own turn and retains every r const channel=writer.channel(module,options,revive); return {...channel,call(name,...args){ const rows=args[0] as JournalStatement[]; - if(name==="statements"&&rows.some(row=>"sql"in row&&row.sql===FINISH_REFERENCE_CLEANUP)) { + if(name==="statements"&&rows.some(row=>"sql"in row&&row.sql===FINISH_REFERENCE_CLEANUP_WITHOUT_CODE)) { injected++; const extra:JournalStatement[]=[]; for(const hash of hashes)extra.push(journalStatement("INSERT OR IGNORE INTO turn_journal_objects VALUES (?,0,'pending')",hash),journalStatement("INSERT OR IGNORE INTO turn_journal_object_refs VALUES ('finish-survivors',?)",hash)); @@ -905,7 +935,7 @@ test("successful actual finish binds cleanup to its own turn and retains every r journalStatement("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json) VALUES ('finish-survivors',1001,'notes/empty.md','content',NULL,'{}')"), journalStatement("INSERT INTO turn_journal_claude_memory VALUES ('finish-survivors','pending','/ithaca','1','2','Athena',NULL,?,'unconfirmed')",JSON.stringify({hash:hashes[2]})), journalStatement("INSERT INTO turn_journal_claude_memory VALUES ('finish-survivors','saved','/ithaca','1','2','Athena',?,NULL,'saved')",JSON.stringify({hash:hashes[3]}))); - const at=rows.findIndex(row=>"sql"in row&&row.sql===FINISH_REFERENCE_CLEANUP); + const at=rows.findIndex(row=>"sql"in row&&row.sql===FINISH_REFERENCE_CLEANUP_WITHOUT_CODE); args[0]=[...rows.slice(0,at),...extra,...rows.slice(at)]; } return channel.call(name,...args);