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.

feat(relay): order opaque uploads without interpreting records [A4,H7]

Corey Olsonc1852e6b04fa
diff --git a/relay/journal.js b/relay/journal.js
new file mode 100644
index 00000000..fe425628
--- /dev/null
+++ b/relay/journal.js
@@ -0,0 +1,102 @@
+/** Durable opaque upload ordering; record interpretation belongs to a later relay adapter [A4,H7]. */
+import { DatabaseSync } from 'node:sqlite';
+import { closeSync, lstatSync, mkdirSync, openSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { Refused } from '../src/refused.js';
+
+const FORMAT = 1;
+const DEFAULT_BYTES = 100_000;
+
+/** Validate a persistent identity before it can name an internal file. */
+function identity(value) {
+ if (typeof value !== 'string' || !/^[0-9a-f]{32}$/.test(value)) throw new Refused('BAD_BOARD', 'use the persistent board id, never a path');
+ return value;
+}
+
+/**
+ * Own a private per-board journal of uninterpreted bytes. It does not compute board state or
+ * promise that a payload is encrypted. Its caller must authenticate and authorize every use.
+ * This separate transport foundation does not replace the frozen #104 engine replay criterion.
+ */
+export function createRelayJournal({ directory, boardId, maxBytes = DEFAULT_BYTES, now = () => new Date() }) {
+ const id = identity(boardId);
+ if (typeof directory !== 'string' || !directory.trim() || typeof now !== 'function') throw new Refused('RELAY_CONFIG', 'configure a private journal directory and clock');
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 10_000_000) throw new Refused('RELAY_CONFIG', 'bound each opaque upload between one and ten million bytes');
+ const root = resolve(directory);
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ const parent = lstatSync(root);
+ if (!parent.isDirectory() || parent.isSymbolicLink() || (parent.mode & 0o077) !== 0) throw new Refused('RELAY_STORAGE', 'use a private directory with mode 700 for relay journals');
+ const file = join(root, id + '.journal.sqlite');
+ try { closeSync(openSync(file, 'wx', 0o600)); } catch (error) { if (error.code !== 'EEXIST') throw error; }
+ const stat = lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0) throw new Refused('RELAY_STORAGE', 'the journal must be a private regular database file');
+ const db = new DatabaseSync(file);
+ let closed = false;
+ try {
+ db.exec('PRAGMA busy_timeout = 30000; PRAGMA journal_mode = WAL; BEGIN IMMEDIATE');
+ db.exec('CREATE TABLE IF NOT EXISTS journal_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS journal_record (sequence INTEGER PRIMARY KEY, received_at TEXT NOT NULL, payload BLOB NOT NULL)');
+ const saved = db.prepare('SELECT key, value FROM journal_meta ORDER BY key').all();
+ if (saved.length === 0) {
+ if (db.prepare('SELECT 1 FROM journal_record LIMIT 1').get()) throw new Refused('RELAY_STORAGE', 'restore the journal with its original identity and format metadata');
+ db.prepare('INSERT INTO journal_meta (key,value) VALUES (?,?), (?,?)').run('board', id, 'format', String(FORMAT));
+ } else if (saved.length !== 2 || saved[0].key !== 'board' || saved[0].value !== id || saved[1].key !== 'format' || saved[1].value !== String(FORMAT)) {
+ throw new Refused('RELAY_STORAGE', 'open this journal with its original board identity and supported transport format');
+ }
+ db.exec('COMMIT');
+ } catch (error) {
+ try { db.exec('ROLLBACK'); } catch { /* Initialization may have failed before its transaction. */ }
+ db.close();
+ throw error;
+ }
+
+ /** Keep calls after shutdown from exposing a native SQLite error. */
+ function open() { if (closed) throw new Refused('RELAY_CLOSED', 'open the journal before reading or appending records'); }
+
+ /** Convert an SQLite row to detached opaque bytes so callers cannot mutate a stored record. */
+ function record(row) { return { sequence: row.sequence, receivedAt: row.received_at, bytes: Buffer.from(row.payload) }; }
+
+ /** Read the latest committed sequence, including an empty journal's initial cursor. */
+ function latest() {
+ open();
+ return db.prepare('SELECT COALESCE(MAX(sequence), 0) AS sequence FROM journal_record').get().sequence;
+ }
+
+ /** Serialize the prefix check and append so concurrent senders cannot both claim one sequence. */
+ function append(sequence, bytes) {
+ open();
+ if (!Number.isSafeInteger(sequence) || sequence < 1) throw new Refused('BAD_SEQUENCE', 'upload a positive safe integer sequence');
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0 || bytes.byteLength > maxBytes) throw new Refused('BAD_UPLOAD', 'send nonempty opaque bytes within the configured upload limit');
+ const payload = Buffer.from(bytes);
+ db.exec('BEGIN IMMEDIATE');
+ try {
+ const next = latest() + 1;
+ if (sequence < next) throw new Refused('SEQUENCE_REPEAT', 'this sequence is already stored; resume after the latest committed sequence');
+ if (sequence > next) throw new Refused('SEQUENCE_GAP', 'send the next sequence after the latest committed record before later uploads');
+ const at = now();
+ if (!(at instanceof Date) || !Number.isFinite(at.getTime())) throw new Refused('RELAY_CONFIG', 'the journal clock must return a valid Date');
+ db.prepare('INSERT INTO journal_record (sequence,received_at,payload) VALUES (?,?,?)').run(sequence, at.toISOString(), payload);
+ const result = record(db.prepare('SELECT * FROM journal_record WHERE sequence=?').get(sequence));
+ db.exec('COMMIT');
+ return result;
+ } catch (error) {
+ db.exec('ROLLBACK');
+ throw error;
+ }
+ }
+
+ /** Replay the committed prefix in order, without parsing or executing its payloads. */
+ function after(sequence = 0) {
+ open();
+ if (!Number.isSafeInteger(sequence) || sequence < 0) throw new Refused('BAD_CURSOR', 'resume after a nonnegative safe integer sequence');
+ return db.prepare('SELECT * FROM journal_record WHERE sequence > ? ORDER BY sequence').all(sequence).map(record);
+ }
+
+ /** Close SQLite once, checkpointing the private journal before its owner removes any files. */
+ function close() {
+ if (closed) return;
+ db.close();
+ closed = true;
+ }
+
+ return { board: id, latest, append, after, close };
+}
diff --git a/test/relay-journal.test.js b/test/relay-journal.test.js
new file mode 100644
index 00000000..1af8836d
--- /dev/null
+++ b/test/relay-journal.test.js
@@ -0,0 +1,122 @@
+/** Opaque relay transport ordering, independent of the pending record interpretation [A4,H7]. */
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { createRelayJournal } from '../relay/journal.js';
+
+const ID = 'a'.repeat(32);
+
+/** Give each test a private directory and close every journal before deleting its files. */
+function fixture(t, options = {}) {
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-relay-order-')));
+ const opened = [];
+ t.after(() => { for (const journal of opened) journal.close(); rmSync(directory, { recursive: true, force: true }); });
+ /** Open the same durable journal through its public interface. */
+ function open(overrides = {}) {
+ const journal = createRelayJournal({ directory, boardId: ID, ...options, ...overrides });
+ opened.push(journal);
+ return journal;
+ }
+ return { directory, open, journal: open() };
+}
+
+test('[A4,H7] ordered opaque bytes survive restart without parsing or aliasing', (t) => {
+ const box = fixture(t, { now: () => new Date('2026-10-07T00:00:00Z') });
+ assert.equal(box.journal.latest(), 0);
+ const bytes = Buffer.from([0, 255, 1, 128, 0]);
+ const first = box.journal.append(1, bytes);
+ assert.equal(first.sequence, 1);
+ assert.equal(first.receivedAt, '2026-10-07T00:00:00.000Z');
+ assert.deepEqual(first.bytes, bytes);
+ bytes.fill(0);
+ first.bytes.fill(0);
+ assert.deepEqual(box.journal.after()[0].bytes, Buffer.from([0, 255, 1, 128, 0]));
+ box.journal.append(2, Buffer.from('an uninterpreted record'));
+ assert.deepEqual(box.journal.after(1).map((row) => row.sequence), [2]);
+ box.journal.close();
+ const reopened = box.open();
+ assert.equal(reopened.latest(), 2);
+ assert.deepEqual(reopened.after().map((row) => row.sequence), [1, 2]);
+ assert.equal(statSync(join(box.directory, ID + '.journal.sqlite')).mode & 0o077, 0);
+});
+
+test('[A4] gaps, repeats, invalid uploads and clock failures leave the prefix unchanged', (t) => {
+ const box = fixture(t, { maxBytes: 4 });
+ assert.throws(() => box.journal.append(2, Buffer.from('x')), { code: 'SEQUENCE_GAP' });
+ assert.equal(box.journal.latest(), 0);
+ box.journal.append(1, Buffer.from('one'));
+ for (const sequence of [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, '2']) {
+ assert.throws(() => box.journal.append(sequence, Buffer.from('x')), { code: 'BAD_SEQUENCE' });
+ }
+ assert.throws(() => box.journal.append(1, Buffer.from('new')), { code: 'SEQUENCE_REPEAT' });
+ assert.throws(() => box.journal.append(3, Buffer.from('new')), { code: 'SEQUENCE_GAP' });
+ for (const bytes of ['', Buffer.alloc(0), Buffer.from('large')]) {
+ assert.throws(() => box.journal.append(2, bytes), { code: 'BAD_UPLOAD' });
+ }
+ assert.throws(() => box.journal.after(-1), { code: 'BAD_CURSOR' });
+ assert.throws(() => box.journal.after('0'), { code: 'BAD_CURSOR' });
+ assert.equal(box.journal.latest(), 1);
+ box.journal.close();
+ const badClock = box.open({ now: () => new Date(NaN) });
+ assert.throws(() => badClock.append(2, Buffer.from('two')), { code: 'RELAY_CONFIG' });
+ assert.equal(badClock.latest(), 1);
+ assert.equal(badClock.after()[0].bytes.toString(), 'one');
+});
+
+test('[A4,H7] two real processes cannot publish the same next sequence', async (t) => {
+ const box = fixture(t);
+ box.journal.close();
+ const worker = join(box.directory, 'worker.mjs');
+ const module = new URL('../relay/journal.js', import.meta.url).href;
+ writeFileSync(worker, [
+ 'import { createRelayJournal } from ' + JSON.stringify(module) + ';',
+ 'const journal = createRelayJournal({ directory: process.argv[2], boardId: process.argv[3] });',
+ 'try {',
+ ' const row = journal.append(1, Buffer.from(process.argv[4]));',
+ ' process.stdout.write(JSON.stringify({ sequence: row.sequence }));',
+ '} catch (error) { process.stdout.write(JSON.stringify({ code: error.code })); }',
+ 'finally { journal.close(); }',
+ ].join('\n'));
+ /** Capture only the synthetic sequence/refusal result of one owned worker. */
+ function run(label) {
+ return new Promise((done, fail) => {
+ const child = spawn(process.execPath, [worker, box.directory, ID, label], { stdio: ['ignore', 'pipe', 'pipe'] });
+ let out = '';
+ let diagnostics = '';
+ child.stdout.on('data', (chunk) => { out += chunk; });
+ child.stderr.on('data', (chunk) => { diagnostics += chunk; });
+ const timer = setTimeout(() => { child.kill('SIGKILL'); fail(new Error('journal worker timed out')); }, 10_000);
+ child.once('error', (error) => { clearTimeout(timer); fail(error); });
+ child.once('exit', (code) => {
+ clearTimeout(timer);
+ if (code !== 0) return fail(new Error('journal worker failed: ' + diagnostics));
+ try { done(JSON.parse(out)); } catch (error) { fail(error); }
+ });
+ });
+ }
+ const results = await Promise.all([run('first record'), run('second record')]);
+ assert.equal(results.filter((row) => row.sequence === 1).length, 1);
+ assert.equal(results.filter((row) => row.code === 'SEQUENCE_REPEAT').length, 1);
+ const journal = box.open();
+ assert.equal(journal.latest(), 1);
+ assert.equal(journal.after().length, 1);
+ assert.ok(['first record', 'second record'].includes(journal.after()[0].bytes.toString()));
+});
+
+test('[H7] board identities isolate journals and cannot follow a symlink', (t) => {
+ const box = fixture(t);
+ box.journal.append(1, Buffer.from('first board'));
+ const other = box.open({ boardId: 'b'.repeat(32) });
+ assert.equal(other.latest(), 0);
+ other.append(1, Buffer.from('second board'));
+ assert.equal(box.journal.after()[0].bytes.toString(), 'first board');
+ assert.equal(other.after()[0].bytes.toString(), 'second board');
+ assert.throws(() => box.open({ boardId: '../outside' }), { code: 'BAD_BOARD' });
+ symlinkSync(join(box.directory, ID + '.journal.sqlite'), join(box.directory, 'c'.repeat(32) + '.journal.sqlite'));
+ assert.throws(() => box.open({ boardId: 'c'.repeat(32) }), { code: 'RELAY_STORAGE' });
+ box.journal.close();
+ assert.throws(() => box.journal.latest(), { code: 'RELAY_CLOSED' });
+});