Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-10127]): persist receiver execution consumption and recovery facts

[._.]/ Adam Eivycfb87caa012e
diff --git a/scripts/lib/dbTestFiles.js b/scripts/lib/dbTestFiles.js
index 8480b35106..2074c9ce16 100644
--- a/scripts/lib/dbTestFiles.js
+++ b/scripts/lib/dbTestFiles.js
@@ -9,6 +9,7 @@ import { posix } from 'node:path';
* listed explicitly below (the drift guard fails the build if you forget).
*/
export const DB_TEST_INCLUDE = [
+ 'services/peerExecutionLedger.db.test.js',
'services/voice/profiles.db.test.js',
'services/voice/studio.db.test.js',
'../scripts/perf/collectionFixture.db.test.js',
diff --git a/server/lib/db/schema/index.js b/server/lib/db/schema/index.js
index 54f9212ef4..154f63596a 100644
--- a/server/lib/db/schema/index.js
+++ b/server/lib/db/schema/index.js
@@ -22,6 +22,7 @@ import { userActionsDdl } from './userActions.js';
import { reviewQueueTriageDdl } from './reviewQueueTriage.js';
import { cosAgentFeedbackDdl } from './cosAgentFeedback.js';
import { aiGraphDdl } from './aiGraph.js';
+import { peerExecutionDdl } from './peerExecution.js';
import { catalogDdl, catalogUserTypesDdl, catalogPendingAppliesDdl } from './catalog.js';
import { mediaDdl } from './media.js';
import { universesDdl } from './universes.js';
@@ -48,6 +49,7 @@ export {
reviewQueueTriageDdl,
cosAgentFeedbackDdl,
aiGraphDdl,
+ peerExecutionDdl,
catalogDdl,
catalogUserTypesDdl,
catalogPendingAppliesDdl,
@@ -85,6 +87,7 @@ export function buildUpgradeDdl() {
...reviewQueueTriageDdl,
...cosAgentFeedbackDdl,
...aiGraphDdl,
+ ...peerExecutionDdl,
];
}
diff --git a/server/lib/db/schema/peerExecution.js b/server/lib/db/schema/peerExecution.js
new file mode 100644
index 0000000000..4702c77d90
--- /dev/null
+++ b/server/lib/db/schema/peerExecution.js
@@ -0,0 +1,29 @@
+// Receiver-local execution consumption survives peer/grant removal. Never federated.
+export const peerExecutionDdl = [
+ `CREATE TABLE IF NOT EXISTS peer_execution_operations (
+ operation_id UUID PRIMARY KEY,
+ host_instance_id UUID NOT NULL,
+ peer_instance_id UUID NOT NULL,
+ request_id UUID NOT NULL,
+ fingerprint TEXT NOT NULL CHECK (fingerprint ~ '^[a-f0-9]{64}$'),
+ binding JSONB NOT NULL,
+ execution_epoch UUID NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('queued', 'draining', 'in-flight', 'awaiting-reconnect', 'succeeded', 'failed', 'uncertain')),
+ revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0),
+ claim JSONB,
+ receipt JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (host_instance_id, peer_instance_id, request_id),
+ CHECK (host_instance_id <> peer_instance_id)
+ )`,
+ `CREATE INDEX IF NOT EXISTS idx_peer_execution_operations_state ON peer_execution_operations (state, operation_id)`,
+ `CREATE TABLE IF NOT EXISTS peer_execution_generation_floors (
+ host_instance_id UUID NOT NULL,
+ peer_instance_id UUID NOT NULL,
+ action TEXT NOT NULL CHECK (action IN ('portos.update', 'portos.restart', 'catalog.install')),
+ generation BIGINT NOT NULL CHECK (generation >= 0),
+ PRIMARY KEY (host_instance_id, peer_instance_id, action),
+ CHECK (host_instance_id <> peer_instance_id)
+ )`,
+];
diff --git a/server/lib/peerExecutionAuthority.js b/server/lib/peerExecutionAuthority.js
new file mode 100644
index 0000000000..a9352e50f6
--- /dev/null
+++ b/server/lib/peerExecutionAuthority.js
@@ -0,0 +1,100 @@
+/** Non-rewound machine authority. No grants, adapter, or HTTP route is installed. */
+import * as fs from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { join } from 'node:path';
+import { z } from 'zod';
+import { assertNotRealDataWrite } from './testDataIsolation.js';
+
+const uuid = z.string().uuid();
+const recordSchema = z.object({
+ version: z.literal(1), epoch: uuid, revision: z.number().int().positive().safe(),
+ phase: z.enum(['ready', 'capturing', 'reconciling']),
+ settledRecoveryId: uuid.nullable(),
+ recovery: z.object({ id: uuid, digest: z.string().regex(/^[a-f0-9]{64}$/).nullable(),
+ count: z.number().int().nonnegative().safe().nullable() }).strict().nullable(),
+}).strict().refine(value => (value.phase === 'ready') === (value.recovery === null))
+ .refine(value => value.phase !== 'reconciling' || (value.recovery.digest && value.recovery.count !== null));
+export const executionAuthorityError = message => Object.assign(new Error(message), {
+ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE', status: 503,
+});
+
+export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = assertNotRealDataWrite, makeId = randomUUID } = {}) {
+ const path = join(dataDir, 'peer-execution-authority.json');
+ const recoveryPath = join(dataDir, 'peer-execution-recovery.jsonl');
+ const lock = join(dataDir, '.peer-execution-authority-lock');
+ let damaged = false;
+ const exists = file => {
+ try { io.lstatSync(file); return true; } catch (err) { if (err.code === 'ENOENT') return false; throw err; }
+ };
+ const syncDirectory = () => {
+ if (process.platform === 'win32') return;
+ const fd = io.openSync(dataDir, 'r');
+ try { io.fsyncSync(fd); } finally { io.closeSync(fd); }
+ };
+ const read = ({ inside = false } = {}) => {
+ if (damaged || (!inside && exists(lock))) throw executionAuthorityError('Execution authority needs reconciliation.');
+ if (!exists(path)) return null;
+ try {
+ if (!io.lstatSync(path).isFile()) throw new Error('not a regular file');
+ return recordSchema.parse(JSON.parse(io.readFileSync(path, 'utf8')));
+ } catch { throw executionAuthorityError('Execution authority is unreadable; it cannot be reset.'); }
+ };
+ const transaction = change => {
+ assertWrite(path, 'peer execution authority');
+ if (damaged) throw executionAuthorityError('Execution authority publication was interrupted.');
+ io.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
+ try { io.mkdirSync(lock, { mode: 0o700 }); }
+ catch { throw executionAuthorityError('Execution authority is being changed or needs recovery.'); }
+ let publishing = false;
+ try {
+ const next = change(read({ inside: true }));
+ recordSchema.parse(next);
+ publishing = true;
+ const pending = join(dataDir, `.peer-execution-authority-${makeId()}.pending`);
+ const fd = io.openSync(pending, 'wx', 0o600);
+ try { io.writeFileSync(fd, JSON.stringify(next) + '\n'); io.fsyncSync(fd); } finally { io.closeSync(fd); }
+ io.renameSync(pending, path);
+ syncDirectory();
+ publishing = false;
+ return structuredClone(next);
+ } catch (err) {
+ if (publishing) damaged = true;
+ throw err;
+ } finally {
+ // Never steal an interrupted publication by age or PID.
+ if (!damaged) {
+ try { io.rmdirSync(lock); syncDirectory(); } catch { damaged = true; }
+ }
+ }
+ };
+ const requireReady = epoch => {
+ const current = read();
+ if (!current || current.phase !== 'ready' || current.epoch !== epoch)
+ throw executionAuthorityError('Execution evidence is stale or a restore is awaiting reconciliation.');
+ return current;
+ };
+ const initialize = () => transaction(current => current ?? {
+ version: 1, epoch: makeId(), revision: 1, phase: 'ready', recovery: null, settledRecoveryId: null,
+ });
+ const beginRestore = id => {
+ uuid.parse(id);
+ return transaction(current => {
+ if (!current) throw executionAuthorityError('Initialize the empty ledger before restoring execution records.');
+ if (current.recovery?.id === id) return current;
+ if (current.phase !== 'ready') throw executionAuthorityError('Another execution recovery is pending.');
+ return { ...current, epoch: makeId(), revision: current.revision + 1, phase: 'capturing',
+ recovery: { id, digest: null, count: null } };
+ });
+ };
+ const recordSnapshot = (id, digest, count) => transaction(current => {
+ if (current?.recovery?.id !== id || current.phase !== 'capturing')
+ throw executionAuthorityError('The execution recovery owner changed.');
+ return { ...current, revision: current.revision + 1, phase: 'reconciling', recovery: { id, digest, count } };
+ });
+ const completeRestore = id => transaction(current => {
+ if (current?.recovery?.id !== id || current.phase !== 'reconciling')
+ throw executionAuthorityError('The execution recovery owner changed.');
+ return { ...current, revision: current.revision + 1, phase: 'ready', recovery: null, settledRecoveryId: id };
+ });
+ return { read, requireReady, initialize, beginRestore, recordSnapshot, completeRestore, recoveryPath, assertWrite };
+}
diff --git a/server/lib/peerExecutionAuthority.test.js b/server/lib/peerExecutionAuthority.test.js
new file mode 100644
index 0000000000..d4ebad5877
--- /dev/null
+++ b/server/lib/peerExecutionAuthority.test.js
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createPeerExecutionAuthority } from './peerExecutionAuthority.js';
+import { peerExecutionBindingSchema } from '../services/peerExecutionLedger.js';
+
+let directory;
+beforeEach(() => { directory = fs.mkdtempSync(join(tmpdir(), 'peer-execution-authority-test-')); });
+afterEach(() => fs.rmSync(directory, { recursive: true, force: true }));
+const make = options => createPeerExecutionAuthority(directory, options);
+
+describe('non-rewound execution authority', () => {
+ it('has no authority until the empty ledger initializes it', () => {
+ expect(make().read()).toBeNull();
+ expect(() => make().requireReady(randomUUID())).toThrow(/stale/);
+ const initialized = make().initialize();
+ expect(make().requireReady(initialized.epoch)).toEqual(initialized);
+ });
+ it('invalidates old evidence before capture, remains fenced after restart, and settles only its exact recovery', () => {
+ const authority = make();
+ const first = authority.initialize();
+ const id = randomUUID();
+ const pending = authority.beginRestore(id);
+ expect(pending.epoch).not.toBe(first.epoch);
+ expect(() => make().requireReady(first.epoch)).toThrow();
+ expect(() => make().requireReady(pending.epoch)).toThrow();
+ expect(() => authority.recordSnapshot(randomUUID(), 'a'.repeat(64), 0)).toThrow();
+ authority.recordSnapshot(id, 'a'.repeat(64), 0);
+ expect(() => authority.completeRestore(randomUUID())).toThrow();
+ const completed = make().completeRestore(id);
+ expect(completed.settledRecoveryId).toBe(id);
+ expect(make().requireReady(pending.epoch).phase).toBe('ready');
+ expect(() => make().requireReady(first.epoch)).toThrow();
+ });
+ it('does not rotate or recapture an already-owned recovery on retry', () => {
+ const authority = make(); authority.initialize();
+ const id = randomUUID();
+ const first = authority.beginRestore(id);
+ expect(authority.beginRestore(id)).toEqual(first);
+ const captured = authority.recordSnapshot(id, 'b'.repeat(64), 3);
+ expect(authority.beginRestore(id)).toEqual(captured);
+ expect(() => authority.beginRestore(randomUUID())).toThrow(/Another/);
+ });
+ it.each(['{not json', JSON.stringify({ version: 99 })])('never resets unreadable/future authority: %s', contents => {
+ fs.writeFileSync(join(directory, 'peer-execution-authority.json'), contents);
+ expect(() => make().initialize()).toThrow(/unreadable/);
+ expect(fs.readFileSync(join(directory, 'peer-execution-authority.json'), 'utf8')).toBe(contents);
+ expect(fs.existsSync(join(directory, '.peer-execution-authority-lock'))).toBe(false);
+ });
+ it('refuses an interrupted writer instead of stealing its lock', () => {
+ const authority = make(); authority.initialize();
+ fs.mkdirSync(join(directory, '.peer-execution-authority-lock'));
+ expect(() => make().read()).toThrow(/reconciliation/);
+ expect(() => make().initialize()).toThrow(/being changed/);
+ });
+ it('keeps publication failure fenced in this process and after restart', () => {
+ const original = make().initialize();
+ const io = { ...fs, renameSync: () => { throw new Error('fixture disk failure'); } };
+ const authority = make({ io });
+ expect(() => authority.beginRestore(randomUUID())).toThrow('fixture disk failure');
+ expect(() => authority.requireReady(original.epoch)).toThrow();
+ expect(() => make().requireReady(original.epoch)).toThrow();
+ });
+ it('rejects planning scope, injected input, oversized values and equal identities before persistence', () => {
+ const input = { hostInstanceId: randomUUID(), peerInstanceId: randomUUID(), requestId: randomUUID(),
+ grantId: randomUUID(), grantGeneration: 1, scope: 'execution-v1', pairBinding: 'a'.repeat(64),
+ intent: { action: 'portos.restart' }, receiverVersion: '1.0.0', evidenceDigest: 'b'.repeat(64), executionEpoch: randomUUID() };
+ expect(peerExecutionBindingSchema.parse(input)).toEqual(input);
+ for (const changed of [{ scope: 'planning-v1' }, { intent: { action: 'portos.restart', command: 'fixture-injection' } },
+ { receiverVersion: 'v'.repeat(101) }, { peerInstanceId: input.hostInstanceId }, { grantGeneration: Number.MAX_SAFE_INTEGER + 1 }]) {
+ expect(peerExecutionBindingSchema.safeParse({ ...input, ...changed }).success).toBe(false);
+ }
+ expect(fs.readdirSync(directory)).toEqual([]);
+ });
+});
diff --git a/server/scripts/db-migrations/013-peer-execution-ledger.js b/server/scripts/db-migrations/013-peer-execution-ledger.js
new file mode 100644
index 0000000000..caab512a6a
--- /dev/null
+++ b/server/scripts/db-migrations/013-peer-execution-ledger.js
@@ -0,0 +1,6 @@
+// Additive receiver-local consumption records; creates no execution authority.
+import { peerExecutionDdl } from '../../lib/db/schema/peerExecution.js';
+
+export async function up(client) {
+ for (const statement of peerExecutionDdl) await client.query(statement);
+}
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 457fcfc8ff..2b09daa63f 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -2340,3 +2340,31 @@ CREATE TABLE IF NOT EXISTS media_prompt_examinations (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_media_prompt_examinations_created ON media_prompt_examinations (created_at DESC, id DESC);
+
+-- Receiver-local peer execution consumption (#10127); never federated.
+CREATE TABLE IF NOT EXISTS peer_execution_operations (
+ operation_id UUID PRIMARY KEY,
+ host_instance_id UUID NOT NULL,
+ peer_instance_id UUID NOT NULL,
+ request_id UUID NOT NULL,
+ fingerprint TEXT NOT NULL CHECK (fingerprint ~ '^[a-f0-9]{64}$'),
+ binding JSONB NOT NULL,
+ execution_epoch UUID NOT NULL,
+ state TEXT NOT NULL CHECK (state IN ('queued', 'draining', 'in-flight', 'awaiting-reconnect', 'succeeded', 'failed', 'uncertain')),
+ revision BIGINT NOT NULL DEFAULT 1 CHECK (revision > 0),
+ claim JSONB,
+ receipt JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (host_instance_id, peer_instance_id, request_id),
+ CHECK (host_instance_id <> peer_instance_id)
+ );
+CREATE INDEX IF NOT EXISTS idx_peer_execution_operations_state ON peer_execution_operations (state, operation_id);
+CREATE TABLE IF NOT EXISTS peer_execution_generation_floors (
+ host_instance_id UUID NOT NULL,
+ peer_instance_id UUID NOT NULL,
+ action TEXT NOT NULL CHECK (action IN ('portos.update', 'portos.restart', 'catalog.install')),
+ generation BIGINT NOT NULL CHECK (generation >= 0),
+ PRIMARY KEY (host_instance_id, peer_instance_id, action),
+ CHECK (host_instance_id <> peer_instance_id)
+ );
diff --git a/server/services/backup.js b/server/services/backup.js
index a026797bd8..d6c5cef9f5 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -1328,20 +1328,25 @@ const OS_METADATA_RSYNC_EXCLUDES = [...OS_METADATA_FILES, '._*'].map(name => `--
* filter, the manifest selection and the scope inventory so preview,
* verification and execution cannot disagree.
*/
-const RESTORE_PRESERVED_FILES = Object.freeze(['database-authority.json']);
+const RESTORE_PRESERVED_FILES = Object.freeze([
+ 'database-authority.json', 'peer-execution-authority.json', 'peer-execution-recovery.jsonl', 'workflow-maintenance',
+]);
// Matched case-insensitively (rsync has no such flag, so each letter becomes a
// `[xX]` class): on a case-insensitive volume a `Database-Authority.json` entry
// would otherwise overwrite the destination's lowercase record.
const caseInsensitiveGlob = (name) => name.replace(/[a-z]/gi, ch => `[${ch.toLowerCase()}${ch.toUpperCase()}]`);
const RESTORE_PRESERVED_RSYNC_EXCLUDES = RESTORE_PRESERVED_FILES.map(name => `--exclude=/${caseInsensitiveGlob(name)}`);
-const isRestorePreservedPath = (relativePath) => RESTORE_PRESERVED_FILES.includes(relativePath.toLowerCase());
+const isRestorePreservedPath = (relativePath) => {
+ const normalized = relativePath.toLowerCase();
+ return RESTORE_PRESERVED_FILES.some(path => normalized === path || normalized.startsWith(`${path}/`));
+};
// A filter naming a preserved file would otherwise be a silent no-op restore.
// Compared case-insensitively after dropping empty/`.` segments, so
// `./Database-Authority.json/` cannot slip past on a case-insensitive volume.
const restoreScopeIsPreservedFile = (subdirFilter) => {
const normalized = subdirFilter?.split('/').filter(part => part && part !== '.').join('/').toLowerCase();
- return RESTORE_PRESERVED_FILES.includes(normalized);
+ return isRestorePreservedPath(normalized);
};
const snapshotFileIntegrityError = (snapshotId, unmanifestedPath = null) => new ServerError(
@@ -1503,7 +1508,7 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub
// never promises a restore that execution would silently skip.
if (restoreScopeIsPreservedFile(subdirFilter)) {
throw new ServerError(
- 'database-authority.json is machine-local and is never restored from a snapshot: it records which database backend a cutover completed on THIS machine, and installing another copy would fence the healthy local database. Restore your records with a data or database restore instead; to change the authority, run a database cutover (see docs/STORAGE.md, retired backend).',
+ 'Machine-local authority and recovery records (database-authority.json, peer-execution-authority.json, peer-execution-recovery.jsonl and workflow-maintenance) are never restored from a snapshot. Restore application records with a data or database restore; existing local authority and unresolved owners must be reconciled on this machine (see docs/STORAGE.md).',
{ status: 400, code: 'BACKUP_RESTORE_MACHINE_LOCAL' },
);
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index d2db3d8d17..ee07e920a6 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -2342,6 +2342,25 @@ describe('restoreSnapshot manifest verification', () => {
}
}
+ it.for(['peer-execution-authority.json', 'peer-execution-recovery.jsonl', 'workflow-maintenance/state.json', 'Workflow-Maintenance/state.json'])
+ ('preserves non-rewound execution authority and ownership at %s (#10127)', async (path, context) => {
+ await withRealRsync(context, async () => {
+ const localPath = joinPath(PATHS.data, path);
+ await realFs.mkdir(dirname(localPath), { recursive: true });
+ await realFs.writeFile(localPath, 'current receiver authority');
+ for (const withManifest of [true, false]) {
+ await realFs.rm(joinPath(snapshotDir, 'manifest.json'), { force: true });
+ const hash = await writeSnapshotFile(path, 'obsolete snapshot authority');
+ const neighbor = await writeSnapshotFile(RECORD, '{"value":"snapshot"}');
+ if (withManifest) await writeManifest({ [path]: hash, [RECORD]: neighbor });
+ const preview = await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: true });
+ expect(preview.changedFiles.some(line => line.includes(path))).toBe(false);
+ await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false });
+ expect(await realFs.readFile(localPath, 'utf8')).toBe('current receiver authority');
+ }
+ });
+ });
+
it.for([
{ name: 'full restore', options: {} },
{ name: 'brain-scoped restore', options: { subdirFilter: 'brain' } },
diff --git a/server/services/peerExecutionLedger.db.test.js b/server/services/peerExecutionLedger.db.test.js
new file mode 100644
index 0000000000..20b14c512a
--- /dev/null
+++ b/server/services/peerExecutionLedger.db.test.js
@@ -0,0 +1,183 @@
+/** Real transaction/restore fixtures only; no grants, peers, adapters or providers. */
+import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';
+import * as fs from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { checkHealth, close, ensureSchema, query, withTransaction } from '../lib/db.js';
+import { requireDbOrSkip } from '../lib/dbTestGate.js';
+import { createPeerExecutionLedger } from './peerExecutionLedger.js';
+
+const health = await checkHealth().catch(() => ({ connected: false }));
+if (health.connected) await ensureSchema();
+const runDb = requireDbOrSkip('services/peerExecutionLedger.db.test', health.connected, 'disposable PostgreSQL unavailable');
+const db = { query, withTransaction };
+let directory, ledger, input;
+const binding = epoch => ({ hostInstanceId: randomUUID(), peerInstanceId: randomUUID(), requestId: randomUUID(),
+ grantId: randomUUID(), grantGeneration: 1, scope: 'execution-v1', pairBinding: 'a'.repeat(64),
+ intent: { action: 'portos.restart' }, receiverVersion: 'fixture-1.0', evidenceDigest: 'b'.repeat(64), executionEpoch: epoch });
+const claim = () => ({ id: randomUUID(), revision: 2, fingerprint: 'c'.repeat(64) });
+const receipt = (epoch, outcome = 'failed') => ({ outcome, code: 'FIXTURE_TERMINAL', evidenceDigest: 'd'.repeat(64), executionEpoch: epoch });
+
+beforeEach(async () => {
+ if (!runDb) return;
+ // This file owns only its new, machine-local test tables; the DB runner is serial.
+ await query('DELETE FROM peer_execution_operations');
+ await query('DELETE FROM peer_execution_generation_floors');
+ directory = fs.mkdtempSync(join(tmpdir(), 'peer-execution-ledger-db-test-'));
+ ledger = createPeerExecutionLedger({ db, dataDir: directory });
+ input = binding((await ledger.initialize()).epoch);
+});
+afterEach(async () => {
+ if (!runDb) return;
+ await query('DELETE FROM peer_execution_operations');
+ await query('DELETE FROM peer_execution_generation_floors');
+ fs.rmSync(directory, { recursive: true, force: true });
+});
+afterAll(async () => { if (health.connected) await close(); });
+
+describe.skipIf(!runDb)('receiver-local permanent execution consumption', () => {
+ it('serializes duplicate first requests, retaining one operation through process reconstruction', async () => {
+ const results = await Promise.all([ledger.consume(input), ledger.consume(input)]);
+ expect(results.map(row => row.isNew).sort()).toEqual([false, true]);
+ expect(results[0].operation.operationId).toBe(results[1].operation.operationId);
+ const restarted = createPeerExecutionLedger({ db, dataDir: directory });
+ expect((await restarted.consume(input)).operation).toEqual(results[0].operation);
+ for (const changed of [{ intent: { action: 'portos.update' } }, { grantId: randomUUID(), grantGeneration: 2 },
+ { pairBinding: 'e'.repeat(64) }, { receiverVersion: 'fixture-2.0' }, { evidenceDigest: 'f'.repeat(64) }]) {
+ await expect(restarted.consume({ ...input, ...changed })).rejects.toMatchObject({ code: 'PEER_EXECUTION_REPLAY_CONFLICT' });
+ }
+ expect(await ledger.list()).toHaveLength(1);
+ });
+ it('serializes conflicting requests and never replaces the winning fingerprint', async () => {
+ const outcomes = await Promise.allSettled([ledger.consume(input), ledger.consume({ ...input, evidenceDigest: 'e'.repeat(64) })]);
+ expect(outcomes.filter(result => result.status === 'fulfilled')).toHaveLength(1);
+ expect(outcomes.filter(result => result.status === 'rejected')).toHaveLength(1);
+ expect(await ledger.list()).toHaveLength(1);
+ });
+ it('retains consumed identity independently of action, renewal, sender and generation floors', async () => {
+ const saved = await ledger.consume(input);
+ await ledger.advanceGenerationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
+ action: input.intent.action, generation: 4 });
+ expect(await ledger.consume(input)).toMatchObject({ isNew: false, operation: saved.operation });
+ await expect(ledger.consume({ ...input, requestId: randomUUID() })).rejects.toMatchObject({ code: 'PEER_EXECUTION_GENERATION_STALE' });
+ expect(await ledger.advanceGenerationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
+ action: input.intent.action, generation: 2 })).toBe(4);
+ expect((await ledger.consume({ ...input, peerInstanceId: randomUUID() })).isNew).toBe(true);
+ });
+ it('has one-way compare-and-set states and cannot turn timeout/uncertainty into a second launch', async () => {
+ const { operation } = await ledger.consume(input);
+ const draining = await ledger.transition(operation.operationId, 1, 'draining');
+ await expect(ledger.transition(operation.operationId, 1, 'draining')).rejects.toMatchObject({ code: 'PEER_EXECUTION_STALE' });
+ await expect(ledger.transition(operation.operationId, draining.revision, 'in-flight')).rejects.toMatchObject({ code: 'PEER_EXECUTION_CLAIM_REQUIRED' });
+ const started = await ledger.transition(operation.operationId, draining.revision, 'in-flight', { claim: claim() });
+ const uncertain = await ledger.transition(operation.operationId, started.revision, 'uncertain');
+ await expect(ledger.transition(operation.operationId, uncertain.revision, 'in-flight', { claim: claim() }))
+ .rejects.toMatchObject({ code: 'PEER_EXECUTION_TRANSITION_REFUSED' });
+ const settled = await ledger.transition(operation.operationId, uncertain.revision, 'failed', { receipt: receipt(input.executionEpoch) });
+ expect((await ledger.consume(input)).operation).toEqual(settled);
+ await expect(ledger.transition(operation.operationId, settled.revision, 'draining')).rejects.toThrow();
+ });
+ it('rechecks the authority epoch after waiting for a PostgreSQL writer lock', async () => {
+ let release, entered;
+ const blocked = new Promise(resolve => { entered = resolve; });
+ const gate = new Promise(resolve => { release = resolve; });
+ const holding = withTransaction(async client => {
+ await client.query('SELECT pg_advisory_xact_lock($1)', [90011027]); entered(); await gate;
+ });
+ await blocked;
+ const queued = ledger.consume(input);
+ const observed = queued.catch(error => error);
+ ledger.authority.beginRestore(randomUUID());
+ release(); await holding;
+ expect(await observed).toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
+ expect(await ledger.list()).toEqual([]);
+ });
+ it('bounds active records and lists, retaining terminal consumption instead of pruning it', async () => {
+ for (let i = 0; i < 32; i++) await ledger.consume({ ...input, requestId: randomUUID() });
+ await expect(ledger.consume(input)).rejects.toMatchObject({ code: 'PEER_EXECUTION_QUEUE_FULL' });
+ const first = (await ledger.list({ limit: 1 }))[0];
+ await ledger.transition(first.operationId, first.revision, 'failed', { receipt: receipt(input.executionEpoch) });
+ expect((await ledger.consume(input)).isNew).toBe(true);
+ expect(await ledger.list()).toHaveLength(33);
+ await expect(ledger.list({ limit: 101 })).rejects.toThrow();
+ });
+ it('refuses missing authority over existing consumption instead of silently minting a new epoch', async () => {
+ await ledger.consume(input);
+ fs.unlinkSync(join(directory, 'peer-execution-authority.json'));
+ await expect(ledger.initialize()).rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
+ });
+ it.each(['empty', 'older'])('reconciles a %s database restore without losing consumption, floors or uncertain ownership', async kind => {
+ const first = (await ledger.consume(input)).operation;
+ const owner = (await ledger.consume({ ...input, requestId: randomUUID() })).operation;
+ const draining = await ledger.transition(owner.operationId, 1, 'draining');
+ const started = await ledger.transition(owner.operationId, draining.revision, 'in-flight', { claim: claim() });
+ await ledger.advanceGenerationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId,
+ action: input.intent.action, generation: 7 });
+ const id = randomUUID();
+ const pending = await ledger.prepareRestore(id);
+ await query('DELETE FROM peer_execution_operations');
+ await query('DELETE FROM peer_execution_generation_floors');
+ if (kind === 'older') {
+ await query(`INSERT INTO peer_execution_generation_floors (host_instance_id, peer_instance_id, action, generation)
+ VALUES ($1,$2,$3,1)`, [input.hostInstanceId, input.peerInstanceId, input.intent.action]);
+ }
+ const restarted = createPeerExecutionLedger({ db, dataDir: directory });
+ expect(await restarted.prepareRestore(id)).toEqual(pending); // Must not capture the rewound DB.
+ await expect(restarted.consume(input)).rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
+ const completed = await restarted.reconcileRestore(id);
+ expect(await restarted.reconcileRestore(id)).toEqual(completed);
+ expect((await restarted.read(first.operationId)).state).toBe('failed');
+ expect(await restarted.read(owner.operationId)).toMatchObject({ state: 'uncertain', claim: started.claim });
+ await expect(restarted.consume(input)).rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });
+ await expect(restarted.consume({ ...input, executionEpoch: completed.epoch }))
+ .rejects.toMatchObject({ code: 'PEER_EXECUTION_REPLAY_CONFLICT' });
+ await expect(restarted.consume({ ...input, requestId: randomUUID(), executionEpoch: completed.epoch }))
+ .rejects.toMatchObject({ code: 'PEER_EXECUTION_GENERATION_STALE' });
+ const current = await restarted.read(owner.operationId);
+ await expect(restarted.transition(owner.operationId, current.revision, 'failed', {
+ authorityEpoch: completed.epoch, receipt: receipt(input.executionEpoch),
+ })).rejects.toMatchObject({ code: 'PEER_EXECUTION_RECEIPT_STALE' });
+ expect((await restarted.transition(owner.operationId, current.revision, 'failed', {
+ authorityEpoch: completed.epoch, receipt: receipt(completed.epoch),
+ })).state).toBe('failed');
+ });
+ it('preserves committed terminal evidence across restore and rejects conflicting restored fingerprints atomically', async () => {
+ const first = (await ledger.consume(input)).operation;
+ await ledger.transition(first.operationId, 1, 'failed', { receipt: receipt(input.executionEpoch) });
+ const id = randomUUID(); await ledger.prepareRestore(id);
+ await ledger.reconcileRestore(id);
+ expect((await ledger.read(first.operationId)).receipt).toEqual(receipt(input.executionEpoch));
+ const second = (await ledger.consume({ ...input, requestId: randomUUID(), executionEpoch: ledger.authority.read().epoch })).operation;
+ const conflictId = randomUUID(); await ledger.prepareRestore(conflictId);
+ await query('UPDATE peer_execution_operations SET fingerprint = $2 WHERE operation_id = $1', [second.operationId, 'f'.repeat(64)]);
+ await expect(ledger.reconcileRestore(conflictId)).rejects.toThrow();
+ expect(ledger.authority.read().phase).toBe('reconciling');
+ });
+ it('keeps missing or modified recovery evidence fenced without applying it', async () => {
+ const saved = (await ledger.consume(input)).operation;
+ const id = randomUUID(); await ledger.prepareRestore(id);
+ await query('DELETE FROM peer_execution_operations');
+ fs.appendFileSync(ledger.authority.recoveryPath, '\n');
+ await expect(ledger.reconcileRestore(id)).rejects.toThrow();
+ expect(await ledger.read(saved.operationId)).toBeNull();
+ expect(ledger.authority.read().phase).toBe('reconciling');
+ });
+ it('retains the recovery fence when the database commit outcome is unknown, then reconciles the same facts', async () => {
+ const saved = (await ledger.consume(input)).operation;
+ const id = randomUUID(); await ledger.prepareRestore(id);
+ await query('DELETE FROM peer_execution_operations');
+ let lost = false;
+ const ambiguous = createPeerExecutionLedger({ dataDir: directory, db: {
+ query, withTransaction: async fn => {
+ const result = await withTransaction(fn);
+ if (!lost) { lost = true; throw new Error('fixture lost commit acknowledgement'); }
+ return result;
+ },
+ } });
+ await expect(ambiguous.reconcileRestore(id)).rejects.toThrow(/acknowledgement/);
+ expect(ledger.authority.read().phase).toBe('reconciling');
+ await ledger.reconcileRestore(id);
+ expect((await ledger.read(saved.operationId)).state).toBe('failed');
+ });
+});
diff --git a/server/services/peerExecutionLedger.js b/server/services/peerExecutionLedger.js
new file mode 100644
index 0000000000..62b6a37c12
--- /dev/null
+++ b/server/services/peerExecutionLedger.js
@@ -0,0 +1,273 @@
+/**
+ * Receiver-local persistence primitives only. A record is neither a grant nor a
+ * launch authorization. No peer route or fixed adapter imports this module yet.
+ */
+import { createHash, randomUUID } from 'node:crypto';
+import * as fs from 'node:fs';
+import { z } from 'zod';
+import { peerAdminIntentSchema, peerAdminActionSchema } from '../lib/peerAdminValidation.js';
+import { createPeerExecutionAuthority, executionAuthorityError } from '../lib/peerExecutionAuthority.js';
+
+const uuid = z.string().uuid().toLowerCase();
+const digest = z.string().regex(/^[a-f0-9]{64}$/);
+const integer = z.number().int().nonnegative().safe();
+const positive = integer.positive();
+export const peerExecutionBindingSchema = z.object({
+ hostInstanceId: uuid, peerInstanceId: uuid, requestId: uuid, grantId: uuid,
+ grantGeneration: positive, scope: z.literal('execution-v1'), pairBinding: digest,
+ intent: peerAdminIntentSchema, receiverVersion: z.string().min(1).max(100), evidenceDigest: digest,
+ executionEpoch: uuid,
+}).strict().refine(value => value.hostInstanceId !== value.peerInstanceId);
+const states = ['queued', 'draining', 'in-flight', 'awaiting-reconnect', 'succeeded', 'failed', 'uncertain'];
+const terminal = state => ['succeeded', 'failed'].includes(state);
+const claimSchema = z.object({ id: uuid, revision: positive, fingerprint: digest }).strict();
+const receiptSchema = z.object({ outcome: z.enum(['succeeded', 'failed']),
+ code: z.string().min(1).max(100).regex(/^[A-Z0-9_]+$/), evidenceDigest: digest.nullable(), executionEpoch: uuid }).strict();
+const operationSchema = z.object({
+ operationId: uuid, binding: peerExecutionBindingSchema, fingerprint: digest,
+ state: z.enum(states), revision: positive, claim: claimSchema.nullable(), receipt: receiptSchema.nullable(),
+}).strict().refine(row => row.fingerprint === fingerprint(row.binding))
+ .refine(row => terminal(row.state) === Boolean(row.receipt) && (!row.receipt || row.receipt.outcome === row.state));
+const floorSchema = z.object({ hostInstanceId: uuid, peerInstanceId: uuid,
+ action: peerAdminActionSchema, generation: integer }).strict();
+const factSchema = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('operation'), value: operationSchema }).strict(),
+ z.object({ kind: z.literal('floor'), value: floorSchema }).strict(),
+]);
+const fingerprint = binding => createHash('sha256').update(JSON.stringify(binding)).digest('hex');
+const fail = (code, message) => { throw Object.assign(new Error(message), { code, status: 409 }); };
+const fromRow = row => {
+ const operation = operationSchema.parse({ operationId: row.operation_id, binding: row.binding,
+ fingerprint: row.fingerprint, state: row.state, revision: Number(row.revision), claim: row.claim, receipt: row.receipt });
+ if (row.host_instance_id !== operation.binding.hostInstanceId || row.peer_instance_id !== operation.binding.peerInstanceId
+ || row.request_id !== operation.binding.requestId || row.execution_epoch !== operation.binding.executionEpoch)
+ throw executionAuthorityError('Execution consumption identity columns conflict with their immutable binding.');
+ return operation;
+};
+const LOCK_KEY = 90011027;
+const ACTIVE_LIMIT = 32;
+const PAGE_SIZE = 100;
+const MAX_FACT_BYTES = 8192;
+
+/** Inject the guarded db.js query/withTransaction and a fixture or receiver data root. */
+export function createPeerExecutionLedger({ db, dataDir, authority = createPeerExecutionAuthority(dataDir), makeId = randomUUID }) {
+ const locked = fn => db.withTransaction(async client => {
+ await client.query('SELECT pg_advisory_xact_lock($1)', [LOCK_KEY]);
+ return fn(client);
+ });
+ const initialize = () => locked(async client => {
+ if (!authority.read()) {
+ const { rows: [row] } = await client.query('SELECT EXISTS(SELECT 1 FROM peer_execution_operations) OR EXISTS(SELECT 1 FROM peer_execution_generation_floors) AS occupied');
+ if (row.occupied) throw executionAuthorityError('Existing consumption has no machine authority; reconcile it instead of resetting it.');
+ authority.initialize();
+ }
+ return authority.read();
+ });
+ const find = async (client, binding) => {
+ const { rows: [row] } = await client.query(`SELECT * FROM peer_execution_operations
+ WHERE host_instance_id = $1 AND peer_instance_id = $2 AND request_id = $3`,
+ [binding.hostInstanceId, binding.peerInstanceId, binding.requestId]);
+ return row ? fromRow(row) : null;
+ };
+ const consume = raw => {
+ const binding = peerExecutionBindingSchema.parse(raw);
+ authority.requireReady(binding.executionEpoch);
+ return locked(async client => {
+ authority.requireReady(binding.executionEpoch); // Also after waiting for the shared writer lock.
+ const previous = await find(client, binding);
+ if (previous) {
+ if (previous.fingerprint !== fingerprint(binding)) fail('PEER_EXECUTION_REPLAY_CONFLICT', 'This authenticated request identity was already consumed with different evidence.');
+ return { operation: previous, isNew: false };
+ }
+ const { rows: [floor] } = await client.query(`SELECT generation FROM peer_execution_generation_floors
+ WHERE host_instance_id = $1 AND peer_instance_id = $2 AND action = $3`,
+ [binding.hostInstanceId, binding.peerInstanceId, binding.intent.action]);
+ if (floor && Number(floor.generation) > binding.grantGeneration)
+ fail('PEER_EXECUTION_GENERATION_STALE', 'The execution grant generation was invalidated.');
+ const { rows: [count] } = await client.query(`SELECT count(*)::int AS count FROM peer_execution_operations
+ WHERE state IN ('queued', 'draining', 'in-flight', 'awaiting-reconnect', 'uncertain')`);
+ if (count.count >= ACTIVE_LIMIT) fail('PEER_EXECUTION_QUEUE_FULL', 'Unresolved execution records must settle before accepting more.');
+ const { rows: [row] } = await client.query(`INSERT INTO peer_execution_operations
+ (operation_id, host_instance_id, peer_instance_id, request_id, fingerprint, binding, execution_epoch, state)
+ VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, 'queued') RETURNING *`,
+ [makeId(), binding.hostInstanceId, binding.peerInstanceId, binding.requestId, fingerprint(binding), JSON.stringify(binding), binding.executionEpoch]);
+ await client.query(`INSERT INTO peer_execution_generation_floors (host_instance_id, peer_instance_id, action, generation)
+ VALUES ($1, $2, $3, $4) ON CONFLICT (host_instance_id, peer_instance_id, action)
+ DO UPDATE SET generation = GREATEST(peer_execution_generation_floors.generation, EXCLUDED.generation)`,
+ [binding.hostInstanceId, binding.peerInstanceId, binding.intent.action, binding.grantGeneration]);
+ authority.requireReady(binding.executionEpoch);
+ return { operation: fromRow(row), isNew: true };
+ });
+ };
+ const read = async id => {
+ uuid.parse(id);
+ const { rows: [row] } = await db.query('SELECT * FROM peer_execution_operations WHERE operation_id = $1', [id]);
+ return row ? fromRow(row) : null;
+ };
+ const advanceGenerationFloor = raw => {
+ const input = floorSchema.parse(raw);
+ return locked(async client => {
+ const { rows: [row] } = await client.query(`INSERT INTO peer_execution_generation_floors
+ (host_instance_id, peer_instance_id, action, generation) VALUES ($1, $2, $3, $4)
+ ON CONFLICT (host_instance_id, peer_instance_id, action) DO UPDATE
+ SET generation = GREATEST(peer_execution_generation_floors.generation, EXCLUDED.generation) RETURNING generation`,
+ [input.hostInstanceId, input.peerInstanceId, input.action, input.generation]);
+ return Number(row.generation);
+ });
+ };
+ // Persistence CAS, not a dispatcher. The future receiver must own and verify
+ // the coordinator claim/adapter evidence before calling this internal method.
+ const transition = (id, revision, state, { claim = null, receipt = null, authorityEpoch = null } = {}) => {
+ uuid.parse(id); positive.parse(revision); z.enum(states).parse(state);
+ if (claim) claimSchema.parse(claim);
+ if (receipt) receiptSchema.parse(receipt);
+ uuid.nullable().parse(authorityEpoch);
+ return locked(async client => {
+ const { rows: [row] } = await client.query('SELECT * FROM peer_execution_operations WHERE operation_id = $1 FOR UPDATE', [id]);
+ if (!row) fail('PEER_EXECUTION_NOT_FOUND', 'The execution operation does not exist.');
+ const current = fromRow(row);
+ const epoch = authorityEpoch ?? current.binding.executionEpoch;
+ authority.requireReady(epoch);
+ if (current.revision !== revision) fail('PEER_EXECUTION_STALE', 'Refresh the current operation revision.');
+ const allowed = { queued: ['draining', 'failed'], draining: ['in-flight', 'failed', 'uncertain'],
+ 'in-flight': ['awaiting-reconnect', 'succeeded', 'failed', 'uncertain'],
+ 'awaiting-reconnect': ['succeeded', 'failed', 'uncertain'], uncertain: ['succeeded', 'failed'], succeeded: [], failed: [] };
+ if (!allowed[current.state].includes(state)) fail('PEER_EXECUTION_TRANSITION_REFUSED', 'An operation cannot move backwards or launch again.');
+ if (state === 'in-flight' && !claim) fail('PEER_EXECUTION_CLAIM_REQUIRED', 'Persist the exact coordinator ownership before recording a start.');
+ if (current.claim && claim && JSON.stringify(current.claim) !== JSON.stringify(claim))
+ fail('PEER_EXECUTION_CLAIM_CHANGED', 'A different coordinator owner cannot replace the recorded start.');
+ if (terminal(state) && receipt?.executionEpoch !== epoch)
+ fail('PEER_EXECUTION_RECEIPT_STALE', 'Terminal evidence must bind the current non-rewound authority epoch.');
+ const next = operationSchema.parse({ ...current, state, revision: revision + 1, claim: claim ?? current.claim, receipt });
+ const { rows: [updated] } = await client.query(`UPDATE peer_execution_operations
+ SET state = $2, revision = $3, claim = $4::jsonb, receipt = $5::jsonb, updated_at = NOW()
+ WHERE operation_id = $1 RETURNING *`, [id, next.state, next.revision, JSON.stringify(next.claim), JSON.stringify(next.receipt)]);
+ authority.requireReady(epoch);
+ return fromRow(updated);
+ });
+ };
+ const list = async ({ after = null, limit = PAGE_SIZE } = {}) => {
+ uuid.nullable().parse(after); z.number().int().min(1).max(PAGE_SIZE).parse(limit);
+ const { rows } = await db.query(`SELECT * FROM peer_execution_operations
+ WHERE ($1::uuid IS NULL OR operation_id > $1) ORDER BY operation_id LIMIT $2`, [after, limit]);
+ return rows.map(fromRow);
+ };
+ const prepareRestore = id => locked(async client => {
+ const started = authority.beginRestore(id); // Invalidates old evidence BEFORE any rewind.
+ if (started.phase !== 'capturing') return started; // Never recapture a rewound database on retry.
+ const pending = `${authority.recoveryPath}.${makeId()}.pending`;
+ authority.assertWrite(pending, 'peer execution restore evidence');
+ const fd = fs.openSync(pending, 'wx', 0o600);
+ const hash = createHash('sha256');
+ let count = 0;
+ const write = fact => {
+ factSchema.parse(fact);
+ const bytes = Buffer.from(JSON.stringify(fact) + '\n');
+ if (bytes.length > MAX_FACT_BYTES) throw executionAuthorityError('A recovery fact exceeds the bounded record size.');
+ fs.writeFileSync(fd, bytes); hash.update(bytes); count++;
+ };
+ try {
+ let after = null;
+ for (;;) {
+ const { rows } = await client.query(`SELECT * FROM peer_execution_operations
+ WHERE ($1::uuid IS NULL OR operation_id > $1) ORDER BY operation_id LIMIT $2`, [after, PAGE_SIZE]);
+ for (const row of rows) write({ kind: 'operation', value: fromRow(row) });
+ if (rows.length < PAGE_SIZE) break;
+ after = rows.at(-1).operation_id;
+ }
+ let floorAfter = [null, null, null];
+ for (;;) {
+ const { rows } = await client.query(`SELECT * FROM peer_execution_generation_floors
+ WHERE ($1::uuid IS NULL OR (host_instance_id, peer_instance_id, action) > ($1::uuid, $2::uuid, $3::text))
+ ORDER BY host_instance_id, peer_instance_id, action LIMIT $4`, [...floorAfter, PAGE_SIZE]);
+ for (const row of rows) write({ kind: 'floor', value: { hostInstanceId: row.host_instance_id,
+ peerInstanceId: row.peer_instance_id, action: row.action, generation: Number(row.generation) } });
+ if (rows.length < PAGE_SIZE) break;
+ const last = rows.at(-1);
+ floorAfter = [last.host_instance_id, last.peer_instance_id, last.action];
+ }
+ fs.fsyncSync(fd);
+ } finally { fs.closeSync(fd); }
+ fs.renameSync(pending, authority.recoveryPath);
+ if (process.platform !== 'win32') {
+ const directory = fs.openSync(dataDir, 'r');
+ try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
+ }
+ return authority.recordSnapshot(id, hash.digest('hex'), count);
+ });
+ // Stream twice: authenticate ALL recovery bytes before applying any rows.
+ const visitFacts = async visit => {
+ const hash = createHash('sha256');
+ let buffer = Buffer.alloc(0), count = 0;
+ const stream = fs.createReadStream(authority.recoveryPath, { highWaterMark: MAX_FACT_BYTES });
+ for await (const chunk of stream) {
+ hash.update(chunk); buffer = Buffer.concat([buffer, chunk]);
+ let newline;
+ while ((newline = buffer.indexOf(10)) >= 0) {
+ if (newline >= MAX_FACT_BYTES) throw executionAuthorityError('Oversized execution recovery fact.');
+ const fact = factSchema.parse(JSON.parse(buffer.subarray(0, newline).toString('utf8')));
+ buffer = buffer.subarray(newline + 1); count++;
+ if (visit) await visit(fact);
+ }
+ if (buffer.length >= MAX_FACT_BYTES) throw executionAuthorityError('Oversized execution recovery fact.');
+ }
+ if (buffer.length) throw executionAuthorityError('Truncated execution recovery evidence.');
+ return { digest: hash.digest('hex'), count };
+ };
+ const reconcileRestore = async id => {
+ const record = authority.read();
+ if (record?.phase === 'ready' && record.settledRecoveryId === id) return record;
+ if (record?.recovery?.id !== id || record.phase !== 'reconciling')
+ throw executionAuthorityError('Complete execution recovery capture before reconciling.');
+ const proof = await visitFacts();
+ if (proof.digest !== record.recovery.digest || proof.count !== record.recovery.count)
+ throw executionAuthorityError('Execution recovery evidence is missing or conflicting.');
+ await locked(async client => {
+ const replayed = await visitFacts(async fact => {
+ if (fact.kind === 'floor') {
+ const floor = fact.value;
+ await client.query(`INSERT INTO peer_execution_generation_floors (host_instance_id, peer_instance_id, action, generation)
+ VALUES ($1, $2, $3, $4) ON CONFLICT (host_instance_id, peer_instance_id, action)
+ DO UPDATE SET generation = GREATEST(peer_execution_generation_floors.generation, EXCLUDED.generation)`,
+ [floor.hostInstanceId, floor.peerInstanceId, floor.action, floor.generation]);
+ return;
+ }
+ const saved = fact.value;
+ const { rows } = await client.query(`SELECT * FROM peer_execution_operations WHERE operation_id = $1 OR
+ (host_instance_id = $2 AND peer_instance_id = $3 AND request_id = $4) FOR UPDATE`,
+ [saved.operationId, saved.binding.hostInstanceId, saved.binding.peerInstanceId, saved.binding.requestId]);
+ if (rows.some(row => row.operation_id !== saved.operationId || fromRow(row).fingerprint !== saved.fingerprint))
+ throw executionAuthorityError('Restored execution consumption conflicts with non-rewound evidence.');
+ if (rows.some(row => terminal(row.state) && terminal(saved.state) && JSON.stringify(receiptSchema.parse(row.receipt)) !== JSON.stringify(saved.receipt)))
+ throw executionAuthorityError('Restored terminal evidence conflicts with non-rewound evidence.');
+ if (rows.some(row => terminal(row.state) && !terminal(saved.state)
+ && (row.receipt.code !== 'EXECUTION_AUTHORITY_RESTORED' || row.receipt.executionEpoch !== record.epoch)))
+ throw executionAuthorityError('Restored completion contradicts non-rewound unresolved ownership.');
+ const started = saved.claim || ['in-flight', 'awaiting-reconnect', 'uncertain'].includes(saved.state);
+ const state = terminal(saved.state) ? saved.state : started ? 'uncertain' : 'failed';
+ const receipt = terminal(saved.state) ? saved.receipt : state === 'failed'
+ ? { outcome: 'failed', code: 'EXECUTION_AUTHORITY_RESTORED', evidenceDigest: null, executionEpoch: record.epoch } : null;
+ await client.query(`INSERT INTO peer_execution_operations
+ (operation_id, host_instance_id, peer_instance_id, request_id, fingerprint, binding, execution_epoch, state, revision, claim, receipt)
+ VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10::jsonb,$11::jsonb)
+ ON CONFLICT (operation_id) DO UPDATE SET state = EXCLUDED.state,
+ revision = GREATEST(peer_execution_operations.revision, EXCLUDED.revision), claim = EXCLUDED.claim, receipt = EXCLUDED.receipt, updated_at = NOW()`,
+ [saved.operationId, saved.binding.hostInstanceId, saved.binding.peerInstanceId, saved.binding.requestId, saved.fingerprint,
+ JSON.stringify(saved.binding), saved.binding.executionEpoch, state, saved.revision + 1, JSON.stringify(saved.claim), JSON.stringify(receipt)]);
+ });
+ if (replayed.digest !== proof.digest || replayed.count !== proof.count)
+ throw executionAuthorityError('Execution recovery evidence changed during reconciliation.');
+ // An old/different snapshot may contain owners not present in this machine's
+ // capture. They also cannot become launchable just because generic restore ended.
+ await client.query(`UPDATE peer_execution_operations SET state = 'uncertain', revision = revision + 1,
+ receipt = NULL, updated_at = NOW() WHERE state IN ('queued', 'draining', 'in-flight', 'awaiting-reconnect')`);
+ const current = authority.read();
+ if (current?.epoch !== record.epoch || current.recovery?.id !== id)
+ throw executionAuthorityError('The execution recovery owner changed during reconciliation.');
+ });
+ const current = authority.read();
+ if (current?.phase === 'ready' && current.settledRecoveryId === id) return current;
+ return authority.completeRestore(id);
+ };
+ return { initialize, consume, read, list, transition, advanceGenerationFloor, prepareRestore, reconcileRestore, authority };
+}