Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/full-journal-receipt-safety.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion .changeset/quiet-workspace-inspection.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
5 changes: 3 additions & 2 deletions docs/decisions/worker-writable-areas.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion docs/hosting/agent-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
28 changes: 2 additions & 26 deletions packages/ui-server/migrations/096_code_change_receipts.journal.sql
Original file line number Diff line number Diff line change
@@ -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;
4 changes: 3 additions & 1 deletion packages/ui-server/src/brain/code-change-history.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -23,14 +24,15 @@ export function createCodeChangeHistory(db: Database, options: {
const { journal } = options;
const pending = new Map<string, Promise<Result>>();
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;
return { id, status: "unknown", error: processAlive(row.pid, row.pid_start) ? "Operation is still settling; read this identity again." : "Interrupted restoration; review the checkout before another action." };
}
async function revert(id: string, principalId: string, sessionId: string, turnId: string, checkout: string): Promise<Result> {
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)!;
Expand Down
33 changes: 30 additions & 3 deletions packages/ui-server/src/brain/journal-accounting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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 };
Expand Down Expand Up @@ -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}[];
Expand Down
3 changes: 3 additions & 0 deletions packages/ui-server/src/brain/journal-reference-cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", "");
8 changes: 5 additions & 3 deletions packages/ui-server/src/brain/journal-store.ts
Original file line number Diff line number Diff line change
@@ -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).
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading