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]): add exclusive maintenance ownership and reconciliation (#10291)

[._.]/b2c174ed3969
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 5c840311c1..3ef26b6f7d 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -25,6 +25,16 @@ operated browser sessions and unrelated host apps do not count. Maintenance neve
cancels work, replays a paid submission, or enables a previously disabled policy.
Resume removes the identified hold only; a stale request cannot remove a later hold.
+The same journal also has one optional exclusive-maintenance ownership slot and
+one last settlement receipt. They fence admission/resume before the DB is usable,
+bind the current operation to its hold and verified evidence, and survive restart.
+They are coordinator authority, **not a parallel execution audit/replay ledger**:
+the last receipt is bounded recovery evidence, not permanent request consumption.
+The eventual peer execution ledger remains receiver-local `db-primary` (below).
+Neither a missing verifier nor timeout/restart releases an in-flight owner.
+Older strict journal readers reject the added fields and fail closed; reverting
+to one cannot resume a claimed hold. Old unclaimed v1 journals still read normally.
+
Operation age or a dead PID is not proof of saved output. On restart, the journal keeps
unresolved ownership; runner survivors reconnect to their existing operation. A lost
worker, failed save, or interrupted journal transaction needs recovery through its owning
diff --git a/docs/features/peer-administration.md b/docs/features/peer-administration.md
index 59cb64cbaa..ac32851fb3 100644
--- a/docs/features/peer-administration.md
+++ b/docs/features/peer-administration.md
@@ -82,13 +82,12 @@ without this protocol remain usable for their existing federation surfaces.
## Required before execution can be enabled
-- Integrate a **coordinator-owned exclusive claim**, bound to the maintenance
- hold ID/revision, with fresh trusted idle evidence and a resume fence. The
- maintenance admission foundation in PR #10122 does not yet provide that
- atomic claim. `status().state === 'ready'` followed by execution is unsafe;
- ordinary `admit` and a second independent lock are not substitutes. All
- admitted agents, provider work, renders and cleanup must settle naturally;
- no cancel, kill, forced pause or interruption fallback.
+- Wire the **coordinator-owned exclusive claim** into an authorized receiver
+ executor after the remaining requirements below are complete. The internal
+ primitive is implemented as described below; the planning protocol still
+ cannot acquire it. `status().state === 'ready'` followed by execution remains
+ unsafe; ordinary `admit` and a second independent lock are not substitutes.
+ All admitted work must settle naturally; no interruption fallback.
- Implement a durable, receiver-local operation ledger and fixed adapters for
the existing fork-aware PortOS update and PortOS-only restart. Recheck target
identity/version/capability and permission at dispatch. Persist request and
@@ -113,3 +112,62 @@ without this protocol remain usable for their existing federation surfaces.
These are dependencies, not permission to operate any peer. Enabling grants,
credentials, live settings, machine updates/restarts and model downloads remains
a separate later operator action.
+
+## Exclusive coordinator foundation (#10127, first slice)
+
+The coordinator now owns `observeIdle`, `claimReady`, `getExclusive`,
+`transitionExclusive` and `settleExclusive`. These are internal construction
+APIs, with no HTTP claim or recovery route, execution grant writer or adapter.
+Existing `planning-v1` grants, previews, receipts and execute refusal keep their
+current behavior. The claim's required `execution-v1` binding describes the
+future protocol; it neither creates nor verifies an execution grant today.
+
+`observeIdle` mints an opaque, process-local observation after all tracked work
+has settled. It is usable once, for at most five seconds, against the exact
+journal revision and hold ID/revision. Copies, wire objects, other coordinator
+instances' observations, backwards clock changes and intervening writes deny.
+`claimReady` rechecks that evidence and the hold under the same cross-process
+transaction used by admission and resume. A second claim or resume loses the
+race without changing ownership. Readiness displays a blocker while claimed.
+
+The bounded current ownership slot records the operation/request UUIDs, peer
+and receiver UUIDs, grant ID/generation, execution scope, pair binding digest,
+fixed intent, receiver version and preflight evidence digest. Its fingerprint
+binds those fields; changing either identity or intent cannot reconcile another
+operation. This is an ownership fence, not permission: the eventual receiver
+must authenticate and recheck current grants, pairing, capability and resource
+evidence before requesting a claim or recording a start.
+
+A reservation needs another fresh observation before it can move to
+`in-flight`. Start is durable **before** any future adapter side effect. From
+there only `awaiting-reconnect` or `uncertain` transitions are allowed; timeout,
+restart and reconnect never authorize another start. A newly observed survivor
+after start moves the claim to uncertain and invalidates stale reconciliation.
+No recovery kills or cancels that survivor.
+
+Only an unstarted reservation may be cancelled. A started/uncertain claim needs
+terminal persistence and cleanup evidence checked by a receiver-owned
+synchronous verifier supplied when constructing the coordinator. The default
+verifier denies every terminal release. Exact claim ID/revision/fingerprint
+comparison prevents stale settlement from releasing changed ownership. An
+interrupted publication retains the exclusive owner and fails closed. Settlement
+leaves the operator hold in place; explicit resume can then restore prior
+policies. The last settlement receipt makes its immediate replay idempotent;
+it is **not** permanent request replay history or the execution audit ledger.
+
+The remaining sequence stays owned by #10127, which this slice does not close:
+
+1. Add the receiver-local Postgres operation ledger and permanent request
+ idempotency/consumption records. Bind its operation identity and verified
+ terminal receipt to this coordinator slot; reconcile journal/DB crash gaps
+ without relaunching uncertain work.
+2. Add separately confirmed execution grants with generation and revocation,
+ sharing dispatch serialization so renewal/rotation during drain cannot
+ pass a stale authority snapshot. Planning grants never gain that scope.
+3. Connect fixed update/restart adapters, then catalog installation with exact
+ source/license/runtime/destination/staging/headroom/memory validation.
+4. Prove the complete receiver authorization, replay, revocation and crash
+ chain in fixtures; update receiver/sender UI before advertising execution.
+
+These are sequential implementation steps, not external blockers or authority
+to change live peers. Keep execution unavailable until all four are complete.
diff --git a/server/lib/README.md b/server/lib/README.md
index 5c1ea0fd6d..5df5f2cbef 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -26,6 +26,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `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. |
| `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/index.js b/server/lib/index.js
index af9abb6e82..b6c7736b0a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -834,6 +834,7 @@ export * from './sandboxDelegation.js';
export * from './forgeMaintenanceTasks.js';
export * from './maintenanceAdmission.js';
+export * from './maintenanceExclusive.js';
export * as peerAdminValidation from './peerAdminValidation.js';
export * from './speechMatch.js';
diff --git a/server/lib/maintenanceAdmission.exclusive.test.js b/server/lib/maintenanceAdmission.exclusive.test.js
new file mode 100644
index 0000000000..492006fcaf
--- /dev/null
+++ b/server/lib/maintenanceAdmission.exclusive.test.js
@@ -0,0 +1,254 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
+import * as fs from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createMaintenanceAdmission } from './maintenanceAdmission.js';
+
+const roots = [];
+const gate = options => {
+ const root = mkdtempSync(join(tmpdir(), 'exclusive-maintenance-'));
+ roots.push(root);
+ const admission = createMaintenanceAdmission(root, options);
+ const hold = admission.begin({ reason: 'Fixture maintenance', owner: 'Local operator' }).hold;
+ return { root, admission, hold };
+};
+const operation = () => ({ operationId: randomUUID(), requestId: randomUUID(), peerInstanceId: randomUUID(),
+ hostInstanceId: randomUUID(), grantId: randomUUID(), grantGeneration: 1, scope: 'execution-v1',
+ pairBinding: 'a'.repeat(64), intent: { action: 'portos.update' }, receiverVersion: '1.2.3', evidenceDigest: 'b'.repeat(64) });
+const expected = claim => ({ id: claim.id, revision: claim.revision, fingerprint: claim.fingerprint });
+const reserve = (admission, hold, op = operation()) => admission.claimReady({ id: hold.id, revision: hold.revision,
+ operation: op }, admission.observeIdle());
+const cancelled = { outcome: 'cancelled', receiptDigest: null };
+const terminal = { outcome: 'succeeded', receiptDigest: 'c'.repeat(64) };
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+
+describe('exclusive maintenance ownership through the coordinator', () => {
+ it('waits for saving and cleanup, without interrupting admitted work', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'exclusive-maintenance-'));
+ roots.push(root);
+ const admission = createMaintenanceAdmission(root);
+ const work = admission.admit('media', 'fixture-render');
+ const hold = admission.begin({ reason: 'Drain', owner: 'Operator' }).hold;
+ expect(() => admission.observeIdle()).toThrow(/cleanup/);
+ const cleanup = admission.admit('settlement', 'Saving', { parentId: work.id });
+ await work.finish();
+ expect(() => admission.observeIdle()).toThrow(/cleanup/);
+ await cleanup.finish();
+ const claim = reserve(admission, hold);
+ expect(admission.status()).toMatchObject({ state: 'draining', hold,
+ blockers: [{ kind: 'exclusive-maintenance', resource: claim.operation.operationId }] });
+ expect(admission.tryAdmit('agent', 'new')).toBeNull();
+ });
+
+ it('refuses forged, copied and foreign-process idle evidence without damaging the hold', () => {
+ const { root, admission, hold } = gate();
+ const input = { id: hold.id, revision: hold.revision, operation: operation() };
+ const proof = admission.observeIdle();
+ for (const invalid of [{}, { ...proof }, createMaintenanceAdmission(root).observeIdle()]) {
+ expect(() => admission.claimReady(input, invalid)).toThrow(/fresh coordinator/);
+ expect(admission.status().state).toBe('ready');
+ }
+ expect(admission.claimReady(input, proof).phase).toBe('reserved');
+ });
+
+ it('bounds observation age and rejects backwards clock changes', () => {
+ let time = 1_800_000_000_000;
+ const { admission, hold } = gate({ now: () => time });
+ const input = { id: hold.id, revision: hold.revision, operation: operation() };
+ const expired = admission.observeIdle();
+ time += 5001;
+ expect(() => admission.claimReady(input, expired)).toThrow(/fresh coordinator/);
+ const future = admission.observeIdle();
+ time--;
+ expect(() => admission.claimReady(input, future)).toThrow(/fresh coordinator/);
+ expect(admission.getExclusive()).toBeNull();
+ });
+
+ it('invalidates idle evidence after intervening work even when that work subsequently settles', async () => {
+ const { admission, hold } = gate();
+ const evidence = admission.observeIdle();
+ const recovered = admission.recoverOwned('runner', 'observed-survivor');
+ await recovered.finish();
+ expect(() => admission.claimReady({ id: hold.id, revision: hold.revision, operation: operation() }, evidence)).toThrow(/fresh coordinator/);
+ expect(reserve(admission, hold).phase).toBe('reserved');
+ });
+
+ it('linearizes competing claims and both orderings of the resume/claim race', () => {
+ const first = gate();
+ const other = createMaintenanceAdmission(first.root);
+ const secondProof = other.observeIdle();
+ const claim = reserve(first.admission, first.hold);
+ expect(() => other.claimReady({ id: first.hold.id, revision: first.hold.revision, operation: operation() }, secondProof)).toThrow(/exclusive owner/);
+ expect(() => other.resume({ id: first.hold.id, revision: first.hold.revision })).toThrow(/exclusive maintenance/);
+ first.admission.settleExclusive(expected(claim), cancelled);
+ expect(other.resume({ id: first.hold.id, revision: first.hold.revision }).state).toBe('normal');
+ const second = gate();
+ const evidence = second.admission.observeIdle();
+ second.admission.resume({ id: second.hold.id, revision: second.hold.revision });
+ expect(() => second.admission.claimReady({ id: second.hold.id, revision: second.hold.revision, operation: operation() }, evidence)).toThrow(/hold changed/);
+ expect(second.admission.getExclusive()).toBeNull();
+ });
+
+ it('requires execution identity and fixed inputs; planning grants and injected commands cannot reserve', () => {
+ const { admission, hold } = gate();
+ const op = operation();
+ for (const invalid of [{ ...op, scope: 'planning-v1' }, { ...op, grantGeneration: 0 },
+ { ...op, intent: { action: 'portos.update', command: 'arbitrary' } }, { ...op, pairBinding: '' },
+ { ...op, peerInstanceId: op.hostInstanceId }]) {
+ expect(() => reserve(admission, hold, invalid)).toThrow();
+ expect(admission.status().state).toBe('ready');
+ }
+ const claim = reserve(admission, hold, op);
+ expect(createMaintenanceAdmission(roots.at(-1)).getExclusive()).toEqual(claim);
+ claim.operation.intent.action = 'portos.restart';
+ expect(admission.getExclusive().operation.intent).toEqual(op.intent);
+ expect(admission.status()).not.toHaveProperty('exclusive');
+ expect(JSON.stringify(admission.status())).not.toContain(op.pairBinding);
+ });
+
+ it('requires a second fresh idle observation at start and cannot start twice', () => {
+ const { admission, hold } = gate();
+ const stale = admission.observeIdle();
+ const claim = reserve(admission, hold);
+ expect(() => admission.transitionExclusive(expected(claim), 'in-flight', stale)).toThrow(/fresh coordinator/);
+ const started = admission.transitionExclusive(expected(claim), 'in-flight', admission.observeIdle());
+ expect(started.revision).toBe(claim.revision + 1);
+ expect(() => admission.transitionExclusive(expected(started), 'in-flight', admission.observeIdle())).toThrow(/launched again/);
+ expect(() => admission.settleExclusive(expected(started), cancelled)).toThrow(/never started/);
+ expect(() => admission.settleExclusive(expected(started), terminal)).toThrow(/Verified terminal/);
+ expect(admission.getExclusive()).toEqual(started);
+ });
+
+ it('denies dispatch while a previously unobserved job finishes under a reservation', async () => {
+ const { admission, hold } = gate();
+ const claim = reserve(admission, hold);
+ const evidence = admission.observeIdle();
+ const work = admission.recoverOwned('media', 'late-survivor');
+ expect(() => admission.transitionExclusive(expected(claim), 'in-flight', evidence)).toThrow(/fresh coordinator/);
+ expect(() => admission.observeIdle()).toThrow(/cleanup/);
+ await work.finish();
+ expect(admission.transitionExclusive(expected(claim), 'in-flight', admission.observeIdle()).phase).toBe('in-flight');
+ });
+
+ it('retains reservation ownership on restart and can cancel only before a start record', () => {
+ const { root, admission, hold } = gate();
+ const claim = reserve(admission, hold);
+ const restarted = createMaintenanceAdmission(root);
+ expect(restarted.getExclusive()).toEqual(claim);
+ expect(() => restarted.resume({ id: hold.id, revision: hold.revision })).toThrow(/exclusive maintenance/);
+ const receipt = restarted.settleExclusive(expected(claim), cancelled);
+ expect(receipt.outcome).toBe('cancelled');
+ expect(restarted.status()).toMatchObject({ state: 'ready', hold });
+ expect(restarted.settleExclusive(expected(claim), cancelled)).toEqual(receipt);
+ expect(() => reserve(restarted, hold, claim.operation)).toThrow(/already settled/);
+ });
+
+ it('never treats restart, timeout or reconnect as completion or permission to relaunch', () => {
+ const { root, admission, hold } = gate();
+ const reserved = reserve(admission, hold);
+ const started = admission.transitionExclusive(expected(reserved), 'in-flight', admission.observeIdle());
+ const restarted = createMaintenanceAdmission(root);
+ expect(restarted.getExclusive()).toEqual(started);
+ const waiting = restarted.transitionExclusive(expected(started), 'awaiting-reconnect');
+ const uncertain = restarted.transitionExclusive(expected(waiting), 'uncertain');
+ expect(() => restarted.transitionExclusive(expected(uncertain), 'in-flight', restarted.observeIdle())).toThrow(/launched again/);
+ expect(() => restarted.resume({ id: hold.id, revision: hold.revision })).toThrow(/exclusive maintenance/);
+ expect(() => restarted.settleExclusive(expected(uncertain), terminal)).toThrow(/Verified terminal/);
+ expect(restarted.getExclusive().phase).toBe('uncertain');
+ });
+
+ it('invalidates reconciliation when observed survivor work changes an in-flight claim', async () => {
+ const { admission, hold } = gate({ verifyExclusiveReceipt: () => true });
+ const reserved = reserve(admission, hold);
+ const started = admission.transitionExclusive(expected(reserved), 'in-flight', admission.observeIdle());
+ const survivor = admission.recoverOwned('provider', 'survivor');
+ expect(admission.getExclusive()).toMatchObject({ phase: 'uncertain', revision: started.revision + 1 });
+ expect(() => admission.settleExclusive(expected(started), terminal)).toThrow(/ownership changed/);
+ await survivor.finish();
+ expect(admission.getExclusive().phase).toBe('uncertain');
+ });
+
+ it('reconciles only exact ownership with receiver-verified terminal persistence; hold stays until resume', () => {
+ let verified = false;
+ const { root, admission, hold } = gate({ verifyExclusiveReceipt: (claim, receipt) =>
+ verified && claim.operation.intent.action === 'portos.update' && receipt.receiptDigest === terminal.receiptDigest });
+ const reserved = reserve(admission, hold);
+ const started = admission.transitionExclusive(expected(reserved), 'in-flight', admission.observeIdle());
+ expect(() => admission.settleExclusive({ ...expected(started), fingerprint: 'f'.repeat(64) }, terminal)).toThrow(/ownership changed/);
+ expect(() => admission.settleExclusive(expected(started), terminal)).toThrow(/Verified terminal/);
+ verified = true;
+ const receipt = admission.settleExclusive(expected(started), terminal);
+ const restarted = createMaintenanceAdmission(root);
+ expect(restarted.getExclusive()).toBeNull();
+ expect(restarted.settleExclusive(expected(started), terminal)).toEqual(receipt);
+ expect(() => restarted.settleExclusive(expected(started), { outcome: 'failed', receiptDigest: terminal.receiptDigest })).toThrow(/ownership changed/);
+ expect(restarted.status()).toMatchObject({ state: 'ready', hold });
+ const next = reserve(restarted, hold);
+ expect(() => restarted.settleExclusive(expected(started), terminal)).toThrow(/ownership changed/);
+ expect(restarted.getExclusive()).toEqual(next);
+ });
+
+ it('refuses asynchronous verification without releasing ownership or losing its rejection', async () => {
+ for (const reason of [new Error('fixture verifier failure'), null, undefined]) {
+ const { admission, hold } = gate({ verifyExclusiveReceipt: () => Promise.reject(reason) });
+ const reserved = reserve(admission, hold);
+ const started = admission.transitionExclusive(expected(reserved), 'in-flight', admission.observeIdle());
+ expect(() => admission.settleExclusive(expected(started), terminal)).toThrow(/Verified terminal/);
+ await Promise.resolve();
+ expect(admission.getExclusive()).toEqual(started);
+ }
+ });
+
+ it('retries a transient synchronous verifier failure without poisoning the transaction lock', () => {
+ let fail = true;
+ const verifyExclusiveReceipt = () => {
+ if (fail) { fail = false; throw new Error('fixture verifier temporarily unavailable'); }
+ return true;
+ };
+ const { root, admission, hold } = gate({ verifyExclusiveReceipt });
+ const reserved = reserve(admission, hold);
+ const started = admission.transitionExclusive(expected(reserved), 'in-flight', admission.observeIdle());
+ expect(() => admission.settleExclusive(expected(started), terminal)).toThrow(/verification is unavailable/);
+ expect(admission.getExclusive()).toEqual(started);
+ const restarted = createMaintenanceAdmission(root, { verifyExclusiveReceipt });
+ expect(restarted.status().state).toBe('draining');
+ expect(restarted.settleExclusive(expected(started), terminal).outcome).toBe('succeeded');
+ expect(restarted.status()).toMatchObject({ state: 'ready', hold });
+ });
+
+ it('preserves exclusive ownership when receipt publication fails', () => {
+ let fail = false;
+ const io = { ...fs, renameSync: (...args) => {
+ if (fail) throw Object.assign(new Error('fixture disk failure'), { code: 'EIO' });
+ return fs.renameSync(...args);
+ } };
+ const { root, admission, hold } = gate({ io, verifyExclusiveReceipt: () => true });
+ const reserved = reserve(admission, hold);
+ const started = admission.transitionExclusive(expected(reserved), 'in-flight', admission.observeIdle());
+ fail = true;
+ expect(() => admission.settleExclusive(expected(started), terminal)).toThrow(/needs recovery/);
+ expect(admission.status().state).toBe('unavailable');
+ expect(JSON.parse(readFileSync(join(admission.directory, 'state.json'), 'utf8')).exclusive).toEqual(started);
+ expect(createMaintenanceAdmission(root).status().state).toBe('unavailable');
+ });
+
+ it('fails closed on damaged binding/hold records while retaining compatibility with older unclaimed journals', () => {
+ const { root, admission, hold } = gate();
+ const file = join(admission.directory, 'state.json');
+ const old = readFileSync(file, 'utf8');
+ expect(createMaintenanceAdmission(root).status().state).toBe('ready');
+ reserve(admission, hold);
+ const claimed = JSON.parse(readFileSync(file, 'utf8'));
+ claimed.exclusive.operation.grantGeneration++;
+ writeFileSync(file, JSON.stringify(claimed));
+ expect(createMaintenanceAdmission(root).status().state).toBe('unavailable');
+ claimed.exclusive.operation.grantGeneration--;
+ claimed.exclusive.holdId = randomUUID();
+ writeFileSync(file, JSON.stringify(claimed));
+ expect(createMaintenanceAdmission(root).status().state).toBe('unavailable');
+ writeFileSync(file, old);
+ expect(createMaintenanceAdmission(root).status().state).toBe('ready');
+ });
+});
diff --git a/server/lib/maintenanceAdmission.js b/server/lib/maintenanceAdmission.js
index b98b23b4c1..b116399f96 100644
--- a/server/lib/maintenanceAdmission.js
+++ b/server/lib/maintenanceAdmission.js
@@ -7,6 +7,7 @@ import { join } from 'node:path';
import { z } from 'zod';
import { PATHS } from './paths.js';
import { assertNotRealDataWrite } from './testDataIsolation.js';
+import { createMaintenanceExclusive, maintenanceExclusiveSchema, maintenanceExclusiveReceiptSchema } from './maintenanceExclusive.js';
const operationSchema = z.object({
id: z.string().uuid(), kind: z.string().min(1), resource: z.string().max(256),
@@ -19,7 +20,10 @@ const schema = z.object({
reason: z.string().min(1).max(500), owner: z.string().min(1).max(128), requestedAt: z.string().datetime(),
}).strict().nullable(),
operations: z.array(operationSchema),
-}).strict();
+ exclusive: maintenanceExclusiveSchema.nullable().optional(),
+ exclusiveReceipt: maintenanceExclusiveReceiptSchema.optional(),
+}).strict().refine(state => !state.exclusive || (state.hold?.id === state.exclusive.holdId
+ && state.hold?.revision === state.exclusive.holdRevision));
export const maintenanceBeginSchema = z.object({ reason: z.string().trim().min(1).max(500) }).strict();
export const maintenanceResumeSchema = z.object({ id: z.string().uuid(), revision: z.number().int().positive() }).strict();
const empty = () => ({ version: 1, revision: 0, hold: null, operations: [] });
@@ -33,7 +37,8 @@ function syncDirectory(path, io) {
try { io.fsyncSync(fd); } finally { io.closeSync(fd); }
}
-export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, assertWrite = assertNotRealDataWrite, makeId = randomUUID } = {}) {
+export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, assertWrite = assertNotRealDataWrite,
+ makeId = randomUUID, now = Date.now, verifyExclusiveReceipt = () => false } = {}) {
const directory = join(dataDir, 'workflow-maintenance');
const file = join(directory, 'state.json');
const lock = join(directory, 'transaction');
@@ -55,9 +60,11 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
} catch { throw unavailable(); }
};
const project = state => ({
- state: state.hold ? (state.operations.length ? 'draining' : 'ready') : 'normal',
+ state: state.hold ? (state.operations.length || state.exclusive ? 'draining' : 'ready') : 'normal',
revision: state.revision, hold: state.hold,
- blockers: state.operations.map(({ kind, resource, startedAt, pid, unsettled }) => ({ kind, resource, startedAt, pid, unsettled })),
+ blockers: [...state.operations.map(({ kind, resource, startedAt, pid, unsettled }) => ({ kind, resource, startedAt, pid, unsettled })),
+ ...(state.exclusive ? [{ kind: 'exclusive-maintenance', resource: state.exclusive.operation.operationId,
+ startedAt: state.exclusive.claimedAt, unsettled: state.exclusive.phase === 'uncertain' }] : [])],
scope: 'PortOS agents, mind turns, provider runs, media renders and scheduled shell/script work, through cleanup and saving. Unrelated host applications are outside this scope.',
});
const status = () => {
@@ -118,6 +125,8 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
} });
return result;
};
+ const exclusive = createMaintenanceExclusive({ transaction, read, lockExists: () => exists(lock), makeId, error, now,
+ verifyReceipt: verifyExclusiveReceipt });
const held = () => status().state !== 'normal';
const assertOpen = () => { if (held()) throw error(status().state === 'unavailable' ? 'MAINTENANCE_UNAVAILABLE' : 'MAINTENANCE_HELD'); };
const currentId = () => context.getStore() ?? null;
@@ -169,6 +178,7 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
const existing = state.operations.find(op => op.kind === kind && op.resource === resource);
if (existing) { recovery = recoverySnapshot(existing); return existing.id; }
const id = makeId();
+ exclusive.observeExistingWork(state);
state.operations.push({ id, kind, resource, pid: process.pid, startedAt: new Date().toISOString() });
return id;
});
@@ -238,11 +248,15 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
transaction(state => {
if (state.hold?.id !== expected.id || state.hold?.revision !== expected.revision)
throw error('MAINTENANCE_STALE', 'This maintenance hold changed. Refresh before resuming.');
+ if (state.exclusive)
+ throw error('MAINTENANCE_STALE', 'An exclusive maintenance operation owns this hold until verified reconciliation.');
state.hold = null;
});
return status();
};
- return { directory, status, held, assertOpen, admit, tryAdmit, recoverOwned, run, currentId, finish, finishResource, withResource, markResourceUnsettled, markCurrentUnsettled, continueSettlement, begin, resume, events };
+ const { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive } = exclusive;
+ return { directory, status, held, assertOpen, admit, tryAdmit, recoverOwned, run, currentId, finish, finishResource, withResource, markResourceUnsettled, markCurrentUnsettled, continueSettlement, begin, resume, events,
+ observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive };
}
// Resolve the configured data root on first use, after host/test setup.
diff --git a/server/lib/maintenanceExclusive.js b/server/lib/maintenanceExclusive.js
new file mode 100644
index 0000000000..9b6681d005
--- /dev/null
+++ b/server/lib/maintenanceExclusive.js
@@ -0,0 +1,130 @@
+/** Coordinator primitives only. No peer route, grant writer or executor uses these yet. */
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+import { peerAdminIntentSchema } from './peerAdminValidation.js';
+
+const uuid = z.string().uuid();
+const digest = z.string().regex(/^[a-f0-9]{64}$/);
+const operationSchema = z.object({
+ operationId: uuid, requestId: uuid, peerInstanceId: uuid, hostInstanceId: uuid,
+ grantId: uuid, grantGeneration: z.number().int().positive(), scope: z.literal('execution-v1'),
+ pairBinding: digest, intent: peerAdminIntentSchema,
+ receiverVersion: z.string().min(1).max(100), evidenceDigest: digest,
+}).strict().refine(value => value.peerInstanceId !== value.hostInstanceId);
+const fingerprint = operation => createHash('sha256').update(JSON.stringify(operation)).digest('hex');
+export const maintenanceExclusiveSchema = z.object({
+ id: uuid, revision: z.number().int().positive(), holdId: uuid, holdRevision: z.number().int().positive(),
+ operation: operationSchema, fingerprint: digest,
+ phase: z.enum(['reserved', 'in-flight', 'awaiting-reconnect', 'uncertain']),
+ claimedAt: z.string().datetime(),
+}).strict().refine(value => fingerprint(value.operation) === value.fingerprint);
+export const maintenanceExclusiveReceiptSchema = z.object({
+ id: uuid, revision: z.number().int().positive(), operationId: uuid, fingerprint: digest,
+ outcome: z.enum(['cancelled', 'succeeded', 'failed']), receiptDigest: digest.nullable(),
+ settledAt: z.string().datetime(),
+}).strict();
+const expectedSchema = z.object({ id: uuid, revision: z.number().int().positive(), fingerprint: digest }).strict();
+const claimSchema = z.object({ id: uuid, revision: z.number().int().positive(), operation: operationSchema }).strict();
+const receiptSchema = z.object({ outcome: z.enum(['cancelled', 'succeeded', 'failed']), receiptDigest: digest.nullable() }).strict();
+
+/** Shares the admission transaction; an independent executor lock cannot fence resume. */
+export function createMaintenanceExclusive({ transaction, read, lockExists, makeId, error, now, verifyReceipt }) {
+ const observations = new WeakMap();
+ const stale = message => { throw error('MAINTENANCE_STALE', message); };
+ const copy = value => value ? structuredClone(value) : null;
+ const current = (state, expected) => {
+ const claim = state.exclusive;
+ if (!claim || claim.id !== expected.id || claim.revision !== expected.revision || claim.fingerprint !== expected.fingerprint)
+ stale('The exclusive maintenance ownership changed. Reconcile its current record.');
+ return claim;
+ };
+ const checkIdle = (state, evidence) => {
+ const proof = observations.get(evidence);
+ observations.delete(evidence);
+ if (!proof || now() < proof.observedAt || now() - proof.observedAt > 5000
+ || proof.revision !== state.revision || proof.holdId !== state.hold?.id
+ || proof.holdRevision !== state.hold?.revision || state.operations.length)
+ stale('A fresh coordinator observation of settled work is required.');
+ };
+ const observeIdle = () => {
+ if (lockExists()) stale('Maintenance state is being changed.');
+ const state = read();
+ if (lockExists() || !state.hold || state.operations.length) stale('Admitted work must finish saving and cleanup first.');
+ const evidence = Object.freeze({});
+ observations.set(evidence, { revision: state.revision, holdId: state.hold.id,
+ holdRevision: state.hold.revision, observedAt: now() });
+ return evidence;
+ };
+ const claimReady = (input, evidence) => {
+ const expected = claimSchema.parse(input);
+ return transaction(state => {
+ if (state.hold?.id !== expected.id || state.hold?.revision !== expected.revision)
+ stale('This maintenance hold changed. Refresh before claiming it.');
+ if (state.exclusive) stale('This maintenance hold already has an exclusive owner.');
+ if (state.exclusiveReceipt?.operationId === expected.operation.operationId)
+ stale('This operation already settled. Its receipt cannot authorize another launch.');
+ checkIdle(state, evidence);
+ state.exclusive = { id: makeId(), revision: 1, holdId: expected.id, holdRevision: expected.revision,
+ operation: expected.operation, fingerprint: fingerprint(expected.operation), phase: 'reserved',
+ claimedAt: new Date(now()).toISOString() };
+ return copy(state.exclusive);
+ });
+ };
+ const getExclusive = () => {
+ if (lockExists()) stale('Maintenance state is being changed.');
+ return copy(read().exclusive);
+ };
+ const transitionExclusive = (input, phase, evidence) => {
+ const expected = expectedSchema.parse(input);
+ return transaction(state => {
+ const claim = current(state, expected);
+ const allowed = { reserved: ['in-flight', 'uncertain'], 'in-flight': ['awaiting-reconnect', 'uncertain'],
+ 'awaiting-reconnect': ['uncertain'], uncertain: [] };
+ if (!allowed[claim.phase].includes(phase)) stale('This operation cannot be launched again or moved backwards.');
+ if (phase === 'in-flight') checkIdle(state, evidence);
+ claim.phase = phase;
+ claim.revision++;
+ return copy(claim);
+ });
+ };
+ const settleExclusive = (input, receiptInput) => {
+ const expected = expectedSchema.parse(input);
+ const receipt = receiptSchema.parse(receiptInput);
+ return transaction(state => {
+ const previous = state.exclusiveReceipt;
+ if (!state.exclusive && previous?.id === expected.id && previous.revision === expected.revision
+ && previous.fingerprint === expected.fingerprint && previous.outcome === receipt.outcome
+ && previous.receiptDigest === receipt.receiptDigest) return copy(previous);
+ const claim = current(state, expected);
+ if (receipt.outcome === 'cancelled') {
+ if (claim.phase !== 'reserved' || receipt.receiptDigest !== null)
+ stale('Only a reservation that never started can be cancelled.');
+ } else if (claim.phase === 'reserved' || !receipt.receiptDigest) {
+ stale('Verified terminal persistence and cleanup evidence is required.');
+ } else {
+ // Verification is a receiver-owned synchronous adapter supplied at
+ // construction, never a caller-supplied boolean or a wire callback.
+ let verified;
+ try { verified = verifyReceipt(copy(claim), copy(receipt)); }
+ catch { stale('Terminal verification is unavailable. Ownership remains held; verification can be retried.'); }
+ if (verified && typeof verified.then === 'function') {
+ // An accidentally async verifier cannot release authority or leave
+ // a detached rejection unowned at this synchronous boundary.
+ Promise.resolve(verified).catch(() => console.error('❌ Exclusive maintenance verifier rejected; ownership remains held.'));
+ }
+ if (verified !== true) stale('Verified terminal persistence and cleanup evidence is required.');
+ }
+ state.exclusiveReceipt = { ...expected, operationId: claim.operation.operationId, ...receipt,
+ settledAt: new Date(now()).toISOString() };
+ state.exclusive = null;
+ return copy(state.exclusiveReceipt);
+ });
+ };
+ const observeExistingWork = state => {
+ if (state.exclusive && state.exclusive.phase !== 'reserved') {
+ state.exclusive.phase = 'uncertain';
+ state.exclusive.revision++;
+ }
+ };
+ return { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, observeExistingWork };
+}