Skip to content

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.

fix(core): recover stamped legacy pin and signing upgrades [M3,E22,H16]

Corey Olsonc8092a153189
diff --git a/src/board-migrate.js b/src/board-migrate.js
index fb95b331..3d831f18 100644
--- a/src/board-migrate.js
+++ b/src/board-migrate.js
@@ -68,8 +68,9 @@ export function schemaDigest(schema, eventLogVersion) {
* @param {string} digest
* @returns {number}
*/
-function schemaStamp(db, digest, guards = null) {
- const shape = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name").all();
+function schemaStamp(db, digest, guards = null, prior = {}) {
+ const shape = db.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name").all()
+ .filter(entry => !prior.omitTriggers?.includes(entry.type === 'trigger' ? entry.name : null));
if (guards) {
const replacements = new Map(guards.map(entry => [entry.name, entry.sql]));
const installed = shape.filter(entry => entry.type === 'trigger' && entry.name.startsWith('machine_'));
@@ -79,7 +80,7 @@ function schemaStamp(db, digest, guards = null) {
}
const meta = shape.some((entry) => entry.type === 'table' && entry.name === 'board_meta')
? db.prepare("SELECT meta_key, meta_value FROM board_meta WHERE meta_key IN ('board_id', 'event_log_version') ORDER BY meta_key").all()
- .map((entry) => (entry.meta_key === 'board_id' ? 'board_id' : entry.meta_value))
+ .map((entry) => (entry.meta_key === 'board_id' ? 'board_id' : prior.eventLogVersion ?? entry.meta_value))
: [];
return createHash('sha256').update(JSON.stringify([digest, shape, meta])).digest().readInt32BE(0) || 1;
}
@@ -148,3 +149,9 @@ export function guardsMatchStoredStamp(db, digest, guards) {
const stored = db.prepare('PRAGMA application_id').get().application_id;
return stored !== 0 && stored === schemaStamp(db, digest, guards);
}
+
+/** Compare one bounded prior authorized shape with the existing header, without modifying schema or metadata. */
+export function priorShapeMatchesStoredStamp(db, digest, guards, prior) {
+ const stored = db.prepare('PRAGMA application_id').get().application_id;
+ return stored !== 0 && stored === schemaStamp(db, digest, guards, prior);
+}
diff --git a/src/board-signing-recovery.js b/src/board-signing-recovery.js
new file mode 100644
index 00000000..65db9401
--- /dev/null
+++ b/src/board-signing-recovery.js
@@ -0,0 +1,54 @@
+/** Recognize only prior full-shape stamps from legacy normal pin/sign operations [M3,E22,H16]. */
+import { AUTHORITY } from './person-authority-schema.js';
+import { AUTHORITY_TRIGGERS } from './person-authority-schema.js';
+import { EVENT_LOG_VERSION } from './board-schema-source.js';
+import { SIGNED_EVENT_LOG_VERSION } from './board-schema-source.js';
+import { priorShapeMatchesStoredStamp } from './board-migrate.js';
+
+/** A local pin is only a syntactic migration prerequisite; it never establishes relay trust. */
+function validPin(value) {
+ try {
+ const pin = JSON.parse(value);
+ return typeof pin?.origin === 'string' && pin.origin.length > 0
+ && typeof pin.publicKey === 'string' && /^[A-Za-z0-9_-]{40,200}$/u.test(pin.publicKey);
+ } catch { return false; }
+}
+
+/** Only normal ordered signing history permits projecting the permanent signed format back to its prior value. */
+function signingHistory(db) {
+ const rows = db.prepare("SELECT event_detail FROM event WHERE event_kind='person_signing' ORDER BY event_id").all();
+ if (!rows.length) return false;
+ try {
+ const details = rows.map(row => JSON.parse(row.event_detail));
+ return details[0]?.signed === true && details.every(detail => typeof detail?.signed === 'boolean');
+ } catch { return false; }
+}
+
+/**
+ * Old pin/sign APIs added three guards or raised format without updating the stamp. Reconstruct only
+ * those exact additive histories, retaining every other schema object and requiring the complete old hash.
+ */
+export function legacySigningMatchesStamp(db, digest, guards) {
+ const installed = db.prepare("SELECT name,sql FROM sqlite_master WHERE type='trigger' AND name LIKE 'machine_%'").all();
+ if (installed.length !== guards.length || installed.some(row => !guards.some(guard => guard.name === row.name))) return false;
+ const authority = db.prepare("SELECT name,sql FROM sqlite_master WHERE name LIKE 'person_authority_%'").all();
+ const pin = db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(AUTHORITY);
+ const pinned = Boolean(pin);
+ if (pinned) {
+ if (!validPin(pin.meta_value) || authority.length !== AUTHORITY_TRIGGERS.length
+ || AUTHORITY_TRIGGERS.some(guard => !authority.some(row => row.name === guard.name
+ && row.sql === guard.sql.replace('CREATE TRIGGER IF NOT EXISTS ', 'CREATE TRIGGER ')))) return false;
+ } else if (authority.length) return false;
+ const version = db.prepare("SELECT meta_value FROM board_meta WHERE meta_key='event_log_version'").get()?.meta_value;
+ const history = signingHistory(db);
+ if (version !== String(history ? SIGNED_EVENT_LOG_VERSION : EVENT_LOG_VERSION)) return false;
+ const omissions = pinned ? [[], AUTHORITY_TRIGGERS.map(guard => guard.name)] : [[]];
+ const versions = history ? [version, String(EVENT_LOG_VERSION)] : [version];
+ for (const omitTriggers of omissions) for (const eventLogVersion of versions) {
+ if (!omitTriggers.length && eventLogVersion === version) continue;
+ for (const machine of [null, guards]) {
+ if (priorShapeMatchesStoredStamp(db, digest, machine, { omitTriggers, eventLogVersion })) return true;
+ }
+ }
+ return false;
+}
diff --git a/src/board-store-guards.js b/src/board-store-guards.js
index f9f6d0cc..f471cd9c 100644
--- a/src/board-store-guards.js
+++ b/src/board-store-guards.js
@@ -2,6 +2,7 @@
import { atomic } from './board-event-log.js';
import { logEvent } from './board-event-log.js';
import { boardStanding } from './board-migrate.js';
+import { legacySigningMatchesStamp } from './board-signing-recovery.js';
import { guardsMatchStoredStamp } from './board-migrate.js';
import { Refused } from './refused.js';
import { recordSchemaStamp } from './board-migrate.js';
@@ -52,13 +53,16 @@ export function guardStore(board) {
*/
export function refreshStoreDeclarations(board) {
const wanted = storeTriggers();
- if (isWhole(differences(board.db, wanted))) return false;
+ const whole = isWhole(differences(board.db, wanted));
+ if (whole && boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION) === 'current') return false;
return atomic(board, () => {
const standing = boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION);
const recovery = standing === 'drifted' && guardsMatchStoredStamp(board.db, SCHEMA_DIGEST, wanted);
- if (standing !== 'current' && !recovery) return false;
+ const legacy = standing === 'drifted' && legacySigningMatchesStamp(board.db, SCHEMA_DIGEST, wanted);
+ if (standing !== 'current' && !recovery && !legacy) return false;
guardStore(board);
- if (!recovery) recordSchemaStamp(board.db, SCHEMA_DIGEST);
+ if (!recovery || legacy) recordSchemaStamp(board.db, SCHEMA_DIGEST);
+ if (legacy) logEvent(board, 'board', 'schema-signing-recovery', null, { prior: 'legacy-pin-or-signing', guards: 'exact', stamp: 'matched' });
if (boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION) !== 'current') {
throw new Refused('SCHEMA_DRIFT', 'the restored guards do not match the stored board stamp; keep the board and ask the coordinator to inspect its schema');
}
diff --git a/src/person-authority-schema.js b/src/person-authority-schema.js
new file mode 100644
index 00000000..81891d64
--- /dev/null
+++ b/src/person-authority-schema.js
@@ -0,0 +1,10 @@
+/** Exact local authority declarations shared by normal pinning and bounded legacy recovery [E22,H16]. */
+export const AUTHORITY = 'person_authority_local';
+
+/** Triggers that keep the pinned relay key from being changed, removed or replaced through SQLite. */
+export const AUTHORITY_TRIGGERS = [
+ ['person_authority_update', `BEFORE UPDATE ON board_meta WHEN OLD.meta_key = '${AUTHORITY}'`],
+ ['person_authority_delete', `BEFORE DELETE ON board_meta WHEN OLD.meta_key = '${AUTHORITY}'`],
+ ['person_authority_replace', `BEFORE INSERT ON board_meta WHEN NEW.meta_key = '${AUTHORITY}' AND EXISTS (SELECT 1 FROM board_meta WHERE meta_key = '${AUTHORITY}')`],
+].map(([name, on]) => ({ name, sql: `CREATE TRIGGER IF NOT EXISTS ${name} ${on}\nBEGIN SELECT RAISE(ABORT, 'PERSON_AUTHORITY: the pinned relay key is kept for good'); END` }));
+
diff --git a/src/person-signing.js b/src/person-signing.js
index 9993eca2..26ba50a1 100644
--- a/src/person-signing.js
+++ b/src/person-signing.js
@@ -32,18 +32,13 @@ import { recordSchemaStamp } from './board-migrate.js';
import { SCHEMA_DIGEST } from './board-schema-source.js';
import { SCHEMA_VERSION } from './board-schema-source.js';
+import { AUTHORITY } from './person-authority-schema.js';
+import { AUTHORITY_TRIGGERS } from './person-authority-schema.js';
+
const PROPOSALS = 'person_proposals';
-const AUTHORITY = 'person_authority_local';
const PROPOSAL_MS = 10 * 60_000;
const KEPT_PROPOSALS = 50;
-/** Triggers that keep the pinned relay key from being changed, removed or replaced through SQLite. */
-const AUTHORITY_TRIGGERS = [
- ['person_authority_update', `BEFORE UPDATE ON board_meta WHEN OLD.meta_key = '${AUTHORITY}'`],
- ['person_authority_delete', `BEFORE DELETE ON board_meta WHEN OLD.meta_key = '${AUTHORITY}'`],
- ['person_authority_replace', `BEFORE INSERT ON board_meta WHEN NEW.meta_key = '${AUTHORITY}' AND EXISTS (SELECT 1 FROM board_meta WHERE meta_key = '${AUTHORITY}')`],
-].map(([name, on]) => ({ name, sql: `CREATE TRIGGER IF NOT EXISTS ${name} ${on}\nBEGIN SELECT RAISE(ABORT, 'PERSON_AUTHORITY: the pinned relay key is kept for good'); END` }));
-
/** Write one board metadata value inside the caller's transaction. */
function meta(board, key, value) {
board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value').run(key, value);
diff --git a/test/board-schema.test.js b/test/board-schema.test.js
index aebb3345..6afba00d 100644
--- a/test/board-schema.test.js
+++ b/test/board-schema.test.js
@@ -310,3 +310,93 @@ test('normal authority pinning and signed-format restore keep a verified stamp w
assert.equal(boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION), 'drifted');
} finally { store.closeBoard(board); store.closeBoard(source); }
});
+
+
+/** Reproduce an old normal API's unchanged header using its actual pre-operation stamp. */
+function legacySigningBoard(t, mode) {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-legacy-signing-'));
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const file = join(directory, 'board.sqlite');
+ const board = store.openBoard(file);
+ try {
+ store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Keep signed legacy data' });
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES(?,?)').run('relay_applied_sequence', '0');
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES(?,?)').run('relay_engine_version', String(ENGINE_VERSION));
+ let stamp = guardImage(board).stamp;
+ const pin = () => pinAuthority(board, 'https://relay.fixture', { version: 1, algorithm: 'Ed25519', publicKey: 'a'.repeat(43) });
+ if (mode === 'sign-then-pin') {
+ setPersonSigning(board, { agentId: 'coordinator', signed: true });
+ stamp = guardImage(board).stamp;
+ pin();
+ } else {
+ if (mode !== 'signed-only') pin();
+ if (mode === 'pin-then-sign') stamp = guardImage(board).stamp;
+ if (mode !== 'pin-only') setPersonSigning(board, { agentId: 'coordinator', signed: true });
+ }
+ // Prior implementations performed these same normal operations but left this pre-operation header.
+ board.db.exec(`PRAGMA application_id = ${stamp}`);
+ } finally { store.closeBoard(board); }
+ return file;
+}
+
+test('main recognizes exact legacy pin-only, signed-only and intermediate signed-format stamps [M3,E22,H16]', t => {
+ for (const mode of ['pin-only', 'signed-only', 'both', 'pin-then-sign', 'sign-then-pin']) {
+ const file = legacySigningBoard(t, mode);
+ const before = observe(file);
+ assert.equal(before.standing, 'drifted', mode);
+ store.openBoardReadOnly(file).close();
+ store.closeBoard(store.openBoard(file, undefined, { isMain: false, onDiagnostic: () => {} }));
+ assert.deepEqual(observe(file), before, `${mode}: readers and non-main do not heal`);
+ const board = store.openBoard(file);
+ try {
+ assert.equal(boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION), 'current', mode);
+ assert.deepEqual(observe(file).items, before.items, `${mode}: business rows survive`);
+ assert.equal(observe(file).identity, before.identity);
+ assert.equal(board.db.prepare("SELECT count(*) AS n FROM event WHERE event_kind='schema-signing-recovery'").get().n, 1);
+ const checkpoint = exportBoard(board);
+ restoreRelaySnapshot(board, checkpoint, 0);
+ assert.equal(undoQueued(board, []), null, `${mode}: restored and queued paths remain usable`);
+ assert.equal(boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION), 'current');
+ assert.equal(localAuthority(board)?.origin ?? null, mode === 'signed-only' ? null : 'https://relay.fixture');
+ } finally { store.closeBoard(board); }
+ const bytes = readFileSync(file);
+ store.closeBoard(store.openBoard(file));
+ assert.deepEqual(readFileSync(file), bytes, `${mode}: recovery is idempotent`);
+ }
+});
+
+test('legacy signing recognition also recovers the exact attested machine declaration [M3,E22,H16]', t => {
+ const file = legacySigningBoard(t, 'both');
+ olderDeclaration(file, false);
+ const before = observe(file);
+ const board = store.openBoard(file);
+ try {
+ assert.equal(boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION), 'current');
+ assert.deepEqual(observe(file).items, before.items);
+ assert.equal(guardImage(board).triggers.find(row => row.name === 'machine_item_move').sql,
+ storeTriggers().find(row => row.name === 'machine_item_move').sql);
+ } finally { store.closeBoard(board); }
+});
+
+test('legacy pin or signing recovery never approves missing guards, extra schema or unknown headers [M3,E22,H16]', t => {
+ const damage = [
+ "DROP TRIGGER person_authority_delete",
+ "DROP TRIGGER person_authority_delete; CREATE TRIGGER person_authority_delete BEFORE DELETE ON board_meta BEGIN SELECT 1; END",
+ "CREATE INDEX unexpected_legacy_index ON item(item_title)",
+ "DROP TRIGGER machine_fields_claimed",
+ "PRAGMA application_id = 123",
+ ];
+ for (const sql of damage) {
+ const file = legacySigningBoard(t, 'both');
+ const db = new DatabaseSync(file);
+ try { db.exec(sql); } finally { db.close(); }
+ const before = observe(file);
+ const board = store.openBoard(file, undefined, { onDiagnostic: () => {} });
+ try {
+ assert.equal(boardStanding(board.db, SCHEMA_DIGEST, SCHEMA_VERSION), 'drifted', sql);
+ assert.deepEqual(observe(file), before, sql);
+ assert.throws(() => undoQueued(board, []), error => error.code === 'SCHEMA_DRIFT');
+ assert.deepEqual(observe(file), before, 'refusal preserves damaged evidence');
+ } finally { store.closeBoard(board); }
+ }
+});
diff --git a/test/move-registry-baseline.json b/test/move-registry-baseline.json
index 1a61783d..face74a3 100644
--- a/test/move-registry-baseline.json
+++ b/test/move-registry-baseline.json
@@ -7144,7 +7144,8 @@
"RELAY_CANARY_CONFIG": "enable this machine's dedicated canary from its ordinary joined seat: pullboard relay canary on",
"RELAY_CANARY_DEADLINE": "read the failed step with pullboard relay canary status; the next minute's probe retries on its own",
"RELAY_CANARY_SEAT": "run the canary from the seat that enabled it, or run pullboard relay canary on in a dedicated joined seat",
- "RELAY_CANARY_STOPPED": "start the watch again with pullboard relay canary watch; pending notices are sent on its next run"
+ "RELAY_CANARY_STOPPED": "start the watch again with pullboard relay canary watch; pending notices are sent on its next run",
+ "SCHEMA_DRIFT": "run pullboard inbox from the main checkout; if drift remains, preserve the board and ask the coordinator to inspect its schema"
},
"replay": {
"initial": {