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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-10127]): durably settle legacy restore compatibility
[._.]/ Adam Eivy24f5629d59d3
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 3ef26b6f7d..87cc1a9a64 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -784,3 +784,42 @@ restart. No operation can run or be recovered from them. The future executionledger must be `db-primary`, receiver-local, retain replay/idempotency evidence,and be covered by PostgreSQL backup before any executor is connected. See[peer administration planning](features/peer-administration.md).++### Receiver execution ledger foundation (#10127)++`peer_execution_operations` and `peer_execution_generation_floors` are receiver-local+`db-primary` records. Consumption is unique on receiver UUID, authenticated sender+UUID and request UUID, independently of action or grant renewal. Immutable binding+fingerprints, operation identities, terminal receipts and monotonic generation+floors are retained permanently; there is no TTL, pruning, grant/peer foreign key+or cascade deletion. Active records are capped at 32 and lists use 100-row keyset+pages. Strict bounded inputs contain fixed intents and evidence digests, never+credentials, shell commands, arbitrary paths or URLs. These tables never federate.+Boot DDL, fresh-install SQL and ordered DB migration 013 install the same schema;+PostgreSQL dumps include it. No seed grants or legacy planning promotion occurs.++`data/peer-execution-authority.json` is boot-safe, machine-local `file-primary`+fencing metadata: a non-rewound execution epoch and the current/last restore owner.+It is not a grant or another operation ledger. An absent authority can initialize+only over empty execution tables; damaged authority cannot silently reset existing+consumption. Restore rotates the epoch before replay, captures minimal request,+owner and floor facts in `peer-execution-recovery.jsonl`, then merges those facts+before ordinary database admission reopens. The recovery file is temporary restore+evidence, streamed in bounded records/pages rather than a writable parallel store.+Unknown DB commit outcomes retain the fence and retry the same evidence. Conflicts,+missing capture and interrupted publication fail closed. Nonterminal records remain+uncertain; missing DB claim evidence never proves that the journal owner did not start.++Filesystem restore preserves both execution files and the whole+`workflow-maintenance/` subtree, case-insensitively, including absent or damaged+local records. Snapshot bytes cannot replace this machine's epoch, recovery facts+or unresolved owner. PostgreSQL restore invokes capture before replay and automatic+reconciliation before generic restore release, including proven rollback. It never+replays a committed dump to recover execution records.++This is a persistence foundation. No execution-grant writer, peer execution route,+adapter or terminal certificate uses it. Pairing/receiver identity invalidation,+filesystem-only restore epoch invalidation, complete shared grant/dispatch locking,+and verified epoch-bound terminal settlement remain owned implementation steps in+#10127 before execution can be advertised. Existing planning routes still refuse+execution; ledger records and restore completion are not permission to launch.diff --git a/docs/features/peer-administration.md b/docs/features/peer-administration.mdindex ac32851fb3..e88a8947c5 100644--- a/docs/features/peer-administration.md+++ b/docs/features/peer-administration.md@@ -171,3 +171,55 @@ The remaining sequence stays owned by #10127, which this slice does not close:These are sequential implementation steps, not external blockers or authorityto change live peers. Keep execution unavailable until all four are complete.++## Durable ledger foundation (#10127, second slice)++The internal receiver ledger now persists request consumption and bounded operation+states in PostgreSQL. A receiver/sender/request identity has one immutable binding+fingerprint and operation UUID for its lifetime. Changed action, pairing evidence,+grant generation or receiver evidence conflicts with that consumed identity;+renewal and peer removal cannot erase it. Generation floors only increase and+their writes require the current ready execution epoch under the shared database+writer lock, including after lock waits. No grant is created by recording a floor.++Persistence transitions use exact revisions and cannot move uncertain work back+to launch. A recorded claim/receipt is storage evidence, not proof of authorization,+adapter cleanup or completion: the future receiver must verify those facts before+calling the internal persistence API. No route imports that API today.++Database restore rotates a machine-local epoch, captures permanent consumption,+generation floors and owners outside the rewind, and reconciles those facts before+reopening database admission. Capture failure prevents replay. Generic committed+or rollback recovery retains its fence until execution reconciliation finishes;+startup retries the same restore without another replay. Missing or conflicting+facts cannot be replaced with an empty history. Queued/draining storage may sit+behind a journal start whose DB write rolled back, so all nonterminal restored+records remain uncertain. Stronger same-owner claim evidence survives, conflicting+owners refuse reconciliation, and the preserved journal must match and remain+stable. Restore never releases a coordinator claim or interrupts active work.++Filesystem restore preserves the epoch/recovery files and maintenance-owner+subtree, including scoped and mixed-case requests. It does not yet invalidate+execution authority for filesystem-only identity/configuration restores.++The remaining owned sequence is concrete:++1. Coordinate pair rotation, unpairing, disablement, receiver identity changes+ and filesystem-only restore with durable invalidation before their file write.+ Offline disablement must remain possible without acknowledging a generation+ update that was not persisted. Stable slots/floors and deterministic lock order+ must cover every authority writer.+2. Add separately confirmed execution grants and receiver authentication/current+ grant checks. Planning grants keep their existing scope. Bind grant/preflight+ evidence to the non-rewound epoch and recheck expiry after waits.+3. Implement bounded adapter ownership handoff under the same authority lock and+ coordinator claim, with immediate fixed-input resource/source checks. Journal+ start plus DB rollback/disconnect stays uncertain and never retries launch.+4. Implement receiver-owned terminal cleanup verification and epoch-bound one-use+ settlement certificates. Re-read committed terminal evidence before reminting+ after restart/publication failure; restore/cutover fences invalidate old proofs.+5. Complete real disposable-Postgres pairing/revocation/expiry/handoff/certificate+ fixtures, then connect the receiver/sender UI and fixed adapters.++This slice does not close #10127 or enable execution. These are implementation+steps owned by the issue, with no additional live setup or creative approval gate.diff --git a/server/lib/README.md b/server/lib/README.mdindex 3e08cb7ac2..5041d2a42d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -27,6 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `maintenanceAdmission.js` | Durable machine-local workflow drain, cross-process admission permits, continuation ownership and stale-resume fencing. || `maintenanceExclusive.js` | Coordinator-owned exclusive ready claims, opaque fresh idle observations, durable ownership and verified settlement; internal only, no executor or peer authority. |+| `peerExecutionAuthority.js` | Non-rewound receiver execution epoch and restore-owner journal; default-deny on stale evidence or pending/conflicting recovery. No grants or adapters. || `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. || `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. || `codeAnimationAcceptance.js` | Code Animation production acceptance: splits run evidence into technical/visual/temporal/sound (unmeasured stays unverified), decides promotability, freezes source/audio/render hashes and detects stale acceptance. Pure. |diff --git a/server/lib/db/schema/README.md b/server/lib/db/schema/README.mdindex c0151ebbc4..dda0bbc440 100644--- a/server/lib/db/schema/README.md+++ b/server/lib/db/schema/README.md@@ -32,6 +32,7 @@ init-db.sql, each with a one-line reason.| `reviewQueueTriage.js` | `reviewQueueTriageDdl` | Machine-local Review Hub presentation markers — snooze, optional dismissal, and delivery generation keyed by canonical action identity || `cosAgentFeedback.js` | `cosAgentFeedbackDdl` | Durable machine-local references to completed manual CoS runs awaiting a rating (agent id + archive locator only) || `aiGraph.js` | `aiGraphDdl` | AI provider connection graph — connections, harness bindings, executable route bindings (machine-local) |+| `peerExecution.js` | `peerExecutionDdl` | Receiver-local permanent execution consumption and generation floors; no grants or federation || `catalog.js` | `catalogDdl`, `catalogUserTypesDdl`, `catalogPendingAppliesDdl` | Catalog scraps/ingredients/tags/media + user-defined types + receiver-local dependency inbox || `media.js` | `mediaDdl` | Creative-director / music-video projects, mood boards, media assets, and Code Animation jobs || `universes.js` | `universesDdl` | Universes, machine-local character voice profiles/renders, + universe run history |@@ -48,7 +49,7 @@ init-db.sql, each with a one-line reason.### Composer (`index.js`)-- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `aiGraph`).+- `buildUpgradeDdl()` → phase-1 list (`core` → `tribe` → `humanActivity` → `post` → `commissions` → `userActions` → `reviewQueueTriage` → `cosAgentFeedback` → `aiGraph` → `peerExecution`).- `buildCatalogDdl()` → phase-2 list (`catalog` → `media` → `catalogUserTypes` →`universes` → `library` → `pipeline` → `writersRoom` → `lora` → `privacy` → `stackerNews` → `x` →`beeper` → `audit` DDL → audit triggers → `syncFeed` DDL → sync-feed triggers).diff --git a/server/lib/index.js b/server/lib/index.jsindex b6c7736b0a..43858a2866 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -835,6 +835,7 @@ export * from './forgeMaintenanceTasks.js';export * from './maintenanceAdmission.js';export * from './maintenanceExclusive.js';+export * from './peerExecutionAuthority.js';export * as peerAdminValidation from './peerAdminValidation.js';export * from './speechMatch.js';diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.jsindex fc7af19843..12a15aa86a 100644--- a/server/services/backup.db.test.js+++ b/server/services/backup.db.test.js@@ -4,6 +4,7 @@ import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { basename, join } from 'node:path';import { spawnSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';import { checkHealth, ensureSchema, query, close, getServerMajorVersion, POOL_CONFIG } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';import { ownTestBodies } from '../lib/mockPathsDataRoot.js';@@ -64,6 +65,7 @@ let dumpPath;const folderId = 'restore-schema-folder-probe';const issueId = 'restore-schema-issue-probe';const personId = '00000000-0000-4000-8000-000000000862';+const executionHostId = randomUUID();const pendingMigration = '007-storyboard-scene-durable-ids.js';const connectionArgs = ['-h', POOL_CONFIG.host, '-p', String(POOL_CONFIG.port), '-U', POOL_CONFIG.user, '-d', POOL_CONFIG.database];const childEnv = { ...process.env, PGPASSWORD: POOL_CONFIG.password };@@ -82,6 +84,8 @@ afterAll(async () => {await query('DROP SCHEMA IF EXISTS restore_external CASCADE');await query('DROP TABLE IF EXISTS public.unexpected_restore_record');await ensureSchema({ force: true });+ await query('DELETE FROM peer_execution_operations WHERE host_instance_id = $1', [executionHostId]);+ await query('DELETE FROM peer_execution_generation_floors WHERE host_instance_id = $1', [executionHostId]);await query('DELETE FROM writers_room_folders WHERE id = $1', [folderId]);await query('DELETE FROM pipeline_issues WHERE id = $1', [issueId]);await query("DELETE FROM tribe_people WHERE id = $1 OR id = '00000000-0000-4000-8000-000000000863'", [personId]);@@ -143,7 +147,8 @@ describe.skipIf(!ready)('restore older database schema', () => {await mkdir(snapshotDir, { recursive: true });dumpPath = join(snapshotDir, 'portos-db.sql');const { binary } = await resolvePgDumpBinary(await getServerMajorVersion());- const dump = spawnSync(binary, [...connectionArgs, '--no-owner', '--no-acl', '--clean', '--if-exists', '-f', dumpPath], { env: childEnv, encoding: 'utf8' });+ const dump = spawnSync(binary, [...connectionArgs, '--no-owner', '--no-acl', '--clean', '--if-exists',+ '--exclude-table=peer_execution_operations', '--exclude-table=peer_execution_generation_floors', '-f', dumpPath], { env: childEnv, encoding: 'utf8' });expect(dump.status, dump.stderr).toBe(0);expect(await readFile(dumpPath, 'utf8')).toContain('COMMENT ON EXTENSION');@@ -199,6 +204,27 @@ describe.skipIf(!ready)('restore older database schema', () => {expect(await readFile(path, 'utf8')).toBe(sql);});+ it('preserves execution consumption and generation floors through a real dump without ledger tables', async () => {+ const { createPeerExecutionLedger } = await import('./peerExecutionLedger.js');+ const { withTransaction } = await import('../lib/db.js');+ const ledger = createPeerExecutionLedger({ db: { query, withTransaction }, dataDir: dataRoot.path });+ const epoch = (await ledger.initialize()).epoch;+ const input = { hostInstanceId: executionHostId, 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 saved = (await ledger.consume(input)).operation;+ await ledger.advanceGenerationFloor({ hostInstanceId: executionHostId, peerInstanceId: input.peerInstanceId,+ action: input.intent.action, generation: 3, executionEpoch: epoch });+ expect(await restore()).toMatchObject({ status: 'ok', dryRun: false });+ expect(await ledger.read(saved.operationId)).toMatchObject({ state: 'uncertain', fingerprint: saved.fingerprint });+ const current = ledger.authority.read();+ expect(current.epoch).not.toBe(epoch);+ await expect(ledger.consume(input)).rejects.toMatchObject({ code: 'PEER_EXECUTION_AUTHORITY_UNAVAILABLE' });+ await expect(ledger.consume({ ...input, executionEpoch: current.epoch })).rejects.toMatchObject({ code: 'PEER_EXECUTION_REPLAY_CONFLICT' });+ const { rows: [floor] } = await query('SELECT generation FROM peer_execution_generation_floors WHERE host_instance_id = $1', [executionHostId]);+ expect(Number(floor.generation)).toBe(3);+ });+// #9725: a committed replay whose repair fails keeps ordinary work fenced// with its receipt and ORIGINAL floors, and recovery repairs without replay.it('fences a committed replay whose migrations fail, then recovers from the receipt and original floors', async () => {diff --git a/server/services/peerExecutionLedger.db.test.js b/server/services/peerExecutionLedger.db.test.jsindex 6cee9a8859..b5d331383f 100644--- a/server/services/peerExecutionLedger.db.test.js+++ b/server/services/peerExecutionLedger.db.test.js@@ -37,6 +37,18 @@ afterEach(async () => {afterAll(async () => { if (health.connected) await close(); });describe.skipIf(!runDb)('receiver-local permanent execution consumption', () => {+ it('durably settles legacy empty committed-restore compatibility before downstream retries', async () => {+ const { createPeerExecutionRestore } = await import('./peerExecutionRestore.js');+ const hooks = createPeerExecutionRestore({ receiver: async () => ledger });+ fs.unlinkSync(join(directory, 'peer-execution-authority.json'));+ const id = randomUUID();+ const first = await hooks.finishPeerExecutionRestore(id);+ expect(first).toMatchObject({ phase: 'ready', settledRecoveryId: id });+ // Federation resync/generic-journal release can fail after this hook returns.+ await expect(Promise.reject(new Error('fixture downstream release failure'))).rejects.toThrow(/downstream/);+ const restarted = createPeerExecutionRestore({ receiver: async () => createPeerExecutionLedger({ db, dataDir: directory }) });+ expect(await restarted.finishPeerExecutionRestore(id)).toEqual(first);+ });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]);diff --git a/server/services/peerExecutionLedger.js b/server/services/peerExecutionLedger.jsindex 3a14a5cbd6..5948f9beeb 100644--- a/server/services/peerExecutionLedger.js+++ b/server/services/peerExecutionLedger.js@@ -69,7 +69,7 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE[binding.hostInstanceId, binding.peerInstanceId, binding.requestId]);return row ? fromRow(row) : null;};- const consume = raw => {+ const consume = async raw => {const binding = peerExecutionBindingSchema.parse(raw);authority.requireReady(binding.executionEpoch);return locked(async client => {@@ -104,7 +104,7 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEconst { rows: [row] } = await db.query('SELECT * FROM peer_execution_operations WHERE operation_id = $1', [id]);return row ? fromRow(row) : null;};- const advanceGenerationFloor = raw => {+ const advanceGenerationFloor = async raw => {const input = floorSchema.extend({ executionEpoch: uuid }).parse(raw);authority.requireReady(input.executionEpoch);return locked(async client => {diff --git a/server/services/peerExecutionRestore.js b/server/services/peerExecutionRestore.jsindex e78818f087..397dd1ebd0 100644--- a/server/services/peerExecutionRestore.js+++ b/server/services/peerExecutionRestore.js@@ -9,25 +9,35 @@ async function receiverLedger({ repairSchema = false } = {}) {return createPeerExecutionLedger({ db, dataDir: PATHS.data });}-export async function preparePeerExecutionRestore(id) {- const ledger = await receiverLedger();- await ledger.initialize();- return ledger.prepareRestore(id);+export function createPeerExecutionRestore({ receiver = receiverLedger } = {}) {+ const preparePeerExecutionRestore = async id => {+ const ledger = await receiver();+ await ledger.initialize();+ return ledger.prepareRestore(id);+ };+ const finishPeerExecutionRestore = async (id, { rolledBack = false } = {}) => {+ const ledger = await receiver({ repairSchema: rolledBack });+ const before = ledger.authority.read();+ const current = await ledger.initialize();+ // A generic restore started by a version predating the ledger has no capture.+ // initialize only permits this when BOTH new tables are empty. Durably settle+ // that empty baseline so downstream repair/release retries remain idempotent.+ if (!before) {+ await ledger.prepareRestore(id);+ return ledger.reconcileRestore(id);+ }+ if (rolledBack && current.phase === 'ready') return current;+ if (current.phase === 'capturing') {+ if (!rolledBack) throw executionAuthorityError('A committed restore lacks completed non-rewound execution capture.');+ // Generic recovery proved no replay session can commit and no receipt exists.+ // Capture the unchanged DB; never recapture a committed/unknown rewind.+ await ledger.prepareRestore(id);+ }+ return ledger.reconcileRestore(id);+ };+ return { preparePeerExecutionRestore, finishPeerExecutionRestore };}-export async function finishPeerExecutionRestore(id, { rolledBack = false } = {}) {- const ledger = await receiverLedger({ repairSchema: rolledBack });- const before = ledger.authority.read();- const current = await ledger.initialize();- // A generic restore started by a version predating the ledger has no capture.- // initialize only permits this when BOTH new tables are empty; no identity is lost.- if (!before) return current;- if (rolledBack && current.phase === 'ready') return current;- if (current.phase === 'capturing') {- if (!rolledBack) throw executionAuthorityError('A committed restore lacks completed non-rewound execution capture.');- // Generic recovery proved no replay session can commit and no receipt exists.- // Capture the unchanged DB; never recapture a committed/unknown rewind.- await ledger.prepareRestore(id);- }- return ledger.reconcileRestore(id);-}+const restoreHooks = createPeerExecutionRestore();+export const preparePeerExecutionRestore = restoreHooks.preparePeerExecutionRestore;+export const finishPeerExecutionRestore = restoreHooks.finishPeerExecutionRestore;