Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(core): preserve relay undo on minimum Node [C7,H21,H16]
Corey Olson2bd1fc174dcb
diff --git a/src/relay-outbox-undo.js b/src/relay-outbox-undo.jsindex 9208e520..f193dfee 100644--- a/src/relay-outbox-undo.js+++ b/src/relay-outbox-undo.js@@ -96,6 +96,77 @@ export function invertChangeset(changeset) {return Buffer.concat(out);}+/** Whether this connection accepts Node's newer callback form; the minimum Node requires a number. */+const CALLBACK_CONFLICTS = new WeakMap();++/** Probe an empty changeset, before any undo writes, without guessing the capability from a Node version. */+function callbackConflicts(db) {+ if (CALLBACK_CONFLICTS.has(db)) return CALLBACK_CONFLICTS.get(db);+ let supported = true;+ try { db.applyChangeset(new Uint8Array(), { onConflict: () => ABORT }); }+ catch (error) {+ if (error.code !== 'ERR_INVALID_ARG_TYPE' || !error.message.includes('options.onConflict') || !error.message.includes('number')) throw error;+ supported = false;+ }+ CALLBACK_CONFLICTS.set(db, supported);+ return supported;+}++/** Decode a primary-key value without losing SQLite's 64-bit integers or blob keys. */+function keyValue(encoded) {+ const bytes = encoded.bytes;+ if (bytes[0] === 1) return bytes.readBigInt64BE(1);+ if (bytes[0] === 2) return bytes.readDoubleBE(1);+ if (bytes[0] === 5) return null;+ if (bytes[0] === 3 || bytes[0] === 4) {+ const length = varint(bytes, 1);+ const content = bytes.subarray(length.next, length.next + length.value);+ return bytes[0] === 3 ? content.toString('utf8') : content;+ }+ throw new Error('a changeset primary key is undefined');+}++/** Quote a SQLite identifier read from the changeset or its actual table schema. */+function identifier(name) { return `"${name.replaceAll('"', '""')}"`; }++/**+ * Numeric REPLACE also replaces a conflicting INSERT, which undo must refuse. Check row existence first,+ * inside the same write transaction, so only changed UPDATE/DELETE values can reach that resolution.+ * Check each changeset just before applying it: an earlier inverse may have restored or removed its keys.+ */+function legacyRowConflict(db, bytes) {+ let columns = 0;+ let keys = [];+ let lookup;+ for (let at = 0; at < bytes.length;) {+ const marker = bytes[at];+ if (marker === 0x54) {+ const count = varint(bytes, at + 1);+ columns = count.value;+ const flags = bytes.subarray(count.next, count.next + columns);+ const end = bytes.indexOf(0, count.next + columns);+ if (end < 0) throw new Error('a changeset table name is unterminated');+ const table = bytes.subarray(count.next + columns, end).toString('utf8');+ const schema = db.prepare(`PRAGMA table_info(${identifier(table)})`).all();+ if (schema.length !== columns || schema.some((column, index) => Boolean(column.pk) !== Boolean(flags[index]))) {+ throw new Error(`changeset primary keys do not match table ${table}`);+ }+ keys = schema.flatMap((column, index) => flags[index] ? [index] : []);+ if (!keys.length) throw new Error(`changeset table ${table} has no primary key`);+ lookup = db.prepare(`SELECT 1 FROM ${identifier(table)} WHERE ${keys.map(index => `${identifier(schema[index].name)} IS ?`).join(' AND ')}`);+ at = end + 1;+ continue;+ }+ if (![INSERT, UPDATE, DELETE].includes(marker) || !lookup) throw new Error(`invalid changeset operation ${marker}`);+ const row = record(bytes, at + 2, columns);+ const exists = Boolean(lookup.get(...keys.map(index => keyValue(row.values[index]))));+ if (marker === INSERT && exists) return CONFLICTS[3];+ if (marker !== INSERT && !exists) return CONFLICTS[2];+ at = marker === UPDATE ? record(bytes, row.next, columns).next : row.next;+ }+ return null;+}+/*** Take queued moves back on `board`, newest first, in one transaction, and put the row counters back as they were* before the oldest. Returns null, or, changing nothing, why it could not: a row they made is gone or a row they@@ -111,6 +182,7 @@ export function invertChangeset(changeset) {export function undoQueued(board, entries) {const db = board.db;let conflict = null;+ const callbacks = callbackConflicts(db);try {atomic(board, () => {// A move's rows come back table by table; references between them are checked once all are back.@@ -123,8 +195,21 @@ export function undoQueued(board, entries) {for (const change of [...(entry.changes ?? [])].reverse()) {// A row changed again since, as a seat's read position is, is put back all the same (its newer read// position is kept by the caller); a row gone or taken is not this undo's to guess at.- const applied = db.applyChangeset(invertChangeset(Buffer.from(change, 'base64')), {- onConflict: (type) => { if (type === CHANGED) return REPLACE; conflict = CONFLICTS[type] ?? `conflict ${type}`; return ABORT; } });+ const inverse = invertChangeset(Buffer.from(change, 'base64'));+ if (!callbacks) conflict = legacyRowConflict(db, inverse);+ let applied = false;+ if (!conflict) {+ try {+ applied = db.applyChangeset(inverse, { onConflict: callbacks+ ? (type) => { if (type === CHANGED) return REPLACE; conflict = CONFLICTS[type] ?? `conflict ${type}`; return ABORT; }+ : REPLACE });+ } catch (error) {+ // Older Node throws for an unsupported REPLACE resolution instead of exposing its conflict type.+ // The parsed changeset and its row keys are valid; refuse constraints and roll back the whole undo.+ if (callbacks || error.code !== 'ERR_SQLITE_ERROR') throw error;+ conflict = 'a constraint or foreign key refused it';+ }+ }if (conflict || applied === false) { conflict ??= 'aborted'; throw new Error(`a queued move's rows changed since it was made: ${conflict}`); }}}diff --git a/test/relay-outbox-undo.test.js b/test/relay-outbox-undo.test.jsnew file mode 100644index 00000000..0dad74f8--- /dev/null+++ b/test/relay-outbox-undo.test.js@@ -0,0 +1,94 @@+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import test from 'node:test';+import * as store from '../src/board.js';+import { undoQueued } from '../src/relay-outbox-undo.js';++/** A real board preserves undo's transaction, triggers and foreign-key behavior on each actual Node runtime. */+function fixture(t, schema) {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-undo-compat-'));+ const board = store.openBoard(join(directory, 'board.sqlite'));+ t.after(() => { store.closeBoard(board); rmSync(directory, { recursive: true, force: true }); });+ board.db.exec(schema);+ return board;+}++/** Capture SQLite's actual changeset, rather than constructing its wire encoding by hand. */+function capture(db, sql) {+ const session = db.createSession();+ try {+ db.exec(sql);+ return { changes: [Buffer.from(session.changeset()).toString('base64')] };+ } finally { session.close(); }+}++/** Snapshot the values and lifecycle triggers which a refused undo must preserve. */+function image(board) {+ return {+ rows: board.db.prepare('SELECT * FROM sample ORDER BY id').all(),+ triggers: board.db.prepare("SELECT name,sql FROM sqlite_master WHERE type='trigger' AND name LIKE 'machine_%' ORDER BY name").all(),+ counters: board.db.prepare('SELECT * FROM sqlite_sequence ORDER BY name').all(),+ };+}++test('outbox undo replaces changed values without losing composite bigint and blob keys [H21,H16]', t => {+ const board = fixture(t, 'CREATE TABLE sample (id INTEGER, token BLOB, value TEXT, PRIMARY KEY(id, token))');+ const key = 9007199254740993n;+ const token = Buffer.from([0, 255, 10]);+ board.db.prepare('INSERT INTO sample VALUES(?,?,?)').run(key, token, 'before');+ const session = board.db.createSession();+ board.db.prepare('UPDATE sample SET value=? WHERE id=? AND token=?').run('queued', key, token);+ const queued = { changes: [Buffer.from(session.changeset()).toString('base64')] };+ session.close();+ board.db.prepare('UPDATE sample SET value=? WHERE id=? AND token=?').run('later cursor', key, token);+ assert.equal(undoQueued(board, [queued]), null);+ assert.equal(board.db.prepare('SELECT value FROM sample WHERE id=? AND token=?').get(key, token).value, 'before');+});++test('outbox undo refuses a missing row and rolls back earlier inverses and trigger changes [H21,H16]', t => {+ const board = fixture(t, "CREATE TABLE sample (id INTEGER PRIMARY KEY, value TEXT); INSERT INTO sample VALUES(2,'before')");+ const first = capture(board.db, "INSERT INTO sample VALUES(1,'queued')");+ const second = capture(board.db, "UPDATE sample SET value='queued too' WHERE id=2");+ board.db.exec('DELETE FROM sample WHERE id=1');+ const before = image(board);+ assert.equal(undoQueued(board, [first, second]), 'a row it changed is gone');+ assert.deepEqual(image(board), before, 'the successful newest inverse is rolled back with the refused older one');+});++test('outbox undo never replaces an occupied row when restoring a deleted row [H21,H16]', t => {+ const board = fixture(t, "CREATE TABLE sample (id INTEGER PRIMARY KEY, value TEXT); INSERT INTO sample VALUES(1,'removed')");+ const queued = capture(board.db, 'DELETE FROM sample');+ board.db.exec("INSERT INTO sample VALUES(1,'another owner')");+ const before = image(board);+ assert.equal(undoQueued(board, [queued]), 'a row it removed is back');+ assert.deepEqual(image(board), before);+});++test('outbox undo refuses a uniqueness constraint without retaining partial changes [H21,H16]', t => {+ const board = fixture(t, "CREATE TABLE sample (id INTEGER PRIMARY KEY, value TEXT UNIQUE); INSERT INTO sample VALUES(1,'before'),(2,'other')");+ const queued = capture(board.db, "UPDATE sample SET value='queued' WHERE id=1");+ board.db.exec("UPDATE sample SET value='before' WHERE id=2");+ const before = image(board);+ assert.match(undoQueued(board, [queued]), /constraint/);+ assert.deepEqual(image(board), before);+});++test('outbox undo restores a whole changeset with cross-table foreign keys [H21,H16]', t => {+ const board = fixture(t, 'CREATE TABLE parent (id INTEGER PRIMARY KEY); CREATE TABLE child (id INTEGER PRIMARY KEY, parent INTEGER REFERENCES parent(id)); INSERT INTO parent VALUES(1); INSERT INTO child VALUES(1,1)');+ const queued = capture(board.db, 'DELETE FROM child; DELETE FROM parent');+ assert.equal(undoQueued(board, [queued]), null);+ assert.deepEqual(board.db.prepare('SELECT * FROM child').all().map(row => ({ ...row })), [{ id: 1, parent: 1 }]);+ assert.deepEqual(board.db.prepare('PRAGMA foreign_key_check').all(), []);+});++test('outbox undo refuses a foreign key conflict and restores its transaction [H21,H16]', t => {+ const board = fixture(t, 'CREATE TABLE parent (id INTEGER PRIMARY KEY); CREATE TABLE sample (id INTEGER PRIMARY KEY, value INTEGER REFERENCES parent(id)); INSERT INTO parent VALUES(1),(2); INSERT INTO sample VALUES(1,1)');+ const queued = capture(board.db, 'UPDATE sample SET value=2');+ board.db.exec('DELETE FROM parent WHERE id=1');+ const before = image(board);+ assert.match(undoQueued(board, [queued]), /foreign key/);+ assert.deepEqual(image(board), before);+ assert.deepEqual(board.db.prepare('PRAGMA foreign_key_check').all(), []);+});