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
Enable scoped peer maintenance with durable recovery
[._.]/ Adam Eivydb3ed16b05c7
diff --git a/client/src/components/instances/PeerAdministrationPanel.jsx b/client/src/components/instances/PeerAdministrationPanel.jsxindex e4891283a4..b13ef66b4c 100644--- a/client/src/components/instances/PeerAdministrationPanel.jsx+++ b/client/src/components/instances/PeerAdministrationPanel.jsx@@ -1,5 +1,8 @@-import { useEffect, useState } from 'react';-import { getPeerAdminSetup, savePeerAdminGrant, previewPeerAdministration } from '../../services/api';+import { useEffect, useRef, useState } from 'react';+import { getPeerAdminSetup, savePeerAdminGrant, previewPeerAdministration, savePeerExecutionGrant, previewPeerExecution, dispatchPeerExecution, getPeerExecutionStatus } from '../../services/api';+import { safeReadJsonStorage, safeWriteJsonStorage, safeReadStorage } from '../../lib/safeStorage';+import socket from '../../services/socket';+import PeerCatalogControls from './PeerCatalogControls';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import useMounted from '../../hooks/useMounted';import { timeUntil } from '../../utils/formatters';@@ -18,15 +21,30 @@ function Controls({ peer }) {const [error, setError] = useState('');const [preview, setPreview] = useState(null);const mounted = useMounted();+ const setupGeneration = useRef(0);+ const updateSetup = value => {+ setupGeneration.current += 1;+ setSetup(value);+ };useEffect(() => {if (!expanded) return;let active = true;+ const refresh = () => {+ const generation = ++setupGeneration.current;+ getPeerAdminSetup(peer.id, { silent: true }).then(value => {+ if (active && generation === setupGeneration.current) setSetup(value);+ }).catch(err => { if (active && generation === setupGeneration.current) setError(err.message); });+ };setError('');- getPeerAdminSetup(peer.id, { silent: true }).then(value => {- if (active) setSetup(value);- }).catch(err => { if (active) setError(err.message); });- return () => { active = false; };+ refresh();+ socket.on('peer-execution:changed', refresh);+ socket.on('connect', refresh);+ return () => {+ active = false;+ socket.off('peer-execution:changed', refresh);+ socket.off('connect', refresh);+ };}, [expanded, peer.id]);const save = async () => {@@ -38,10 +56,10 @@ function Controls({ peer }) {const value = await savePeerAdminGrant({peerId: peer.id, action: row.action,confirmedHostInstanceId: setup.hostInstanceId, confirmedPeerInstanceId: setup.peerInstanceId,- previousGrantId: row.grant?.id ?? null, expiresInMinutes: 60,+ previousGrantId: confirmation.grantId, expiresInMinutes: 60,allowPlanning: confirmation.allow,}, { silent: true });- if (mounted.current) { setSetup(value); setConfirmation(null); }+ if (mounted.current) { updateSetup(value); setConfirmation(null); }} catch (err) { if (mounted.current) setError(err.message); }finally { if (mounted.current) setBusy(false); }};@@ -61,10 +79,10 @@ function Controls({ peer }) {return <section className="border-t border-port-border pt-3 mt-3 text-sm"><button type="button" aria-expanded={expanded} disabled={busy}className="min-h-[44px] text-port-accent" onClick={() => { setExpanded(value => !value); setSetup(null); setConfirmation(null); }}>- Peer administration · planning only+ Peer administration</button>{expanded && <div className="space-y-3">- <p className="text-gray-400">Update, restart and model installation cannot execute in this version. Previews never queue work or interrupt active jobs. Execution needs the maintenance coordinator and a separate future permission.</p>+ <p className="text-gray-400">Planning previews never queue work or interrupt active jobs. Execution requires a separate local permission on the receiving host.</p>{error && <p role="alert" className="text-port-error">{error}</p>}{setup && <><p className="font-medium">Allow this peer to plan actions on this host</p>@@ -78,9 +96,9 @@ function Controls({ peer }) {<div className="flex gap-2"><button type="button" disabled={busy || !setup.paired}className="min-h-[44px] text-port-accent disabled:opacity-50"- onClick={() => setConfirmation({ action: row.action, allow: true })}>Review {row.active ? 'renewal' : 'grant'}</button>+ onClick={() => setConfirmation({ action: row.action, allow: true, grantId: row.grant?.id ?? null })}>Review {row.active ? 'renewal' : 'grant'}</button>{row.grant?.allowed && <button type="button" disabled={busy}- className="min-h-[44px] text-port-warning" onClick={() => setConfirmation({ action: row.action, allow: false })}>Revoke {LABELS[row.action]}</button>}+ className="min-h-[44px] text-port-warning" onClick={() => setConfirmation({ action: row.action, allow: false, grantId: row.grant?.id ?? null })}>Revoke {LABELS[row.action]}</button>}</div></div>)}{confirmation && <div className="rounded border border-port-border p-3 space-y-2">@@ -100,14 +118,115 @@ function Controls({ peer }) {<p>Planned only · not queued · not in flight</p><p>Request: {preview.plan.requestId}</p><p>Verified peer version: {preview.preflight.version}</p>- <p className="text-port-warning">Execution unavailable: an exclusive maintenance claim and completion reconciliation are required.</p>+ <p className="text-port-warning">This planning receipt cannot authorize execution. Use a separate execution preview below.</p></div>}</div>+ {setup.execution && <ExecutionControls peer={peer} setup={setup} onSetup={updateSetup} />}</>}</div>}</section>;}+function ExecutionControls({ peer, setup, onSetup }) {+ const execution = setup.execution;+ const [confirmation, setConfirmation] = useState(null);+ const [preflight, setPreflight] = useState(null);+ const storageKey = `peer-execution:${setup.hostInstanceId}:${peer.id}:${setup.peerInstanceId}`;+ const [request, setRequest] = useState(() => {+ const saved = safeReadJsonStorage(storageKey);+ return typeof saved?.requestId === 'string' ? saved : null;+ });+ const [busy, setBusy] = useState(false);+ const busyRef = useRef(false);+ const [error, setError] = useState('');+ const mounted = useMounted();+ const unresolved = request && !['succeeded', 'failed'].includes(request.state);+ const remember = (value, requireDurable = false) => {+ safeWriteJsonStorage(storageKey, value);+ if (requireDurable && safeReadStorage(storageKey) !== JSON.stringify(value)) {+ throw new Error('Execution was not submitted because this browser could not save its recovery record. Enable persistent browser storage and prepare the action again.');+ }+ if (mounted.current) setRequest(value);+ };+ const run = async work => {+ if (busyRef.current) return;+ busyRef.current = true;+ setBusy(true);+ setError('');+ await work().catch(err => { if (mounted.current) setError(err.message); });+ busyRef.current = false;+ if (mounted.current) setBusy(false);+ };+ const saveGrant = () => run(async () => {+ const row = execution.actions.find(entry => entry.action === confirmation.action);+ const value = await savePeerExecutionGrant({+ peerId: peer.id, action: row.action,+ confirmedHostInstanceId: setup.hostInstanceId, confirmedPeerInstanceId: setup.peerInstanceId,+ previousGrantId: confirmation.grantId, expiresInMinutes: 60,+ allowExecution: confirmation.allow, confirmation: 'execution-v1',+ }, { silent: true });+ if (mounted.current) { onSetup(value); setConfirmation(null); }+ });+ const prepare = intent => run(async () => {+ setPreflight(null);+ const value = await previewPeerExecution({ peerId: peer.id, intent }, { silent: true });+ if (mounted.current) setPreflight(value);+ });+ const dispatch = () => run(async () => {+ // Verify persistent storage BEFORE launch so recovery survives reloads and tab closure.+ const pending = { requestId: preflight.payload.requestId, state: 'uncertain' };+ remember(pending, true);+ const envelope = preflight;+ setPreflight(null);+ const value = await dispatchPeerExecution({ peerId: peer.id, preflight: envelope }, { silent: true });+ remember(value);+ });+ const checkStatus = () => run(async () => {+ const value = await getPeerExecutionStatus({ peerId: peer.id, requestId: request.requestId }, { silent: true });+ if (!Number.isSafeInteger(request.revision) || value.revision >= request.revision) remember(value);+ });++ return <div className="border-t border-port-border pt-3 space-y-3">+ <p className="font-medium">Allow this peer to execute on this host</p>+ <p className="text-gray-400">Execution permission is separate from planning and applies only to the receiving host and paired caller identities above. Each action is denied until explicitly granted here. Active work must drain before maintenance can run.</p>+ {execution.actions.map(row => <div key={row.action} className="flex flex-wrap items-center justify-between gap-2">+ <span>{LABELS[row.action]} — {row.active ? `Execution allowed · expires ${timeUntil(row.grant.expiresAt)}` : 'Execution denied'}</span>+ <div className="flex gap-2">+ <button type="button" disabled={busy || !setup.paired} className="min-h-[44px] text-port-accent disabled:opacity-50"+ onClick={() => setConfirmation({ action: row.action, allow: true, grantId: row.grant?.id ?? null })}>Review execution {row.active ? 'renewal' : 'grant'} for {LABELS[row.action]}</button>+ {row.grant?.allowed && <button type="button" disabled={busy} className="min-h-[44px] text-port-warning"+ onClick={() => setConfirmation({ action: row.action, allow: false, grantId: row.grant?.id ?? null })}>Revoke execution for {LABELS[row.action]}</button>}+ </div>+ </div>)}+ {confirmation && <div className="rounded border border-port-border p-3 space-y-2">+ <p>{confirmation.allow ? 'Allow' : 'Revoke'} {LABELS[confirmation.action]} execution by paired caller {setup.peerInstanceId} on receiving host {setup.hostInstanceId}{confirmation.allow ? ' for one hour' : ''}. This permission does not accept model licenses or start work by itself.</p>+ <ConfirmButtonPair tone="warning" confirmText={confirmation.allow ? 'Allow execution for one hour' : 'Confirm execution revocation'}+ onConfirm={saveGrant} onCancel={() => setConfirmation(null)} busy={busy} />+ </div>}+ <p className="font-medium">Execute on the remote peer</p>+ <p className="text-gray-400">The remote peer must separately grant this host the selected action. Review a fresh signed preview before submitting work.</p>+ {error && <p role="alert" className="text-port-error">{error}</p>}+ <div className="flex flex-wrap gap-3">+ {['portos.update', 'portos.restart'].map(action => <button key={action} type="button" disabled={busy || !setup.paired || unresolved}+ className="min-h-[44px] text-port-accent disabled:opacity-50" onClick={() => prepare({ action })}>Prepare {LABELS[action]} execution</button>)}+ </div>+ <PeerCatalogControls hostInstanceId={setup.hostInstanceId} disabled={busy || !setup.paired || Boolean(unresolved)} onPrepare={prepare} />+ {preflight && <div className="rounded border border-port-border p-3 space-y-2 break-all">+ <p>{LABELS[preflight.payload.intent.action]} on {preflight.payload.targetInstanceId}</p>+ {preflight.payload.intent.catalogKey && <p>Catalog entry: {preflight.payload.intent.catalogKey} · {preflight.payload.intent.backend}</p>}+ <p>Verified peer version: {preflight.payload.version} · Preview expires {timeUntil(preflight.payload.expiresAt)}</p>+ <p>Request: {preflight.payload.requestId}</p>+ <ConfirmButtonPair tone="warning" confirmText="Submit execution" onConfirm={dispatch} onCancel={() => setPreflight(null)} busy={busy} />+ </div>}+ {request && <div role="status" className="rounded bg-port-bg p-3 space-y-2 break-all">+ <p>Execution status: {request.state}</p><p>Request: {request.requestId}</p>+ {request.code && <p>{request.code}</p>}+ {unresolved && <p className="text-port-warning">Keep this request ID. Check status after reconnecting; an unavailable response does not mean the operation failed. Do not submit the action again.</p>}+ <button type="button" disabled={busy} className="min-h-[44px] text-port-accent disabled:opacity-50" onClick={checkStatus}>Check execution status</button>+ </div>}+ </div>;+}+export default function PeerAdministrationPanel({ peer }) {// Identity changes retire outstanding UI responses and confirmation state.return <Controls key={`${peer.id}:${peer.instanceId}:${peer.enabled}:${peer.hasSyncSecret}`} peer={peer} />;diff --git a/client/src/components/instances/PeerAdministrationPanel.test.jsx b/client/src/components/instances/PeerAdministrationPanel.test.jsxindex 8f8a98ec92..159dddf196 100644--- a/client/src/components/instances/PeerAdministrationPanel.test.jsx+++ b/client/src/components/instances/PeerAdministrationPanel.test.jsx@@ -1,9 +1,14 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import socket from '../../services/socket';+import * as storage from '../../lib/safeStorage';+import { safeRemoveStorage, safeRemoveSession } from '../../lib/safeStorage';import PeerAdministrationPanel from './PeerAdministrationPanel';-import { getPeerAdminSetup, savePeerAdminGrant, previewPeerAdministration } from '../../services/api';+import { getPeerAdminSetup, savePeerAdminGrant, previewPeerAdministration, savePeerExecutionGrant, previewPeerExecution, dispatchPeerExecution, getPeerExecutionStatus, getPeerCatalogReviews } from '../../services/api';+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));vi.mock('../../services/api', () => ({getPeerAdminSetup: vi.fn(), savePeerAdminGrant: vi.fn(), previewPeerAdministration: vi.fn(),+ savePeerExecutionGrant: vi.fn(), previewPeerExecution: vi.fn(), dispatchPeerExecution: vi.fn(), getPeerExecutionStatus: vi.fn(), getPeerCatalogReviews: vi.fn(),}));const peer = { id: 'peer-example', instanceId: '11111111-1111-4111-8111-111111111111', enabled: true, hasSyncSecret: true };const setup = {@@ -11,7 +16,12 @@ const setup = {paired: true, executionSupported: false,actions: ['portos.update', 'portos.restart', 'catalog.install'].map(action => ({ action, active: false, grant: null })),};-beforeEach(() => { vi.clearAllMocks(); getPeerAdminSetup.mockResolvedValue(setup); });+beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ safeRemoveStorage(`peer-execution:${setup.hostInstanceId}:${peer.id}:${setup.peerInstanceId}`);+ getPeerAdminSetup.mockResolvedValue(setup);+});describe('planning-only peer administration', () => {it('requires review and explicit confirmation and binds the save to both displayed identities', async () => {@@ -67,3 +77,113 @@ describe('planning-only peer administration', () => {expect(savePeerAdminGrant).not.toHaveBeenCalled();});});+++describe('separate peer execution controls', () => {+ const executionSetup = { ...setup, execution: { scope: 'execution-v1', actions: setup.actions } };+ const envelope = { signature: 'signed-fixture', payload: {+ requestId: '33333333-3333-4333-8333-333333333333', intent: { action: 'portos.restart' },+ targetInstanceId: peer.instanceId, version: '1.0.0', expiresAt: Date.now() + 60_000,+ } };+ const open = async () => {+ getPeerAdminSetup.mockResolvedValue(executionSetup);+ const view = render(<PeerAdministrationPanel peer={peer} />);+ fireEvent.click(screen.getByRole('button', { name: /Peer administration/ }));+ await screen.findByText('Allow this peer to execute on this host');+ return view;+ };++ it('requires a distinct execution confirmation bound to both identities and the selected action', async () => {+ savePeerExecutionGrant.mockResolvedValue(executionSetup);+ await open();+ fireEvent.click(screen.getByRole('button', { name: 'Review execution grant for PortOS restart' }));+ expect(savePeerExecutionGrant).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Allow execution for one hour' }));+ await waitFor(() => expect(savePeerExecutionGrant).toHaveBeenCalledWith({+ peerId: peer.id, action: 'portos.restart', confirmedHostInstanceId: setup.hostInstanceId,+ confirmedPeerInstanceId: peer.instanceId, previousGrantId: null, expiresInMinutes: 60,+ allowExecution: true, confirmation: 'execution-v1',+ }, { silent: true }));+ expect(dispatchPeerExecution).not.toHaveBeenCalled();+ expect(savePeerAdminGrant).not.toHaveBeenCalled();+ });++ it('passes a selected catalog intent into signed preview and retains the exact selection for dispatch', async () => {+ const intent = { action: 'catalog.install', backend: 'lmstudio', catalogKey: 'example-model' };+ const preview = { ...envelope, payload: { ...envelope.payload, intent } };+ getPeerCatalogReviews.mockResolvedValue({ candidates: [{ backend: 'lmstudio', catalogKey: 'example-model', name: 'Example model' }], reviews: [] });+ previewPeerExecution.mockResolvedValue(preview);+ dispatchPeerExecution.mockResolvedValue({ requestId: preview.payload.requestId, state: 'draining', revision: 1 });+ await open();+ fireEvent.click(screen.getByRole('button', { name: 'Choose a catalog model' }));+ fireEvent.change(await screen.findByLabelText('Catalog model (LM Studio)'), { target: { value: 'example-model' } });+ fireEvent.click(screen.getByRole('button', { name: 'Prepare catalog installation on remote peer' }));+ await screen.findByText('Catalog entry: example-model · lmstudio');+ expect(previewPeerExecution).toHaveBeenCalledWith({ peerId: peer.id, intent }, { silent: true });+ expect(dispatchPeerExecution).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Submit execution' }));+ await screen.findByText('Execution status: draining');+ expect(dispatchPeerExecution).toHaveBeenCalledWith({ peerId: peer.id, preflight: preview }, { silent: true });+ });++ it.each(['unavailable', 'mismatched'])('refuses dispatch when recovery storage readback is %s', async failure => {+ previewPeerExecution.mockResolvedValue(envelope);+ await open();+ fireEvent.click(screen.getByRole('button', { name: 'Prepare PortOS restart execution' }));+ await screen.findByRole('button', { name: 'Submit execution' });+ vi.spyOn(storage, 'safeWriteJsonStorage').mockImplementationOnce(key => {+ if (failure === 'mismatched') storage.safeWriteStorage(key, JSON.stringify({ requestId: envelope.payload.requestId, state: 'failed' }));+ });+ fireEvent.click(screen.getByRole('button', { name: 'Submit execution' }));+ await screen.findByText(/Execution was not submitted because this browser could not save its recovery record/);+ expect(dispatchPeerExecution).not.toHaveBeenCalled();+ expect(screen.queryByText('Execution status: uncertain')).toBeNull();+ });++ it('retains an uncertain launch across tab closure and recovers with status without a second dispatch', async () => {+ previewPeerExecution.mockResolvedValue(envelope);+ dispatchPeerExecution.mockRejectedValue(new Error('Response timed out'));+ getPeerExecutionStatus.mockResolvedValue({ requestId: envelope.payload.requestId, state: 'succeeded', revision: 3, code: null });+ const view = await open();+ fireEvent.click(screen.getByRole('button', { name: 'Prepare PortOS restart execution' }));+ await screen.findByRole('button', { name: 'Submit execution' });+ expect(dispatchPeerExecution).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Submit execution' }));+ await screen.findByText('Response timed out');+ expect(screen.getByText('Execution status: uncertain')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Submit execution' })).toBeNull();+ expect(screen.getByRole('button', { name: 'Prepare PortOS restart execution' }).disabled).toBe(true);+ view.unmount();+ safeRemoveSession(`peer-execution:${setup.hostInstanceId}:${peer.id}:${setup.peerInstanceId}`);+ await open();+ expect(screen.getByText('Execution status: uncertain')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Check execution status' }));+ await screen.findByText('Execution status: succeeded');+ expect(dispatchPeerExecution).toHaveBeenCalledTimes(1);+ expect(dispatchPeerExecution).toHaveBeenCalledWith({ peerId: peer.id, preflight: envelope }, { silent: true });+ expect(getPeerExecutionStatus).toHaveBeenCalledWith({ peerId: peer.id, requestId: envelope.payload.requestId }, { silent: true });+ });+});+++it('refreshes local execution grants on change and reconnect, retaining the reviewed grant identity', async () => {+ const execution = { scope: 'execution-v1', actions: setup.actions };+ getPeerAdminSetup.mockResolvedValue({ ...setup, execution });+ savePeerExecutionGrant.mockRejectedValue(new Error('Refresh the changed grant'));+ const view = render(<PeerAdministrationPanel peer={peer} />);+ fireEvent.click(screen.getByRole('button', { name: /Peer administration/ }));+ fireEvent.click(await screen.findByRole('button', { name: 'Review execution grant for PortOS restart' }));+ const refresh = socket.on.mock.calls.find(([event]) => event === 'peer-execution:changed')[1];+ getPeerAdminSetup.mockResolvedValue({ ...setup, execution: { ...execution, actions: execution.actions.map(row => ({+ ...row, active: true, grant: { id: 'new-grant', allowed: true, expiresAt: Date.now() + 60_000 },+ })) } });+ await act(async () => { refresh(); });+ await screen.findByRole('button', { name: 'Review execution renewal for PortOS restart' });+ fireEvent.click(screen.getByRole('button', { name: 'Allow execution for one hour' }));+ await screen.findByText('Refresh the changed grant');+ expect(savePeerExecutionGrant.mock.calls[0][0].previousGrantId).toBeNull();+ expect(socket.on).toHaveBeenCalledWith('connect', refresh);+ view.unmount();+ expect(socket.off).toHaveBeenCalledWith('peer-execution:changed', refresh);+ expect(socket.off).toHaveBeenCalledWith('connect', refresh);+});diff --git a/client/src/components/instances/PeerCatalogControls.jsx b/client/src/components/instances/PeerCatalogControls.jsxnew file mode 100644index 0000000000..e08a9651fa--- /dev/null+++ b/client/src/components/instances/PeerCatalogControls.jsx@@ -0,0 +1,142 @@+import { useEffect, useId, useRef, useState } from 'react';+import { getPeerCatalogReview, getPeerCatalogReviews, savePeerCatalogReview } from '../../services/api';+import useMounted from '../../hooks/useMounted';+import { formatBytes } from '../../utils/formatters';++const FIELDS = [+ { key: 'sourceRevision', label: 'Pinned source commit', pattern: '[a-f0-9]{40}', hint: 'Full 40-character commit SHA from the source repository.' },+ { key: 'fileName', label: 'GGUF file name', pattern: '[A-Za-z0-9][A-Za-z0-9._-]*\\.gguf', hint: 'One GGUF file name only, without a directory or URL.' },+ { key: 'artifactDigest', label: 'Artifact SHA-256', pattern: '[a-f0-9]{64}', hint: 'Exact 64-character digest of the reviewed file.' },+ { key: 'downloadBytes', label: 'Exact download size (bytes)', type: 'number', hint: 'The exact file size from the pinned source.' },+ { key: 'license', label: 'Reviewed license', maxLength: 256, hint: 'License identifier or name verified at the pinned source.' },+ { key: 'runtimeMemoryBytes', label: 'Required runtime memory (bytes)', type: 'number', hint: 'Reviewed memory requirement, including runtime overhead; at least the download size.' },+];++function LocalReview({ catalogKey, hostInstanceId, onSaved }) {+ const [observation, setObservation] = useState(null);+ const [error, setError] = useState('');+ const [busy, setBusy] = useState(false);+ const saving = useRef(false);+ const [fields, setFields] = useState({});+ const [sourceReviewed, setSourceReviewed] = useState(false);+ const [runtimeReviewed, setRuntimeReviewed] = useState(false);+ const mounted = useMounted();+ const id = useId();+ useEffect(() => {+ let active = true;+ getPeerCatalogReview('lmstudio', catalogKey, { silent: true }).then(value => {+ if (active) setObservation(value);+ }).catch(err => { if (active) setError(err.message); });+ return () => { active = false; };+ }, [catalogKey]);++ const save = async event => {+ event.preventDefault();+ if (saving.current || !observation || !sourceReviewed || !runtimeReviewed) return;+ const downloadBytes = Number(fields.downloadBytes);+ const runtimeMemoryBytes = Number(fields.runtimeMemoryBytes);+ if (!Number.isSafeInteger(downloadBytes) || downloadBytes <= 0+ || !Number.isSafeInteger(runtimeMemoryBytes) || runtimeMemoryBytes < downloadBytes) {+ setError('Use positive whole byte counts; runtime memory must cover at least the download size.');+ return;+ }+ saving.current = true;+ setBusy(true);+ setError('');+ await savePeerCatalogReview({+ backend: 'lmstudio', catalogKey,+ sourceRevision: fields.sourceRevision, fileName: fields.fileName, artifactDigest: fields.artifactDigest,+ downloadBytes, license: fields.license, runtimeMemoryBytes, runtime: observation.runtime,+ sourceLicenseReviewed: true, runtimeCompatibilityReviewed: true,+ }, { silent: true }).then(value => {+ if (mounted.current) onSaved(value);+ }).catch(err => { if (mounted.current) setError(err.message); });+ saving.current = false;+ if (mounted.current) setBusy(false);+ };++ return <div className="rounded border border-port-border p-3 space-y-3">+ <p className="font-medium">Review installation on this host</p>+ <p className="text-gray-400 break-all">Receiving host: {hostInstanceId}. This review applies only here. To install on the remote peer, complete its review there.</p>+ {error && <p role="alert" className="text-port-error">{error}</p>}+ {!observation && !error && <p role="status">Reading local catalog and runtime…</p>}+ {observation && <form onSubmit={save} className="space-y-3">+ <dl className="text-xs text-gray-400 break-all space-y-1">+ <dt>Catalog source</dt><dd><a href={`https://huggingface.co/${observation.sourceRepo}`} target="_blank" rel="noreferrer" className="text-port-accent">{observation.sourceRepo}</a></dd>+ <dt>Observed local runtime fingerprint</dt><dd>{observation.runtime}</dd>+ <dt>Managed models folder</dt><dd>{observation.modelsDirectory || 'Receiver-configured models folder'}</dd>+ <dt>Managed destination fingerprint</dt><dd>{observation.destinationDigest}</dd>+ </dl>+ <p className="text-gray-400">Inspect the pinned source, file digest, license and compatibility with this installed runtime before recording the review. Saving does not download or execute a model.</p>+ <div className="grid gap-3 sm:grid-cols-2">+ {FIELDS.map(field => <div key={field.key} className="min-w-0">+ <label htmlFor={`${id}-${field.key}`} className="block text-sm">{field.label}</label>+ <input id={`${id}-${field.key}`} type={field.type || 'text'} required disabled={busy}+ pattern={field.pattern} maxLength={field.maxLength} min={field.type === 'number' ? 1 : undefined}+ step={field.type === 'number' ? 1 : undefined} value={fields[field.key] || ''}+ onChange={event => setFields(current => ({ ...current, [field.key]: event.target.value }))}+ className="w-full min-w-0 rounded border border-port-border bg-port-bg p-2" />+ <p className="text-xs text-gray-400">{field.hint}</p>+ </div>)}+ </div>+ <div className="flex items-start gap-2">+ <input id={`${id}-source`} type="checkbox" checked={sourceReviewed} disabled={busy} onChange={event => setSourceReviewed(event.target.checked)} />+ <label htmlFor={`${id}-source`}>I reviewed this pinned source, exact artifact and license for installation on this host.</label>+ </div>+ <div className="flex items-start gap-2">+ <input id={`${id}-runtime`} type="checkbox" checked={runtimeReviewed} disabled={busy} onChange={event => setRuntimeReviewed(event.target.checked)} />+ <label htmlFor={`${id}-runtime`}>I reviewed compatibility and memory requirements against the observed local runtime.</label>+ </div>+ <button type="submit" disabled={busy || !sourceReviewed || !runtimeReviewed}+ className="min-h-[44px] text-port-accent disabled:opacity-50">Save local catalog review</button>+ </form>}+ </div>;+}++export default function PeerCatalogControls({ hostInstanceId, disabled, onPrepare }) {+ const [expanded, setExpanded] = useState(false);+ const [catalog, setCatalog] = useState(null);+ const [selected, setSelected] = useState('');+ const [reviewing, setReviewing] = useState(false);+ const [error, setError] = useState('');+ const id = useId();+ useEffect(() => {+ if (!expanded) return;+ let active = true;+ getPeerCatalogReviews({ silent: true }).then(value => {+ if (active) setCatalog(value);+ }).catch(err => { if (active) setError(err.message); });+ return () => { active = false; };+ }, [expanded]);+ const review = catalog?.reviews.find(entry => entry.backend === 'lmstudio' && entry.catalogKey === selected);+ return <div className="space-y-3">+ <button type="button" className="min-h-[44px] text-port-accent" aria-expanded={expanded}+ onClick={() => setExpanded(value => !value)}>Choose a catalog model</button>+ {expanded && <>+ <p className="text-gray-400">Supported LM Studio catalog entries use one pinned GGUF artifact. The receiving host must have its own reviewed source, license and runtime requirements.</p>+ {error && <p role="alert" className="text-port-error">{error}</p>}+ {catalog && <>+ <label htmlFor={`${id}-catalog`} className="block">Catalog model (LM Studio)</label>+ <select id={`${id}-catalog`} value={selected} disabled={disabled}+ className="w-full max-w-lg rounded border border-port-border bg-port-bg p-2"+ onChange={event => { setSelected(event.target.value); setReviewing(false); }}>+ <option value="">Choose a catalog entry</option>+ {catalog.candidates.map(entry => <option key={entry.catalogKey} value={entry.catalogKey}>{entry.name}</option>)}+ </select>+ {selected && <>+ {review && <p role="status" className="text-xs text-gray-400 break-all">Local review saved: {review.fileName} · {formatBytes(review.downloadBytes)} · {review.license} · commit {review.sourceRevision}</p>}+ <div className="flex flex-wrap gap-3">+ <button type="button" disabled={disabled} className="min-h-[44px] text-port-accent disabled:opacity-50"+ onClick={() => setReviewing(value => !value)}>Review catalog source on this host</button>+ <button type="button" disabled={disabled} className="min-h-[44px] text-port-accent disabled:opacity-50"+ onClick={() => onPrepare({ action: 'catalog.install', backend: 'lmstudio', catalogKey: selected })}>Prepare catalog installation on remote peer</button>+ </div>+ {reviewing && <LocalReview key={selected} catalogKey={selected} hostInstanceId={hostInstanceId} onSaved={value => {+ setCatalog(current => ({ ...current, reviews: [...current.reviews.filter(entry => !(entry.backend === value.backend && entry.catalogKey === value.catalogKey)), value] }));+ setReviewing(false);+ }} />}+ </>}+ </>}+ </>}+ </div>;+}diff --git a/client/src/components/instances/PeerCatalogControls.test.jsx b/client/src/components/instances/PeerCatalogControls.test.jsxnew file mode 100644index 0000000000..d79fa3435f--- /dev/null+++ b/client/src/components/instances/PeerCatalogControls.test.jsx@@ -0,0 +1,81 @@+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import PeerCatalogControls from './PeerCatalogControls';+import { getPeerCatalogReview, getPeerCatalogReviews, savePeerCatalogReview } from '../../services/api';+vi.mock('../../services/api', () => ({+ getPeerCatalogReview: vi.fn(), getPeerCatalogReviews: vi.fn(), savePeerCatalogReview: vi.fn(),+}));+const hostInstanceId = '11111111-1111-4111-8111-111111111111';+const candidates = [{ backend: 'lmstudio', catalogKey: 'example-model', name: 'Example model' },+ { backend: 'lmstudio', catalogKey: 'second-model', name: 'Second model' }];+const observation = { backend: 'lmstudio', catalogKey: 'example-model', name: 'Example model',+ sourceRepo: 'example/model-GGUF', runtime: 'observed-runtime-fingerprint', destinationDigest: 'destination-fingerprint' };+const fields = {+ 'Pinned source commit': 'a'.repeat(40), 'GGUF file name': 'example-q4.gguf',+ 'Artifact SHA-256': 'b'.repeat(64), 'Exact download size (bytes)': '1024',+ 'Reviewed license': 'MIT', 'Required runtime memory (bytes)': '2048',+};+beforeEach(() => {+ vi.clearAllMocks();+ getPeerCatalogReviews.mockResolvedValue({ candidates, reviews: [] });+ getPeerCatalogReview.mockResolvedValue(observation);+});+async function choose(onPrepare = vi.fn()) {+ render(<PeerCatalogControls hostInstanceId={hostInstanceId} disabled={false} onPrepare={onPrepare} />);+ expect(getPeerCatalogReviews).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Choose a catalog model' }));+ fireEvent.change(await screen.findByLabelText('Catalog model (LM Studio)'), { target: { value: 'example-model' } });+ return onPrepare;+}++describe('operator catalog review', () => {+ it('records explicit source and runtime review against the exact receiver observation without executing', async () => {+ savePeerCatalogReview.mockImplementation(async value => value);+ const onPrepare = await choose();+ fireEvent.click(screen.getByRole('button', { name: 'Review catalog source on this host' }));+ await screen.findByText(observation.runtime);+ expect(screen.getByRole('link', { name: observation.sourceRepo }).getAttribute('href')).toBe('https://huggingface.co/example/model-GGUF');+ const save = screen.getByRole('button', { name: 'Save local catalog review' });+ expect(save.disabled).toBe(true);+ for (const [label, value] of Object.entries(fields)) {+ expect(screen.getByLabelText(label).value).toBe('');+ fireEvent.change(screen.getByLabelText(label), { target: { value } });+ }+ fireEvent.click(screen.getByLabelText(/I reviewed this pinned source/));+ expect(save.disabled).toBe(true);+ fireEvent.click(screen.getByLabelText(/I reviewed compatibility/));+ fireEvent.click(save);+ await screen.findByText(/Local review saved: example-q4.gguf/);+ expect(savePeerCatalogReview).toHaveBeenCalledWith({+ backend: 'lmstudio', catalogKey: 'example-model', sourceRevision: fields['Pinned source commit'],+ fileName: 'example-q4.gguf', artifactDigest: fields['Artifact SHA-256'], downloadBytes: 1024,+ license: 'MIT', runtimeMemoryBytes: 2048, runtime: observation.runtime,+ sourceLicenseReviewed: true, runtimeCompatibilityReviewed: true,+ }, { silent: true });+ expect(onPrepare).not.toHaveBeenCalled();+ });++ it('prepares only the catalog intent for the peer, without borrowing a local review or accepting its license', async () => {+ const onPrepare = await choose();+ fireEvent.click(screen.getByRole('button', { name: 'Prepare catalog installation on remote peer' }));+ expect(onPrepare).toHaveBeenCalledWith({ action: 'catalog.install', backend: 'lmstudio', catalogKey: 'example-model' });+ expect(getPeerCatalogReview).not.toHaveBeenCalled();+ expect(savePeerCatalogReview).not.toHaveBeenCalled();+ });++ it('drops a stale runtime observation and requires a new review when the selected model changes', async () => {+ let resolveOld;+ getPeerCatalogReview.mockReturnValueOnce(new Promise(resolve => { resolveOld = resolve; }))+ .mockResolvedValueOnce({ ...observation, catalogKey: 'second-model', runtime: 'second-runtime' });+ await choose();+ fireEvent.click(screen.getByRole('button', { name: 'Review catalog source on this host' }));+ await waitFor(() => expect(getPeerCatalogReview).toHaveBeenCalledTimes(1));+ fireEvent.change(screen.getByLabelText('Catalog model (LM Studio)'), { target: { value: 'second-model' } });+ fireEvent.click(screen.getByRole('button', { name: 'Review catalog source on this host' }));+ await screen.findByText('second-runtime');+ await act(async () => resolveOld(observation));+ expect(screen.queryByText(observation.runtime)).toBeNull();+ expect(screen.getByRole('button', { name: 'Save local catalog review' }).disabled).toBe(true);+ expect(savePeerCatalogReview).not.toHaveBeenCalled();+ });+});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex d64906c540..0e2c1e2888 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -627,3 +627,11 @@ export const resumeMaintenance = (hold, options = {}) => request('/system/mainteexport const getPeerAdminSetup = (peerId, options) => request(`/peer-administration/peers/${encodeURIComponent(peerId)}`, options);export const savePeerAdminGrant = (data, options) => request('/peer-administration/grants', { ...options, method: 'POST', body: JSON.stringify(data) });export const previewPeerAdministration = (data, options) => request('/peer-administration/preview', { ...options, method: 'POST', body: JSON.stringify(data) });++export const savePeerExecutionGrant = (data, options) => request('/peer-administration/execution-grants', { ...options, method: 'POST', body: JSON.stringify(data) });+export const previewPeerExecution = (data, options) => request('/peer-administration/execution-preview', { ...options, method: 'POST', body: JSON.stringify(data) });+export const dispatchPeerExecution = (data, options) => request('/peer-administration/execution-dispatch', { ...options, method: 'POST', body: JSON.stringify(data) });+export const getPeerExecutionStatus = (data, options) => request('/peer-administration/execution-status', { ...options, method: 'POST', body: JSON.stringify(data) });+export const getPeerCatalogReviews = (options) => request('/peer-administration/catalog-reviews', options);+export const getPeerCatalogReview = (backend, catalogKey, options) => request(`/peer-administration/catalog-review?backend=${encodeURIComponent(backend)}&catalogKey=${encodeURIComponent(catalogKey)}`, options);+export const savePeerCatalogReview = (data, options) => request('/peer-administration/catalog-review', { ...options, method: 'PUT', body: JSON.stringify(data) });diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 88063d81ca..06fee816f8 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -30,7 +30,7 @@ one last settlement receipt. They fence admission/resume before the DB is usablebind 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).+The 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; revertingto one cannot resume a claimed hold. Old unclaimed v1 journals still read normally.@@ -823,9 +823,26 @@ or unresolved owner. PostgreSQL restore invokes capture before replay and automareconciliation before generic restore release, including proven rollback. It neverreplays 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.+The execution receiver now uses this ledger with separate `execution-v1` grants,+a coordinator-issued one-use launch capability, fixed adapters and epoch-bound+terminal receipts. Existing planning grants remain powerless. Pair identity changes+and filesystem identity restores rotate the execution epoch before publication,+under the same identity writer lock used through dispatch handoff. Invalidation+needs no database write, so an unavailable database cannot preserve stale grants.++`peer-execution-grants.json` and `peer-execution-catalog.json` are machine-local+`file-primary` operator configuration, not app records or a parallel operation+ledger. They have bounded, strict schemas; absent files grant nothing.+They never federate or restore from snapshots. Grant generations are fenced by+the permanent PostgreSQL floors and the non-rewound epoch. Catalog reviews bind+immutable source pins, license review, runtime and exact artifact requirements;+unknown entries deny. No seed/migration creates reviews or execution authority.++`peer-execution/<operation-uuid>/` holds machine-local, file-primary detached+adapter launch/exit evidence needed across a server restart, indexed by the+permanent ledger operation identity. It cannot authorize another launch or replace+ledger consumption. Preserve it across restores with the authority and maintenance+journal; do not delete unresolved evidence. Status reconciliation re-reads exact+terminal proof before settling the current claim. A crash after ledger completion+but before journal settlement or hold release is recoverable without relaunch.+See [peer administration](features/peer-administration.md) for supported actions.diff --git a/docs/features/peer-administration.md b/docs/features/peer-administration.mdindex 2044c83812..4d613b17f4 100644--- a/docs/features/peer-administration.md+++ b/docs/features/peer-administration.md@@ -1,232 +1,116 @@-# Peer administration planning (draft)--This draft is a **dependency foundation, not executable remote administration**.-Every advertised action reports `executionSupported: false`. A valid plan stays-`state: planned`, `queued: false`, `inFlight: false`. It cannot update, restart,-download, install, cancel active work, or become a queued operation after an-upgrade. No executor, shell command or maintenance override is wired here.--The fixed vocabulary is `portos.update`, `portos.restart`, and-`catalog.install`. Update/restart have no user-provided arguments. Catalog plans-accept only a shipped catalog key and `ollama` or `lmstudio`; free-form model IDs,-URLs, filesystem paths, code recipes, tokens, force flags and license-acceptance-flags are rejected. Gated models and Ollama import recipes require local setup-and cannot be planned through this surface. No terms are accepted by a plan.--## Later operator setup--Nothing is granted by installation, discovery, pairing, sync opt-in, this PR,-or an instance's display name. No migration creates permission or credentials.--1. On the **receiving host**, use an operator session (including its existing- delegated agent session), or a local connection on a password-free install.- Enable and pair the known peer using the existing pairing workflow.-2. Open Instances → the peer → **Peer administration · planning only**. Compare- the receiving host UUID and paired caller UUID. These IDs, the existing pair- credential binding, and the exact action define authority; names do not.-3. Review a specific grant, then explicitly allow planning for one hour. The API- supports one minute to 24 hours. The API/UI returns a grant ID and timestamps.- This is `planning-v1`, not permission to execute. A future execution protocol- must require another explicit operator grant with a different scope.-4. On the sending host, an operator can preview update/restart requirements.- The peer must separately have granted that sender planning access. Catalog- plans are API-only until source/license/destination review is available.-5. Revoke an action on the receiving host at any time. Revocation and renewal- rotate its grant ID; existing preflights/plans immediately become unusable.- Expiry, disabled/deleted peers, identity changes and pair-secret rotation- deny access. Disabling suspends the grant; use Revoke to permanently remove- its permission. Re-enabling cannot extend its original expiry.--Grant writes compare the prior grant ID to prevent stale browser saves from-resurrecting revoked permission. Setup is always behind `requireHostControl`;-that gate and existing update, restart, model, settings and socket routes retain-their original authority rules. There is no instance-password or Basic fallback-on this protocol. Operator credentials are never forwarded to the peer.--## Protocol and audit identity--Exact POST routes under `/api/federation/admin/v1/` are `preflight`, `plans`,-`receipt`, and `execute`. Every route requires the current verified paired-credential even when the optional instance password is off. The global gate-only admits these exact paths; it does not give peers host-control authority.--- Preflight: `{ protocolVersion: 1, challenge: <uuid>, intent }`. The receiver- validates the action grant and catalog entry, rechecks identity/grant after- probes, and signs a snapshot with a domain-separated HMAC using the existing- pair secret. It binds sender/receiver UUIDs, version, action, grant ID, unique- preflight ID, challenge and a maximum 60-second expiry. The sender verifies- that proof, target identity, version contract and freshness before planning.-- Plan: `{ protocolVersion: 1, requestId: <uuid>, preflightId, grantId, intent }`.- The preflight is consumed once. An exact same-request retry returns the same- signed receipt; changed payloads reusing a request ID are rejected. A new- request ID cannot consume an already-used preflight. Reconciliation uses- `receipt` with `{ requestId }`, authenticated and scoped to that peer.-- Execute: `{ requestId }` verifies ownership/current permission, then returns- `503 PEER_ADMIN_EXECUTION_UNAVAILABLE`. It never responds with job acceptance- or restart completion and never creates an operation.--Receipts contain server-derived sender/target UUIDs, request/preflight/grant IDs,-intent, timestamps, version and blockers. They are **temporary diagnostics, not-an execution audit ledger**: maximum 128 preflights and 128 plans per process,-60-second preflights, five-minute plans, additionally limited by grant expiry.-Expiry or process restart returns not-found/stale, never resumes work. Duplicate-preflight challenges within the live window are rejected. There is no eviction-of live receipts to make room. A future durable execution ledger must retain-idempotency/replay tombstones independently of these ephemeral previews.--The operator sender makes only an explicitly requested two-hop preview, with-one ten-second timeout, a 64 KiB response limit and no redirects. It sends only-existing pair credentials; network failures never cause automatic retries or-fallback to broad tokens. An unverifiable response is a refusal. Older peers-without this protocol remain usable for their existing federation surfaces.--## Required before execution can be enabled--- 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- grant identity before launch. Distinguish queued, draining, in-flight,- awaiting-reconnect, succeeded, failed and uncertain; request acceptance never- proves restart or update completion. Reconcile the same operation after a- crash, bound deadlines and expose typed errors. Retain the exclusive hold- when side effects are uncertain; never retry a launch based only on timeout.-- Integrate the existing catalog source/license review and installer preflight- for the exact receiver-side entry/backend. Verify actual destination disk- capacity including staging/headroom, memory/runtime fit, installed runtime- and reviewed source identity. Preserve local terms and code-review gates;- unknown size/requirements, new terms, unknown code and changed catalogs deny.- This draft reports only advisory data-volume/OS memory telemetry and explicit- missing-check flags. It does **not** claim those are installation checks.-- Surface rollback only when an adapter supplies a verified supported recovery- path; otherwise report manual recovery. Never offer generic git reset, shell,- command, URL/path execution or deletion as rollback. Test grant revocation- during drain, queued cancellation, dispatch races, crash reconciliation,- durable replay rejection and no active-work interruption before enabling.--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.--## 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.--Legacy committed restores that predate this ledger may adopt only a positively-empty pair of ledger tables. Adoption persists the exact recovery ID directly in-a fenced capture state, with an atomic same-ID intent covering first publication.-Database-lock waits, capture failures and interrupted publication resume only that-empty-adoption owner after another empty-table proof. Ordinary committed rewinds-never recapture an empty database. Downstream repair retries reuse the settled ID.--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.+# Peer administration++Peer administration is receiver-authorized, private federation between paired+instances. Installation, pairing, discovery, display names, and planning grants+never authorize execution. Development and fixture tests do not create live+grants, downloads, updates, or restarts.++## Setup and supported actions++On the receiving host, open Instances → the peer → Peer administration. Compare+both instance UUIDs, then review a separate, action-specific execution grant.+`execution-v1` requires explicit confirmation; existing `planning-v1` grants+remain planning-only. The UI grants one hour; the API permits one minute through+24 hours. The audit identity is the server-derived operator session (including+delegated agent sessions), or a genuine local operator on a password-free host.+Setup and local catalog review retain `requireHostControl`.++The fixed action vocabulary accepts no arbitrary commands, credentials, paths,+URLs, force flags, scripts, import recipes, or license-acceptance flags:++- `portos.update`: the receiver's clean `main` checkout, pinned to the exact+ preflight origin commit. Forks must be synchronized locally first. The adapter+ preserves fork-aware preflight and never forces, resets, or rebases divergent+ work. Pinned updates use fast-forward only.+- `portos.restart`: only the receiver's verified PortOS server and CoS processes.+ Script identities are verified; no unrelated applications are restarted.+- `catalog.install`: only supported, receiver-reviewed single-file LM Studio+ GGUF catalog artifacts. Configure `LM_STUDIO_MODELS_DIR` locally to the actual+ LM Studio model folder; the adapter refuses a guessed default. A local review binds the catalog key, immutable source+ revision, filename, SHA-256, exact size, license, installed runtime,+ destination, and runtime memory requirement. Source repositories and actual+ destinations are derived by the receiver. Unknown, gated, unreviewed, changed,+ unsupported, or insufficient-resource entries deny. Ollama, MLX, and sharded+ artifacts are not supported by this execution adapter.++Catalog review is configuration, not a download, model launch, acceptance of new+terms, or permission to execute. A paired sender still needs the separate+catalog execution grant. Installation verifies the streamed byte count and hash+before publication and never replaces an existing destination file.++On the sending host, prepare the desired action, inspect its exact signed+preflight, then request execution. The sender stores the request identity before+sending and refuses dispatch if that recovery record cannot be read back.+An uncertain response retains the request and offers **Check status**; it never+starts another attempt automatically. The receiving host owns the durable ledger;+browser storage is a convenience for finding its receipt.++## Authority and drain++Execution grants are machine-local settings, bound to both instance UUIDs,+current pair credentials, action, grant ID/generation, expiry and the non-rewound+execution epoch. Grant changes use compare-and-swap on the previous grant ID and+advance the PostgreSQL generation floor before publishing policy. A failed policy+write therefore cannot leave old authority active.++Execution shares the instance identity writer lock through the launch handoff.+Credential, peer enablement/membership, or receiver identity changes rotate the+machine execution epoch before publication. This invalidates all execution grants+on that receiver; review new grants afterward. Ordinary telemetry/name changes+preserve grants. Restoring instance identity files also rotates the epoch under+that lock. Grants and execution receipts are never restored from snapshots.++The receiver consumes a request durably before side effects. Its own maintenance+hold drains admitted agents, provider work, renders, saves and cleanup naturally.+It never kills or cancels active work. It claims the exact hold ID/revision using+a fresh coordinator-owned idle observation, then rechecks identity, grants,+version, source and resource evidence. Resume and ordinary admission share this+same journal transaction; a separate lock or a ready-status read cannot launch.++A one-use in-process capability binds the exact in-flight claim to a fixed action+and evidence digest. Copies, recovered claims, stale revisions and repeated use+cannot launch. Revocation during drain prevents dispatch. After launch, revocation+does not interrupt work already running; the receiver reconciles that operation.++## Protocol and recovery++Planning endpoints retain their original behavior under+`/api/federation/admin/v1/{preflight,plans,receipt,execute}`. Planning `execute`+always refuses; upgrading never turns a temporary plan into queued work.++Separate execution POST endpoints are+`/api/federation/admin/v1/execution/{preflight,dispatch,status}`. Every endpoint+requires the current scoped paired credential, including on password-free hosts.+The sender never forwards Basic auth, instance passwords, sessions or agent tokens.+Exact endpoint admission does not grant general host-control access.++Execution preflights expire within 60 seconds and bind the request, both UUIDs,+grant generation, receiver version, epoch, fixed intent and evidence digest.+Execution signatures use canonical JSON and a separate HMAC purpose; planning+wire signatures remain compatible. Dispatch returns acceptance, not completion.+Changed input under a consumed request ID is refused permanently, including after+restart, grant renewal or database restore. Identical retries return the existing+operation; there is no second launch.++States are `queued`, `draining`, `in-flight`, `awaiting-reconnect`, `succeeded`,+`failed` and `uncertain`. Active ledger rows are capped at 32; preflights at 128.+Timeouts, disconnected callers, dead PIDs, and general host health never prove+completion. Unknown side effects retain exclusive ownership. Boot never replays a+launch; explicit status reads can reconcile exact completion evidence arriving+after boot. Terminal database persistence, journal settlement and hold release+are independently recoverable, including crashes between those boundaries.++Updates and restarts write per-operation launch evidence before starting their+detached adapter. Reconciliation requires its exact successful exit receipt and+matching target evidence: restarted fixed process identities, or the expected+boot/current commit with verified build, dependencies, submodules and migrations.+Catalog installation requires its verified artifact and completed publication.+Missing or conflicting evidence remains uncertain. No generic rollback or force+Ready button exists. Proven completion releases only the operation's own hold and+re-evaluates the already-saved scheduling policies; it never enables a policy.++The durable receiver ledger and restore reconciliation are documented in+[STORAGE](../STORAGE.md#receiver-execution-ledger-foundation-10127). Fixtures cover+authorization refusal, planning compatibility, revocation/rotation during drain,+replay, resume fencing, crash gaps, delayed completion and negative resource/hash+checks without operating any live peer.diff --git a/server/lib/README.md b/server/lib/README.mdindex fd50f6e4ba..9ba80990f5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -26,8 +26,8 @@ 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. |-| `peerExecutionAuthority.js` | Non-rewound receiver execution epoch and restore-owner journal; default-deny on stale evidence or pending/conflicting recovery. No grants or adapters. |+| `maintenanceExclusive.js` | Coordinator-owned exclusive claims, opaque idle observations, durable ownership, one-use fixed-adapter capabilities and verified settlement. Peer credentials alone never grant authority. |+| `peerExecutionAuthority.js` | Non-rewound receiver execution epoch and restore-owner journal; default-deny on stale evidence or pending/conflicting recovery. Invalidates grants on identity changes and refuses stale epochs. || `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. |@@ -856,6 +856,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `forgeMaintenanceTasks.js` | Current forge-maintenance screening version, queue-compatible identity check, task classification, and legacy refusal reason. |-| `peerAdminValidation.js` | Strict planning-only peer administration schemas, fixed actions and grant scope. |+| `peerAdminValidation.js` | Strict, separate planning and execution schemas with fixed intents, signed receipts and explicit grant scopes. || `musicVideoReviewDraft.js` | Pure imported Animatic review candidates, newest immutable version first; exact version URLs remain separate from native production approvals. |diff --git a/server/lib/apiAccessPolicy.js b/server/lib/apiAccessPolicy.jsindex f7a8b9afe4..2fbe2c83a9 100644--- a/server/lib/apiAccessPolicy.js+++ b/server/lib/apiAccessPolicy.js@@ -50,7 +50,7 @@ export const PEER_API_SURFACE = Object.freeze([{ path: '/api/peer-sync/push', methods: Object.freeze(['POST']) },// Planning-only administration. Each exact endpoint independently verifies// the current paired identity and a host-local action grant. Never host control.- ...['preflight', 'plans', 'receipt', 'execute'].map(endpoint => ({+ ...['preflight', 'plans', 'receipt', 'execute', 'execution/preflight', 'execution/dispatch', 'execution/status'].map(endpoint => ({path: `/api/federation/admin/v1/${endpoint}`, methods: Object.freeze(['POST']),})),// Peer-facing provider APIs; each applies its own per-peer admission.diff --git a/server/lib/maintenanceAdmission.js b/server/lib/maintenanceAdmission.jsindex b116399f96..7e2df4c4e5 100644--- a/server/lib/maintenanceAdmission.js+++ b/server/lib/maintenanceAdmission.js@@ -254,9 +254,9 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse});return status();};- const { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive } = exclusive;+ const { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability } = 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 };+ observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability };}// Resolve the configured data root on first use, after host/test setup.diff --git a/server/lib/maintenanceExclusive.js b/server/lib/maintenanceExclusive.jsindex 9b6681d005..36dc76c5bc 100644--- a/server/lib/maintenanceExclusive.js+++ b/server/lib/maintenanceExclusive.js@@ -1,8 +1,27 @@-/** Coordinator primitives only. No peer route, grant writer or executor uses these yet. */+/** Exclusive coordinator ownership and receiver-local one-use launch capabilities. */import { createHash } from 'node:crypto';import { z } from 'zod';import { peerAdminIntentSchema } from './peerAdminValidation.js';+// Tokens never serialize. Reopening an in-flight journal cannot mint another launch.+const executionCapabilities = new WeakMap();+export function assertPeerExecutionCapability(capability, intent, evidenceDigest) {+ const proof = executionCapabilities.get(capability);+ if (!proof || JSON.stringify(proof.operation.intent) !== JSON.stringify(intent)+ || proof.operation.evidenceDigest !== evidenceDigest) {+ throw Object.assign(new Error('A receiver-issued execution capability is required.'), { code: 'PEER_EXECUTION_CAPABILITY_REQUIRED', status: 409 });+ }+ proof.assertCurrent();+ return structuredClone(proof.operation);+}+export function consumePeerExecutionCapability(capability, intent, evidenceDigest) {+ const operation = assertPeerExecutionCapability(capability, intent, evidenceDigest);+ const proof = executionCapabilities.get(capability);+ if (proof.consumed) throw Object.assign(new Error('This execution capability was already consumed.'), { code: 'PEER_EXECUTION_CAPABILITY_CONSUMED', status: 409 });+ proof.consumed = true;+ return operation;+}+const uuid = z.string().uuid();const digest = z.string().regex(/^[a-f0-9]{64}$/);const operationSchema = z.object({@@ -30,6 +49,7 @@ const receiptSchema = z.object({ outcome: z.enum(['cancelled', 'succeeded', 'fai/** 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 startedClaims = new WeakMap();const stale = message => { throw error('MAINTENANCE_STALE', message); };const copy = value => value ? structuredClone(value) : null;const current = (state, expected) => {@@ -76,7 +96,7 @@ export function createMaintenanceExclusive({ transaction, read, lockExists, make};const transitionExclusive = (input, phase, evidence) => {const expected = expectedSchema.parse(input);- return transaction(state => {+ const result = transaction(state => {const claim = current(state, expected);const allowed = { reserved: ['in-flight', 'uncertain'], 'in-flight': ['awaiting-reconnect', 'uncertain'],'awaiting-reconnect': ['uncertain'], uncertain: [] };@@ -86,6 +106,24 @@ export function createMaintenanceExclusive({ transaction, read, lockExists, makeclaim.revision++;return copy(claim);});+ if (phase === 'in-flight') startedClaims.set(result, { id: result.id, revision: result.revision, fingerprint: result.fingerprint });+ return result;+ };+ const issueExecutionCapability = claim => {+ if (!startedClaims.has(claim)) stale('Only the fresh in-flight transition can authorize a launch.');+ const expected = startedClaims.get(claim);+ startedClaims.delete(claim);+ const assertCurrent = () => {+ if (lockExists()) stale('Maintenance state is being changed.');+ const state = read();+ const live = current(state, expected);+ if (live.phase !== 'in-flight' || state.operations.length) stale('Exclusive execution ownership is no longer idle and in-flight.');+ return live;+ };+ const live = assertCurrent();+ const capability = Object.freeze({});+ executionCapabilities.set(capability, { operation: copy(live.operation), assertCurrent, consumed: false });+ return capability;};const settleExclusive = (input, receiptInput) => {const expected = expectedSchema.parse(input);@@ -126,5 +164,5 @@ export function createMaintenanceExclusive({ transaction, read, lockExists, makestate.exclusive.revision++;}};- return { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, observeExistingWork };+ return { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, observeExistingWork, issueExecutionCapability };}diff --git a/server/lib/peerAdminValidation.js b/server/lib/peerAdminValidation.jsindex bcfecaf0ee..49a793fb61 100644--- a/server/lib/peerAdminValidation.js+++ b/server/lib/peerAdminValidation.js@@ -40,3 +40,30 @@ export const peerAdminPlanSchema = z.object({}).strict();export const peerAdminReceiptSchema = z.object({ requestId: uuid }).strict();export const peerAdminRemotePlanSchema = z.object({ peerId, intent: peerAdminIntentSchema }).strict();++// Independent confirmation: planning records never authorize execution.+export const PEER_EXECUTION_SCOPE = 'execution-v1';+export const peerExecutionGrantSchema = peerAdminGrantSchema.omit({ allowPlanning: true }).extend({+ allowExecution: z.boolean(), confirmation: z.literal(PEER_EXECUTION_SCOPE),+}).strict();+export const peerExecutionPreflightSchema = z.object({ protocolVersion: z.literal(1), requestId: uuid, intent: peerAdminIntentSchema }).strict();+export const peerExecutionDispatchSchema = peerExecutionPreflightSchema.extend({+ grantId: uuid, grantGeneration: z.number().int().positive().safe(),+ evidenceDigest: z.string().regex(/^[a-f0-9]{64}$/), executionEpoch: uuid,+ version: z.string().min(1).max(100),+}).strict();+export const peerExecutionPreflightPayloadSchema = peerExecutionDispatchSchema.extend({+ scope: z.literal(PEER_EXECUTION_SCOPE), senderInstanceId: uuid, targetInstanceId: uuid,+ expiresAt: z.number().int().positive().safe(),+}).strict();+export const peerExecutionRemoteDispatchSchema = peerAdminPeerSchema.extend({+ preflight: z.object({ payload: peerExecutionPreflightPayloadSchema, signature: z.string().regex(/^[a-f0-9]{64}$/) }).strict(),+}).strict();+export const peerExecutionRemoteStatusSchema = peerAdminPeerSchema.extend({ requestId: uuid }).strict();++export const peerExecutionReceiptPayloadSchema = z.object({+ protocolVersion: z.literal(1), scope: z.literal(PEER_EXECUTION_SCOPE), requestId: uuid,+ senderInstanceId: uuid, targetInstanceId: uuid, operationId: uuid,+ state: z.enum(['queued', 'draining', 'in-flight', 'awaiting-reconnect', 'succeeded', 'failed', 'uncertain']),+ revision: z.number().int().positive().safe(), code: z.string().regex(/^[A-Z0-9_]{1,100}$/).nullable(),+}).strict();diff --git a/server/lib/peerExecutionAuthority.js b/server/lib/peerExecutionAuthority.jsindex d72cf5d596..08d0cdbbff 100644--- a/server/lib/peerExecutionAuthority.js+++ b/server/lib/peerExecutionAuthority.js@@ -96,6 +96,13 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = aconst initialize = () => transaction(current => current ?? {version: 1, epoch: makeId(), revision: 1, phase: 'ready', recovery: null, settledRecoveryId: null, emptyAdoptionId: null,});+ const invalidate = () => {+ if (!read()) return null; // No execution authority to revoke on a new install.+ return transaction(current => {+ if (current.phase !== 'ready') throw executionAuthorityError('Execution recovery is pending; authority cannot be rewritten.');+ return { ...current, epoch: makeId(), revision: current.revision + 1 };+ });+ };const beginRestore = id => {uuid.parse(id);return transaction(current => {@@ -153,6 +160,6 @@ export function createPeerExecutionAuthority(dataDir, { io = fs, assertWrite = athrow executionAuthorityError('The execution recovery owner changed.');return { ...current, revision: current.revision + 1, phase: 'ready', recovery: null, settledRecoveryId: id };});- return { read, requireReady, initialize, beginRestore, beginEmptyAdoption, recoverEmptyAdoption,+ return { read, requireReady, initialize, invalidate, beginRestore, beginEmptyAdoption, recoverEmptyAdoption,recordSnapshot, completeRestore, recoveryPath, assertWrite };}diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 981f73d866..220adf4647 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -44,6 +44,7 @@ const loomRunSnapshot = (production) => Object.freeze({});export const SOCKET_EVENT_CONTRACTS = Object.freeze({+ 'peer-execution:changed': Object.freeze({ direction: 'server-to-client', summary: 'Invalidate authenticated peer execution setup and status; no credentials or operation data.', payloadSchema: { type: 'null' } }),'genome:clinvar-progress': {direction: 'server-to-client', summary: 'ClinVar download and indexing progress for an optional client request ID.',payloadSchema: { type: 'object', required: ['message'], properties: { message: { type: 'string' }, requestId: { type: 'string', format: 'uuid' } } },diff --git a/server/routes/peerAdminOperator.js b/server/routes/peerAdminOperator.jsindex a62afe3abd..07de077617 100644--- a/server/routes/peerAdminOperator.js+++ b/server/routes/peerAdminOperator.js@@ -1,24 +1,67 @@import { Router } from 'express';+import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import { peerAdminPeerSchema, peerAdminGrantSchema, peerAdminRemotePlanSchema } from '../lib/peerAdminValidation.js';+import { peerAdminPeerSchema, peerAdminGrantSchema, peerAdminRemotePlanSchema, peerExecutionGrantSchema, peerExecutionRemoteDispatchSchema, peerExecutionRemoteStatusSchema } from '../lib/peerAdminValidation.js';import { requireHostControl } from '../services/authGate.js';import { describePeerAdminSetup, savePeerAdminGrant } from '../services/peerAdministration.js';-import { planPeerAdministration } from '../services/peerAdminConsumer.js';+import { planPeerAdministration, preparePeerExecution, dispatchPeerExecution, getPeerExecutionStatus } from '../services/peerAdminConsumer.js';+async function setup(peerId) {+ const result = await describePeerAdminSetup(peerId);+ const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');+ return { ...result, execution: await (await peerExecutionRuntime()).describe(peerId) };+}const router = Router();router.use(requireHostControl);router.get('/peers/:peerId', asyncHandler(async (req, res) => {const { peerId } = validateRequest(peerAdminPeerSchema, req.params);- res.set('Cache-Control', 'no-store').json(await describePeerAdminSetup(peerId));+ res.set('Cache-Control', 'no-store').json(await setup(peerId));}));router.post('/grants', asyncHandler(async (req, res) => {const input = validateRequest(peerAdminGrantSchema, req.body);- res.json(await savePeerAdminGrant(input, req));+ await savePeerAdminGrant(input, req);+ res.json(await setup(input.peerId));}));router.post('/preview', asyncHandler(async (req, res) => {const input = validateRequest(peerAdminRemotePlanSchema, req.body);res.set('Cache-Control', 'no-store').json(await planPeerAdministration(input));}));+router.post('/execution-grants', asyncHandler(async (req, res) => {+ const input = validateRequest(peerExecutionGrantSchema, req.body);+ const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');+ await (await peerExecutionRuntime()).saveGrant(input, req);+ res.json(await setup(input.peerId));+}));+router.post('/execution-preview', asyncHandler(async (req, res) => {+ const input = validateRequest(peerAdminRemotePlanSchema, req.body);+ res.set('Cache-Control', 'no-store').json(await preparePeerExecution(input));+}));+router.post('/execution-dispatch', asyncHandler(async (req, res) => {+ const input = validateRequest(peerExecutionRemoteDispatchSchema, req.body);+ res.set('Cache-Control', 'no-store').json(await dispatchPeerExecution(input));+}));+router.post('/execution-status', asyncHandler(async (req, res) => {+ const input = validateRequest(peerExecutionRemoteStatusSchema, req.body);+ res.set('Cache-Control', 'no-store').json(await getPeerExecutionStatus(input));+}));+const catalogQuerySchema = z.object({ backend: z.literal('lmstudio'), catalogKey: z.string().min(1).max(100).regex(/^[a-z0-9][a-z0-9-]*$/) }).strict();+router.get('/catalog-review', asyncHandler(async (req, res) => {+ const input = validateRequest(catalogQuerySchema, req.query);+ const { describePeerCatalogReview } = await import('../services/peerCatalogInstaller.js');+ res.set('Cache-Control', 'no-store').json(await describePeerCatalogReview(input));+}));+router.get('/catalog-reviews', asyncHandler(async (_req, res) => {+ const { listPeerCatalogReviews } = await import('../services/peerCatalogInstaller.js');+ res.set('Cache-Control', 'no-store').json(await listPeerCatalogReviews());+}));+router.put('/catalog-review', asyncHandler(async (req, res) => {+ const { peerCatalogReviewSchema, savePeerCatalogReview } = await import('../services/peerCatalogInstaller.js');+ const input = validateRequest(peerCatalogReviewSchema, req.body);+ const result = await savePeerCatalogReview(input, req);+ const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');+ (await peerExecutionRuntime()).notify();+ res.json(result);+}));export default router;diff --git a/server/routes/peerAdministration.js b/server/routes/peerAdministration.jsindex ffbdea01bd..ff34c3e2fd 100644--- a/server/routes/peerAdministration.js+++ b/server/routes/peerAdministration.js@@ -2,7 +2,7 @@ import { Router } from 'express';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import {- peerAdminPreflightSchema, peerAdminPlanSchema, peerAdminReceiptSchema,+ peerAdminPreflightSchema, peerAdminPlanSchema, peerAdminReceiptSchema, peerExecutionPreflightSchema, peerExecutionDispatchSchema,} from '../lib/peerAdminValidation.js';import {createPeerAdminPreflight,@@ -28,4 +28,19 @@ router.post('/execute', asyncHandler(async (req, _res) => {const { requestId } = validateRequest(peerAdminReceiptSchema, req.body);await rejectPeerAdminExecution(req, requestId);}));+router.post('/execution/preflight', asyncHandler(async (req, res) => {+ const input = validateRequest(peerExecutionPreflightSchema, req.body);+ const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');+ res.json(await (await peerExecutionRuntime()).preflight(req, input));+}));+router.post('/execution/dispatch', asyncHandler(async (req, res) => {+ const input = validateRequest(peerExecutionDispatchSchema, req.body);+ const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');+ res.status(202).json(await (await peerExecutionRuntime()).dispatch(req, input));+}));+router.post('/execution/status', asyncHandler(async (req, res) => {+ const input = validateRequest(peerAdminReceiptSchema, req.body);+ const { peerExecutionRuntime } = await import('../services/peerExecutionRuntime.js');+ res.json(await (await peerExecutionRuntime()).status(req, input));+}));export default router;diff --git a/server/routes/peerAdministration.test.js b/server/routes/peerAdministration.test.jsindex 2a310ae931..b8427d132e 100644--- a/server/routes/peerAdministration.test.js+++ b/server/routes/peerAdministration.test.js@@ -92,6 +92,18 @@ beforeEach(() => {afterAll(cleanup);describe('bounded administration through the real authority boundary', () => {+ it('keeps planning grants powerless on the independently authenticated execution surface', async () => {+ await grant();+ const input = { protocolVersion: 1, requestId: randomUUID(), intent };+ const denied = await peerRequest('execution/preflight', input);+ expect(denied.status).toBe(403);+ expect(denied.body.code).toBe('PEER_EXECUTION_GRANT_REQUIRED');+ expect((await request(app).post(`${ROOT}/execution/preflight`).send(input)).status).toBe(401);+ expect((await peerRequest('execution/dispatch', { ...input, command: 'fixture-injection' })).status).toBe(400);+ expect(execution.restart).not.toHaveBeenCalled();+ expect(execution.update).not.toHaveBeenCalled();+ expect(execution.install).not.toHaveBeenCalled();+ });it('defaults to deny and never elevates a peer to existing host control', async () => {const body = { protocolVersion: 1, challenge: randomUUID(), intent };expect((await peerRequest('preflight', body)).body.code).toBe('PEER_ADMIN_GRANT_REQUIRED');diff --git a/server/services/backup.js b/server/services/backup.jsindex 65f2e76a47..d8b10d30da 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -1329,7 +1329,7 @@ const OS_METADATA_RSYNC_EXCLUDES = [...OS_METADATA_FILES, '._*'].map(name => `--* verification and execution cannot disagree.*/const RESTORE_PRESERVED_FILES = Object.freeze([- 'database-authority.json', 'peer-execution-authority.json', 'peer-execution-recovery.jsonl', 'workflow-maintenance',+ 'database-authority.json', 'peer-execution', 'peer-execution-catalog.json', 'peer-execution-grants.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@@ -1567,7 +1567,15 @@ export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, sub// until it finishes (#7302), so this restore's idle floor scales to it.const idleTimeoutMs = restoreIdleTimeoutMs(verification.largestFileBytes);const restoreFiles = async () => {- const [transfer] = await Promise.allSettled([runRsync(srcDir, PATHS.data, flags, { idleTimeoutMs })]);+ const transferFiles = () => runRsync(srcDir, PATHS.data, flags, { idleTimeoutMs });+ const transferWithIdentityFence = async () => {+ if (!dryRun && (!scope || scope === 'instances.json') && await stat(join(srcDir, 'instances.json')).then(info => info.isFile(), error => { if (error.code === 'ENOENT') return false; throw error; })) {+ const { withPeerExecutionIdentityRestore } = await import('./peerExecutionRuntime.js');+ return withPeerExecutionIdentityRestore(transferFiles);+ }+ return transferFiles();+ };+ const [transfer] = await Promise.allSettled([transferWithIdentityFence()]);const reconciliationError = !dryRun? await reconcileLiveFileRestore(subdirFilter).then(() => null,diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 1faf139afe..9c4dfa5282 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -2383,7 +2383,24 @@ describe('restoreSnapshot manifest verification', () => {}}- it.for(['peer-execution-authority.json', 'peer-execution-recovery.jsonl', 'workflow-maintenance/state.json', 'Workflow-Maintenance/state.json'])+ it('invalidates execution grants before restoring instance identity bytes', async context => {+ await withRealRsync(context, async () => {+ const { createPeerExecutionAuthority } = await import('../lib/peerExecutionAuthority.js');+ const path = joinPath(PATHS.data, 'peer-execution-authority.json');+ await realFs.rm(path, { force: true });+ const authority = createPeerExecutionAuthority(PATHS.data);+ const before = authority.initialize();+ const identity = '{"self":{"instanceId":"00000000-0000-4000-8000-000000000001"},"peers":[]}';+ const hash = await writeSnapshotFile('instances.json', identity);+ await writeManifest({ 'instances.json': hash });+ await restoreSnapshot(tmpRoot, 'snap-1', { dryRun: false, subdirFilter: 'instances.json' });+ expect(authority.read().epoch).not.toBe(before.epoch);+ expect(await realFs.readFile(joinPath(PATHS.data, 'instances.json'), 'utf8')).toBe(identity);+ await realFs.rm(path, { force: true });+ });+ });++ it.for(['peer-execution-grants.json', 'peer-execution-catalog.json', 'peer-execution/fixture-operation/evidence.json', '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);@@ -3041,6 +3058,9 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>'--exclude=._*',// Machine-local admission state is never installed by a restore (#10064).'--exclude=/[dD][aA][tT][aA][bB][aA][sS][eE]-[aA][uU][tT][hH][oO][rR][iI][tT][yY].[jJ][sS][oO][nN]',+ '--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]',+ '--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[cC][aA][tT][aA][lL][oO][gG].[jJ][sS][oO][nN]',+ '--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[gG][rR][aA][nN][tT][sS].[jJ][sS][oO][nN]','--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[aA][uU][tT][hH][oO][rR][iI][tT][yY].[jJ][sS][oO][nN]','--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[rR][eE][cC][oO][vV][eE][rR][yY].[jJ][sS][oO][nN][lL]','--exclude=/[wW][oO][rR][kK][fF][lL][oO][wW]-[mM][aA][iI][nN][tT][eE][nN][aA][nN][cC][eE]',@@ -3070,6 +3090,9 @@ describe('restoreSnapshot snapshotId, filter flags, and settings re-sync', () =>'--exclude=desktop.ini','--exclude=._*','--exclude=/[dD][aA][tT][aA][bB][aA][sS][eE]-[aA][uU][tT][hH][oO][rR][iI][tT][yY].[jJ][sS][oO][nN]',+ '--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]',+ '--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[cC][aA][tT][aA][lL][oO][gG].[jJ][sS][oO][nN]',+ '--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[gG][rR][aA][nN][tT][sS].[jJ][sS][oO][nN]','--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[aA][uU][tT][hH][oO][rR][iI][tT][yY].[jJ][sS][oO][nN]','--exclude=/[pP][eE][eE][rR]-[eE][xX][eE][cC][uU][tT][iI][oO][nN]-[rR][eE][cC][oO][vV][eE][rR][yY].[jJ][sS][oO][nN][lL]','--exclude=/[wW][oO][rR][kK][fF][lL][oO][wW]-[mM][aA][iI][nN][tT][eE][nN][aA][nN][cC][eE]',diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 8470606889..f661fbd30c 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -957,7 +957,12 @@ export const runBootSequence = ({ io, httpServer, localHttpServer, httpsEnabled,markRecoveryDone();}),- runDatabasePhase: runDatabaseBootPhase,+ runDatabasePhase: async () => {+ await runDatabaseBootPhase();+ const { bindPeerExecutionIo, initializePeerExecution } = await import('./peerExecutionRuntime.js');+ bindPeerExecutionIo(io);+ await initializePeerExecution().catch(err => console.error(`❌ Peer execution recovery remains held: ${err.message}`));+ },// One-time series cover-thumbnail backfill: derive `series.coverImage` (the// rendered volume/issue cover shown on the pipeline list) for series whosediff --git a/server/services/instanceIdentity.js b/server/services/instanceIdentity.jsindex 9ff82979ae..559e63885e 100644--- a/server/services/instanceIdentity.js+++ b/server/services/instanceIdentity.js@@ -37,6 +37,13 @@ const INSTANCES_FILE = dataPath('instances.json');export const UNKNOWN_INSTANCE_ID = 'unknown';const withLock = createMutex();+// Receiver execution shares the identity writer lock through launch handoff.+// Registration keeps this identity leaf independent of the execution graph.+export const withInstanceIdentityLock = fn => withLock(fn);+let executionAuthorityGuard = null;+export const registerInstanceExecutionAuthorityGuard = guard => { executionAuthorityGuard = guard; };+const authorityProjection = data => JSON.stringify({ self: data.self?.instanceId ?? null,+ peers: (data.peers ?? []).map(peer => ({ id: peer.id, instanceId: peer.instanceId, syncSecret: peer.syncSecret, enabled: peer.enabled !== false })) });// Default data shapeconst DEFAULT_DATA = {@@ -64,7 +71,9 @@ async function saveData(data) {export async function withData(fn) {return withLock(async () => {const data = await loadData();+ const previousAuthority = authorityProjection(data);const result = await fn(data);+ if (previousAuthority !== authorityProjection(data)) await executionAuthorityGuard?.();await saveData(data);return result;});diff --git a/server/services/instanceIdentity.test.js b/server/services/instanceIdentity.test.jsindex b5d8015ec7..5de855d2b1 100644--- a/server/services/instanceIdentity.test.js+++ b/server/services/instanceIdentity.test.js@@ -31,21 +31,42 @@ vi.mock('../lib/asyncMutex.js', () => ({createMutex: () => (fn) => fn()}));-import { readJSONFile } from '../lib/fileUtils.js';+import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';import {ensureSelf,getSelf,getInstanceId,ensureInstanceId,- updateSelf,+ updateSelf, withData, registerInstanceExecutionAuthorityGuard,} from './instanceIdentity.js';describe('instanceIdentity.js', () => {beforeEach(() => {vi.clearAllMocks();+ registerInstanceExecutionAuthorityGuard(null);readJSONFile.mockResolvedValue({ self: null, peers: [] });});+ it('invalidates execution authority before changing paired credentials and refuses publication if invalidation fails', async () => {+ const peer = { id: 'fixture-peer', instanceId: 'fixture-instance', syncSecret: 'fixture-old-secret', enabled: true };+ readJSONFile.mockResolvedValue({ self: { instanceId: 'fixture-host' }, peers: [peer] });+ const guard = vi.fn(async () => {+ expect(atomicWrite).not.toHaveBeenCalled();+ throw new Error('fixture authority unavailable');+ });+ registerInstanceExecutionAuthorityGuard(guard);+ await expect(withData(data => { data.peers[0].enabled = false; })).rejects.toThrow('fixture authority unavailable');+ expect(guard).toHaveBeenCalledOnce();+ expect(atomicWrite).not.toHaveBeenCalled();+ });+ it('preserves execution grants during non-authority telemetry updates', async () => {+ readJSONFile.mockResolvedValue({ self: { instanceId: 'fixture-host' }, peers: [{ id: 'fixture-peer', status: 'online' }] });+ const guard = vi.fn(); registerInstanceExecutionAuthorityGuard(guard);+ await withData(data => { data.peers[0].status = 'offline'; });+ expect(guard).not.toHaveBeenCalled();+ expect(atomicWrite).toHaveBeenCalledOnce();+ });+describe('ensureSelf', () => {it('should create identity when none exists', async () => {readJSONFile.mockResolvedValue({ self: null, peers: [] });diff --git a/server/services/peerAdminConsumer.js b/server/services/peerAdminConsumer.jsindex 967aba599e..d800a2b140 100644--- a/server/services/peerAdminConsumer.js+++ b/server/services/peerAdminConsumer.js@@ -1,8 +1,9 @@import { randomUUID } from 'node:crypto';import { peerFetch, readPeerBody } from '../lib/peerHttpClient.js';import { peerBaseUrl } from '../lib/peerUrl.js';+import { canonicalStringify } from '../lib/objects.js';import { ServerError } from '../lib/errorHandler.js';-import { PEER_ADMIN_SCOPE } from '../lib/peerAdminValidation.js';+import { PEER_ADMIN_SCOPE, peerExecutionPreflightPayloadSchema, peerExecutionReceiptPayloadSchema } from '../lib/peerAdminValidation.js';import { peerAdminIdentity, verifyPeerAdminSignature } from './peerAdministration.js';const failed = () => { throw new ServerError('Peer administration response could not be verified. No execution was requested.', { status: 502, code: 'PEER_ADMIN_UNVERIFIED_RESPONSE' }); };@@ -10,6 +11,9 @@ const failed = () => { throw new ServerError('Peer administration response couldconst ENDPOINTS = Object.freeze({preflight: '/api/federation/admin/v1/preflight',plans: '/api/federation/admin/v1/plans',+ executionPreflight: '/api/federation/admin/v1/execution/preflight',+ executionDispatch: '/api/federation/admin/v1/execution/dispatch',+ executionStatus: '/api/federation/admin/v1/execution/status',});async function exchange(peer, endpoint, body, signal) {@@ -21,7 +25,7 @@ async function exchange(peer, endpoint, body, signal) {}, { ...peer, auth: null, peerAuthAccepted: true });if (!response.ok) {await response.body?.cancel();- throw new ServerError('The peer refused administration planning. Check pairing, its local grant and protocol support.', {+ throw new ServerError('The peer refused administration. Check pairing, its local grant and protocol support.', {status: 502, code: 'PEER_ADMIN_REMOTE_REFUSED',});}@@ -70,3 +74,76 @@ export async function planPeerAdministration({ peerId, intent }) {});});}+++const executionFailed = () => {+ throw new ServerError('The peer execution response could not be verified. Check the saved request status before requesting another action.', {+ status: 502, code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE',+ });+};++function verifiedExecution(peer, self, envelope, purpose, requestId) {+ const payload = envelope?.payload;+ if (!payload || !verifyPeerAdminSignature(peer, purpose, payload, envelope.signature)+ || payload.protocolVersion !== 1 || payload.scope !== 'execution-v1'+ || payload.targetInstanceId !== peer.instanceId || payload.senderInstanceId !== self.instanceId+ || payload.requestId !== requestId) executionFailed();+ return payload;+}++function verifiedExecutionPreflight(peer, self, envelope, requestId) {+ const payload = verifiedExecution(peer, self, envelope, 'execution-preflight', requestId);+ if (!peerExecutionPreflightPayloadSchema.safeParse(payload).success+ || payload.expiresAt <= Date.now() || payload.expiresAt > Date.now() + 60_000) executionFailed();+ return payload;+}++async function unchangedPair(peerId, peer, self) {+ const fresh = await peerAdminIdentity(peerId);+ if (fresh.peer.syncSecret !== peer.syncSecret || fresh.peer.instanceId !== peer.instanceId+ || fresh.self.instanceId !== self.instanceId || peerBaseUrl(fresh.peer) !== peerBaseUrl(peer)) executionFailed();+}++const executionUnavailable = error => {+ if (error instanceof ServerError) throw error;+ throw new ServerError('Peer execution is unavailable or the response timed out. Preserve this request and check its status; do not repeat dispatch.', {+ status: 504, code: 'PEER_EXECUTION_UNAVAILABLE',+ });+};++/** Preflight authorizes no work. Preserve its signed envelope through the UI. */+export async function preparePeerExecution({ peerId, intent }) {+ const { peer, self } = await peerAdminIdentity(peerId);+ const requestId = randomUUID();+ const envelope = await exchange(peer, 'executionPreflight', { protocolVersion: 1, requestId, intent }, AbortSignal.timeout(10_000))+ .catch(executionUnavailable);+ const payload = verifiedExecutionPreflight(peer, self, envelope, requestId);+ if (canonicalStringify(payload.intent) !== canonicalStringify(intent)) executionFailed();+ await unchangedPair(peerId, peer, self);+ return envelope;+}++function verifiedExecutionReceipt(peer, self, envelope, requestId) {+ const payload = verifiedExecution(peer, self, envelope, 'execution-receipt', requestId);+ if (!peerExecutionReceiptPayloadSchema.safeParse(payload).success) executionFailed();+ return payload;+}++/** Exactly one dispatch attempt; a lost response is recovered through status. */+export async function dispatchPeerExecution({ peerId, preflight }) {+ const { peer, self } = await peerAdminIdentity(peerId);+ const payload = verifiedExecutionPreflight(peer, self, preflight, preflight?.payload?.requestId);+ const { requestId, grantId, grantGeneration, intent, evidenceDigest, executionEpoch, version } = payload;+ const envelope = await exchange(peer, 'executionDispatch', {+ protocolVersion: 1, requestId, grantId, grantGeneration, intent, evidenceDigest, executionEpoch, version,+ }, AbortSignal.timeout(10_000)).catch(executionUnavailable);+ await unchangedPair(peerId, peer, self);+ return verifiedExecutionReceipt(peer, self, envelope, requestId);+}++export async function getPeerExecutionStatus({ peerId, requestId }) {+ const { peer, self } = await peerAdminIdentity(peerId);+ const envelope = await exchange(peer, 'executionStatus', { requestId }, AbortSignal.timeout(10_000)).catch(executionUnavailable);+ await unchangedPair(peerId, peer, self);+ return verifiedExecutionReceipt(peer, self, envelope, requestId);+}diff --git a/server/services/peerAdminConsumer.test.js b/server/services/peerAdminConsumer.test.jsnew file mode 100644index 0000000000..fdd4ac6d7c--- /dev/null+++ b/server/services/peerAdminConsumer.test.js@@ -0,0 +1,88 @@+import { randomUUID } from 'node:crypto';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { peerExecutionRemoteDispatchSchema } from '../lib/peerAdminValidation.js';+import { peerFetch, readPeerBody } from '../lib/peerHttpClient.js';+import { peerAdminIdentity, signPeerAdmin } from './peerAdministration.js';+import { dispatchPeerExecution, getPeerExecutionStatus, preparePeerExecution } from './peerAdminConsumer.js';++vi.mock('../lib/peerHttpClient.js', async importOriginal => ({+ ...await importOriginal(), peerFetch: vi.fn(), readPeerBody: vi.fn(),+}));+vi.mock('./peerAdministration.js', async importOriginal => ({+ ...await importOriginal(), peerAdminIdentity: vi.fn(),+}));+const peer = { id: 'peer-example', instanceId: randomUUID(), address: '192.0.2.10', port: 5555, syncSecret: 'fixture-only-pair-secret-with-32-characters', auth: 'never-forward' };+const self = { instanceId: randomUUID() };+const intent = { action: 'portos.restart' };+const snapshot = requestId => ({+ protocolVersion: 1, scope: 'execution-v1', requestId, grantId: randomUUID(), grantGeneration: 1,+ senderInstanceId: self.instanceId, targetInstanceId: peer.instanceId, version: '1.0.0', intent,+ evidenceDigest: 'a'.repeat(64), executionEpoch: randomUUID(), expiresAt: Date.now() + 59_000,+});+const signed = (payload, purpose = 'execution-preflight') => ({ payload, signature: signPeerAdmin(peer, purpose, payload) });+const receipt = requestId => ({ protocolVersion: 1, scope: 'execution-v1', requestId,+ senderInstanceId: self.instanceId, targetInstanceId: peer.instanceId, operationId: randomUUID(),+ state: 'draining', revision: 1, code: null,+});+beforeEach(() => {+ vi.clearAllMocks();+ peerAdminIdentity.mockResolvedValue({ peer, self });+ peerFetch.mockResolvedValue({ ok: true });+});++describe('peer execution sender boundary', () => {+ it('prepares a signed preview then sends exactly its bound dispatch and verifies the receipt', async () => {+ readPeerBody.mockImplementationOnce(async () => signed(snapshot(JSON.parse(peerFetch.mock.calls[0][1].body).requestId)));+ const preflight = await preparePeerExecution({ peerId: peer.id, intent });+ const result = receipt(preflight.payload.requestId);+ readPeerBody.mockResolvedValueOnce(signed(result, 'execution-receipt'));+ // Route validation reorders keys: the signature must survive this round trip.+ const input = peerExecutionRemoteDispatchSchema.parse({ peerId: peer.id, preflight });+ await expect(dispatchPeerExecution(input)).resolves.toEqual(result);+ expect(peerFetch).toHaveBeenCalledTimes(2);+ const [url, options, credential] = peerFetch.mock.calls[1];+ expect(url).toMatch(/execution\/dispatch$/);+ expect(JSON.parse(options.body)).toEqual({ protocolVersion: 1, requestId: preflight.payload.requestId,+ grantId: preflight.payload.grantId, grantGeneration: 1, intent,+ evidenceDigest: preflight.payload.evidenceDigest, executionEpoch: preflight.payload.executionEpoch, version: '1.0.0' });+ expect(credential.auth).toBeNull();+ expect(credential.peerAuthAccepted).toBe(true);+ });++ it('rejects a forged or expired preview before making a dispatch request', async () => {+ const preflight = signed(snapshot(randomUUID()));+ preflight.payload.intent = { action: 'portos.update' };+ await expect(dispatchPeerExecution({ peerId: peer.id, preflight })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });+ await expect(dispatchPeerExecution({ peerId: peer.id, preflight: signed({ ...snapshot(randomUUID()), expiresAt: Date.now() - 1 }) }))+ .rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });+ expect(peerFetch).not.toHaveBeenCalled();+ });++ it('rejects signed responses with another intent or a pair changed while preparing', async () => {+ readPeerBody.mockImplementationOnce(async () => signed({ ...snapshot(JSON.parse(peerFetch.mock.calls[0][1].body).requestId), intent: { action: 'portos.update' } }));+ await expect(preparePeerExecution({ peerId: peer.id, intent })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });+ readPeerBody.mockImplementationOnce(async () => signed(snapshot(JSON.parse(peerFetch.mock.calls[1][1].body).requestId)));+ peerAdminIdentity.mockResolvedValueOnce({ peer, self }).mockResolvedValueOnce({ peer: { ...peer, syncSecret: 'replacement-secret' }, self });+ await expect(preparePeerExecution({ peerId: peer.id, intent })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });+ expect(peerFetch.mock.calls.every(([url]) => url.endsWith('/preflight'))).toBe(true);+ });++ it('does not retry after a lost dispatch response and permits read-only recovery by request ID', async () => {+ const preflight = signed(snapshot(randomUUID()));+ peerFetch.mockRejectedValueOnce(new Error('connection lost'));+ await expect(dispatchPeerExecution({ peerId: peer.id, preflight })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNAVAILABLE' });+ expect(peerFetch).toHaveBeenCalledTimes(1);+ const completed = { ...receipt(preflight.payload.requestId), state: 'succeeded', revision: 4 };+ readPeerBody.mockResolvedValueOnce(signed(completed, 'execution-receipt'));+ await expect(getPeerExecutionStatus({ peerId: peer.id, requestId: preflight.payload.requestId })).resolves.toEqual(completed);+ expect(peerFetch.mock.calls[1][0]).toMatch(/execution\/status$/);+ });++ it('rejects a valid signature for an unrelated receipt or incorrect signature purpose', async () => {+ const requestId = randomUUID();+ readPeerBody.mockResolvedValueOnce(signed(receipt(randomUUID()), 'execution-receipt'));+ await expect(getPeerExecutionStatus({ peerId: peer.id, requestId })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });+ readPeerBody.mockResolvedValueOnce(signed(receipt(requestId), 'execution-preflight'));+ await expect(getPeerExecutionStatus({ peerId: peer.id, requestId })).rejects.toMatchObject({ code: 'PEER_EXECUTION_UNVERIFIED_RESPONSE' });+ });+});diff --git a/server/services/peerAdministration.js b/server/services/peerAdministration.jsindex 169ea342d8..504fd4e76c 100644--- a/server/services/peerAdministration.js+++ b/server/services/peerAdministration.js@@ -10,6 +10,7 @@ import { join } from 'node:path';import { z } from 'zod';import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { parseFilesystemStats } from '../lib/fileCore.js';+import { canonicalStringify } from '../lib/objects.js';import { createMutex } from '../lib/asyncMutex.js';import { ServerError } from '../lib/errorHandler.js';import { loadData } from './instanceIdentity.js';@@ -42,7 +43,7 @@ const sameSecret = (a, b) => {const right = Buffer.from(b);return left.length === right.length && timingSafeEqual(left, right);};-const binding = (peer, self) => createHmac('sha256', peer.syncSecret)+export const peerAdminPairBinding = (peer, self) => createHmac('sha256', peer.syncSecret).update(`portos-peer-admin:binding:v1:${self.instanceId}:${peer.id}:${peer.instanceId}`).digest('hex');const wireGrant = ({ pairBinding: _pairBinding, ...grant }) => grant;@@ -53,12 +54,12 @@ async function readGrants() {return parsed.data;}-export async function peerAdminIdentity(peerId) {+export async function peerAdminIdentity(peerId, { allowInactive = false } = {}) {const { self, peers } = await loadData();const peer = peers?.find(entry => entry.id === peerId);if (!uuid.safeParse(self?.instanceId).success || !uuid.safeParse(peer?.instanceId).success- || peer.instanceId === self.instanceId || peer.enabled === false- || typeof peer.syncSecret !== 'string' || peer.syncSecret.length < 32) {+ || peer.instanceId === self.instanceId || (!allowInactive && (peer.enabled === false+ || typeof peer.syncSecret !== 'string' || peer.syncSecret.length < 32))) {refuse('PEER_ADMIN_PAIR_REQUIRED', 'An enabled pair with verified instance identities is required');}return { peer, self };@@ -67,7 +68,7 @@ export async function peerAdminIdentity(peerId) {// Revalidate the CURRENT pair credential at each receiver operation and after// preflight probes. Names, headers alone, Basic and operator sessions cannot// impersonate a paired caller on the receiver endpoints, even with auth off.-async function caller(req) {+export async function peerAdminCaller(req) {if (req.portosAuthContext?.method !== 'peer' || req.portosAuthContext?.authenticated !== true) {refuse('PEER_ADMIN_PEER_REQUIRED', 'A scoped paired-peer credential is required');}@@ -85,7 +86,7 @@ async function currentGrant(identity, action) {const grant = store.grants.find(entry => entry.peerId === peer.id && entry.action === action);if (!grant || !grant.allowed || grant.expiresAt <= Date.now() || grant.scope !== PEER_ADMIN_SCOPE|| grant.peerInstanceId !== peer.instanceId || grant.hostInstanceId !== self.instanceId- || !sameSecret(grant.pairBinding, binding(peer, self))) {+ || !sameSecret(grant.pairBinding, peerAdminPairBinding(peer, self))) {refuse('PEER_ADMIN_GRANT_REQUIRED', 'This paired identity has no current grant for that action');}return grant;@@ -105,7 +106,7 @@ export async function describePeerAdminSetup(peerId) {const grant = store.grants.find(entry => entry.peerId === peerId && entry.action === action);const active = Boolean(paired && grant?.allowed && grant.expiresAt > Date.now()&& grant.hostInstanceId === self.instanceId && grant.peerInstanceId === peer.instanceId- && sameSecret(grant.pairBinding, binding(peer, self)));+ && sameSecret(grant.pairBinding, peerAdminPairBinding(peer, self)));return { action, grant: grant ? wireGrant(grant) : null, active };}),};@@ -132,7 +133,7 @@ export const savePeerAdminGrant = (input, req) => withLock(async () => {const grant = {id: randomUUID(), peerId: peer.id, peerInstanceId: peer.instanceId, hostInstanceId: self.instanceId,action: input.action, scope: PEER_ADMIN_SCOPE,- pairBinding: input.allowPlanning ? binding(peer, self) : store.grants[index].pairBinding,+ pairBinding: input.allowPlanning ? peerAdminPairBinding(peer, self) : store.grants[index].pairBinding,allowed: input.allowPlanning, createdAt: now, expiresAt: now + input.expiresInMinutes * 60_000,authority: req.portosAuthContext.method === 'session' ? 'operator-session' : 'local-operator',};@@ -148,8 +149,8 @@ function sweep() {for (const map of [preflights, plans]) for (const [id, value] of map) if (value.expiresAt <= now) map.delete(id);}-function signPeerAdmin(peer, purpose, payload) {- return createHmac('sha256', peer.syncSecret).update(`portos-peer-admin:v1:${purpose}:${JSON.stringify(payload)}`).digest('hex');+export function signPeerAdmin(peer, purpose, payload) {+ return createHmac('sha256', peer.syncSecret).update(`portos-peer-admin:v1:${purpose}:${purpose.startsWith('execution-') ? canonicalStringify(payload) : JSON.stringify(payload)}`).digest('hex');}export const verifyPeerAdminSignature = (peer, purpose, payload, signature) => sameSecret(signPeerAdmin(peer, purpose, payload), signature);@@ -180,7 +181,7 @@ async function resourceSnapshot() {export const createPeerAdminPreflight = (req, input) => withLock(async () => {sweep();- const identity = await caller(req);+ const identity = await peerAdminCaller(req);const grant = await currentGrant(identity, input.intent.action);const model = catalogTarget(input.intent);if (preflights.has(input.challenge)) refuse('PEER_ADMIN_REPLAY', 'Use a fresh preflight challenge', 409);@@ -188,7 +189,7 @@ export const createPeerAdminPreflight = (req, input) => withLock(async () => {const version = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8')).version;const resources = await resourceSnapshot();// Re-read after probes, so rotation/revocation during I/O invalidates admission.- const fresh = await caller(req);+ const fresh = await peerAdminCaller(req);const freshGrant = await currentGrant(fresh, input.intent.action);if (freshGrant.id !== grant.id) refuse('PEER_ADMIN_GRANT_CHANGED', 'Grant changed during preflight', 409);const now = Date.now();@@ -207,7 +208,7 @@ export const createPeerAdminPreflight = (req, input) => withLock(async () => {export const createPeerAdminPlan = (req, input) => withLock(async () => {sweep();- const identity = await caller(req);+ const identity = await peerAdminCaller(req);const grant = await currentGrant(identity, input.intent.action);if (grant.id !== input.grantId) refuse('PEER_ADMIN_GRANT_CHANGED', 'The preflight grant is stale', 409);const key = `${identity.peer.id}:${input.requestId}`;@@ -240,7 +241,7 @@ export const createPeerAdminPlan = (req, input) => withLock(async () => {export const getPeerAdminPlan = (req, requestId) => withLock(async () => {sweep();- const identity = await caller(req);+ const identity = await peerAdminCaller(req);const receipt = plans.get(`${identity.peer.id}:${requestId}`);if (!receipt) refuse('PEER_ADMIN_PLAN_NOT_FOUND', 'Plan expired or not found; it has not been queued', 404);const grant = await currentGrant(identity, receipt.payload.intent.action);diff --git a/server/services/peerCatalogInstaller.js b/server/services/peerCatalogInstaller.jsnew file mode 100644index 0000000000..829cb7973b--- /dev/null+++ b/server/services/peerCatalogInstaller.js@@ -0,0 +1,287 @@+/** Receiver-reviewed, pinned, single-file GGUF imports. No peer-provided recipe. */+import { createHash } from 'node:crypto';+import { isAbsolute, join } from 'node:path';+import * as fs from 'node:fs/promises';+import { z } from 'zod';+import { canonicalStringify } from '../lib/objects.js';+import { assertNotRealDataWrite } from '../lib/testDataIsolation.js';+import { assertPeerExecutionCapability } from '../lib/maintenanceExclusive.js';++const digest = z.string().regex(/^[a-f0-9]{64}$/);+const bytes = z.number().int().min(16).max(512 * 1024 ** 3).safe();+export const peerCatalogReviewTargetSchema = z.object({ backend: z.literal('lmstudio'),+ catalogKey: z.string().min(1).max(100).regex(/^[a-z0-9][a-z0-9-]*$/) }).strict();+export const peerCatalogReviewSchema = peerCatalogReviewTargetSchema.extend({+ sourceRevision: z.string().regex(/^[a-f0-9]{40}$/),+ fileName: z.string().max(180).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*\.gguf$/)+ .refine(value => !/\.\.|mmproj|\d+-of-\d+/i.test(value), 'Choose one complete GGUF, without projector or shards.'),+ artifactDigest: digest, downloadBytes: bytes, license: z.string().trim().min(1).max(256),+ runtimeMemoryBytes: bytes, runtime: z.string().min(1).max(256),+ sourceLicenseReviewed: z.literal(true), runtimeCompatibilityReviewed: z.literal(true),+}).strict().refine(row => row.runtimeMemoryBytes >= row.downloadBytes, 'The reviewed memory budget must cover the weights.');+const hash = value => createHash('sha256').update(canonicalStringify(value)).digest('hex');+const fail = (code, message) => { throw Object.assign(new Error(message), { code, status: 409 }); };+const sourceFor = entry => {+ const repo = entry?.lmstudio?.split('@')[0];+ if (!entry || !/^[a-z0-9][a-z0-9-]*$/.test(entry.key) || entry.gated || entry.appleSiliconOnly || entry.format === 'mlx'+ || entry.capabilities?.includes('vision') || !/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(repo ?? '')+ || repo.includes('..') || !/gguf/i.test(repo)) return null;+ return repo;+};+const publicReview = row => {+ const { sourceLicenseReviewed: _source, runtimeCompatibilityReviewed: _runtime, sourceRepo: _repo,+ authority: _authority, ...review } = row;+ return { ...review, modelId: row.sourceRepo, scratchBytes: 512 * 1024 ** 2 };+};+const exists = path => fs.lstat(path).then(() => true, error => {+ if (error.code === 'ENOENT') return false;+ throw error;+});+async function syncDirectory(path) {+ if (process.platform === 'win32') return;+ const file = await fs.open(path, 'r');+ try { await file.sync(); } finally { await file.close(); }+}++/** Inject only receiver-owned probes/settings and an offline fixture transport in tests. */+export function _createPeerCatalogInstaller({ catalog, readReviews, writeReviews, inspectRuntime,+ fetchImpl = fetch, download = args => downloadPinned({ ...args, fetchImpl }),+ afterInstall = async () => {}, assertWrite = assertNotRealDataWrite } = {}) {+ const read = async () => {+ const value = await readReviews();+ // Parse the input portion independently because input is intentionally strict.+ const rows = z.array(z.record(z.string(), z.unknown())).max(32).parse(value);+ return rows.map(row => {+ const { sourceRepo, destinationDigest, reviewRevision, authority, ...input } = row;+ const parsed = peerCatalogReviewSchema.parse(input);+ const metadata = z.object({ sourceRepo: z.string(), destinationDigest: digest, reviewRevision: digest,+ authority: z.enum(['operator-session', 'local-operator']) }).strict().parse({ sourceRepo, destinationDigest, reviewRevision, authority });+ return { ...parsed, ...metadata };+ });+ };+ const target = raw => {+ const input = peerCatalogReviewTargetSchema.parse(raw);+ const entry = catalog.find(row => row.key === input.catalogKey);+ const sourceRepo = sourceFor(entry);+ if (!sourceRepo) fail('PEER_EXECUTION_CATALOG_UNSUPPORTED', 'Only catalog-backed, non-gated, single-file GGUF imports are supported.');+ return { ...input, sourceRepo, name: entry.name };+ };+ const observed = async () => {+ const runtime = await inspectRuntime();+ if (!runtime?.modelsRoot || !runtime.runtime) fail('PEER_EXECUTION_RUNTIME_UNKNOWN', 'The installed local LM Studio runtime and models directory must be known.');+ const root = await fs.realpath(runtime.modelsRoot);+ const rootStat = await fs.stat(root);+ if (!rootStat.isDirectory()) fail('PEER_EXECUTION_DESTINATION_UNKNOWN', 'The actual models volume is unavailable.');+ return { ...runtime, modelsRoot: root, destinationDigest: hash({ root, dev: rootStat.dev, ino: rootStat.ino }) };+ };+ const describe = async raw => {+ const selection = target(raw);+ const runtime = await observed();+ return { ...selection, runtime: runtime.runtime, destinationDigest: runtime.destinationDigest, modelsDirectory: runtime.modelsRoot };+ };+ const save = async (raw, authority) => {+ const input = peerCatalogReviewSchema.parse(raw);+ z.enum(['operator-session', 'local-operator']).parse(authority);+ const selection = await describe({ backend: input.backend, catalogKey: input.catalogKey });+ const quant = catalog.find(row => row.key === input.catalogKey).lmstudio.split('@')[1];+ if (quant && !input.fileName.toLowerCase().includes(quant.toLowerCase()))+ fail('PEER_EXECUTION_CATALOG_QUANT_CHANGED', 'The reviewed file must match the catalog quantization.');+ if (input.runtime !== selection.runtime) fail('PEER_EXECUTION_RUNTIME_CHANGED', 'Refresh and review the current installed runtime.');+ const row = { ...input, sourceRepo: selection.sourceRepo, destinationDigest: selection.destinationDigest, authority };+ const review = { ...row, reviewRevision: hash(row) };+ const previous = await read();+ const next = previous.filter(row => row.catalogKey !== input.catalogKey);+ if (next.length >= 32) fail('PEER_EXECUTION_CATALOG_LIMIT', 'The bounded review store is full.');+ await writeReviews([...next, review]);+ return review;+ };+ const list = async () => ({ candidates: catalog.filter(sourceFor).map(row => ({ catalogKey: row.key,+ backend: 'lmstudio', name: row.name })), reviews: await read() });+ const resolve = async intent => {+ const selection = target({ backend: intent.backend, catalogKey: intent.catalogKey });+ const row = (await read()).find(item => item.catalogKey === selection.catalogKey);+ if (!row) fail('PEER_EXECUTION_CATALOG_UNREVIEWED', 'Review this exact source, license and runtime locally first.');+ if (row.sourceRepo !== selection.sourceRepo) fail('PEER_EXECUTION_CATALOG_CHANGED', 'The reviewed source changed.');+ const { reviewRevision, ...reviewed } = row;+ if (hash(reviewed) !== reviewRevision) fail('PEER_EXECUTION_CATALOG_CHANGED', 'The stored review is inconsistent.');+ return resolveLocation(row);+ };+ const resolveLocation = async row => {+ const runtime = await observed();+ if (row.runtime !== runtime.runtime || row.destinationDigest !== runtime.destinationDigest)+ fail('PEER_EXECUTION_CATALOG_CHANGED', 'The reviewed runtime or destination changed.');+ const directory = join(runtime.modelsRoot, ...row.sourceRepo.split('/'));+ // The root itself may deliberately be a configured symlink. Descendants+ // cannot redirect the receiver-reviewed destination to another volume.+ for (const path of [join(runtime.modelsRoot, row.sourceRepo.split('/')[0]), directory]) {+ const entry = await fs.lstat(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });+ if (entry && !entry.isDirectory()) fail('PEER_EXECUTION_DESTINATION_CHANGED', 'Model destination contains a symlink or non-directory.');+ }+ return { row, runtime, directory, destination: join(directory, row.fileName) };+ };+ const probe = async intent => {+ const { row, runtime, destination } = await resolve(intent);+ if (await exists(destination)) fail('PEER_EXECUTION_MODEL_EXISTS', 'The reviewed model file already exists; it will not be overwritten.');+ return { review: publicReview(row), resources: { destinationFreeBytes: runtime.destinationFreeBytes,+ availableMemoryBytes: runtime.availableMemoryBytes, runtime: runtime.runtime, destinationDigest: runtime.destinationDigest } };+ };+ const install = async ({ operation, evidence, evidenceDigest, capability }) => {+ // The dispatcher holds the shared identity mutex through this recheck and+ // launch; downloads then run outside it, so grants may still be revoked.+ const resolved = await resolve(evidence.intent);+ if (hash({ version: 1, intent: evidence.intent, target: publicReview(resolved.row) }) !== evidenceDigest)+ fail('PEER_EXECUTION_CATALOG_CHANGED', 'The reviewed artifact changed before launch.');+ assertPeerExecutionCapability(capability, evidence.intent, evidenceDigest);+ const id = z.string().uuid().parse(operation.operationId);+ const { row, runtime, directory, destination } = resolved;+ assertWrite(directory, 'peer catalog model installation');+ if (await exists(destination)) fail('PEER_EXECUTION_MODEL_EXISTS', 'Existing model files are never replaced.');+ if (runtime.destinationFreeBytes < row.downloadBytes + 512 * 1024 ** 2 || runtime.availableMemoryBytes < row.runtimeMemoryBytes)+ fail('PEER_EXECUTION_RESOURCES_INSUFFICIENT', 'The actual model destination or runtime has insufficient capacity.');+ await fs.mkdir(directory, { recursive: true });+ // Re-resolve after directory creation and before launching the write.+ if (await fs.realpath(directory) !== directory) fail('PEER_EXECUTION_DESTINATION_CHANGED', 'Model destination changed before launch.');+ const staging = join(directory, `.portos-peer-${id}`);+ await fs.mkdir(staging, { mode: 0o700 }); // no reuse/resume of an earlier launch+ assertPeerExecutionCapability(capability, evidence.intent, evidenceDigest);+ let published = false;+ const complete = async () => {+ const artifact = join(staging, 'artifact');+ const result = await download({ url: `https://huggingface.co/${row.sourceRepo}/resolve/${row.sourceRevision}/${encodeURIComponent(row.fileName)}`,+ artifact, expectedBytes: row.downloadBytes, expectedDigest: row.artifactDigest });+ if (result.bytes !== row.downloadBytes || result.digest !== row.artifactDigest)+ fail('PEER_EXECUTION_ARTIFACT_MISMATCH', 'Downloaded bytes do not match the reviewed artifact.');+ const currentRuntime = await observed();+ if (currentRuntime.destinationDigest !== row.destinationDigest || currentRuntime.runtime !== row.runtime+ || await fs.realpath(directory) !== directory)+ fail('PEER_EXECUTION_CATALOG_CHANGED', 'The runtime or model destination changed during download.');+ // Never replace a file installed concurrently outside PortOS. Same-volume+ // hardlink is atomic and preserves the verified bytes without another copy.+ await fs.link(artifact, destination);+ published = true;+ await syncDirectory(directory);+ await fs.rm(staging, { recursive: true });+ await syncDirectory(directory);+ await afterInstall(row);+ return { state: 'succeeded', code: 'PEER_EXECUTION_CATALOG_INSTALLED', evidenceDigest: hash({ operationId: id,+ evidenceDigest, artifactDigest: row.artifactDigest, bytes: row.downloadBytes, cleanup: true }) };+ };+ // A failure never claims clean terminal persistence. Reconciliation can+ // verify a published artifact after a crash, otherwise ownership stays held.+ return { completion: complete().catch(async error => {+ if (published) throw error;+ await fs.rm(staging, { recursive: true });+ await syncDirectory(directory);+ return { state: 'failed', code: /^[A-Z0-9_]{1,100}$/.test(error.code) ? error.code : 'PEER_EXECUTION_CATALOG_DOWNLOAD_FAILED',+ evidenceDigest: hash({ operationId: id, evidenceDigest, published: false, cleanup: true }) };+ }) };+ };+ const reconcile = async (operation, evidence) => {+ if (hash(evidence) !== operation.binding.evidenceDigest+ || canonicalStringify(evidence.intent) !== canonicalStringify(operation.binding.intent)) return null;+ // The immutable launch snapshot, not today's replaceable review, owns the+ // artifact after a crash. A later local review cannot erase completion proof.+ const target = evidence.target;+ const row = { ...peerCatalogReviewSchema.parse({ backend: target.backend, catalogKey: target.catalogKey,+ sourceRevision: target.sourceRevision, fileName: target.fileName, artifactDigest: target.artifactDigest,+ downloadBytes: target.downloadBytes, license: target.license, runtimeMemoryBytes: target.runtimeMemoryBytes,+ runtime: target.runtime, sourceLicenseReviewed: true, runtimeCompatibilityReviewed: true }),+ sourceRepo: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9][A-Za-z0-9_.-]*$/)+ .refine(value => !value.includes('..')).parse(target.modelId),+ destinationDigest: digest.parse(target.destinationDigest) };+ const { destination, directory } = await resolveLocation(row);+ const entry = await fs.lstat(destination).catch(() => null);+ if (!entry?.isFile() || entry.size !== row.downloadBytes) return null;+ const { sha256File } = await import('../lib/fileCore.js');+ if (await sha256File(destination) !== row.artifactDigest) return null;+ const staging = join(directory, `.portos-peer-${z.string().uuid().parse(operation.operationId)}`);+ assertWrite(staging, 'peer catalog completed stage cleanup');+ if (await exists(staging)) {+ if (!(await fs.lstat(staging)).isDirectory()) return null;+ const names = await fs.readdir(staging);+ if (names.some(name => name !== 'artifact')) return null;+ await fs.rm(staging, { recursive: true });+ await syncDirectory(directory);+ }+ await afterInstall(row);+ return { state: 'succeeded', code: 'PEER_EXECUTION_CATALOG_VERIFIED', evidenceDigest: hash({ operationId: operation.operationId,+ evidenceDigest: operation.binding.evidenceDigest, artifactDigest: row.artifactDigest, bytes: row.downloadBytes, cleanup: true }) };+ };+ return { describe, save, list, probe, install, reconcile };+}++async function downloadPinned({ url, artifact, expectedBytes, expectedDigest, fetchImpl = fetch }) {+ const response = await fetchImpl(url, { signal: AbortSignal.timeout(30 * 60_000), headers: { 'Accept-Encoding': 'identity' } });+ if (!response.ok || !response.body) fail('PEER_EXECUTION_DOWNLOAD_FAILED', 'Pinned artifact download failed.');+ const file = await fs.open(artifact, 'wx', 0o600);+ const hasher = createHash('sha256');+ let count = 0;+ let header = Buffer.alloc(0);+ try {+ for await (const chunk of response.body) {+ count += chunk.length;+ if (count > expectedBytes) fail('PEER_EXECUTION_ARTIFACT_MISMATCH', 'Artifact exceeds reviewed size.');+ if (header.length < 8) header = Buffer.concat([header, Buffer.from(chunk).subarray(0, 8 - header.length)]);+ hasher.update(chunk);+ await file.writeFile(chunk);+ }+ const actual = hasher.digest('hex');+ if (count !== expectedBytes || actual !== expectedDigest || header.length < 8+ || header.subarray(0, 4).toString('ascii') !== 'GGUF' || ![2, 3].includes(header.readUInt32LE(4)))+ fail('PEER_EXECUTION_ARTIFACT_MISMATCH', 'Downloaded GGUF does not match the reviewed bytes.');+ await file.sync();+ return { bytes: count, digest: actual };+ } finally { await file.close(); }+}++let singleton;+async function production() {+ if (singleton) return singleton;+ const [{ LOCAL_LLM_CATALOG }, { PATHS, readJSONFile, atomicWrite }, manager, { findCommandOnPath }, { bufferedSpawn }, os] = await Promise.all([+ import('../lib/localLlmCatalog.js'), import('../lib/fileUtils.js'), import('./lmStudioManager.js'),+ import('../lib/processEnv.js'), import('../lib/bufferedSpawn.js'), import('node:os'),+ ]);+ const path = join(PATHS.data, 'peer-execution-catalog.json');+ singleton = _createPeerCatalogInstaller({ catalog: LOCAL_LLM_CATALOG,+ readReviews: () => readJSONFile(path, [], { strict: true, logError: false }), writeReviews: rows => atomicWrite(path, rows),+ inspectRuntime: async () => {+ const binary = findCommandOnPath('lms');+ if (!binary) fail('PEER_EXECUTION_RUNTIME_UNKNOWN', 'Install and configure LM Studio locally first.');+ // Documented read-only inventory; never runtime get/select/update.+ const result = await bufferedSpawn(binary, ['runtime', 'ls'], { timeoutMs: 10000, shell: false });+ if (!result.success || !/llama.cpp/i.test(result.stdout) || result.stdout.length > 16384)+ fail('PEER_EXECUTION_RUNTIME_UNKNOWN', 'The installed GGUF runtime inventory is unavailable.');+ // A conventional folder may be stale after the app's GUI directory was+ // changed. Require the receiver's explicit model-root configuration.+ const configuredRoot = process.env.LM_STUDIO_MODELS_DIR;+ if (!configuredRoot || !isAbsolute(configuredRoot))+ fail('PEER_EXECUTION_DESTINATION_UNKNOWN', 'Set LM_STUDIO_MODELS_DIR to the Models directory configured in LM Studio before reviewing peer imports.');+ const modelsRoot = await fs.realpath(configuredRoot);+ if (modelsRoot !== await fs.realpath(await manager.getModelsDir()))+ fail('PEER_EXECUTION_DESTINATION_CHANGED', 'LM Studio model destination could not be verified.');+ const disk = await fs.statfs(modelsRoot);+ return { modelsRoot, runtime: `lmstudio:${hash({ binary: await fs.realpath(binary), inventory: result.stdout.trim() })}`,+ destinationFreeBytes: disk.bavail * disk.bsize, availableMemoryBytes: os.freemem() };+ }, download: downloadPinned, afterInstall: async row => {+ manager.resetCache();+ const [{ recordModelInstall }, { localModelInventoryRow }, { invalidateModelObservation }] = await Promise.all([+ import('./modelManifest.js'), import('../lib/modelInventory.js'), import('./modelObservation.js'),+ ]);+ await recordModelInstall({ ...localModelInventoryRow({ backend: 'lmstudio', modelId: row.sourceRepo }), source: 'download' });+ invalidateModelObservation('loaded-models');+ invalidateModelObservation('provider-readiness');+ },+ });+ return singleton;+}+export const describePeerCatalogReview = async input => (await production()).describe(input);+export const listPeerCatalogReviews = async () => (await production()).list();+export async function savePeerCatalogReview(input, req) {+ const [{ withInstanceIdentityLock }, { requestHasHostControl }] = await Promise.all([import('./instanceIdentity.js'), import('./authGate.js')]);+ const method = req?.portosAuthContext?.method;+ if (!req || method === 'peer' || !requestHasHostControl(req)) fail('PEER_EXECUTION_REVIEW_AUTHORITY', 'A receiver operator must review model installation.');+ return withInstanceIdentityLock(async () => (await production()).save(input, method === 'session' ? 'operator-session' : 'local-operator'));+}+export const probePeerCatalog = async intent => (await production()).probe(intent);+export const installPeerCatalog = async context => (await production()).install(context);+export const reconcilePeerCatalog = async (operation, evidence) => (await production()).reconcile(operation, evidence);diff --git a/server/services/peerCatalogInstaller.test.js b/server/services/peerCatalogInstaller.test.jsnew file mode 100644index 0000000000..024a356570--- /dev/null+++ b/server/services/peerCatalogInstaller.test.js@@ -0,0 +1,105 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createHash, randomUUID } from 'node:crypto';+import * as fs from 'node:fs/promises';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { _createPeerCatalogInstaller, peerCatalogReviewSchema } from './peerCatalogInstaller.js';+import { _createPeerExecutionAdapters, peerExecutionEvidenceDigest } from './peerExecutionAdapters.js';+import { createMaintenanceAdmission } from '../lib/maintenanceAdmission.js';++const roots = [];+afterEach(async () => { for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true }); });+const intent = { action: 'catalog.install', backend: 'lmstudio', catalogKey: 'fixture' };+const payload = Buffer.alloc(32, 1);+payload.write('GGUF'); payload.writeUInt32LE(3, 4);+const digest = value => createHash('sha256').update(value).digest('hex');+const reviewInput = () => ({ backend: 'lmstudio', catalogKey: 'fixture', sourceRevision: 'a'.repeat(40),+ fileName: 'fixture-Q4_K_M.gguf', artifactDigest: digest(payload), downloadBytes: payload.length,+ license: 'fixture-license', runtimeMemoryBytes: 1024, runtime: 'fixture-runtime',+ sourceLicenseReviewed: true, runtimeCompatibilityReviewed: true });+async function fixture() {+ const root = await fs.mkdtemp(join(tmpdir(), 'peer-catalog-')); roots.push(root);+ let rows = [];+ let runtime = { modelsRoot: root, runtime: 'fixture-runtime', destinationFreeBytes: 1024 ** 3, availableMemoryBytes: 4096 };+ const fetchImpl = vi.fn(async () => new Response(payload));+ const service = _createPeerCatalogInstaller({ catalog: [{ key: 'fixture', name: 'Fixture', lmstudio: 'fixture/model-GGUF' }],+ readReviews: async () => rows, writeReviews: async next => { rows = next; }, inspectRuntime: async () => runtime, fetchImpl });+ const adapters = _createPeerExecutionAdapters({ probeCatalog: service.probe, installCatalog: service.install });+ const authorize = evidence => {+ const coordinator = createMaintenanceAdmission(join(root, 'data'));+ const hold = coordinator.begin({ reason: 'Fixture drain', owner: 'Fixture operator' }).hold;+ const operation = { operationId: randomUUID(), requestId: randomUUID(), peerInstanceId: randomUUID(), hostInstanceId: randomUUID(),+ grantId: randomUUID(), grantGeneration: 1, scope: 'execution-v1', pairBinding: 'a'.repeat(64),+ intent, receiverVersion: '1.2.3', evidenceDigest: peerExecutionEvidenceDigest(evidence) };+ const claim = coordinator.claimReady({ id: hold.id, revision: hold.revision, operation }, coordinator.observeIdle());+ const started = coordinator.transitionExclusive({ id: claim.id, revision: claim.revision, fingerprint: claim.fingerprint }, 'in-flight', coordinator.observeIdle());+ return { capability: coordinator.issueExecutionCapability(started), operation };+ };+ return { root, service, adapters, fetchImpl, authorize, setRuntime: value => { runtime = { ...runtime, ...value }; },+ destination: join(root, 'fixture/model-GGUF', reviewInput().fileName) };+}++describe('receiver-reviewed pinned GGUF installation', () => {+ it('installs only the reviewed bytes into the actual model tree and reconciles them after restart', async () => {+ const f = await fixture();+ expect(await f.service.describe({ backend: 'lmstudio', catalogKey: 'fixture' })).toMatchObject({ sourceRepo: 'fixture/model-GGUF', runtime: 'fixture-runtime' });+ await f.service.save(reviewInput(), 'operator-session');+ const evidence = await f.adapters.prepare(intent);+ const { capability, operation } = f.authorize(evidence);+ const launched = await f.adapters.run(intent, evidence, { capability });+ expect(launched.completion).toBeInstanceOf(Promise);+ await expect(launched.completion).resolves.toMatchObject({ state: 'succeeded' });+ expect(await fs.readFile(f.destination)).toEqual(payload);+ expect(f.fetchImpl.mock.calls[0][0]).toBe(`https://huggingface.co/fixture/model-GGUF/resolve/${'a'.repeat(40)}/fixture-Q4_K_M.gguf`);+ expect(await fs.readdir(join(f.root, 'fixture/model-GGUF'))).toEqual([reviewInput().fileName]);+ // A receiver may review the next version while this operation is in flight.+ await f.service.save({ ...reviewInput(), sourceRevision: 'b'.repeat(40), fileName: 'next.gguf' }, 'operator-session');+ const recovered = { operationId: operation.operationId, binding: { intent, evidenceDigest: operation.evidenceDigest } };+ await expect(f.service.reconcile(recovered, evidence)).resolves.toMatchObject({ state: 'succeeded' });+ await fs.writeFile(f.destination, Buffer.alloc(32));+ await expect(f.service.reconcile(recovered, evidence)).resolves.toBeNull();+ });++ it('never publishes a wrong hash, oversized stream or non-GGUF, and proves staging cleanup on failure', async () => {+ for (const [body, artifactDigest] of [[Buffer.alloc(32), digest(payload)], [Buffer.alloc(33), digest(payload)],+ [Buffer.alloc(31), digest(payload)], [Buffer.alloc(32), digest(Buffer.alloc(32))]]) {+ const f = await fixture();+ await f.service.save({ ...reviewInput(), artifactDigest }, 'local-operator');+ f.fetchImpl.mockImplementation(async () => new Response(body));+ const evidence = await f.adapters.prepare(intent);+ const { capability } = f.authorize(evidence);+ const launched = await f.adapters.run(intent, evidence, { capability });+ await expect(launched.completion).resolves.toMatchObject({ state: 'failed', code: 'PEER_EXECUTION_ARTIFACT_MISMATCH' });+ expect(await fs.readdir(join(f.root, 'fixture/model-GGUF'))).toEqual([]);+ }+ });++ it('refuses changed runtime, insufficient destination capacity and an existing file before downloading', async () => {+ const f = await fixture();+ await expect(f.adapters.prepare(intent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_CATALOG_UNREVIEWED' });+ await f.service.save(reviewInput(), 'operator-session');+ f.setRuntime({ runtime: 'changed-runtime' });+ await expect(f.adapters.prepare(intent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_CATALOG_CHANGED' });+ f.setRuntime({ runtime: 'fixture-runtime', destinationFreeBytes: 20 });+ await expect(f.adapters.prepare(intent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_RESOURCES_INSUFFICIENT' });+ f.setRuntime({ destinationFreeBytes: 1024 ** 3 });+ await fs.mkdir(join(f.root, 'fixture/model-GGUF'), { recursive: true });+ await fs.writeFile(f.destination, 'preserve');+ await expect(f.adapters.prepare(intent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_MODEL_EXISTS' });+ expect(await fs.readFile(f.destination, 'utf8')).toBe('preserve');+ expect(f.fetchImpl).not.toHaveBeenCalled();+ });++ it('refuses peer recipes, shards, incomplete local review and destination symlinks', async () => {+ const f = await fixture();+ expect(peerCatalogReviewSchema.safeParse({ ...reviewInput(), url: 'https://arbitrary.invalid' }).success).toBe(false);+ expect(peerCatalogReviewSchema.safeParse({ ...reviewInput(), fileName: '../model.gguf' }).success).toBe(false);+ expect(peerCatalogReviewSchema.safeParse({ ...reviewInput(), fileName: 'model-00001-of-00002.gguf' }).success).toBe(false);+ expect(peerCatalogReviewSchema.safeParse({ ...reviewInput(), sourceLicenseReviewed: false }).success).toBe(false);+ await f.service.save(reviewInput(), 'operator-session');+ const outside = await fs.mkdtemp(join(tmpdir(), 'peer-catalog-outside-')); roots.push(outside);+ await fs.symlink(outside, join(f.root, 'fixture'), 'dir');+ await expect(f.adapters.prepare(intent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_DESTINATION_CHANGED' });+ expect(f.fetchImpl).not.toHaveBeenCalled();+ });+});diff --git a/server/services/peerExecution.js b/server/services/peerExecution.jsnew file mode 100644index 0000000000..c62924b2cb--- /dev/null+++ b/server/services/peerExecution.js@@ -0,0 +1,238 @@+/** Receiver-owned execution state machine. An accepted request is never a completion. */+import { createHash } from 'node:crypto';+import { canonicalStringify } from '../lib/objects.js';+import { createMutex } from '../lib/asyncMutex.js';+import { peerExecutionError } from './peerExecutionGrants.js';+import { peerAdminPairBinding, signPeerAdmin } from './peerAdministration.js';++const hash = value => createHash('sha256').update(canonicalStringify(value)).digest('hex');+const claimRef = claim => ({ id: claim.id, revision: claim.revision, fingerprint: claim.fingerprint });+const terminal = operation => ['succeeded', 'failed'].includes(operation.state);+const fail = (code, message) => { throw peerExecutionError(code, message); };+const journalOperation = operation => {+ const { executionEpoch: _epoch, ...binding } = operation.binding;+ return { operationId: operation.operationId, ...binding };+};++export function createPeerExecutionReceiver({ ledger, grants, coordinator, adapters, caller, version,+ now = Date.now, changed = () => {}, identityLock = fn => fn(), terminalProofs = new Map(), resume = input => coordinator.resume(input) }) {+ const withLock = createMutex();+ const locked = fn => identityLock(() => withLock(fn));+ const preflights = new Map();+ const pending = new Map();+ const running = new Set();+ let draining = false;+ let drainAgain = false;+ const emit = () => { try { changed(); } catch { console.error('❌ Peer execution status notification failed.'); } };+ const assertCurrent = async (peerId, binding) => {+ const pair = await grants.current(peerId, binding.intent.action);+ const grant = pair.grant;+ ledger.authority.requireReady(binding.executionEpoch);+ if (pair.self.instanceId !== binding.hostInstanceId || pair.peer.instanceId !== binding.peerInstanceId+ || peerAdminPairBinding(pair.peer, pair.self) !== binding.pairBinding+ || grant.id !== binding.grantId || grant.generation !== binding.grantGeneration+ || version !== binding.receiverVersion) fail('PEER_EXECUTION_AUTHORITY_CHANGED', 'Pair, grant, receiver or execution authority changed.');+ return pair;+ };+ const receipt = (operation, pair) => {+ const payload = { protocolVersion: 1, scope: 'execution-v1', requestId: operation.binding.requestId,+ senderInstanceId: pair.peer.instanceId, targetInstanceId: pair.self.instanceId,+ operationId: operation.operationId, state: operation.state, revision: operation.revision, code: operation.receipt?.code ?? null };+ return { payload, signature: signPeerAdmin(pair.peer, 'execution-receipt', payload) };+ };+ const findRequest = (pair, requestId) => ledger.readRequest({ hostInstanceId: pair.self.instanceId, peerInstanceId: pair.peer.instanceId, requestId });+ const preflight = (req, input) => locked(async () => {+ for (const [key, value] of preflights) if (value.payload.expiresAt <= now()) preflights.delete(key);+ const pair = await caller(req);+ if (await findRequest(pair, input.requestId)) fail('PEER_EXECUTION_CONSUMED', 'Use status for an already-consumed request.');+ if (preflights.size >= 128) fail('PEER_EXECUTION_PREFLIGHT_LIMIT', 'Too many outstanding execution preflights.');+ const { grant } = await grants.current(pair.peer.id, input.intent.action);+ const evidence = await adapters.prepare(input.intent);+ const binding = { hostInstanceId: pair.self.instanceId, peerInstanceId: pair.peer.instanceId,+ requestId: input.requestId, grantId: grant.id, grantGeneration: grant.generation, scope: 'execution-v1',+ pairBinding: peerAdminPairBinding(pair.peer, pair.self), intent: input.intent, receiverVersion: version,+ evidenceDigest: hash(evidence), executionEpoch: grant.executionEpoch };+ await caller(req);+ await assertCurrent(pair.peer.id, binding);+ const payload = { protocolVersion: 1, scope: 'execution-v1', requestId: input.requestId,+ grantId: grant.id, grantGeneration: grant.generation, intent: input.intent, version,+ evidenceDigest: binding.evidenceDigest, executionEpoch: binding.executionEpoch,+ senderInstanceId: pair.peer.instanceId, targetInstanceId: pair.self.instanceId,+ expiresAt: Math.min(now() + 60_000, grant.expiresAt) };+ const key = `${pair.peer.instanceId}:${input.requestId}`;+ if (preflights.has(key)) fail('PEER_EXECUTION_PREFLIGHT_REPLAY', 'Use a fresh request identity for preflight.');+ preflights.set(key, { payload, binding, evidence });+ return { payload, signature: signPeerAdmin(pair.peer, 'execution-preflight', payload) };+ });+ const finish = async (operation, result, claim) => {+ const state = result.state;+ if (!['succeeded', 'failed'].includes(state) || !/^[A-Z0-9_]{1,100}$/.test(result.code))+ fail('PEER_EXECUTION_RECEIPT_INVALID', 'The adapter did not prove a terminal outcome.');+ const epoch = ledger.authority.read()?.epoch;+ const proof = { outcome: state, code: result.code, evidenceDigest: result.evidenceDigest ?? hash(result), executionEpoch: epoch };+ const completed = terminal(operation) ? operation : await ledger.transition(operation.operationId, operation.revision, state, { receipt: proof, authorityEpoch: epoch });+ if (claim) ledger.authority.requireReady(completed.receipt.executionEpoch);+ if (claim) {+ const current = coordinator.getExclusive();+ if (!current || current.id !== claim.id || current.fingerprint !== claim.fingerprint+ || hash(current.operation) !== hash(journalOperation(completed))+ || (completed.claim && (completed.claim.id !== current.id || completed.claim.fingerprint !== current.fingerprint)))+ fail('PEER_EXECUTION_CLAIM_CHANGED', 'Completion cannot release a different maintenance owner.');+ const receiptDigest = hash(completed.receipt);+ terminalProofs.set(current.operation.operationId, { fingerprint: current.fingerprint, receiptDigest, outcome: state });+ coordinator.settleExclusive(claimRef(current), { outcome: state, receiptDigest });+ terminalProofs.delete(current.operation.operationId);+ }+ pending.delete(operation.operationId);+ const status = coordinator.status();+ if (status.hold?.owner === `peer-execution:${operation.operationId}` && !coordinator.getExclusive())+ await resume({ id: status.hold.id, revision: status.hold.revision });+ emit();+ return completed;+ };+ const uncertain = async (operation, claim) => {+ const current = coordinator.getExclusive();+ if (claim && current?.id === claim.id && current.phase !== 'uncertain')+ coordinator.transitionExclusive(claimRef(current), 'uncertain');+ if (!terminal(operation) && operation.state !== 'uncertain')+ await ledger.transition(operation.operationId, operation.revision, 'uncertain');+ pending.delete(operation.operationId);+ emit();+ };+ const drain = async () => {+ if (draining) { drainAgain = true; return; }+ draining = true;+ try {+ for (const [id, accepted] of pending) {+ let launched;+ await locked(async () => {+ let operation = await ledger.read(id);+ if (!operation || terminal(operation)) { pending.delete(id); return; }+ let claim;+ try {+ await assertCurrent(accepted.peerId, operation.binding);+ let status = coordinator.status();+ if (status.state === 'normal') status = coordinator.begin({ reason: 'Authorized peer administration; existing work settles naturally.', owner: `peer-execution:${id}` });+ if (status.hold?.owner !== `peer-execution:${id}`) return;+ if (operation.state === 'queued') operation = await ledger.transition(id, operation.revision, 'draining');+ if (status.state !== 'ready') return;+ claim = coordinator.claimReady({ id: status.hold.id, revision: status.hold.revision, operation: journalOperation(operation) }, coordinator.observeIdle());+ const evidence = await adapters.prepare(operation.binding.intent);+ if (hash(evidence) !== operation.binding.evidenceDigest)+ fail('PEER_EXECUTION_EVIDENCE_CHANGED', 'Receiver-side requirements changed during drain. Preview again.');+ await assertCurrent(accepted.peerId, operation.binding);+ // No await between the last authority check and the coordinator's+ // atomic idle/revision transition; resume and ordinary admission fence here.+ claim = coordinator.transitionExclusive(claimRef(claim), 'in-flight', coordinator.observeIdle());+ operation = await ledger.transition(id, operation.revision, 'in-flight', { claim: claimRef(claim) });+ await assertCurrent(accepted.peerId, operation.binding);+ const capability = coordinator.issueExecutionCapability(claim);+ const result = await adapters.run(operation.binding.intent, evidence, { capability, coordinator });+ launched = { operation, claim, result };+ running.add(id);+ pending.delete(id);+ emit();+ } catch (error) {+ const current = coordinator.getExclusive();+ if (current?.operation.operationId === id && current.phase !== 'reserved') {+ await uncertain(operation, current);+ } else {+ if (current?.operation.operationId === id) coordinator.settleExclusive(claimRef(current), { outcome: 'cancelled', receiptDigest: null });+ await finish(operation, { state: 'failed', code: /^[A-Z0-9_]{1,100}$/.test(error.code) ? error.code : 'PEER_EXECUTION_PREFLIGHT_FAILED' }, null);+ }+ }+ });+ if (launched) {+ const { operation, claim, result } = launched;+ // Completion owns its rejection outside the Express lifecycle. No+ // timeout, rejection or reconnect path ever calls run again.+ Promise.resolve(result.completion ?? result).then(outcome => locked(async () => {+ const current = await ledger.read(operation.operationId);+ running.delete(operation.operationId);+ if (outcome.state === 'awaiting-reconnect') {+ const owner = coordinator.getExclusive();+ coordinator.transitionExclusive(claimRef(owner), 'awaiting-reconnect');+ await ledger.transition(current.operationId, current.revision, 'awaiting-reconnect');+ emit();+ } else await finish(current, outcome, claim);+ })).catch(async () => {+ running.delete(operation.operationId);+ try { await locked(async () => uncertain(await ledger.read(operation.operationId), claim)); }+ catch { console.error('❌ Peer execution completion is uncertain; maintenance ownership remains held.'); }+ });+ }+ }+ } finally {+ draining = false;+ if (drainAgain) { drainAgain = false; queueMicrotask(kick); }+ }+ };+ const kick = () => { drain().catch(() => console.error('❌ Peer execution drain needs recovery; no retry launch was scheduled.')); };+ const dispatch = async (req, input) => {+ const response = await locked(async () => {+ const pair = await caller(req);+ const previous = await findRequest(pair, input.requestId);+ if (previous) {+ const b = previous.binding;+ if (b.grantId !== input.grantId || b.grantGeneration !== input.grantGeneration || b.evidenceDigest !== input.evidenceDigest+ || b.executionEpoch !== input.executionEpoch || b.receiverVersion !== input.version || hash(b.intent) !== hash(input.intent))+ fail('PEER_EXECUTION_REPLAY_CONFLICT', 'This request identity already belongs to different input.');+ return receipt(previous, pair);+ }+ const key = `${pair.peer.instanceId}:${input.requestId}`;+ const saved = preflights.get(key);+ if (!saved || saved.payload.expiresAt <= now()) fail('PEER_EXECUTION_PREFLIGHT_STALE', 'A fresh receiver preflight is required.');+ const { scope: _scope, senderInstanceId: _sender, targetInstanceId: _target, expiresAt: _expiry, ...expected } = saved.payload;+ if (hash(expected) !== hash(input)) fail('PEER_EXECUTION_PREFLIGHT_STALE', 'Dispatch differs from the signed preflight.');+ await assertCurrent(pair.peer.id, saved.binding);+ const { operation, isNew } = await ledger.consume(saved.binding);+ preflights.delete(key);+ if (isNew) pending.set(operation.operationId, { peerId: pair.peer.id });+ emit();+ return receipt(operation, pair);+ });+ kick();+ return response;+ };+ const reconcileOperation = async operation => {+ const claim = coordinator.getExclusive();+ const owns = claim?.operation.operationId === operation.operationId;+ if (terminal(operation)) {+ await finish(operation, { state: operation.state, code: operation.receipt.code }, owns ? claim : null);+ } else if ((owns && claim.phase !== 'reserved') || ['in-flight', 'awaiting-reconnect', 'uncertain'].includes(operation.state)) {+ const result = await adapters.reconcile(operation);+ if (result && ['succeeded', 'failed'].includes(result.state)) await finish(operation, result, owns ? claim : null);+ else await uncertain(operation, owns ? claim : null);+ } else {+ if (owns) coordinator.settleExclusive(claimRef(claim), { outcome: 'cancelled', receiptDigest: null });+ await finish(operation, { state: 'failed', code: 'PEER_EXECUTION_INTERRUPTED_BEFORE_LAUNCH' }, null);+ }+ };+ const status = (req, { requestId }) => locked(async () => {+ const pair = await caller(req);+ let operation = await findRequest(pair, requestId);+ if (!operation) throw peerExecutionError('PEER_EXECUTION_NOT_FOUND', 'Execution request not found.', 404);+ // A deliberate receipt read may observe completion written after server boot.+ // It never dispatches work, retries a launch, or cancels live local work.+ if (!pending.has(operation.operationId) && !running.has(operation.operationId)) {+ await reconcileOperation(operation);+ operation = await ledger.read(operation.operationId);+ }+ return receipt(operation, pair);+ });+ const recover = () => locked(async () => {+ // Reconcile both sides of the terminal-DB -> journal-settle -> resume gap.+ const rows = new Map((await ledger.listActive()).map(row => [row.operationId, row]));+ const owner = coordinator.getExclusive()?.operation.operationId+ ?? coordinator.status().hold?.owner?.match(/^peer-execution:([a-f0-9-]{36})$/)?.[1];+ if (owner && !rows.has(owner)) {+ const operation = await ledger.read(owner);+ if (!operation) fail('PEER_EXECUTION_OWNER_MISSING', 'Maintenance ownership has no matching durable consumption.');+ rows.set(owner, operation);+ }+ for (const operation of rows.values()) await reconcileOperation(operation);+ });+ return { preflight, dispatch, status, recover, kick, drain, notify: emit,+ describe: peerId => locked(() => grants.describe(peerId)),+ saveGrant: async (input, req) => { const result = await locked(() => grants.save(input, req)); emit(); kick(); return result; } };+}diff --git a/server/services/peerExecution.test.js b/server/services/peerExecution.test.jsnew file mode 100644index 0000000000..20a202c637--- /dev/null+++ b/server/services/peerExecution.test.js@@ -0,0 +1,159 @@+import { beforeEach, afterEach, describe, it, expect, vi } from 'vitest';+import { randomUUID, createHash } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { createMaintenanceAdmission } from '../lib/maintenanceAdmission.js';+import { createPeerExecutionReceiver } from './peerExecution.js';+import { createPeerExecutionGrants } from './peerExecutionGrants.js';+import { peerExecutionPreflightPayloadSchema, peerExecutionDispatchSchema, peerExecutionGrantSchema } from '../lib/peerAdminValidation.js';+import { peerAdminPairBinding } from './peerAdministration.js';++let directory, pair, ledger, grants, receiver, adapters, coordinator, store, epoch, operations, floors, proofs;+const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');+const intent = { action: 'portos.restart' };+const terminal = state => ['succeeded', 'failed'].includes(state);+beforeEach(async () => {+ directory = mkdtempSync(join(tmpdir(), 'peer-execution-fixture-'));+ pair = { self: { instanceId: randomUUID() }, peer: { id: 'fixture-peer', instanceId: randomUUID(), syncSecret: 'fixture-pair-secret'.repeat(3) } };+ epoch = randomUUID(); operations = new Map(); floors = new Map(); proofs = new Map();+ store = { version: 1, grants: [] };+ ledger = {+ authority: { read: () => ({ epoch, phase: 'ready' }), requireReady: value => { if (value !== epoch) throw Object.assign(new Error('stale epoch'), { code: 'STALE_EPOCH' }); } },+ initialize: async () => ({ epoch, phase: 'ready' }),+ generationFloor: async ({ action }) => floors.get(action) ?? 0,+ advanceGenerationFloor: async ({ action, generation }) => { floors.set(action, generation); return generation; },+ consume: async binding => {+ const existing = [...operations.values()].find(row => row.binding.requestId === binding.requestId);+ if (existing) return { operation: existing, isNew: false };+ const operation = { operationId: randomUUID(), binding, fingerprint: hash(binding), revision: 1, state: 'queued', claim: null, receipt: null };+ operations.set(operation.operationId, operation); return { operation, isNew: true };+ },+ read: async id => operations.get(id),+ readRequest: async ({ hostInstanceId, peerInstanceId, requestId }) => [...operations.values()].find(row => row.binding.requestId === requestId+ && row.binding.hostInstanceId === hostInstanceId && row.binding.peerInstanceId === peerInstanceId) ?? null,+ listActive: async () => [...operations.values()].filter(row => !terminal(row.state)),+ transition: async (id, revision, state, extra = {}) => {+ const row = operations.get(id);+ if (row.revision !== revision || terminal(row.state)) throw new Error('stale transition');+ const next = { ...row, state, revision: revision + 1, claim: extra.claim ?? row.claim, receipt: extra.receipt ?? null };+ operations.set(id, next); return next;+ },+ };+ coordinator = createMaintenanceAdmission(directory, { verifyExclusiveReceipt: (claim, receipt) => {+ const proof = proofs.get(claim.operation.operationId);+ return proof?.fingerprint === claim.fingerprint && proof.receiptDigest === receipt.receiptDigest && proof.outcome === receipt.outcome;+ } });+ grants = createPeerExecutionGrants({ ledger, readStore: async () => structuredClone(store), writeStore: async value => { store = structuredClone(value); }, identity: async id => {+ if (id !== pair.peer.id || pair.peer.enabled === false) throw new Error('pair missing'); return pair;+ } });+ adapters = { prepare: vi.fn(async () => ({ version: 1, intent, target: 'fixture-fixed-process' })),+ run: vi.fn(async () => ({ state: 'succeeded', code: 'FIXTURE_FINISHED' })), reconcile: vi.fn(async () => null) };+ receiver = makeReceiver();+});+afterEach(() => rmSync(directory, { recursive: true, force: true }));+const makeReceiver = () => createPeerExecutionReceiver({ ledger, grants, coordinator, adapters, terminalProofs: proofs,+ caller: async req => { if (req !== 'paired') throw Object.assign(new Error('pair required'), { status: 403 }); return pair; }, version: '1.0.0' });+const grantInput = (extra = {}) => peerExecutionGrantSchema.parse({ peerId: pair.peer.id, action: intent.action,+ confirmedHostInstanceId: pair.self.instanceId, confirmedPeerInstanceId: pair.peer.instanceId,+ previousGrantId: store.grants[0]?.id ?? null, expiresInMinutes: 60, allowExecution: true, confirmation: 'execution-v1', ...extra });+const grant = (extra = {}) => receiver.saveGrant(grantInput(extra), { portosAuthContext: { method: 'session' } });+const prepare = async () => {+ const envelope = await receiver.preflight('paired', { protocolVersion: 1, requestId: randomUUID(), intent });+ expect(peerExecutionPreflightPayloadSchema.safeParse(envelope.payload).success).toBe(true);+ const { scope: _scope, senderInstanceId: _sender, targetInstanceId: _target, expiresAt: _expiry, ...input } = envelope.payload;+ return peerExecutionDispatchSchema.parse(input);+};+const idle = () => vi.waitFor(() => expect([...operations.values()].every(row => terminal(row.state) || row.state === 'uncertain' || row.state === 'awaiting-reconnect')).toBe(true));++describe('receiver execution public workflow with fixture-only side effects', () => {+ it('requires independently confirmed execution authority and refuses unauthenticated callers', async () => {+ expect(peerExecutionGrantSchema.safeParse({ ...grantInput(), confirmation: 'planning-v1' }).success).toBe(false);+ await expect(prepare()).rejects.toMatchObject({ code: 'PEER_EXECUTION_GRANT_REQUIRED' });+ await grant();+ await expect(receiver.preflight('session', { intent, requestId: randomUUID() })).rejects.toMatchObject({ status: 403 });+ expect(adapters.run).not.toHaveBeenCalled();+ });+ it('records acceptance before launch, completes once and permanently refuses mutated replay', async () => {+ await grant(); const input = await prepare();+ const accepted = await receiver.dispatch('paired', input);+ expect(accepted.payload.state).toBe('queued');+ await idle();+ expect(adapters.run).toHaveBeenCalledTimes(1);+ expect(coordinator.status().state).toBe('normal');+ expect((await receiver.dispatch('paired', input)).payload.state).toBe('succeeded');+ await expect(receiver.dispatch('paired', { ...input, intent: { action: 'portos.update' } })).rejects.toMatchObject({ code: 'PEER_EXECUTION_REPLAY_CONFLICT' });+ const restarted = makeReceiver(); await restarted.recover();+ expect((await restarted.status('paired', input)).payload.state).toBe('succeeded');+ expect(adapters.run).toHaveBeenCalledTimes(1);+ });+ it('lets admitted work settle naturally and rechecks revocation before dispatch', async () => {+ const active = coordinator.admit('provider', 'Fixture provider');+ await grant(); const input = await prepare(); await receiver.dispatch('paired', input);+ await vi.waitFor(() => expect(coordinator.status().state).toBe('draining'));+ expect(adapters.run).not.toHaveBeenCalled();+ await grant({ allowExecution: false });+ await active.finish(); await receiver.drain(); await idle();+ expect((await receiver.status('paired', input)).payload.state).toBe('failed');+ expect(adapters.run).not.toHaveBeenCalled();+ });+ it.each(['credential', 'epoch', 'generation', 'evidence'])('refuses %s changes during drain', async change => {+ const active = coordinator.admit('render', 'Fixture render');+ await grant(); const input = await prepare(); await receiver.dispatch('paired', input);+ await vi.waitFor(() => expect(coordinator.status().state).toBe('draining'));+ if (change === 'credential') pair.peer.syncSecret = 'different-fixture-secret'.repeat(3);+ if (change === 'epoch') epoch = randomUUID();+ if (change === 'generation') floors.set(intent.action, 100);+ if (change === 'evidence') adapters.prepare.mockResolvedValue({ version: 2, target: 'changed' });+ await active.finish(); await receiver.drain(); await idle();+ expect(adapters.run).not.toHaveBeenCalled();+ });+ it('fences resume and never relaunches after an ambiguous launch or process restart', async () => {+ adapters.run.mockRejectedValue(new Error('fixture transport lost after launch'));+ await grant(); const input = await prepare(); await receiver.dispatch('paired', input); await idle();+ expect((await receiver.status('paired', input)).payload.state).toBe('uncertain');+ const hold = coordinator.status().hold;+ expect(() => coordinator.resume({ id: hold.id, revision: hold.revision })).toThrow();+ await makeReceiver().recover(); await receiver.dispatch('paired', input);+ expect(adapters.run).toHaveBeenCalledTimes(1);+ expect(coordinator.getExclusive().phase).toBe('uncertain');+ });+ it('requires exact receiver evidence for reconnect completion before releasing the hold', async () => {+ adapters.run.mockResolvedValue({ state: 'awaiting-reconnect' });+ await grant(); const input = await prepare(); await receiver.dispatch('paired', input); await idle();+ expect(coordinator.getExclusive()).not.toBeNull();+ adapters.reconcile.mockResolvedValue({ state: 'succeeded', code: 'FIXTURE_RESTART_PROVED' });+ await makeReceiver().recover();+ expect((await receiver.status('paired', input)).payload.state).toBe('succeeded');+ expect(coordinator.status().state).toBe('normal');+ expect(adapters.run).toHaveBeenCalledTimes(1);+ });+ it.each(['settle', 'resume'])('recovers a crash after terminal persistence before %s', async boundary => {+ const original = coordinator[boundary === 'settle' ? 'settleExclusive' : 'resume'];+ coordinator[boundary === 'settle' ? 'settleExclusive' : 'resume'] = vi.fn(() => { throw new Error('fixture crash gap'); });+ await grant(); const input = await prepare(); await receiver.dispatch('paired', input); await idle();+ await vi.waitFor(() => expect(coordinator.status().state).not.toBe('normal'));+ coordinator[boundary === 'settle' ? 'settleExclusive' : 'resume'] = original;+ await makeReceiver().recover();+ expect(coordinator.status().state).toBe('normal');+ expect((await receiver.status('paired', input)).payload.state).toBe('succeeded');+ expect(adapters.run).toHaveBeenCalledTimes(1);+ });+ it('reconciles late detached completion on status without restarting or relaunching', async () => {+ adapters.run.mockResolvedValue({ state: 'awaiting-reconnect' });+ await grant(); const input = await prepare(); await receiver.dispatch('paired', input); await idle();+ const rebooted = makeReceiver(); await rebooted.recover();+ expect((await rebooted.status('paired', input)).payload.state).toBe('uncertain');+ adapters.reconcile.mockResolvedValue({ state: 'succeeded', code: 'FIXTURE_LATE_COMPLETION' });+ expect((await rebooted.status('paired', input)).payload.state).toBe('succeeded');+ expect(coordinator.status().state).toBe('normal');+ expect(adapters.run).toHaveBeenCalledTimes(1);+ });+ it('invalidates previous authority if policy publication fails after the generation floor', async () => {+ await grant();+ const failedGrants = createPeerExecutionGrants({ ledger, identity: async () => pair, readStore: async () => structuredClone(store), writeStore: async () => { throw new Error('fixture write failure'); } });+ await expect(failedGrants.save(grantInput({ allowExecution: false }), { portosAuthContext: { method: 'session' } })).rejects.toThrow('fixture write failure');+ await expect(grants.current(pair.peer.id, intent.action)).rejects.toMatchObject({ code: 'PEER_EXECUTION_GRANT_REQUIRED' });+ expect(store.grants[0].pairBinding).toBe(peerAdminPairBinding(pair.peer, pair.self));+ });+});diff --git a/server/services/peerExecutionAdapters.js b/server/services/peerExecutionAdapters.jsnew file mode 100644index 0000000000..caa508ff55--- /dev/null+++ b/server/services/peerExecutionAdapters.js@@ -0,0 +1,234 @@+/** Fixed receiver-side actions. Peer input never selects commands, paths or URLs. */+import { createHash } from 'node:crypto';+import { join } from 'node:path';+import { z } from 'zod';+import { canonicalStringify } from '../lib/objects.js';+import { peerAdminIntentSchema } from '../lib/peerAdminValidation.js';+import { assertPeerExecutionCapability, consumePeerExecutionCapability } from '../lib/maintenanceExclusive.js';++const sha = z.string().regex(/^[a-f0-9]{40}$/);+const digest = z.string().regex(/^[a-f0-9]{64}$/);+const bytes = z.number().int().positive().safe();+const text = z.string().min(1).max(256);+const updateSchema = z.object({ headSha: sha, targetSha: sha, originDigest: digest,+ branch: z.literal('main'), tag: z.string().regex(/^v\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/),+ isFork: z.boolean(), forkSyncFresh: z.boolean() }).strict();+const restartSchema = z.object({ processes: z.array(z.object({ name: z.enum(['portos-server', 'portos-cos']),+ pid: z.number().int().positive(), scriptDigest: digest }).strict()).min(1).max(2) }).strict();+// A curated display entry is not a reviewed executable artifact. These facts+// must come from receiver-owned review metadata, never the request or a URL.+export const peerCatalogExecutionReviewSchema = z.object({ catalogKey: text, backend: z.enum(['ollama', 'lmstudio']),+ modelId: text, fileName: text, artifactDigest: digest, sourceRevision: text, license: text, reviewRevision: digest,+ destinationDigest: digest, downloadBytes: bytes, scratchBytes: bytes, runtimeMemoryBytes: bytes,+ runtime: text }).strict();+const fail = (code, message) => { throw Object.assign(new Error(message), { code, status: 409 }); };+export const peerExecutionEvidenceDigest = evidence => createHash('sha256').update(canonicalStringify(evidence)).digest('hex');+const freeze = value => {+ for (const child of Object.values(value)) if (child && typeof child === 'object') freeze(child);+ return Object.freeze(value);+};++/** All probes/launchers are receiver-owned dependencies; wire input is only intent. */+export function _createPeerExecutionAdapters({ probeUpdate, probeRestart, probeCatalog, launchUpdate,+ launchRestart, installCatalog, reconcileReceipt = async () => null } = {}) {+ const prepare = async raw => {+ const intent = peerAdminIntentSchema.parse(raw);+ if (intent.action === 'portos.update') {+ const target = updateSchema.parse(await probeUpdate());+ if (target.isFork && !target.forkSyncFresh) fail('PEER_EXECUTION_FORK_REVIEW_REQUIRED', 'Sync the fork locally before requesting a peer update.');+ if (target.headSha === target.targetSha) fail('PEER_EXECUTION_ALREADY_CURRENT', 'The origin target is already installed.');+ return freeze({ version: 1, intent, target });+ }+ if (intent.action === 'portos.restart') {+ const target = restartSchema.parse(await probeRestart());+ if (!target.processes.some(row => row.name === 'portos-server')+ || new Set(target.processes.map(row => row.name)).size !== target.processes.length)+ fail('PEER_EXECUTION_RESTART_UNAVAILABLE', 'PortOS process identity is unavailable.');+ return freeze({ version: 1, intent, target });+ }+ const snapshot = await probeCatalog(intent);+ const parsed = peerCatalogExecutionReviewSchema.safeParse(snapshot?.review);+ if (!parsed.success) fail('PEER_EXECUTION_CATALOG_UNREVIEWED', 'Exact source, license, destination and runtime review is required locally.');+ const review = parsed.data;+ if (review.catalogKey !== intent.catalogKey || review.backend !== intent.backend)+ fail('PEER_EXECUTION_CATALOG_CHANGED', 'The reviewed catalog target changed.');+ const resources = z.object({ destinationFreeBytes: bytes, availableMemoryBytes: bytes,+ runtime: text, destinationDigest: digest }).strict().parse(snapshot.resources);+ if (resources.runtime !== review.runtime || resources.destinationDigest !== review.destinationDigest)+ fail('PEER_EXECUTION_CATALOG_CHANGED', 'The reviewed destination or runtime changed.');+ if (resources.destinationFreeBytes < review.downloadBytes + review.scratchBytes+ || resources.availableMemoryBytes < review.runtimeMemoryBytes)+ fail('PEER_EXECUTION_RESOURCES_INSUFFICIENT', 'The actual model destination or runtime has insufficient capacity.');+ // Available capacity changes constantly; bind the checked requirements and+ // destination, then re-probe capacity at launch rather than digesting noise.+ return freeze({ version: 1, intent, target: review });+ };+ const run = async (raw, evidence, { capability } = {}) => {+ const intent = peerAdminIntentSchema.parse(raw);+ const evidenceDigest = peerExecutionEvidenceDigest(evidence);+ const operation = consumePeerExecutionCapability(capability, intent, evidenceDigest);+ const fresh = await prepare(intent);+ if (peerExecutionEvidenceDigest(fresh) !== evidenceDigest)+ fail('PEER_EXECUTION_EVIDENCE_CHANGED', 'Receiver evidence changed after preflight.');+ assertPeerExecutionCapability(capability, intent, evidenceDigest);+ const context = { capability, evidence: fresh, operation, evidenceDigest };+ if (intent.action === 'portos.update') return launchUpdate(context);+ if (intent.action === 'portos.restart') return launchRestart(context);+ if (!installCatalog) fail('PEER_EXECUTION_CATALOG_UNAVAILABLE', 'No reviewed artifact installer is available.');+ return installCatalog(context);+ };+ const reconcile = async operation => {+ // Health, elapsed time and the absence of a PID are never completion proof.+ const receipt = await reconcileReceipt(operation);+ return receipt ?? { state: 'uncertain', code: 'PEER_EXECUTION_RECEIPT_UNAVAILABLE' };+ };+ return { prepare, run, reconcile };+}++const production = _createPeerExecutionAdapters({+ probeUpdate: async () => {+ const [{ getUpdateStatus }, { checkUpdateRepoReadiness }, { execGitSafe }, { PATHS }] = await Promise.all([+ import('./updateChecker.js'), import('./updateRepoReadiness.js'), import('../lib/execGit.js'), import('../lib/paths.js'),+ ]);+ const [status, repo] = await Promise.all([getUpdateStatus(), checkUpdateRepoReadiness({ fetch: false })]);+ const canDrain = repo.repairable?.length === 0 && repo.reasons?.every(reason => reason === 'agent-at-work');+ if ((!repo.ready && !canDrain) || repo.branch !== 'main' || !status.remoteInfo?.hasOrigin)+ fail('PEER_EXECUTION_UPDATE_NOT_READY', 'A clean, fast-forwardable main checkout with origin is required.');+ const git = async args => (await execGitSafe(args, PATHS.root)).stdout.trim();+ const [headSha, targetSha, origin] = await Promise.all([+ git(['rev-parse', 'HEAD']), git(['rev-parse', 'refs/remotes/origin/main']), git(['remote', 'get-url', 'origin']),+ ]);+ const ancestor = await execGitSafe(['merge-base', '--is-ancestor', headSha, targetSha], PATHS.root, { ignoreExitCode: true });+ if (ancestor.exitCode !== 0) fail('PEER_EXECUTION_UPDATE_DIVERGED', 'The selected origin target is not a fast-forward.');+ return { headSha, targetSha, originDigest: createHash('sha256').update(origin).digest('hex'), branch: 'main',+ tag: status.latestRelease?.tag, isFork: status.remoteInfo.isFork === true, forkSyncFresh: status.forkSyncFresh === true };+ },+ probeRestart: async () => {+ const [{ listMaintenanceProcesses }, { PATHS }] = await Promise.all([import('./pm2.js'), import('../lib/paths.js')]);+ const list = await listMaintenanceProcesses();+ const selected = list.filter(row => ['portos-server', 'portos-cos'].includes(row.name));+ const scripts = { 'portos-server': join(PATHS.root, 'server/start.js'), 'portos-cos': join(PATHS.root, 'server/cos-runner/index.js') };+ if (selected.some(row => row.cwd !== PATHS.root || row.script !== scripts[row.name] || row.status !== 'online'))+ fail('PEER_EXECUTION_RESTART_UNAVAILABLE', 'PortOS process identity is unavailable.');+ return { processes: selected.map(({ name, pid, script }) => ({ name, pid,+ scriptDigest: createHash('sha256').update(script).digest('hex') })).sort((a, b) => a.name.localeCompare(b.name)) };+ },+ probeCatalog: async intent => {+ const { probePeerCatalog } = await import('./peerCatalogInstaller.js');+ return probePeerCatalog(intent);+ },+ installCatalog: async context => {+ await persistLaunch(context.operation, context.evidence);+ const { installPeerCatalog } = await import('./peerCatalogInstaller.js');+ return installPeerCatalog(context);+ },+ launchUpdate: async ({ capability, evidence, operation }) => {+ await persistLaunch(operation, evidence);+ const { startPortosSelfUpdate } = await import('./portosSelfUpdate.js');+ const result = await startPortosSelfUpdate({ peerExecution: { capability, evidence } });+ return { state: 'awaiting-reconnect', code: 'PEER_EXECUTION_UPDATE_STARTED', ...result };+ },+ launchRestart: async ({ capability, evidence, operation, evidenceDigest }) => {+ await persistLaunch(operation, evidence);+ const [{ spawnDetached }, { PATHS }, { createRequire }, { countActiveCosAgents, getPersistentMindImageWorkGuard }] = await Promise.all([+ import('../lib/detachedSpawn.js'), import('../lib/paths.js'), import('node:module'), import('./updatePreflight.js'),+ ]);+ const [agents, mind] = await Promise.all([countActiveCosAgents(), getPersistentMindImageWorkGuard()]);+ if (agents || !mind.trusted || !mind.safe) fail('PEER_EXECUTION_RESTART_BUSY', 'Existing agent or mind work must settle before restarting.');+ assertPeerExecutionCapability(capability, evidence.intent, evidenceDigest);+ const require = createRequire(import.meta.url);+ const child = await spawnDetached(process.execPath, [require.resolve('pm2/bin/pm2'), 'restart',+ ...evidence.target.processes.map(row => row.name)], { cwd: PATHS.root,+ controlDir: join(PATHS.data, 'peer-execution', operation.operationId), cleanup: false });+ child.on('error', () => console.error('❌ Peer restart launch failed; exclusive ownership remains held.'));+ return { state: 'awaiting-reconnect', code: 'PEER_EXECUTION_RESTART_STARTED' };+ },+ reconcileReceipt: reconcileProductionReceipt,+});+export const preparePeerExecution = production.prepare;+export const runPeerExecution = production.run;+export const reconcilePeerExecution = production.reconcile;+++async function persistLaunch(operation, evidence) {+ const [{ mkdir, open }, { PATHS }, { assertNotRealDataWrite }] = await Promise.all([+ import('node:fs/promises'), import('../lib/paths.js'), import('../lib/testDataIsolation.js'),+ ]);+ const operationId = z.string().uuid().parse(operation.operationId);+ const directory = join(PATHS.data, 'peer-execution', operationId);+ assertNotRealDataWrite(directory, 'peer execution launch proof');+ await mkdir(directory, { recursive: true, mode: 0o700 });+ const file = await open(join(directory, 'evidence.json'), 'wx', 0o600);+ try {+ await file.writeFile(canonicalStringify({ operationId, evidenceDigest: operation.evidenceDigest, evidence }));+ await file.sync();+ } finally { await file.close(); }+ if (process.platform !== 'win32') {+ const dir = await open(directory, 'r');+ try { await dir.sync(); } finally { await dir.close(); }+ }+}++/** Security boundary: only exact launch identity AND terminal facts can settle. */+export function _verifyPeerExecutionCompletion(operation, launch, facts) {+ if (!launch?.evidence?.intent || launch.operationId !== operation.operationId+ || launch.evidenceDigest !== operation.binding.evidenceDigest+ || peerExecutionEvidenceDigest(launch.evidence) !== operation.binding.evidenceDigest+ || canonicalStringify(launch.evidence.intent) !== canonicalStringify(operation.binding.intent)+ || facts?.exit !== '0') return null;+ const { intent, target } = launch.evidence;+ if (intent.action === 'portos.restart') {+ const previous = restartSchema.safeParse(target);+ const current = restartSchema.safeParse(facts.restart);+ if (!previous.success || !current.success || previous.data.processes.length !== current.data.processes.length+ || previous.data.processes.some(old => !current.data.processes.some(row => row.name === old.name+ && row.pid !== old.pid && row.scriptDigest === old.scriptDigest))) return null;+ } else if (intent.action === 'portos.update') {+ if (!updateSchema.safeParse(target).success || facts.install?.bootCommit !== target.targetSha+ || facts.install?.currentCommit !== target.targetSha || facts.install?.outOfSync !== false+ || facts.install?.staleBuild !== false || facts.install?.staleDeps?.stale !== false+ || facts.install?.submodules?.stale !== false || facts.install?.pendingMigrations?.count !== 0+ || facts.verified !== true) return null;+ } else return null;+ return { state: 'succeeded', code: 'PEER_EXECUTION_VERIFIED',+ evidenceDigest: peerExecutionEvidenceDigest({ launch, facts }) };+}++async function reconcileProductionReceipt(operation) {+ const [{ open, lstat }, { PATHS }] = await Promise.all([import('node:fs/promises'), import('../lib/paths.js')]);+ const operationId = z.string().uuid().parse(operation.operationId);+ const directory = join(PATHS.data, 'peer-execution', operationId);+ const readBounded = async (name, maxBytes) => {+ const path = join(directory, name);+ if (!(await lstat(path)).isFile()) return null;+ const file = await open(path, 'r');+ try {+ const buffer = Buffer.alloc(maxBytes + 1);+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);+ return bytesRead > maxBytes ? null : buffer.subarray(0, bytesRead).toString('utf8');+ } finally { await file.close(); }+ };+ const raw = await readBounded('evidence.json', 16384).catch(() => null);+ if (!raw) return null;+ const launch = await Promise.resolve().then(() => JSON.parse(raw)).catch(() => null);+ if (!launch?.evidence || launch.operationId !== operation.operationId+ || launch.evidenceDigest !== operation.binding.evidenceDigest+ || peerExecutionEvidenceDigest(launch.evidence) !== operation.binding.evidenceDigest) return null;+ if (operation.binding.intent.action === 'catalog.install') {+ const { reconcilePeerCatalog } = await import('./peerCatalogInstaller.js');+ return reconcilePeerCatalog(operation, launch.evidence).catch(() => null);+ }+ const exit = await readBounded('exit', 32).catch(() => null);+ if (exit?.trim() !== '0') return null;+ let facts;+ if (operation.binding.intent.action === 'portos.restart') {+ // This read revalidates fixed script paths and online status.+ const current = await production.prepare({ action: 'portos.restart' }).catch(() => null);+ facts = { exit: '0', restart: current?.target };+ } else if (operation.binding.intent.action === 'portos.update') {+ const { getInstallState } = await import('./installState.js');+ const [install, log] = await Promise.all([getInstallState(), readBounded('stdout.log', 1024 * 1024)]).catch(() => [null, null]);+ facts = { exit: '0', install, verified: /(?:^|\n)STEP:verify:done:/.test(log ?? '') };+ }+ return _verifyPeerExecutionCompletion(operation, launch, facts);+}diff --git a/server/services/peerExecutionAdapters.production.test.js b/server/services/peerExecutionAdapters.production.test.jsnew file mode 100644index 0000000000..e1b451153c--- /dev/null+++ b/server/services/peerExecutionAdapters.production.test.js@@ -0,0 +1,29 @@+import { describe, expect, it, vi } from 'vitest';++vi.mock('./updateChecker.js', () => ({ getUpdateStatus: async () => ({ latestRelease: { tag: 'v1.2.3' },+ remoteInfo: { hasOrigin: true, isFork: false }, forkSyncFresh: false }) }));+vi.mock('./updateRepoReadiness.js', () => ({ checkUpdateRepoReadiness: async () => ({ ready: false,+ branch: 'main', reasons: ['agent-at-work'], repairable: [] }) }));+vi.mock('../lib/execGit.js', () => ({ execGitSafe: async args => ({ exitCode: 0,+ stdout: args[0] === 'remote' ? 'https://github.com/fixture/PortOS.git' : args[1] === 'HEAD' ? 'a'.repeat(40) : 'b'.repeat(40) }) }));+vi.mock('./pm2.js', async () => {+ const { PATHS } = await import('../lib/paths.js');+ const { join } = await import('node:path');+ return { listMaintenanceProcesses: async () => [{ name: 'portos-server', pid: 123,+ status: 'online', cwd: PATHS.root, script: join(PATHS.root, 'server/start.js') }] };+});+vi.mock('./updatePreflight.js', () => ({ countActiveCosAgents: vi.fn(async () => 2),+ getPersistentMindImageWorkGuard: vi.fn(async () => ({ trusted: true, safe: false })) }));+import { preparePeerExecution } from './peerExecutionAdapters.js';+import { countActiveCosAgents, getPersistentMindImageWorkGuard } from './updatePreflight.js';++describe('production preview before graceful draining', () => {+ it('can queue stable update/restart targets while admitted agent and mind work finishes', async () => {+ await expect(preparePeerExecution({ action: 'portos.update' })).resolves.toMatchObject({+ target: { headSha: 'a'.repeat(40), targetSha: 'b'.repeat(40) } });+ await expect(preparePeerExecution({ action: 'portos.restart' })).resolves.toMatchObject({+ target: { processes: [{ name: 'portos-server', pid: 123 }] } });+ expect(countActiveCosAgents).not.toHaveBeenCalled();+ expect(getPersistentMindImageWorkGuard).not.toHaveBeenCalled();+ });+});diff --git a/server/services/peerExecutionAdapters.test.js b/server/services/peerExecutionAdapters.test.jsnew file mode 100644index 0000000000..14c464e737--- /dev/null+++ b/server/services/peerExecutionAdapters.test.js@@ -0,0 +1,125 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createMaintenanceAdmission } from '../lib/maintenanceAdmission.js';+import { _createPeerExecutionAdapters, peerExecutionEvidenceDigest, _verifyPeerExecutionCompletion } from './peerExecutionAdapters.js';++const roots = [];+afterEach(() => roots.splice(0).forEach(root => rmSync(root, { recursive: true, force: true })));+const intent = { action: 'portos.update' };+const update = () => ({ headSha: 'a'.repeat(40), targetSha: 'b'.repeat(40), originDigest: 'c'.repeat(64),+ branch: 'main', tag: 'v1.2.3', isFork: false, forkSyncFresh: false });+const expected = claim => ({ id: claim.id, revision: claim.revision, fingerprint: claim.fingerprint });+function owner(evidence) {+ const root = mkdtempSync(join(tmpdir(), 'peer-adapters-'));+ roots.push(root);+ const coordinator = createMaintenanceAdmission(root);+ const hold = coordinator.begin({ reason: 'Fixture drain', owner: 'Fixture operator' }).hold;+ const claim = coordinator.claimReady({ id: hold.id, revision: hold.revision, operation: {+ operationId: randomUUID(), requestId: randomUUID(), peerInstanceId: randomUUID(), hostInstanceId: randomUUID(),+ grantId: randomUUID(), grantGeneration: 1, scope: 'execution-v1', pairBinding: 'd'.repeat(64),+ intent: evidence.intent, receiverVersion: '1.2.3', evidenceDigest: peerExecutionEvidenceDigest(evidence),+ } }, coordinator.observeIdle());+ const started = coordinator.transitionExclusive(expected(claim), 'in-flight', coordinator.observeIdle());+ return { coordinator, root, started, capability: coordinator.issueExecutionCapability(started) };+}++describe('fixed peer actions under exclusive receiver ownership', () => {+ it('allows exactly one launch bound to immutable evidence and refuses forged, copied and recovered capabilities', async () => {+ const launchUpdate = vi.fn(async () => ({ state: 'awaiting-reconnect' }));+ const adapters = _createPeerExecutionAdapters({ probeUpdate: async () => update(), launchUpdate });+ const evidence = await adapters.prepare(intent);+ expect(Object.isFrozen(evidence.target)).toBe(true);+ const { capability, coordinator, started, root } = owner(evidence);+ await expect(adapters.run(intent, evidence, { capability: {} })).rejects.toMatchObject({ code: 'PEER_EXECUTION_CAPABILITY_REQUIRED' });+ expect(() => coordinator.issueExecutionCapability(structuredClone(started))).toThrow();+ expect(() => coordinator.issueExecutionCapability(started)).toThrow();+ const recovered = createMaintenanceAdmission(root);+ expect(() => recovered.issueExecutionCapability(recovered.getExclusive())).toThrow();+ await expect(adapters.run(intent, evidence, { capability })).resolves.toEqual({ state: 'awaiting-reconnect' });+ await expect(adapters.run(intent, evidence, { capability })).rejects.toMatchObject({ code: 'PEER_EXECUTION_CAPABILITY_CONSUMED' });+ expect(launchUpdate).toHaveBeenCalledTimes(1);+ expect(coordinator.held()).toBe(true);+ await expect(adapters.reconcile({})).resolves.toMatchObject({ state: 'uncertain' });+ });++ it('rechecks the exact origin target and never launches stale or fork-unreviewed work', async () => {+ let target = update();+ const launchUpdate = vi.fn();+ const adapters = _createPeerExecutionAdapters({ probeUpdate: async () => target, launchUpdate });+ const evidence = await adapters.prepare(intent);+ const { capability } = owner(evidence);+ target = { ...target, targetSha: 'e'.repeat(40) };+ await expect(adapters.run(intent, evidence, { capability })).rejects.toMatchObject({ code: 'PEER_EXECUTION_EVIDENCE_CHANGED' });+ target = { ...target, isFork: true };+ await expect(adapters.prepare(intent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_FORK_REVIEW_REQUIRED' });+ expect(launchUpdate).not.toHaveBeenCalled();+ });++ it('revoking current exclusive ownership invalidates an already-issued capability', async () => {+ const launchUpdate = vi.fn();+ const adapters = _createPeerExecutionAdapters({ probeUpdate: async () => update(), launchUpdate });+ const evidence = await adapters.prepare(intent);+ const { capability, coordinator, started } = owner(evidence);+ coordinator.transitionExclusive(expected(started), 'uncertain');+ await expect(adapters.run(intent, evidence, { capability })).rejects.toMatchObject({ code: 'MAINTENANCE_STALE' });+ expect(launchUpdate).not.toHaveBeenCalled();+ });++ it('rejects arbitrary commands and unrelated PM2 targets before taking launch authority', async () => {+ const adapters = _createPeerExecutionAdapters({ probeRestart: async () => ({ processes: [{ name: 'unrelated-app', pid: 1, scriptDigest: 'a'.repeat(64) }] }) });+ await expect(adapters.prepare({ action: 'portos.restart', command: 'arbitrary' })).rejects.toThrow();+ await expect(adapters.prepare({ action: 'portos.restart' })).rejects.toThrow();+ });++ it('requires reviewed exact artifacts and actual destination/runtime capacity, rechecking capacity before install', async () => {+ const installIntent = { action: 'catalog.install', backend: 'ollama', catalogKey: 'fixture' };+ const unreviewed = _createPeerExecutionAdapters({ probeCatalog: async () => null });+ await expect(unreviewed.prepare(installIntent)).rejects.toMatchObject({ code: 'PEER_EXECUTION_CATALOG_UNREVIEWED' });+ const review = { ...installIntent, modelId: 'fixture:1', fileName: 'fixture.gguf', artifactDigest: 'a'.repeat(64), sourceRevision: 'revision',+ license: 'reviewed-license', reviewRevision: 'b'.repeat(64), destinationDigest: 'c'.repeat(64),+ downloadBytes: 100, scratchBytes: 100, runtimeMemoryBytes: 400, runtime: 'fixture-runtime' };+ delete review.action;+ let resources = { destinationFreeBytes: 250, availableMemoryBytes: 500, runtime: review.runtime, destinationDigest: review.destinationDigest };+ const installCatalog = vi.fn();+ const adapters = _createPeerExecutionAdapters({ probeCatalog: async () => ({ review, resources }), installCatalog });+ const evidence = await adapters.prepare(installIntent);+ const { capability } = owner(evidence);+ resources = { ...resources, destinationFreeBytes: 199 };+ await expect(adapters.run(installIntent, evidence, { capability })).rejects.toMatchObject({ code: 'PEER_EXECUTION_RESOURCES_INSUFFICIENT' });+ expect(installCatalog).not.toHaveBeenCalled();+ });+});+++describe('post-restart completion proof', () => {+ it('requires the matching durable launch, successful exit and every intended process to have restarted', () => {+ const evidence = { version: 1, intent: { action: 'portos.restart' }, target: { processes: [+ { name: 'portos-server', pid: 100, scriptDigest: 'a'.repeat(64) },+ { name: 'portos-cos', pid: 101, scriptDigest: 'b'.repeat(64) },+ ] } };+ const operation = { operationId: randomUUID(), binding: { intent: evidence.intent, evidenceDigest: peerExecutionEvidenceDigest(evidence) } };+ const launch = { operationId: operation.operationId, evidenceDigest: operation.binding.evidenceDigest, evidence };+ const facts = { exit: '0', restart: { processes: evidence.target.processes.map(row => ({ ...row, pid: row.pid + 10 })) } };+ expect(_verifyPeerExecutionCompletion(operation, launch, facts)).toMatchObject({ state: 'succeeded' });+ expect(_verifyPeerExecutionCompletion(operation, { ...launch, operationId: randomUUID() }, facts)).toBeNull();+ expect(_verifyPeerExecutionCompletion(operation, launch, { ...facts, exit: '1' })).toBeNull();+ expect(_verifyPeerExecutionCompletion(operation, launch, { exit: '0', restart: evidence.target })).toBeNull();+ expect(_verifyPeerExecutionCompletion(operation, launch, { exit: '0', restart: { processes: facts.restart.processes.slice(0, 1) } })).toBeNull();+ });++ it('does not call an update complete from a version, health, or exit code without exact boot/build/install evidence', () => {+ const evidence = { version: 1, intent, target: update() };+ const operation = { operationId: randomUUID(), binding: { intent, evidenceDigest: peerExecutionEvidenceDigest(evidence) } };+ const launch = { operationId: operation.operationId, evidenceDigest: operation.binding.evidenceDigest, evidence };+ const facts = { exit: '0', verified: true, install: { bootCommit: evidence.target.targetSha,+ currentCommit: evidence.target.targetSha, outOfSync: false, staleBuild: false, staleDeps: { stale: false },+ submodules: { stale: false }, pendingMigrations: { count: 0 } } };+ expect(_verifyPeerExecutionCompletion(operation, launch, facts)).toMatchObject({ state: 'succeeded' });+ expect(_verifyPeerExecutionCompletion(operation, launch, { exit: '0', verified: true })).toBeNull();+ expect(_verifyPeerExecutionCompletion(operation, launch, { ...facts, install: { ...facts.install, bootCommit: evidence.target.headSha } })).toBeNull();+ expect(_verifyPeerExecutionCompletion(operation, launch, { ...facts, install: { ...facts.install, staleBuild: null } })).toBeNull();+ });+});diff --git a/server/services/peerExecutionGrants.js b/server/services/peerExecutionGrants.jsnew file mode 100644index 0000000000..600b5716a1--- /dev/null+++ b/server/services/peerExecutionGrants.js@@ -0,0 +1,73 @@+/** Machine-local execution policy. Planning grants are deliberately never read. */+import { randomUUID } from 'node:crypto';+import { z } from 'zod';+import { peerAdminActionSchema, PEER_ADMIN_ACTIONS, PEER_EXECUTION_SCOPE } from '../lib/peerAdminValidation.js';+import { peerAdminPairBinding } from './peerAdministration.js';++const uuid = z.string().uuid();+const record = z.object({+ id: uuid, peerId: z.string().min(1).max(100), peerInstanceId: uuid, hostInstanceId: uuid,+ action: peerAdminActionSchema, scope: z.literal(PEER_EXECUTION_SCOPE),+ pairBinding: z.string().regex(/^[a-f0-9]{64}$/), executionEpoch: uuid,+ generation: z.number().int().positive().safe(), allowed: z.boolean(),+ expiresAt: z.number().int().positive().safe(), createdAt: z.number().int().positive().safe(),+ authority: z.enum(['operator-session', 'local-operator']),+}).strict();+const storeSchema = z.object({ version: z.literal(1), grants: z.array(record).max(300) }).strict();+export const peerExecutionError = (code, message, status = 409) => Object.assign(new Error(message), { code, status });+const fail = (code, message, status) => { throw peerExecutionError(code, message, status); };+const floorKey = (identity, action) => ({ hostInstanceId: identity.self.instanceId, peerInstanceId: identity.peer.instanceId, action });++// The receiver owns a single mutex across save and dispatch; these methods are+// internal to that boundary. Publish the generation floor BEFORE policy bytes.+export function createPeerExecutionGrants({ ledger, readStore, writeStore, identity, now = Date.now }) {+ const read = async () => storeSchema.parse(await readStore());+ const active = async (grant, pair) => {+ const authority = ledger.authority.read();+ return Boolean(grant?.allowed && grant.expiresAt > now() && authority?.phase === 'ready'+ && grant.executionEpoch === authority.epoch && grant.hostInstanceId === pair.self.instanceId+ && grant.peerInstanceId === pair.peer.instanceId && grant.pairBinding === peerAdminPairBinding(pair.peer, pair.self)+ && grant.generation === await ledger.generationFloor(floorKey(pair, grant.action)));+ };+ const current = async (peerId, action) => {+ const pair = await identity(peerId);+ const grant = (await read()).grants.find(entry => entry.peerId === peerId && entry.action === action);+ if (!await active(grant, pair)) fail('PEER_EXECUTION_GRANT_REQUIRED', 'A fresh execution grant for this exact pair and action is required.', 403);+ return { ...pair, grant };+ };+ const describe = async peerId => {+ const store = await read();+ let pair;+ try { pair = await identity(peerId); } catch { pair = null; }+ return { scope: PEER_EXECUTION_SCOPE, actions: await Promise.all(PEER_ADMIN_ACTIONS.map(async action => {+ const grant = store.grants.find(entry => entry.peerId === peerId && entry.action === action);+ const { pairBinding: _secret, executionEpoch: _epoch, ...publicGrant } = grant ?? {};+ return { action, grant: grant ? publicGrant : null, active: Boolean(pair && await active(grant, pair)) };+ })) };+ };+ const save = async (input, req) => {+ const pair = await identity(input.peerId, { allowInactive: !input.allowExecution });+ if (input.confirmedHostInstanceId !== pair.self.instanceId || input.confirmedPeerInstanceId !== pair.peer.instanceId)+ fail('PEER_ADMIN_IDENTITY_CHANGED', 'The confirmed pair identity changed.');+ const authority = await ledger.initialize();+ ledger.authority.requireReady(authority.epoch);+ const store = await read();+ const index = store.grants.findIndex(entry => entry.peerId === input.peerId && entry.action === input.action);+ const previous = store.grants[index];+ if ((previous?.id ?? null) !== input.previousGrantId) fail('PEER_ADMIN_GRANT_CHANGED', 'Refresh the current grant before changing it.');+ if (!input.allowExecution && !previous) fail('PEER_ADMIN_GRANT_CHANGED', 'There is no execution grant to revoke.');+ if (index < 0 && store.grants.length >= 300) fail('PEER_ADMIN_GRANT_LIMIT', 'The bounded execution policy store is full.');+ const generation = Math.max(previous?.generation ?? 0, await ledger.generationFloor(floorKey(pair, input.action))) + 1;+ const grant = record.parse({ id: randomUUID(), peerId: input.peerId, ...floorKey(pair, input.action),+ scope: PEER_EXECUTION_SCOPE, generation, executionEpoch: authority.epoch,+ pairBinding: input.allowExecution ? peerAdminPairBinding(pair.peer, pair.self) : previous.pairBinding, allowed: input.allowExecution,+ createdAt: now(), expiresAt: now() + input.expiresInMinutes * 60_000,+ authority: req.portosAuthContext.method === 'session' ? 'operator-session' : 'local-operator' });+ await ledger.advanceGenerationFloor({ ...floorKey(pair, input.action), generation, executionEpoch: authority.epoch });+ if (index >= 0) store.grants[index] = grant; else store.grants.push(grant);+ ledger.authority.requireReady(authority.epoch);+ await writeStore(store);+ return describe(input.peerId);+ };+ return { current, describe, save };+}diff --git a/server/services/peerExecutionLedger.db.test.js b/server/services/peerExecutionLedger.db.test.jsindex ade7aaf7cb..54156ebd27 100644--- a/server/services/peerExecutionLedger.db.test.js+++ b/server/services/peerExecutionLedger.db.test.js@@ -1,5 +1,5 @@-/** Real transaction/restore fixtures only; no grants, peers, adapters or providers. */-import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest';+/** Disposable transaction/restore and receiver workflow fixtures; no live peer or provider actions. */+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import * as fs from 'node:fs';import { randomUUID } from 'node:crypto';import { tmpdir } from 'node:os';@@ -38,6 +38,33 @@ afterEach(async () => {afterAll(async () => { if (health.connected) await close(); });describe.skipIf(!runDb)('receiver-local permanent execution consumption', () => {+ it('executes one fixture adapter through real grant floors, consumption and terminal recovery', async () => {+ const [{ createPeerExecutionReceiver }, { createPeerExecutionGrants }, { createMaintenanceAdmission }] = await Promise.all([+ import('./peerExecution.js'), import('./peerExecutionGrants.js'), import('../lib/maintenanceAdmission.js'),+ ]);+ const pair = { self: { instanceId: input.hostInstanceId }, peer: { id: 'fixture-pair', instanceId: input.peerInstanceId, syncSecret: 'fixture-secret'.repeat(4) } };+ let store = { version: 1, grants: [] };+ const proofs = new Map();+ const coordinator = createMaintenanceAdmission(directory, { verifyExclusiveReceipt: (claim, receipt) => {+ const proof = proofs.get(claim.operation.operationId);+ return proof?.fingerprint === claim.fingerprint && proof.receiptDigest === receipt.receiptDigest;+ } });+ const grants = createPeerExecutionGrants({ ledger, identity: async () => pair, readStore: async () => store, writeStore: async value => { store = value; } });+ const run = vi.fn(async () => ({ state: 'succeeded', code: 'FIXTURE_COMPLETED' }));+ const receiver = createPeerExecutionReceiver({ ledger, grants, coordinator, caller: async () => pair,+ version: 'fixture-1.0', terminalProofs: proofs, adapters: { prepare: async () => ({ exact: 'fixture' }), run, reconcile: async () => null } });+ await receiver.saveGrant({ peerId: pair.peer.id, action: input.intent.action, confirmedHostInstanceId: pair.self.instanceId,+ confirmedPeerInstanceId: pair.peer.instanceId, previousGrantId: null, expiresInMinutes: 60, allowExecution: true },+ { portosAuthContext: { method: 'session' } });+ const { payload } = await receiver.preflight({}, { protocolVersion: 1, requestId: input.requestId, intent: input.intent });+ const { scope: _scope, senderInstanceId: _sender, targetInstanceId: _target, expiresAt: _expiry, ...dispatch } = payload;+ await receiver.dispatch({}, dispatch);+ await vi.waitFor(async () => expect((await receiver.status({}, input)).payload.state).toBe('succeeded'));+ await receiver.dispatch({}, dispatch);+ expect(run).toHaveBeenCalledOnce();+ expect(coordinator.status().state).toBe('normal');+ expect(await ledger.generationFloor({ hostInstanceId: input.hostInstanceId, peerInstanceId: input.peerInstanceId, action: input.intent.action })).toBe(1);+ });it.each(['acquisition', 'capture-query', 'begin-publication', 'snapshot-publication', 'completion-publication', 'directory-sync'])('resumes only the same legacy empty-adoption owner after %s failure and process reconstruction', async boundary => {const { _createPeerExecutionRestore } = await import('./peerExecutionRestore.js');diff --git a/server/services/peerExecutionLedger.js b/server/services/peerExecutionLedger.jsindex 6d46f0731e..05acf02dd8 100644--- a/server/services/peerExecutionLedger.js+++ b/server/services/peerExecutionLedger.js@@ -1,6 +1,6 @@/**- * 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.+ * Receiver-local durable consumption. A record is neither a grant nor launch+ * authorization; the receiver verifies authority, ownership and adapter evidence.*/import { createHash, randomUUID } from 'node:crypto';import * as fs from 'node:fs';@@ -99,6 +99,16 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEreturn { operation: fromRow(row), isNew: true };});};+ const readRequest = async ({ hostInstanceId, peerInstanceId, requestId }) => {+ uuid.parse(hostInstanceId); uuid.parse(peerInstanceId); uuid.parse(requestId);+ return find(db, { hostInstanceId, peerInstanceId, requestId });+ };+ const generationFloor = async ({ hostInstanceId, peerInstanceId, action }) => {+ floorSchema.omit({ generation: true }).parse({ hostInstanceId, peerInstanceId, action });+ const { rows: [row] } = await db.query(`SELECT generation FROM peer_execution_generation_floors+ WHERE host_instance_id = $1 AND peer_instance_id = $2 AND action = $3`, [hostInstanceId, peerInstanceId, action]);+ return row ? Number(row.generation) : 0;+ };const read = async id => {uuid.parse(id);const { rows: [row] } = await db.query('SELECT * FROM peer_execution_operations WHERE operation_id = $1', [id]);@@ -118,7 +128,7 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEreturn Number(row.generation);});};- // Persistence CAS, not a dispatcher. The future receiver must own and verify+ // Persistence CAS, not a dispatcher. The 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);@@ -137,7 +147,7 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerE'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))+ if (current.claim && claim && (current.claim.id !== claim.id || current.claim.fingerprint !== claim.fingerprint || claim.revision < current.claim.revision))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.');@@ -155,6 +165,11 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEWHERE ($1::uuid IS NULL OR operation_id > $1) ORDER BY operation_id LIMIT $2`, [after, limit]);return rows.map(fromRow);};+ const listActive = async () => {+ const { rows } = await db.query(`SELECT * FROM peer_execution_operations+ WHERE state IN ('queued', 'draining', 'in-flight', 'awaiting-reconnect', 'uncertain') ORDER BY created_at LIMIT 32`);+ return rows.map(fromRow);+ };const captureRestore = async (client, id, started) => {if (started.phase !== 'capturing') return started; // Never recapture a rewound database on retry.const pending = `${authority.recoveryPath}.${makeId()}.pending`;@@ -312,5 +327,5 @@ export function createPeerExecutionLedger({ db, dataDir, authority = createPeerEif (current?.phase === 'ready' && current.settledRecoveryId === id) return current;return authority.completeRestore(id);};- return { initialize, consume, read, list, transition, advanceGenerationFloor, prepareRestore, adoptEmptyRestore, reconcileRestore, authority };+ return { initialize, consume, read, readRequest, generationFloor, list, listActive, transition, advanceGenerationFloor, prepareRestore, adoptEmptyRestore, reconcileRestore, authority };}diff --git a/server/services/peerExecutionRuntime.js b/server/services/peerExecutionRuntime.jsnew file mode 100644index 0000000000..34d55ec06a--- /dev/null+++ b/server/services/peerExecutionRuntime.js@@ -0,0 +1,61 @@+/** Lazy production composition. Reading setup never creates an execution grant. */+import { watch, mkdirSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import { assertNotRealDataWrite } from '../lib/testDataIsolation.js';+import { createMaintenanceAdmission } from '../lib/maintenanceAdmission.js';+import { createPeerExecutionLedger } from './peerExecutionLedger.js';+import { createPeerExecutionGrants } from './peerExecutionGrants.js';+import { createPeerExecutionReceiver } from './peerExecution.js';+import { withInstanceIdentityLock, registerInstanceExecutionAuthorityGuard } from './instanceIdentity.js';+import { peerAdminCaller, peerAdminIdentity } from './peerAdministration.js';++let singleton;+let io;+let watcher;+export function bindPeerExecutionIo(socketIo) { io = socketIo; }+export function peerExecutionRuntime() {+ singleton ??= compose();+ return singleton;+}+async function compose() {+ const db = await import('../lib/db.js');+ const adapters = await import('./peerExecutionAdapters.js');+ const ledger = createPeerExecutionLedger({ db, dataDir: PATHS.data });+ registerInstanceExecutionAuthorityGuard(() => ledger.authority.invalidate());+ const terminalProofs = new Map();+ const coordinator = createMaintenanceAdmission(PATHS.data, { verifyExclusiveReceipt: (claim, receipt) => {+ const proof = terminalProofs.get(claim.operation.operationId);+ return proof?.fingerprint === claim.fingerprint && proof.receiptDigest === receipt.receiptDigest && proof.outcome === receipt.outcome;+ } });+ const path = join(PATHS.data, 'peer-execution-grants.json');+ const grants = createPeerExecutionGrants({ ledger, identity: peerAdminIdentity,+ readStore: () => readJSONFile(path, { version: 1, grants: [] }, { strict: true, logError: false }),+ writeStore: store => atomicWrite(path, store) });+ const version = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8')).version;+ const receiver = createPeerExecutionReceiver({ ledger, grants, coordinator, caller: peerAdminCaller, version, terminalProofs, identityLock: withInstanceIdentityLock,+ adapters: { prepare: adapters.preparePeerExecution, run: adapters.runPeerExecution, reconcile: adapters.reconcilePeerExecution },+ changed: () => io?.emit('peer-execution:changed'),+ resume: async input => (await import('./maintenanceControl.js')).resumeMaintenance(input) });+ return { ...receiver, ledger, coordinator };+}+export async function initializePeerExecution() {+ const receiver = await peerExecutionRuntime();+ // A new install remains silent and default-deny; no ledger/authority init at boot.+ if (receiver.ledger.authority.read()) await receiver.recover();+ if (!watcher) {+ assertNotRealDataWrite(receiver.coordinator.directory, 'peer execution drain notifications');+ mkdirSync(receiver.coordinator.directory, { recursive: true, mode: 0o700 });+ watcher = watch(receiver.coordinator.directory, () => receiver.kick());+ watcher.unref?.();+ }+}++export async function withPeerExecutionIdentityRestore(fn) {+ const { createPeerExecutionAuthority } = await import('../lib/peerExecutionAuthority.js');+ return withInstanceIdentityLock(async () => {+ createPeerExecutionAuthority(PATHS.data).invalidate();+ return fn();+ });+}diff --git a/server/services/portosSelfUpdate.js b/server/services/portosSelfUpdate.jsindex ea05613b39..09b41149b5 100644--- a/server/services/portosSelfUpdate.js+++ b/server/services/portosSelfUpdate.js@@ -125,6 +125,7 @@ export async function startPortosSelfUpdate({preflightAlreadyRun = false,mode = 'release',onStep,+ peerExecution,} = {}) {// Never restart PortOS out from under a live CoS agent, in-flight Persistent// Mind image work, or an unacknowledged fork. Fast-fail before the lock so@@ -189,7 +190,7 @@ export async function startPortosSelfUpdate({console.error(`❌ Failed to release update lock after launch failure: ${releaseErr.message}`);});};- const launch = await launchUpdate(tag, emit, { forceCleanWorkspaces }).catch(async err => {+ const launch = await launchUpdate(tag, emit, { forceCleanWorkspaces, ...(peerExecution ? { peerExecution } : {}) }).catch(async err => {await reportFailure(err);throw err;});diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex 2c708ccdb3..eae739c69b 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -1,4 +1,7 @@import { readFile, unlink } from 'fs/promises';+import { createHash } from 'node:crypto';+import { canonicalStringify } from '../lib/objects.js';+import { assertPeerExecutionCapability } from '../lib/maintenanceExclusive.js';import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';import { spawnDetached, isDetachedRunning } from '../lib/detachedSpawn.js';@@ -44,7 +47,7 @@ const CLEANABLE_WORKSPACES = new Set(['.', 'client', 'server', 'autofixer']);* Refusal returns its recorded result; spawn failures reject. A successful* launch returns separately from completion, which may outlive this server.*/-export async function launchUpdate(tag, emit, { forceCleanWorkspaces } = {}) {+export async function launchUpdate(tag, emit, { forceCleanWorkspaces, peerExecution } = {}) {const targetVersion = tag.replace(/^v/, '');const isWindows = process.platform === 'win32';const cmd = isWindows ? 'powershell' : 'bash';@@ -63,6 +66,18 @@ export async function launchUpdate(tag, emit, { forceCleanWorkspaces } = {}) {? forceCleanWorkspaces.filter(w => CLEANABLE_WORKSPACES.has(w)): [];const childEnv = { ...process.env };+ // Never inherit peer-only pinning from an operator's ambient environment.+ delete childEnv.PORTOS_PEER_UPDATE_TARGET_SHA;+ delete childEnv.PORTOS_PEER_UPDATE_EXPECTED_SHA;+ if (peerExecution) {+ const { capability, evidence } = peerExecution;+ assertPeerExecutionCapability(capability, { action: 'portos.update' },+ createHash('sha256').update(canonicalStringify(evidence)).digest('hex'));+ if (!/^[a-f0-9]{40}$/.test(evidence.target.targetSha) || !/^[a-f0-9]{40}$/.test(evidence.target.headSha))+ throw new Error('Invalid peer update revision.');+ childEnv.PORTOS_PEER_UPDATE_TARGET_SHA = evidence.target.targetSha;+ childEnv.PORTOS_PEER_UPDATE_EXPECTED_SHA = evidence.target.headSha;+ }if (cleanList.length) {childEnv.PORTOS_FORCE_CLEAN_WORKSPACES = cleanList.join(',');} else {@@ -77,7 +92,11 @@ export async function launchUpdate(tag, emit, { forceCleanWorkspaces } = {}) {// works unchanged. The control dir is reused across updates (spawnDetached// truncates stale files) and kept afterward as the post-mortem record of the// launch.- const controlDir = join(PATHS.data, 'update-detached');+ const peerOperation = peerExecution && assertPeerExecutionCapability(peerExecution.capability, { action: 'portos.update' },+ createHash('sha256').update(canonicalStringify(peerExecution.evidence)).digest('hex'));+ const controlDir = peerOperation+ ? join(PATHS.data, 'peer-execution', peerOperation.operationId)+ : join(PATHS.data, 'update-detached');// Refuse to reuse the control dir while a prior update script is still// running (survival path: the old script outlives the server restart it@@ -96,6 +115,8 @@ export async function launchUpdate(tag, emit, { forceCleanWorkspaces } = {}) {return { started: false, result: { success: false, failedStep: 'starting', errorMessage } };}+ if (peerExecution) assertPeerExecutionCapability(peerExecution.capability, { action: 'portos.update' },+ createHash('sha256').update(canonicalStringify(peerExecution.evidence)).digest('hex'));const child = await spawnDetached(cmd, args, {cwd: PATHS.root,env: childEnv,diff --git a/update.ps1 b/update.ps1index b9b3e02508..5c77cc15ae 100644--- a/update.ps1+++ b/update.ps1@@ -309,6 +309,12 @@ if ($hasChanges) {Step "git-pull" "failed" "Checkout is dirty; no stash was created"Stop-UpdateScript 1}+if ($env:PORTOS_PEER_UPDATE_TARGET_SHA) {+ if ($env:PORTOS_PEER_UPDATE_TARGET_SHA -cnotmatch '^[a-f0-9]{40}$' -or $env:PORTOS_PEER_UPDATE_EXPECTED_SHA -cnotmatch '^[a-f0-9]{40}$' -or $currentBranch -ne 'main' -or (git rev-parse HEAD) -ne $env:PORTOS_PEER_UPDATE_EXPECTED_SHA) {+ Step "git-pull" "failed" "Peer update evidence changed"+ Stop-UpdateScript 1+ }+}if ($currentBranch -ne "main") {if (-not $currentBranch) {$detachedCommit = git rev-parse --short HEAD@@ -330,7 +336,11 @@ if (-not (Repair-StaleSubmodules)) {# post-pull HEAD yields exactly the pull's delta on main, so a manifest change# the update brings is detected even when launched from another branch.$prePullSha = git rev-parse HEAD 2>$null-Invoke-Logged git pull --rebase+if ($env:PORTOS_PEER_UPDATE_TARGET_SHA) {+ Invoke-Logged git merge --ff-only $env:PORTOS_PEER_UPDATE_TARGET_SHA+} else {+ Invoke-Logged git pull --rebase+}if ($LASTEXITCODE -ne 0) { Stop-UpdateScript $LASTEXITCODE }Step "git-pull" "done" "Latest changes pulled"diff --git a/update.sh b/update.shindex c39c26ef4d..3d689b186d 100755--- a/update.sh+++ b/update.sh@@ -167,6 +167,12 @@ if has_local_changes; thenstep "git-pull" "failed" "Checkout is dirty; no stash was created"exit 1fi+if [ -n "${PORTOS_PEER_UPDATE_TARGET_SHA:-}" ]; then+ if [[ ! "$PORTOS_PEER_UPDATE_TARGET_SHA" =~ ^[a-f0-9]{40}$ ]] || [[ ! "${PORTOS_PEER_UPDATE_EXPECTED_SHA:-}" =~ ^[a-f0-9]{40}$ ]] || [ "$current_branch" != "main" ] || [ "$(git rev-parse HEAD)" != "$PORTOS_PEER_UPDATE_EXPECTED_SHA" ]; then+ step "git-pull" "failed" "Peer update evidence changed"+ exit 1+ fi+fiif [ "$current_branch" != "main" ]; thenlog "⚠️ On branch '${current_branch:-detached HEAD}' — switching to main for update"run git checkout main@@ -182,7 +188,11 @@ fi# post-pull HEAD yields exactly the pull's delta on main, so a manifest change# the update brings is detected even when launched from another branch.pre_pull_sha=$(git rev-parse HEAD 2>/dev/null || echo "")-run git pull --rebase+if [ -n "${PORTOS_PEER_UPDATE_TARGET_SHA:-}" ]; then+ run git merge --ff-only "$PORTOS_PEER_UPDATE_TARGET_SHA"+else+ run git pull --rebase+fistep "git-pull" "done" "Latest changes pulled"# Determine which workspaces' package.json this update touched, so safe_install