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
feat: add durable graceful maintenance drain (#10122)
[._.]/e0be988ddd1e
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex d027c9914c..797c882336 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -1,3 +1,4 @@+import MaintenanceBanner from './MaintenanceBanner.jsx';import { useState, useEffect, useLayoutEffect, useMemo, useRef, useCallback } from 'react';import useFocusTrap from '../hooks/useFocusTrap.js';import { Outlet, NavLink, useLocation, useNavigate } from 'react-router';@@ -1088,6 +1089,7 @@ export default function Layout() {<UpdateBanners /><SetupBanner /><PasswordRiskWarning />+ <MaintenanceBanner />{/* Main content */}{(() => {diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex be9788c44d..3ca2520339 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -25,6 +25,7 @@ vi.mock('../hooks/useAgentFeedbackToast', () => ({ useAgentFeedbackToast: () =>vi.mock('../hooks/useAIStatusNotifications', () => ({ useAIStatusNotifications: () => {} }));vi.mock('./UpdateBanners', () => ({ default: () => null }));vi.mock('./SetupBanner', () => ({ default: () => null }));+vi.mock('./MaintenanceBanner.jsx', () => ({ default: () => null }));vi.mock('./PasswordRiskWarning.jsx', () => ({ default: () => null }));vi.mock('../hooks/useNotifications', () => ({useNotifications: () => ({diff --git a/client/src/components/MaintenanceBanner.jsx b/client/src/components/MaintenanceBanner.jsxnew file mode 100644index 0000000000..5362b2931f--- /dev/null+++ b/client/src/components/MaintenanceBanner.jsx@@ -0,0 +1,11 @@+import { Link } from 'react-router';+import { formatCount } from '../utils/formatters.js';+import { useMaintenance } from '../hooks/useMaintenance.js';+export default function MaintenanceBanner() {+ const { status } = useMaintenance();+ if (!status || status.state === 'normal') return null;+ const label = status.state === 'ready' ? 'Maintenance ready — new work is held.'+ : status.state === 'draining' ? `Maintenance draining — ${formatCount(status.blockers.length)} operation(s) finishing.`+ : 'Maintenance readiness unknown.';+ return <div role="status" className="px-4 py-2 text-sm bg-port-card border-b border-port-border">{label} <Link className="underline" to="/settings/general">View maintenance</Link></div>;+}diff --git a/client/src/components/settings/GeneralTab.jsx b/client/src/components/settings/GeneralTab.jsxindex 305f269b5c..4d4d25f43f 100644--- a/client/src/components/settings/GeneralTab.jsx+++ b/client/src/components/settings/GeneralTab.jsx@@ -1,3 +1,4 @@+import MaintenancePanel from './MaintenancePanel.jsx';import { useState, useEffect, useMemo } from 'react';import { Clock3, MapPin, Palette, Save } from 'lucide-react';import toast from '../ui/Toast';@@ -183,6 +184,7 @@ export function GeneralTab() {className="@container space-y-4"><h2 id="general-settings-heading" className="sr-only">General settings</h2>+ <MaintenancePanel /><UnsavedChangesConfirmguard={routeGuard}when={hasDiscardableChanges}diff --git a/client/src/components/settings/GeneralTab.test.jsx b/client/src/components/settings/GeneralTab.test.jsxindex 5ece005b1b..7addc98f2f 100644--- a/client/src/components/settings/GeneralTab.test.jsx+++ b/client/src/components/settings/GeneralTab.test.jsx@@ -3,6 +3,8 @@ import { StrictMode } from 'react';import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { createMemoryRouter, RouterProvider } from 'react-router';+vi.mock('./MaintenancePanel.jsx', () => ({ default: () => null }));+vi.mock('../../services/api', () => ({getSettings: vi.fn(),updateSettings: vi.fn(),diff --git a/client/src/components/settings/MaintenancePanel.jsx b/client/src/components/settings/MaintenancePanel.jsxnew file mode 100644index 0000000000..04aa3b4628--- /dev/null+++ b/client/src/components/settings/MaintenancePanel.jsx@@ -0,0 +1,33 @@+import { useState } from 'react';+import { formatDateTime, formatTimeOfDay } from '../../utils/formatters.js';+import { useMaintenance } from '../../hooks/useMaintenance.js';+import useMounted from '../../hooks/useMounted.js';+import { beginMaintenance, resumeMaintenance } from '../../services/apiSystem.js';++export default function MaintenancePanel() {+ const { status, refresh } = useMaintenance();+ const mounted = useMounted();+ const [reason, setReason] = useState('Maintenance');+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState('');+ const act = async () => {+ setBusy(true); setError('');+ try {+ if (status.hold) await resumeMaintenance(status.hold, { silent: true });+ else await beginMaintenance(reason.trim(), { silent: true });+ } catch (err) { if (mounted.current) setError(err.message); }+ finally { await refresh(); if (mounted.current) setBusy(false); }+ };+ const unknown = !status || ['unknown', 'unavailable'].includes(status.state);+ return <section className="bg-port-card border border-port-border rounded-xl p-5 space-y-3" aria-labelledby="maintenance-heading">+ <h3 id="maintenance-heading" className="font-semibold text-port-text">Graceful maintenance</h3>+ <p role="status" className="text-sm">{status ? ({ normal: 'Normal — new work can start', draining: 'Draining — letting active work finish', ready: 'Ready — maintenance hold is active', unavailable: 'Recovery needed — new work is held', unknown: 'Readiness unknown' }[status.state]) : 'Loading maintenance status…'}</p>+ <p className="text-sm text-port-text-muted">New agents, mind turns and renders wait. Active work finishes, including saving and cleanup. Queues and existing scheduling policies are preserved.</p>+ {status?.hold ? <p className="text-sm">{status.hold.reason} · {status.hold.owner} · {formatDateTime(status.hold.requestedAt)}</p> : <label htmlFor="maintenance-reason" className="block text-sm">Reason<input id="maintenance-reason" className="block w-full mt-1 p-2 rounded bg-port-bg border border-port-border" value={reason} maxLength={500} onChange={e => setReason(e.target.value)} disabled={busy || unknown} /></label>}+ {status?.blockers?.length > 0 && <ul className="text-sm space-y-1 max-h-56 overflow-auto" aria-label="Maintenance blockers">{status.blockers.map((b, i) => <li key={`${b.kind}:${b.resource}:${i}`}>{b.kind}: {b.resource || 'Preparing'}{b.unsettled ? ' — saving or cleanup needs recovery' : ''} · since {formatTimeOfDay(b.startedAt)}</li>)}</ul>}+ <p className="text-xs text-port-text-muted">{status?.scope || 'Readiness covers admitted PortOS automation and media work. Unrelated applications on this computer are outside this scope.'} A restart never clears a hold or unresolved work. Resuming cancels this hold; it does not certify readiness.</p>+ {(error || status?.error) && <p role="alert" className="text-sm text-port-error">{error || status.error}</p>}+ <button className="px-4 py-2 rounded bg-port-accent text-white disabled:opacity-50" disabled={busy || unknown || (!status?.hold && !reason.trim())} onClick={act}>{busy ? 'Saving…' : status?.hold ? 'Resume previous policies' : 'Enter maintenance'}</button>+ {unknown && <button className="ml-3 text-sm underline" onClick={refresh}>Refresh status</button>}+ </section>;+}diff --git a/client/src/components/settings/MaintenancePanel.test.jsx b/client/src/components/settings/MaintenancePanel.test.jsxnew file mode 100644index 0000000000..16d92171ee--- /dev/null+++ b/client/src/components/settings/MaintenancePanel.test.jsx@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+const fixture = vi.hoisted(() => ({ status: null, refresh: vi.fn(), begin: vi.fn(), resume: vi.fn() }));+vi.mock('../../hooks/useMaintenance.js', () => ({ useMaintenance: () => fixture }));+vi.mock('../../services/apiSystem.js', () => ({ beginMaintenance: fixture.begin, resumeMaintenance: fixture.resume }));+import MaintenancePanel from './MaintenancePanel.jsx';++beforeEach(() => {+ fixture.status = { state: 'normal', blockers: [] };+ fixture.refresh.mockReset().mockResolvedValue(undefined);+ fixture.begin.mockReset().mockResolvedValue(undefined);+ fixture.resume.mockReset().mockResolvedValue(undefined);+});++describe('maintenance controls', () => {+ it('requests a hold with the entered reason and refreshes confirmed status', async () => {+ render(<MaintenancePanel />);+ fireEvent.change(screen.getByLabelText('Reason'), { target: { value: ' Service work ' } });+ fireEvent.click(screen.getByRole('button', { name: 'Enter maintenance' }));+ await waitFor(() => expect(fixture.refresh).toHaveBeenCalledTimes(1));+ expect(fixture.begin).toHaveBeenCalledWith('Service work', { silent: true });+ expect(screen.getByRole('status')).toHaveTextContent('Normal');+ });++ it('sends the displayed hold identity and exposes a stale resume refusal', async () => {+ const hold = { id: '00000000-0000-4000-8000-000000000001', revision: 4, owner: 'Operator', reason: 'Work', requestedAt: '2026-10-04T12:00:00.000Z' };+ fixture.status = { state: 'draining', hold, blockers: [] };+ fixture.resume.mockRejectedValueOnce(new Error('This maintenance hold changed.'));+ render(<MaintenancePanel />);+ fireEvent.click(screen.getByRole('button', { name: 'Resume previous policies' }));+ expect(await screen.findByRole('alert')).toHaveTextContent('hold changed');+ expect(fixture.resume).toHaveBeenCalledWith(hold, { silent: true });+ expect(screen.getByRole('status')).toHaveTextContent('Draining');+ });++ it('disables mutations while readiness is unknown', () => {+ fixture.status = { state: 'unknown' };+ render(<MaintenancePanel />);+ expect(screen.getByRole('button', { name: 'Enter maintenance' })).toBeDisabled();+ expect(screen.getByRole('status')).toHaveTextContent('Readiness unknown');+ expect(fixture.begin).not.toHaveBeenCalled();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 31ac4b146e..8036fb8a5b 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -99,6 +99,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. || `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. || `useCharacterAugmentation` | The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns `preview`/`accepted`/`proposing`/`applying` and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an `onApplied`. | A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. |+| `useMaintenance` | Server-confirmed maintenance status and `refresh`. | Admission hold, blockers, and reconnect invalidation. || `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. || `useMemoRecorder` | Owns one memo recorder through permission prompts, stop/cancel, and unmount; exposes `{ recording, starting, start, stop, cancel, stream }`. | Catalog voice memos and song takes. || `usePortosRestartWatch` | Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on `portos:update:complete`, or on a socket disconnect confirmed unreachable, then polls `/api/system/health` for a version change, a down→up dip, or an uptime reset. `update.sh` pm2-deletes the server mid-run, so there is no completion event to await. | Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. `useAppOperation` already wires it, so App Management surfaces read `restarting` from there instead. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 8e744e5b90..55053d45da 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -83,6 +83,7 @@ export { default as useBeeperOutbox } from './useBeeperOutbox.js';export { default as useBeeperRealtime } from './useBeeperRealtime.js';export { default as useMoltworldWs } from './useMoltworldWs.js';export { default as useCharacterAugmentation } from './useCharacterAugmentation.js';+export { useMaintenance } from './useMaintenance.js';export { default as useMounted } from './useMounted.js';export { default as useMemoRecorder } from './useMemoRecorder.js';export { default as usePendingListRows } from './usePendingListRows.js';diff --git a/client/src/hooks/useMaintenance.js b/client/src/hooks/useMaintenance.jsnew file mode 100644index 0000000000..7c2b51770c--- /dev/null+++ b/client/src/hooks/useMaintenance.js@@ -0,0 +1,34 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import useMounted from './useMounted.js';+import { useSocket } from './useSocket.js';+import { getMaintenanceStatus } from '../services/apiSystem.js';++export function useMaintenance() {+ const [status, setStatus] = useState(null);+ const mounted = useMounted();+ const generation = useRef(0);+ const socket = useSocket();+ const refresh = useCallback(async () => {+ const requested = ++generation.current;+ try {+ const next = await getMaintenanceStatus({ silent: true });+ if (mounted.current && requested === generation.current) setStatus(next);+ } catch {+ if (mounted.current && requested === generation.current) setStatus({ state: 'unknown', error: 'Could not read maintenance status.' });+ }+ }, [mounted]);+ useEffect(() => {+ refresh();+ const disconnected = () => { ++generation.current; setStatus({ state: 'unknown', error: 'Connection lost. Readiness is unknown.' }); };+ socket.on('maintenance:changed', refresh);+ socket.on('connect', refresh);+ socket.on('disconnect', disconnected);+ return () => {+ ++generation.current;+ socket.off('maintenance:changed', refresh);+ socket.off('connect', refresh);+ socket.off('disconnect', disconnected);+ };+ }, [socket, refresh]);+ return { status, refresh };+}diff --git a/client/src/hooks/useMaintenance.test.jsx b/client/src/hooks/useMaintenance.test.jsxnew file mode 100644index 0000000000..0bc07501e2--- /dev/null+++ b/client/src/hooks/useMaintenance.test.jsx@@ -0,0 +1,39 @@+import { act, cleanup, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+const { listeners, fetchStatus } = vi.hoisted(() => ({ listeners: new Map(), fetchStatus: vi.fn() }));+vi.mock('../services/apiSystem.js', () => ({ getMaintenanceStatus: fetchStatus }));+vi.mock('./useSocket.js', () => ({ useSocket: () => socket }));+const socket = { on: (name, fn) => listeners.set(name, fn), off: (name) => listeners.delete(name) };+import { useMaintenance } from './useMaintenance.js';+const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; };+afterEach(() => { cleanup(); fetchStatus.mockReset(); listeners.clear(); });+describe('confirmed maintenance readiness', () => {+ it('discards an older Ready response after a newer hold invalidation', async () => {+ const old = deferred(); const next = deferred();+ fetchStatus.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise);+ const { result } = renderHook(useMaintenance);+ act(() => { listeners.get('maintenance:changed')(); });+ await act(async () => next.resolve({ state: 'draining', blockers: [{ kind: 'mind-turn' }] }));+ await act(async () => old.resolve({ state: 'ready', blockers: [] }));+ expect(result.current.status.state).toBe('draining');+ });+ it('invalidates readiness on disconnect and requires a fresh reconnect read', async () => {+ fetchStatus.mockResolvedValueOnce({ state: 'ready' });+ const { result } = renderHook(useMaintenance);+ await act(async () => {});+ expect(result.current.status.state).toBe('ready');+ act(() => listeners.get('disconnect')());+ expect(result.current.status.state).toBe('unknown');+ fetchStatus.mockResolvedValueOnce({ state: 'draining' });+ await act(async () => listeners.get('connect')());+ expect(result.current.status.state).toBe('draining');+ });+ it('treats a failed read as unknown and cleans up all subscriptions', async () => {+ fetchStatus.mockRejectedValueOnce(new Error('offline'));+ const { result, unmount } = renderHook(useMaintenance);+ await act(async () => {});+ expect(result.current.status.state).toBe('unknown');+ unmount();+ expect(listeners.size).toBe(0);+ });+});diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 73cc97dff5..a93ffcef85 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -615,3 +615,11 @@ export const runCosStorage = (input, options) => request('/data/cos/storage/run'export const cancelCosStorage = (options) => request('/data/cos/storage/cancel', { ...options, method: 'POST' });export const saveCosStoragePolicy = (policy, options) => request('/data/cos/storage/policy', { ...options, method: 'PUT', body: JSON.stringify(policy) });export const pinCosRecording = (input, options) => request('/data/cos/storage/pin', { ...options, method: 'PUT', body: JSON.stringify(input) });++export const getMaintenanceStatus = (options) => request('/system/maintenance', options);+export const beginMaintenance = (reason, options = {}) => request('/system/maintenance', {+ method: 'POST', body: JSON.stringify({ reason }), ...options,+});+export const resumeMaintenance = (hold, options = {}) => request('/system/maintenance/resume', {+ method: 'POST', body: JSON.stringify({ id: hold.id, revision: hold.revision }), ...options,+});diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 0e86600643..4a9485dad7 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -6,6 +6,34 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](> For the full domain-by-domain inventory (every current table and `data/` store, with Postgres-fit notes), see the plan doc: [`docs/plans/2026-06-06-create-postgres-storage-inventory.md`](./plans/2026-06-06-create-postgres-storage-inventory.md). This page covers the **contract and decision rules**, not the exhaustive list.+Graceful maintenance uses `data/workflow-maintenance/state.json` as a **file-primary,+machine-local runtime journal**. It must fence both the API and standalone CoS runner+before either can use PostgreSQL or start work. Its bounded live-operation set and+operator hold are not app records, never federate, and are included in the data backup.+The schema is versioned; an absent file starts Normal, while corrupt/future state or+an interrupted transaction fails closed. Replacement uses exclusive directory locking,+file/directory fsync and atomic rename. No seed or DB migration is required.++Ready means every admitted agent, persistent-mind turn, provider run, media render+(including its browser/export preparation), and scheduled shell/script has released+ownership after its final saving and cleanup. This includes federated jobs dispatched+by this instance, through remote completion and verified local publication; a peer+being unreachable is not completion. New peer dispatch stays held. A held restart+retains unresolved remote ownership without replaying an unknown submission.+Idle daemons, queued work, independently+operated browser sessions and unrelated host apps do not count. Maintenance never+cancels work, replays a paid submission, or enables a previously disabled policy.+Resume removes the identified hold only; a stale request cannot remove a later hold.++Operation age or a dead PID is not proof of saved output. On restart, the journal keeps+unresolved ownership; runner survivors reconnect to their existing operation. A lost+worker, failed save, or interrupted journal transaction needs recovery through its owning+service and inspection of durable output before readiness can be certified. There is no+force-Ready/expiry button. Resuming an unresolved hold permits new work but does not+certify the old work finished. Do not delete this journal to claim readiness; preserve it+with the related run/job records for recovery. A backup restored on another installation+therefore starts conservatively if it contains a hold or outstanding operations.+## The Four Storage Classes| Class | Bytes live | Searchable metadata | Use when | PortOS examples |diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 69581788e4..0f8e7f2ccd 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';import '../services/databaseBootFence.js';/*** CoS Agent Runner - Standalone PM2 Process@@ -109,6 +110,7 @@ const io = new SocketServer(server, {const httpDrain = createHttpDrain([server]);let transportClose;const lifecycle = createRunnerShutdown({+ admission: maintenance,stopIntake: (deadlineMs) => httpDrain.begin(deadlineMs),closeTransports: () => {transportClose ??= new Promise(resolve => {@@ -723,6 +725,7 @@ app.post('/spawn', lifecycle.spawnRoute(async (req, res) => {} catch (err) {lifecycle.reportFailure(err);activeAgents.delete(agentId);+ return false;}}));diff --git a/server/cos-runner/requestSchemas.js b/server/cos-runner/requestSchemas.jsindex 95aaa22921..46ca4411b2 100644--- a/server/cos-runner/requestSchemas.js+++ b/server/cos-runner/requestSchemas.js@@ -24,6 +24,7 @@ const looseRecord = z.record(z.string(), z.unknown()).nullish();export const spawnTuiBodySchema = z.object({agentId: optionalString,+ maintenanceParentId: z.string().uuid().nullish(),taskId: optionalString,sessionId: optionalString,command: optionalString,@@ -38,6 +39,7 @@ export const spawnTuiBodySchema = z.object({export const spawnBodySchema = z.object({agentId: optionalString,+ maintenanceParentId: z.string().uuid().nullish(),taskId: optionalString,prompt: optionalString,workspacePath: optionalString,diff --git a/server/cos-runner/shutdown.js b/server/cos-runner/shutdown.jsindex 009ead83af..22600635a3 100644--- a/server/cos-runner/shutdown.js+++ b/server/cos-runner/shutdown.js@@ -4,10 +4,11 @@ import { armForceKill } from './forceKill.js';// Owns processes until their actual exit AND asynchronous finalization, even// when a terminate route has already removed them from the public agent map.export function createRunnerShutdown({- stopIntake, closeTransports, drainState, exit, logError = console.error,+ admission, stopIntake, closeTransports, drainState, exit, logError = console.error,deadlineMs = 25_000, graceMs = 5000,}) {const owned = new Set();+ const spawnPermits = new Map();const pending = new Set();let stopping = false;let failed = false;@@ -35,10 +36,30 @@ export function createRunnerShutdown({const spawnRoute = (handler) => (req, res) => {if (rejectSpawn(res)) return;- return trackWork(() => handler(req, res));+ if (!admission) return trackWork(() => handler(req, res));+ let permit;+ try {+ permit = admission.admit('runner', String(req.body?.agentId ?? '').slice(0, 256), {+ parentId: req.body?.maintenanceParentId ?? null,+ });+ } catch (err) { return res.status(err.status || 503).json({ error: err.message, code: err.code }); }+ const entry = { permit, handedOff: false };+ spawnPermits.set(permit.id, entry);+ return trackWork(() => permit.run(async () => {+ try {+ const result = await handler(req, res);+ if (!entry.handedOff) permit.finish();+ return result;+ } finally {+ if (!entry.handedOff) await permit.finish();+ spawnPermits.delete(permit.id);+ }+ }));};const agentExit = (agentId, agent, finalize) => {+ const lease = spawnPermits.get(admission?.currentId());+ if (lease) lease.handedOff = true;const ownership = { agentId, agent };owned.add(ownership);let finish;@@ -50,7 +71,10 @@ export function createRunnerShutdown({owned.delete(ownership);if (agent.killTimer) clearTimeout(agent.killTimer);agent.killTimer = null;- finalization = trackWork(() => finalize(...args)).catch(() => {}).finally(() => {+ finalization = trackWork(() => finalize(...args)).then(result => {+ if (result === false) lease?.permit.markUnsettled();+ else return lease?.permit.finish();+ }).catch(() => { lease?.permit.markUnsettled(); }).finally(() => {pending.delete(completed);finish();});diff --git a/server/cos-runner/shutdown.test.js b/server/cos-runner/shutdown.test.jsindex a9054e5a5d..3fc648a7ed 100644--- a/server/cos-runner/shutdown.test.js+++ b/server/cos-runner/shutdown.test.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { EventEmitter } from 'node:events';import { mkdtempSync, readFileSync, rmSync } from 'node:fs';@@ -68,7 +69,7 @@ function runner(assertDatabaseAdmission = vi.fn()) {watch: vi.fn(() => () => {}),}));runInNewContext(source, {- assertDatabaseAdmission,+ assertDatabaseAdmission, maintenance,express, http: { createServer: () => server }, SocketServer: function () { return io; },process, console, Buffer, Date, setTimeout, clearTimeout, join, basename,PATHS: { root: '/example', cosAgents: '/example/agents' }, PORTS: { COS: 0 },diff --git a/server/cos-runner/tuiExit.js b/server/cos-runner/tuiExit.jsindex c8bb1b2902..844f96d8fe 100644--- a/server/cos-runner/tuiExit.js+++ b/server/cos-runner/tuiExit.js@@ -69,6 +69,7 @@ export function createTuiExitHandler({ agentId, taskId, sessionId, agent, activeconsole.error(`❌ TUI agent ${agentId} exit handler error: ${err.message}`);activeAgents.delete(agentId);onError?.(err);+ return false;}};}diff --git a/server/index.js b/server/index.jsindex 4e062f4dce..f6ddb855c2 100644--- a/server/index.js+++ b/server/index.js@@ -1,3 +1,4 @@+import maintenanceRoutes from './routes/maintenance.js';import './services/databaseBootFence.js';import express from 'express';import { Server } from 'socket.io';@@ -302,6 +303,7 @@ app.use('/api/alerts', alertsRoutes);app.use('/api/avatar', avatarRoutes);app.use('/api/system', systemActivityRoutes);app.use('/api/system', systemHealthRoutes);+app.use('/api/system', maintenanceRoutes);app.use('/api/system/capabilities', systemCapabilitiesRoutes);app.use('/api/system-resources', systemResourcesRoutes);app.use('/api/remote-desktop', remoteDesktopRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 1d6121de22..050dceebfc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -25,6 +25,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `maintenanceAdmission.js` | Durable machine-local workflow drain, cross-process admission permits, continuation ownership and stale-resume fencing. || `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. |@@ -308,7 +309,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `cliStderrNoise.js` | `isKnownCliStderrNoise(trimmedLine)` — drops the real Anthropic `claude` CLI's harmless `[claude-code:unrecognized_model]` SDK telemetry line, which fires on every claude-ollama / claude-ollama-tui run because those providers point the binary's `ANTHROPIC_BASE_URL` at a local Ollama model the SDK doesn't recognize. || `codex.js` | OpenAI Codex CLI (`codex`) provider helpers — the `CODEX_COMMAND`/`CODEX_CLI_ID` constants, the `isCodexCommand` and `isVisionCapableCodexTuiProvider` predicates, and `ensureCodexTuiArgs` (injects `--dangerously-bypass-approvals-and-sandbox` + disables the startup update-check config, skipped when the argv already declares an approval/sandbox posture via `argvHasFlag`). Extracted from `tuiHandshake.js` (#3618) to match the one-file-per-vendor shape of `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`, which `providerVendors.js` consumes as registry rows. Also owns `buildCodexOssArgs` — the `--oss --local-provider <ns>` pair emitted from a record's `ollamaBacked` marker, so the Codex harness runs on a local model without rewriting the user's `~/.codex/config.toml` (the record-classification half of that lives in `providerModels.js`, so `providerPrerequisites.js` can classify a codex record without importing a vendor argv module). || `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — the `CURSOR_COMMAND` binary constant, the `isCursorCommand` predicate, and the `ensureCursorHeadlessArgs` (`--print --force`, folding any pinned reasoning effort into `--model`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |-| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |+| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback; `cleanup({ throwOnError: true })` reports cleanup failure to an owning lifecycle). || `falVideoModels.js` | Curated fal.ai VIDEO model catalog — `FAL_VIDEO_MODELS` (Hailuo-02 standard t2v/i2v default, MiniMax H3 Max/Max Turbo i2v, H3 reference-to-video, H3 lip-sync, Seedance 2.5 t2v/i2v/reference, Kling v3 Pro i2v, Veo 3.1 Fast i2v) with per-model duration rules (enum/range/audio), resolutions, aspect ratios, optional inputs and list prices verified on `FAL_VIDEO_PRICING_VERIFIED_AT`; `getFalVideoModel()`, `coerceFalVideoSeconds()` (round UP to a covering length), `resolveFalVideoResolution()`, `buildFalVideoRequest()` (the exact queue body per model; null for an uncurated id, which keeps the legacy body), `estimateFalVideoCostUsd()` (null = unknown), `describeFalVideoRate()`. Dependency-free; the client re-exports it. || `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. || `musicVideoShotTiming.js` | Music Video shot modes (#8977): `MUSIC_VIDEO_SHOT_MODES` (`cutaway`/`performance`), `isPerformanceScene`, `selectedPerformanceInstruction(scene)` (the selected take's shot instruction, performance scenes only), `SOURCE_AUDIO_LIPSYNC` (verified source-audio lip-sync lanes — only fal.ai MiniMax H3 lip-sync, 5–30s per take, default 1080P), `falSceneTake()` (the fal model/length/resolution a scene take requests and its estimated cost — shared by the board, the submit path and the autopilot spend cap) + `falTakeRequestFields(take)` (that take as `/api/video-gen` fields), `performanceCapability(backend)`, `performanceBlockedReason(backend)` (Grok is cutaway-only), `planPerformanceWindow()` (provider-bounded audio window + clip-relative edit in/out points; refuses over-long shots instead of relying on provider truncation), `planPerformanceRepair()` (complete measured suffix evidence, safe word-gap boundary, source/clip timebases and next spend), `clipRelativeCues()`, `grokCoverage(spanSec)` (covering 6/10s request, flags spans needing a split), `approximateMotionCues()`, `shotSplitLimit(scene, backend)` (per-take limit: lip-sync window or Grok's longest clip), `planShotSplit()` (contiguous pieces cut at lyric pauses → line/phrase boundaries → beats; one extra piece at most to avoid cutting a sung line). Dependency-free; the client re-exports it. |diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex cd1d1acbde..ab17c57a38 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -24,6 +24,14 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy**Provider-service extension point.** `createProviderService` / `createAIToolkit` accept `onProvidersSaved(data)`, invoked after every SUCCESSFUL `providers.json` write with the data that landed. PortOS injects it in `server/services/bootstrap.js` to keep its machine-local provider connection graph (`server/services/providerGraph.js`, #6367) reconciled with a file that a legacy `PATCH /api/providers/:id`, a model refresh, a migration or a downgraded release may also write. The hook is deliberately non-fatal: the write already landed and the cache already reflects it, and callers include boot warmups and schedulers with no `next(err)` to bubble to, so a throwing hook is logged and swallowed. Pair it with `applyProviderPatches(patches)`, which applies partial updates to SEVERAL named records in ONE write and — unlike `updateProvider` — performs no sibling fan-out, because a projection must touch exactly the routes it named and no conventional neighbour.+**Host run admission.** `createAIToolkit` accepts `withRunAdmission(handler)` for the+manual create-run route. The wrapper owns the complete async handler lifetime,+including preparation after an HTTP disconnect; do not release it on response close.+API execution also accepts `onPersistenceFailure` and `onSettled` callbacks. The latter+fires after both stream cleanup and terminal persistence/hooks, independently of+`onComplete` (which can precede transport settlement on timeout). These are host hooks,+not toolkit imports of a host's workflow policy.+**Runner extension points.** The runner exposes a small declared override surface (in `runner.js`) so the host (PortOS) supplies its own runners without reaching into private internals:- `setCliRunner(fn)` / `setTuiRunner(fn)` — register host CLI/TUI runners (pass `null` to revert). PortOS calls both in `server/index.js`: its CLI variant is stdin-based and knows the per-CLI argv conventions (Codex `exec -`, Antigravity `agy --print`, Claude Code `-p -`); the TUI runner has no toolkit built-in, and `setTuiRunner` attaches/detaches `executeTuiRun` so the runs router's `typeof runnerService.executeTuiRun === 'function'` gate stays honest.diff --git a/server/lib/aiToolkit/index.js b/server/lib/aiToolkit/index.jsindex 79b0e8724d..47b7d72f13 100644--- a/server/lib/aiToolkit/index.js+++ b/server/lib/aiToolkit/index.js@@ -51,6 +51,7 @@ export function createAIToolkit(config = {}) {// thrown errors still produce the canonical envelope (not Express 5's HTML// error page). PortOS injects its own asyncHandler (→ errorMiddleware).asyncHandler = defaultAsyncHandler,+ withRunAdmission = handler => handler,// Host-injected HTTP error class (PortOS passes its `ServerError` so route// errors normalize into `{ error, code, timestamp, context? }`). Threaded// to every router; routes default to the toolkit's own ToolkitHttpError@@ -129,7 +130,7 @@ export function createAIToolkit(config = {}) {// `ServerError: undefined` lets the router's own default (ToolkitHttpError)// apply — destructuring defaults fire for undefined values.const providersRouter = createProvidersRoutes(providerService, { asyncHandler, ServerError });- const runsRouter = createRunsRoutes(runnerService, { asyncHandler, io, ServerError });+ const runsRouter = createRunsRoutes(runnerService, { asyncHandler, io, ServerError, withRunAdmission });const promptsRouter = createPromptsRoutes(promptsService, { asyncHandler, ServerError });let providerStatusRouter = null;diff --git a/server/lib/aiToolkit/internal/runFinalizer.js b/server/lib/aiToolkit/internal/runFinalizer.jsindex 8535b7dee1..3e55d11a14 100644--- a/server/lib/aiToolkit/internal/runFinalizer.js+++ b/server/lib/aiToolkit/internal/runFinalizer.js@@ -23,11 +23,21 @@ export function createRunFinalizer({onComplete,handleProviderError,safeJsonParse,- safeSettle,consumeActiveStop,+ onPersistenceFailure,}) {+ const pendingHooks = [];+ const failed = () => onPersistenceFailure?.();+ const settleTerminal = (fn, label) => {+ try {+ const result = fn();+ if (result?.then) pendingHooks.push(Promise.resolve(result).catch(err => {+ failed(); console.error(`❌ ${label} failed: ${err.message}`);+ }));+ } catch (err) { failed(); console.error(`❌ ${label} failed: ${err.message}`); }+ };const readMetadata = async () => metadataObject(- safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => '{}'))+ safeJsonParse(await readFile(metadataPath, 'utf-8').catch(() => { failed(); return '{}'; })));const terminalState = () => {@@ -43,7 +53,7 @@ export function createRunFinalizer({const openTerminalMetadata = async () => {const state = terminalState();- if (state.partialOutput) await atomicWrite(outputPath, state.partialOutput).catch(() => {});+ if (state.partialOutput) await atomicWrite(outputPath, state.partialOutput).catch(failed);const metadata = await readMetadata();metadata.endTime = new Date().toISOString();metadata.duration = Date.now() - startTime;@@ -76,9 +86,10 @@ export function createRunFinalizer({});}- safeSettle(() => hooks.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);- safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ settleTerminal(() => hooks.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);+ settleTerminal(() => onComplete?.(metadata), `Run ${runId} onComplete`);} catch (writeErr) {+ failed();console.error(`❌ Run ${runId} success finalize error: ${writeErr.message}`);const failMetadata = await readMetadata();failMetadata.endTime = new Date().toISOString();@@ -87,9 +98,9 @@ export function createRunFinalizer({failMetadata.error = `Run finalization failed: ${writeErr.message}`;failMetadata.errorCategory = ERROR_CATEGORIES.UNKNOWN;failMetadata.outputSize = Buffer.byteLength(getOutput());- await atomicWrite(metadataPath, failMetadata).catch(() => {});- safeSettle(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, getOutput()), `Run ${runId} onRunFailed hook`);- safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);+ await atomicWrite(metadataPath, failMetadata).catch(failed);+ settleTerminal(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, getOutput()), `Run ${runId} onRunFailed hook`);+ settleTerminal(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);}};@@ -114,12 +125,13 @@ export function createRunFinalizer({const { metadata, partialOutput } = await openTerminalMetadata();Object.assign(metadata, terminal);await atomicWrite(metadataPath, metadata);- safeSettle(() => hooks.onRunFailed?.(metadata, error, partialOutput), `Run ${runId} onRunFailed hook`);- safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ settleTerminal(() => hooks.onRunFailed?.(metadata, error, partialOutput), `Run ${runId} onRunFailed hook`);+ settleTerminal(() => onComplete?.(metadata), `Run ${runId} onComplete`);} catch (finalErr) {+ failed();console.error(`❌ API run ${runId} timeout finalize error: ${finalErr.message}`);const salvaged = terminalState().partialOutput;- safeSettle(() => onComplete?.({+ settleTerminal(() => onComplete?.({success: false,...terminal,endTime: new Date().toISOString(),@@ -136,10 +148,11 @@ export function createRunFinalizer({metadata.error = 'API run canceled';metadata.errorCategory = ERROR_CATEGORIES.CANCELED;await atomicWrite(metadataPath, metadata).catch(err => {+ failed();console.error(`❌ API run ${runId} cancel finalize error: ${err.message}`);});- safeSettle(() => hooks.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);- safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ settleTerminal(() => hooks.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);+ settleTerminal(() => onComplete?.(metadata), `Run ${runId} onComplete`);};const finalizeHttpError = async ({ status, statusText, body, headers }) => {@@ -159,8 +172,8 @@ export function createRunFinalizer({}await atomicWrite(metadataPath, metadata);- safeSettle(() => hooks.onRunFailed?.(metadata, metadata.error, ''), `Run ${runId} onRunFailed hook`);- safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ settleTerminal(() => hooks.onRunFailed?.(metadata, metadata.error, ''), `Run ${runId} onRunFailed hook`);+ settleTerminal(() => onComplete?.(metadata), `Run ${runId} onComplete`);};const finalizeStreamError = async (error) => {@@ -178,8 +191,8 @@ export function createRunFinalizer({}await atomicWrite(metadataPath, metadata);- safeSettle(() => hooks.onRunFailed?.(metadata, metadata.error, partialOutput), `Run ${runId} onRunFailed hook`);- safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);+ settleTerminal(() => hooks.onRunFailed?.(metadata, metadata.error, partialOutput), `Run ${runId} onRunFailed hook`);+ settleTerminal(() => onComplete?.(metadata), `Run ${runId} onComplete`);};const finalizeHandlerError = async (handlerErr) => {@@ -190,12 +203,12 @@ export function createRunFinalizer({error: `Run finalization failed: ${handlerErr.message}`,outputSize: Buffer.byteLength(getOutput()),};- await atomicWrite(metadataPath, failMetadata).catch(() => {});- safeSettle(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, getOutput()), `Run ${runId} onRunFailed hook`);- safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);+ await atomicWrite(metadataPath, failMetadata).catch(failed);+ settleTerminal(() => hooks.onRunFailed?.(failMetadata, failMetadata.error, getOutput()), `Run ${runId} onRunFailed hook`);+ settleTerminal(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);};- const finalize = async (cause) => {+ const finalizeOnce = async (cause) => {if (!lifecycle.markSettled()) return false;activeRuns.delete(runId);try {@@ -212,11 +225,20 @@ export function createRunFinalizer({else if (cause.type === 'canceled') await finalizeCanceled();return true;} catch (handlerErr) {+ failed();console.error(`❌ Run ${runId} failure handler error: ${handlerErr.message}`);await finalizeHandlerError(handlerErr);return true;+ } finally {+ await Promise.all(pendingHooks);}};- return { finalize };+ let pending;+ const finalize = cause => {+ if (pending) return Promise.resolve(false);+ pending = finalizeOnce(cause);+ return pending;+ };+ return { finalize, settled: () => pending || Promise.resolve() };}diff --git a/server/lib/aiToolkit/internal/runFinalizer.test.js b/server/lib/aiToolkit/internal/runFinalizer.test.jsnew file mode 100644index 0000000000..272c6d7623--- /dev/null+++ b/server/lib/aiToolkit/internal/runFinalizer.test.js@@ -0,0 +1,35 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+const { write, read } = vi.hoisted(() => ({ write: vi.fn(), read: vi.fn() }));+vi.mock('./atomicWrite.js', () => ({ atomicWrite: write }));+vi.mock('fs/promises', () => ({ readFile: read }));+import { createRunFinalizer } from './runFinalizer.js';+afterEach(() => { write.mockReset(); read.mockReset(); });+const fixture = (hooks = {}) => {+ let settled = false;+ const failed = vi.fn(); const complete = vi.fn();+ read.mockResolvedValue('{}'); write.mockResolvedValue();+ const finalizer = createRunFinalizer({ runId: 'example', provider: { id: 'example' }, startTime: Date.now(),+ activeRuns: new Map(), lifecycle: { markSettled: () => { if (settled) return false; settled = true; return true; } },+ outputPath: 'output', metadataPath: 'metadata', getOutput: () => 'thought', getReasoning: () => '',+ hooks, onComplete: complete, onPersistenceFailure: failed, consumeActiveStop: () => false,+ safeJsonParse: JSON.parse, safeSettle: fn => fn(), stallTimeout: 10, absoluteTimeout: 20 });+ return { finalizer, failed, complete };+};+describe('authoritative API finalization evidence', () => {+ it.each(['success', 'canceled', 'timeout'])('reports failed output persistence for %s', async type => {+ const { finalizer, failed, complete } = fixture();+ write.mockImplementation(async path => { if (path === 'output') throw new Error('write failed'); });+ await finalizer.finalize({ type, bound: 'stall' });+ expect(failed).toHaveBeenCalled();+ expect(complete).toHaveBeenCalledTimes(1);+ });+ it('holds settlement until asynchronous output hooks have finished', async () => {+ let release; const waiting = new Promise(resolve => { release = resolve; });+ const { finalizer, complete } = fixture({ onRunCompleted: () => waiting });+ const finishing = finalizer.finalize({ type: 'success' });+ await vi.waitFor(() => expect(complete).toHaveBeenCalledTimes(1));+ let done = false; finalizer.settled().then(() => { done = true; });+ await Promise.resolve(); expect(done).toBe(false);+ release(); await finishing; expect(done).toBe(true);+ });+});diff --git a/server/lib/aiToolkit/routes/runs.admission.test.js b/server/lib/aiToolkit/routes/runs.admission.test.jsnew file mode 100644index 0000000000..7fcdb5bfa3--- /dev/null+++ b/server/lib/aiToolkit/routes/runs.admission.test.js@@ -0,0 +1,36 @@+import { afterEach, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { mkdtempSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { createMaintenanceAdmission } from '../../maintenanceAdmission.js';+import { createRunsRoutes } from './runs.js';+const roots = [];+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });+it('retains admission after an HTTP disconnect until handler completion and child transfer', async () => {+ const root = mkdtempSync(join(tmpdir(), 'run-admission-')); roots.push(root);+ const gate = createMaintenanceAdmission(root);+ let created; let child;+ const pending = new Promise(resolve => { created = resolve; });+ const runner = { createRun: () => pending, executeApiRun: vi.fn(() => {+ child = gate.admit('api-run', 'example-run', { continuation: true });+ return Promise.resolve('example-run');+ }) };+ const router = createRunsRoutes(runner, {+ asyncHandler: handler => handler,+ withRunAdmission: handler => (req, res) => gate.run('manual-run', 'Runs', () => handler(req, res)),+ });+ const handler = router.stack.find(layer => layer.route?.methods.post).route.stack[0].handle;+ const res = Object.assign(new EventEmitter(), { status() { return this; }, json: vi.fn() });+ const running = handler({ body: { providerId: 'example', prompt: 'Example thought' } }, res);+ gate.begin({ reason: 'Work', owner: 'Operator' });+ res.emit('close');+ expect(gate.status().state).toBe('draining');+ expect(runner.executeApiRun).not.toHaveBeenCalled();+ created({ runId: 'example-run', provider: { type: 'api' }, metadata: {} });+ await running;+ expect(runner.executeApiRun).toHaveBeenCalledTimes(1);+ expect(gate.status().blockers.map(op => op.kind)).toEqual(['api-run']);+ await child.finish();+ expect(gate.status().state).toBe('ready');+});diff --git a/server/lib/aiToolkit/routes/runs.js b/server/lib/aiToolkit/routes/runs.jsindex 01b1d688c7..2768beccb8 100644--- a/server/lib/aiToolkit/routes/runs.js+++ b/server/lib/aiToolkit/routes/runs.js@@ -8,7 +8,7 @@ export function createRunsRoutes(runnerService, options = {}) {// real ServerError + asyncHandler so thrown errors normalize into// `{ error, code, timestamp, context? }` and route to errorMiddleware).// Standalone, the toolkit's own defaults serialize the same envelope.- const { asyncHandler = defaultAsyncHandler, io = null, ServerError = ToolkitHttpError } = options;+ const { asyncHandler = defaultAsyncHandler, io = null, ServerError = ToolkitHttpError, withRunAdmission = handler => handler } = options;router.get('/', asyncHandler(async (req, res) => {const limit = parseInt(req.query.limit) || 50;@@ -19,7 +19,7 @@ export function createRunsRoutes(runnerService, options = {}) {res.json(result);}));- router.post('/', asyncHandler(async (req, res) => {+ router.post('/', asyncHandler(withRunAdmission(async (req, res) => {// Validate up front so invalid types (timeout: "abc", screenshots: "x")// can't reach the runner — setTimeout would treat "abc" as 0 and kill// the run immediately, and iterating a string `screenshots` would walk@@ -98,7 +98,7 @@ export function createRunsRoutes(runnerService, options = {}) {: provider;if (provider.type === 'cli') {- runnerService.executeCliRun({+ void Promise.resolve(runnerService.executeCliRun({runId,provider: cliProvider,prompt,@@ -111,9 +111,12 @@ export function createRunsRoutes(runnerService, options = {}) {io?.emit(`run:${runId}:complete`, finalMetadata);},timeout: effectiveTimeout,+ })).catch(error => {+ console.error(`❌ Run ${runId} executor failed: ${error.message}`);+ io?.emit(`run:${runId}:complete`, { id: runId, success: false, error: error.message });});} else if (provider.type === 'api') {- runnerService.executeApiRun({+ void Promise.resolve(runnerService.executeApiRun({runId,provider,model: runModel,@@ -127,6 +130,9 @@ export function createRunsRoutes(runnerService, options = {}) {io?.emit(`run:${runId}:complete`, finalMetadata);},timeout: effectiveTimeout,+ })).catch(error => {+ console.error(`❌ Run ${runId} executor failed: ${error.message}`);+ io?.emit(`run:${runId}:complete`, { id: runId, success: false, error: error.message });});} else if (provider.type === 'tui' && typeof runnerService.executeTuiRun === 'function') {// Honor the user-picked model from the Runs UI — `executeTuiRun` reads@@ -138,7 +144,7 @@ export function createRunsRoutes(runnerService, options = {}) {const effectiveProvider = runModel? { ...provider, defaultModel: runModel }: provider;- runnerService.executeTuiRun({+ void Promise.resolve(runnerService.executeTuiRun({runId,provider: effectiveProvider,prompt,@@ -151,6 +157,9 @@ export function createRunsRoutes(runnerService, options = {}) {io?.emit(`run:${runId}:complete`, finalMetadata);},timeout: effectiveTimeout,+ })).catch(error => {+ console.error(`❌ Run ${runId} executor failed: ${error.message}`);+ io?.emit(`run:${runId}:complete`, { id: runId, success: false, error: error.message });});} else {throw new ServerError(`Unsupported provider type: ${provider.type}`, {@@ -168,7 +177,7 @@ export function createRunsRoutes(runnerService, options = {}) {status: 'started',metadata});- }));+ })));router.get('/:id', asyncHandler(async (req, res) => {const metadata = await runnerService.getRun(req.params.id);diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex 7a3c33bc62..c92fed1213 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -669,7 +669,7 @@ export function createRunnerService(config = {}) {return runId;},- async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout, absoluteTimeoutMs, maxTokens, beforeExecute }) {+ async executeApiRun({ runId, provider, model, prompt, workspacePath, screenshots, onData, onComplete, timeout, absoluteTimeoutMs, maxTokens, beforeExecute, onSettled, onPersistenceFailure }) {const runDir = join(RUNS_PATH, runId);const outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');@@ -715,6 +715,7 @@ export function createRunnerService(config = {}) {providerStatusService,hooks,onComplete,+ onPersistenceFailure,handleProviderError,safeJsonParse,safeSettle,@@ -760,12 +761,16 @@ export function createRunnerService(config = {}) {: { success: false, error: `Endpoint blocked: ${endpointGuard.reason}` };if (controller.signal.aborted) {await finalizer.finalize({ type: 'canceled' });+ await finalizer.settled();+ onSettled?.();return runId;}if (ready.success && beforeExecute) {try { await beforeExecute(); }catch {await finalizer.finalize({ type: 'canceled' });+ await finalizer.settled();+ onSettled?.();return runId;}}@@ -817,6 +822,8 @@ export function createRunnerService(config = {}) {body: responseBody,headers: response.headers,});+ await finalizer.settled();+ onSettled?.();return runId;}@@ -950,10 +957,18 @@ export function createRunnerService(config = {}) {});};- processStream().catch(err => {- void finalizer.finalize({ type: 'stream-error', error: err }).catch(handlerErr => {- console.error(`❌ Run ${runId} failure handler error: ${handlerErr.message}`);- });+ processStream().catch(async err => {+ await finalizer.finalize({ type: 'stream-error', error: err });+ }).finally(async () => {+ // A timeout can finish metadata before the aborted reader settles.+ // Resource ownership ends only after both transport and saving finish.+ try { await reader.cancel?.(); reader.releaseLock?.(); }+ catch (err) { onPersistenceFailure?.(); console.error(`❌ Run ${runId} reader cleanup failed: ${err.message}`); }+ await finalizer.settled();+ onSettled?.();+ }).catch(handlerErr => {+ onPersistenceFailure?.();+ console.error(`❌ Run ${runId} failure handler error: ${handlerErr.message}`);});return runId;diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex bb237351fd..ced1a5db77 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -39,6 +39,31 @@ describe('AI Toolkit runner service', () => {}});+ it('reports settled only after API stream cleanup and asynchronous output hooks', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);+ await mkdir(join(dataDir, 'runs', 'settlement'), { recursive: true });+ await writeFile(join(dataDir, 'runs', 'settlement', 'metadata.json'), '{}');+ let releaseHook; let releaseReader;+ const hook = new Promise(resolve => { releaseHook = resolve; });+ const cleanup = new Promise(resolve => { releaseReader = resolve; });+ const reader = { read: vi.fn(async () => ({ done: true })), cancel: vi.fn(() => cleanup), releaseLock: vi.fn() };+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, body: { getReader: () => reader } })));+ const completed = vi.fn(); const settled = vi.fn(); const failed = vi.fn();+ const runner = createRunnerService({ dataDir, hooks: { onRunCompleted: () => hook } });+ await runner.executeApiRun({ runId: 'settlement', provider: { id: 'example', endpoint: 'https://api.example.com/v1' },+ prompt: 'Example', onComplete: completed, onSettled: settled, onPersistenceFailure: failed });+ await vi.waitFor(() => expect(completed).toHaveBeenCalledTimes(1));+ expect(settled).not.toHaveBeenCalled();+ releaseHook();+ await vi.waitFor(() => expect(reader.cancel).toHaveBeenCalled());+ expect(settled).not.toHaveBeenCalled();+ releaseReader();+ await vi.waitFor(() => expect(settled).toHaveBeenCalledTimes(1));+ expect(reader.releaseLock).toHaveBeenCalledTimes(1);+ expect(failed).not.toHaveBeenCalled();+ });+it('passes request capability requirements to proactive fallback selection', async () => {const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));tempDirs.push(dataDir);diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.jsindex 75efcae6c7..62cb3cec8f 100644--- a/server/lib/backupSnapshotBoundary.js+++ b/server/lib/backupSnapshotBoundary.js@@ -1,3 +1,4 @@+import { maintenance } from './maintenanceAdmission.js';/*** Process-local admission for durable file-plus-row publications during backup.* Callers hold one mutation lease across BOTH stores, not around individual@@ -31,6 +32,10 @@ function releasePublications() {/** Hold one admission across an entire file-plus-row workflow. Nested calls reuse it. */export async function withBackupAssetPublication(work) {+ return maintenance.continueSettlement(() => withAdmittedBackupAssetPublication(work));+}++async function withAdmittedBackupAssetPublication(work) {const scope = publicationScope.getStore();if (scope?.active) return work();// Work spawned by a still-admitted lease joins it: the cut already waits for that lease.diff --git a/server/lib/grok.js b/server/lib/grok.jsindex 8f59f628b2..69187aa01b 100644--- a/server/lib/grok.js+++ b/server/lib/grok.js@@ -138,7 +138,9 @@ export function ensureGrokTuiArgs(args = []) {* the grok stdin sentinel, so it's safe to call unconditionally before a spawn.* @param {string[]} args - the built argv (may contain the /dev/stdin sentinel)* @param {string} prompt - the prompt text- * @returns {{ args: string[], useStdin: boolean, cleanup: () => void }}+ * `cleanup({ throwOnError: true })` lets an owner retain failed cleanup as a+ * recovery blocker; the default remains best-effort for existing callers.+ * @returns {{ args: string[], useStdin: boolean, cleanup: (options?: {throwOnError?: boolean}) => void }}*/export function prepareGrokPromptFile(args, prompt) {if (process.platform !== 'win32') return { args, useStdin: true, cleanup: NOOP_CLEANUP };@@ -163,6 +165,9 @@ export function prepareGrokPromptFile(args, prompt) {return {args: rewritten,useStdin: false,- cleanup: () => { try { unlinkSync(file); } catch { /* already gone */ } },+ cleanup: ({ throwOnError = false } = {}) => {+ try { unlinkSync(file); }+ catch (error) { if (throwOnError && error.code !== 'ENOENT') throw error; }+ },};}diff --git a/server/lib/grok.test.js b/server/lib/grok.test.jsindex dcec0d246c..f1c608b632 100644--- a/server/lib/grok.test.js+++ b/server/lib/grok.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { existsSync, readFileSync } from 'fs';+import { existsSync, mkdirSync, readFileSync, rmSync, unlinkSync } from 'fs';import { pinPlatform } from './testHelper.js';import {@@ -163,4 +163,19 @@ describe('grok — prepareGrokPromptFile', () => {expect(fileA).not.toBe(fileB);a.cleanup(); b.cleanup();});++ it('can report an uncertain prompt-file cleanup without changing best-effort callers', () => {+ pinPlatform('win32');+ const result = prepareGrokPromptFile(['--prompt-file', '/dev/stdin'], 'synthetic prompt');+ const file = result.args[result.args.indexOf('--prompt-file') + 1];+ unlinkSync(file);+ mkdirSync(file);+ try {+ expect(() => result.cleanup()).not.toThrow();+ expect(() => result.cleanup({ throwOnError: true })).toThrow();+ } finally {+ rmSync(file, { recursive: true, force: true });+ }+ expect(() => result.cleanup({ throwOnError: true })).not.toThrow();+ });});diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex b3b94138a1..749511919c 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -132,6 +132,8 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// Generic runs accept arbitrary prompts/workspaces, including API-to-CLI fallback.'POST /api/runs',+ 'POST /api/system/maintenance',+ 'POST /api/system/maintenance/resume','POST /api/voice/studio/setup',// Instances: runs the Tailscale CLI and writes a TLS certificate and privatediff --git a/server/lib/index.js b/server/lib/index.jsindex 041a283767..8704ad8887 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -829,3 +829,5 @@ export * from './musicVideoMediaPolicy.js';export * from './sandboxDelegation.js';export * from './forgeMaintenanceTasks.js';++export * from './maintenanceAdmission.js';diff --git a/server/lib/maintenanceAdmission.js b/server/lib/maintenanceAdmission.jsnew file mode 100644index 0000000000..c421d38998--- /dev/null+++ b/server/lib/maintenanceAdmission.js@@ -0,0 +1,229 @@+/** Machine-local graceful drain. The same journal fences the server and runner. */+import { AsyncLocalStorage } from 'node:async_hooks';+import { EventEmitter } from 'node:events';+import { randomUUID } from 'node:crypto';+import * as fs from 'node:fs';+import { join } from 'node:path';+import { z } from 'zod';+import { PATHS } from './paths.js';+import { assertNotRealDataWrite } from './testDataIsolation.js';++const operationSchema = z.object({+ id: z.string().uuid(), kind: z.string().min(1), resource: z.string().max(256),+ pid: z.number().int().positive(), startedAt: z.string().datetime(), unsettled: z.boolean().optional(),+}).strict();+const schema = z.object({+ version: z.literal(1), revision: z.number().int().nonnegative(),+ hold: z.object({ id: z.string().uuid(), revision: z.number().int().positive(),+ reason: z.string().min(1).max(500), owner: z.string().min(1).max(128), requestedAt: z.string().datetime(),+ }).strict().nullable(),+ operations: z.array(operationSchema),+}).strict();+export const maintenanceBeginSchema = z.object({ reason: z.string().trim().min(1).max(500) }).strict();+export const maintenanceResumeSchema = z.object({ id: z.string().uuid(), revision: z.number().int().positive() }).strict();+const empty = () => ({ version: 1, revision: 0, hold: null, operations: [] });+const error = (code = 'MAINTENANCE_HELD', message = 'Maintenance is holding new work. Existing work can finish.') =>+ Object.assign(new Error(message), { status: code === 'MAINTENANCE_STALE' ? 409 : 503, code });+export const isMaintenanceHold = err => ['MAINTENANCE_HELD', 'MAINTENANCE_UNAVAILABLE'].includes(err?.code);++function syncDirectory(path, io) {+ if (process.platform === 'win32') return;+ const fd = io.openSync(path, 'r');+ try { io.fsyncSync(fd); } finally { io.closeSync(fd); }+}++export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, assertWrite = assertNotRealDataWrite, makeId = randomUUID } = {}) {+ const directory = join(dataDir, 'workflow-maintenance');+ const file = join(directory, 'state.json');+ const lock = join(directory, 'transaction');+ const context = new AsyncLocalStorage();+ const events = new EventEmitter();+ // A failed publication must not reopen admission in this process, even if+ // an operator removes an interrupted transaction before restarting it.+ let uncertain = false;+ const unavailable = () => error('MAINTENANCE_UNAVAILABLE', 'Maintenance state needs recovery; new work remains held.');+ const exists = path => {+ try { io.lstatSync(path); return true; } catch (err) { if (err.code === 'ENOENT') return false; throw err; }+ };+ const read = () => {+ if (uncertain) throw unavailable();+ try {+ if (!exists(file)) return empty();+ if (!io.lstatSync(file).isFile()) throw unavailable();+ return schema.parse(JSON.parse(io.readFileSync(file, 'utf8')));+ } catch { throw unavailable(); }+ };+ const project = state => ({+ state: state.hold ? (state.operations.length ? 'draining' : 'ready') : 'normal',+ revision: state.revision, hold: state.hold,+ blockers: state.operations.map(({ kind, resource, startedAt, pid, unsettled }) => ({ kind, resource, startedAt, pid, unsettled })),+ scope: 'PortOS agents, mind turns, provider runs, media renders and scheduled shell/script work, through cleanup and saving. Unrelated host applications are outside this scope.',+ });+ const status = () => {+ try {+ if (exists(lock)) throw unavailable();+ return project(read());+ } catch {+ return { state: 'unavailable', revision: null, hold: null, blockers: [],+ error: 'Maintenance state needs recovery. New work is held; readiness is unknown.' };+ }+ };+ // Synchronous mkdir + read/replace is the shared linearization point. Never+ // steal this lock by age/PID: a crash or failed fsync stays fail-closed.+ const transaction = change => {+ assertWrite(directory, 'workflow maintenance transaction');+ if (uncertain) throw unavailable();+ try {+ io.mkdirSync(directory, { recursive: true, mode: 0o700 });+ // Writers do no async work while holding this lock. Same-process calls+ // cannot contend; briefly yield the CPU to a competing server/runner.+ // A crashed writer remains closed, rather than stealing its lock.+ for (let attempt = 0; ; attempt++) {+ try { io.mkdirSync(lock, { mode: 0o700 }); break; }+ catch (err) {+ if (err.code !== 'EEXIST' || attempt === 99) throw err;+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);+ }+ }+ } catch { throw unavailable(); }+ let published = false;+ let result;+ try {+ const state = read();+ result = change(state);+ state.revision++;+ schema.parse(state);+ const pending = join(directory, `pending-${makeId()}.json`);+ const fd = io.openSync(pending, 'wx', 0o600);+ try { io.writeFileSync(fd, JSON.stringify(state) + '\n'); io.fsyncSync(fd); } finally { io.closeSync(fd); }+ io.renameSync(pending, file);+ syncDirectory(directory, io);+ published = true;+ } catch (err) {+ // Refused admission/stale requests didn't attempt a publication.+ if (['MAINTENANCE_HELD', 'MAINTENANCE_STALE'].includes(err.code)) published = true;+ else uncertain = true;+ throw err.code?.startsWith('MAINTENANCE_') ? err : unavailable();+ } finally {+ if (published) {+ try { io.rmdirSync(lock); syncDirectory(directory, io); } catch { uncertain = true; }+ }+ }+ if (uncertain) throw unavailable();+ // Listener errors must never turn a committed reservation into a failed+ // admission whose caller cannot own/release it.+ queueMicrotask(() => { for (const listener of events.listeners('changed')) {+ try { listener(status()); } catch (err) { console.error(`❌ Maintenance notification failed: ${err.message}`); }+ } });+ return result;+ };+ const held = () => status().state !== 'normal';+ const assertOpen = () => { if (held()) throw error(status().state === 'unavailable' ? 'MAINTENANCE_UNAVAILABLE' : 'MAINTENANCE_HELD'); };+ const currentId = () => context.getStore() ?? null;+ const admit = (kind, resource = '', { continuation = false, parentId = null, parentKinds = null, reconnect = false } = {}) => {+ const inheritedId = parentId ?? (continuation ? currentId() : null);+ let id = makeId();+ transaction(state => {+ const inherited = inheritedId && state.operations.some(op => op.id === inheritedId && (!op.unsettled || kind === 'settlement') && (!parentKinds || parentKinds.includes(op.kind)));+ if (state.hold && !inherited) throw error();+ // An explicitly supplied expired parent must never become new work.+ if (parentId && !inherited) throw error('MAINTENANCE_HELD', 'The admitted parent operation has already settled.');+ // Reconciliation may submit an idempotent replay, so it still obeys the+ // admission fence above; reuse ownership only after that fence passes.+ const existing = reconnect && state.operations.find(op => op.kind === kind && op.resource === resource);+ if (existing) { id = existing.id; return; }+ state.operations.push({ id, kind, resource, pid: process.pid, startedAt: new Date().toISOString() });+ });+ return permitFor(id);+ };+ const permitFor = id => ({+ id,+ run: fn => context.run(id, fn),+ finish: () => finish(id),+ markUnsettled: () => markUnsettled(op => op.id === id),+ identify: resource => transaction(state => { const op = state.operations.find(op => op.id === id); if (op) op.resource = resource; }),+ });+ // Trusted recovery only: this records observed existing work, never starts it.+ const recoverOwned = (kind, resource) => permitFor(transaction(state => {+ const existing = state.operations.find(op => op.kind === kind && op.resource === resource);+ if (existing) return existing.id;+ const id = makeId();+ state.operations.push({ id, kind, resource, pid: process.pid, startedAt: new Date().toISOString() });+ return id;+ }));+ const tryAdmit = (...args) => { try { return admit(...args); } catch (err) { if (isMaintenanceHold(err)) return null; throw err; } };+ const finishing = new Map();+ const finish = id => {+ if (finishing.has(id)) return finishing.get(id);+ // A runner and server can finish in the same millisecond. Contention is+ // retried; never lose a completion solely because another writer owns mkdir.+ const settle = async () => {+ for (let attempt = 0; attempt < 10; attempt++) {+ try {+ transaction(state => { state.operations = state.operations.filter(op => op.id !== id || op.unsettled); });+ return true;+ } catch {+ if (uncertain || !exists(lock)) break;+ await new Promise(resolve => { const timer = setTimeout(resolve, 50); timer.unref?.(); });+ }+ }+ console.error('❌ Maintenance settlement needs recovery; preserving its blocker.');+ return false;+ };+ const pending = settle().finally(() => finishing.delete(id));+ finishing.set(id, pending);+ return pending;+ };+ // Only trusted lifecycle code calls this after terminal persistence/cleanup.+ // A server restarted during a runner job can finish the old owner's record.+ const resourceOperations = (kind, resource) => read().operations.filter(op => op.kind === kind && op.resource === resource);+ const finishResource = (kind, resource) => Promise.all(resourceOperations(kind, resource).map(op => finish(op.id)));+ const withResource = (kind, resource, fn) => {+ const operation = resourceOperations(kind, resource).find(op => !op.unsettled);+ return operation ? context.run(operation.id, fn) : fn();+ };+ const markUnsettled = matches => {+ try { transaction(state => { for (const op of state.operations) if (matches(op)) op.unsettled = true; }); }+ catch { uncertain = true; console.error('❌ Maintenance recovery record could not be saved; readiness remains unknown.'); }+ };+ const markResourceUnsettled = (kind, resource) => markUnsettled(op => op.kind === kind && op.resource === resource);+ const markCurrentUnsettled = () => {+ const id = currentId();+ if (id) markUnsettled(op => op.id === id);+ };+ const continueSettlement = fn => currentId() ? run('settlement', 'Output publication', fn, { continuation: true }) : fn();+ const run = async (kind, resource, fn, options) => {+ const permit = admit(kind, resource, options);+ try { return await permit.run(fn); }+ catch (err) { if (kind === 'settlement') permit.markUnsettled(); throw err; }+ finally { await permit.finish(); }+ };+ const begin = ({ reason, owner }) => {+ const input = maintenanceBeginSchema.parse({ reason });+ transaction(state => {+ if (state.hold) throw error('MAINTENANCE_STALE', 'A maintenance hold already exists. Refresh its status.');+ state.hold = { id: makeId(), revision: state.revision + 1, ...input, owner,+ requestedAt: new Date().toISOString() };+ });+ return status();+ };+ const resume = input => {+ const expected = maintenanceResumeSchema.parse(input);+ transaction(state => {+ if (state.hold?.id !== expected.id || state.hold?.revision !== expected.revision)+ throw error('MAINTENANCE_STALE', 'This maintenance hold changed. Refresh before resuming.');+ state.hold = null;+ });+ return status();+ };+ return { directory, status, held, assertOpen, admit, tryAdmit, recoverOwned, run, currentId, finish, finishResource, withResource, markResourceUnsettled, markCurrentUnsettled, continueSettlement, begin, resume, events };+}++// Resolve the configured data root on first use, after host/test setup.+let defaultAdmission;+export const maintenance = new Proxy({}, {+ get(_target, property) {+ defaultAdmission ??= createMaintenanceAdmission();+ return defaultAdmission[property];+ },+});diff --git a/server/lib/maintenanceAdmission.test.js b/server/lib/maintenanceAdmission.test.jsnew file mode 100644index 0000000000..c7e20c8245--- /dev/null+++ b/server/lib/maintenanceAdmission.test.js@@ -0,0 +1,131 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createMaintenanceAdmission } from './maintenanceAdmission.js';++const roots = [];+const gate = () => {+ const root = mkdtempSync(join(tmpdir(), 'workflow-admission-'));+ roots.push(root);+ return { root, admission: createMaintenanceAdmission(root) };+};+afterEach(() => { vi.useRealTimers(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });++describe('durable graceful maintenance', () => {+ it('reuses remote reconciliation ownership without bypassing a hold', async () => {+ const { admission } = gate();+ const existing = admission.admit('media', 'peer-render');+ const hold = admission.begin({ reason: 'Drain', owner: 'Operator' }).hold;+ expect(admission.tryAdmit('media', 'peer-render', { reconnect: true })).toBeNull();+ admission.resume({ id: hold.id, revision: hold.revision });+ const reconnected = admission.admit('media', 'peer-render', { reconnect: true });+ expect(reconnected.id).toBe(existing.id);+ expect(admission.status().blockers).toHaveLength(1);+ await reconnected.finish();+ expect(admission.status().blockers).toEqual([]);+ });++ it('fences every new admission while an admitted thought can finish its next provider call and saving', async () => {+ const { admission } = gate();+ const turn = admission.admit('mind-turn', 'thought');+ const hold = admission.begin({ reason: 'Update renderer', owner: 'Local operator' });+ expect(hold.state).toBe('draining');+ for (const kind of ['agent', 'media', 'mind-turn', 'runner', 'shell-job']) {+ expect(() => admission.admit(kind, 'new')).toThrowError(/holding new work/);+ }+ let releaseSave;+ const saving = new Promise(resolve => { releaseSave = resolve; });+ const completion = turn.run(() => admission.run('provider', 'next call', () => saving, { continuation: true }));+ await turn.finish();+ expect(admission.status().state).toBe('draining');+ releaseSave();+ await completion;+ expect(admission.status().state).toBe('ready');+ expect(admission.status().hold.id).toBe(hold.hold.id);+ expect(admission.status().blockers).toEqual([]);+ });++ it('runs required completion callbacks after a failed save while retaining the original blocker', async () => {+ const { admission } = gate();+ const provider = admission.admit('provider', 'example');+ admission.begin({ reason: 'Work', owner: 'Operator' });+ provider.markUnsettled();+ const callback = vi.fn(async () => 'completed');+ expect(await provider.run(() => admission.continueSettlement(callback))).toBe('completed');+ await provider.finish();+ expect(callback).toHaveBeenCalledTimes(1);+ expect(admission.status()).toMatchObject({ state: 'draining', blockers: [{ unsettled: true }] });+ });++ it('reconnects observed existing work under its original durable identity during a hold', async () => {+ const { root, admission } = gate();+ const original = admission.admit('media', 'training');+ admission.begin({ reason: 'Work', owner: 'Operator' });+ const restarted = createMaintenanceAdmission(root);+ const recovered = restarted.recoverOwned('media', 'training');+ expect(recovered.id).toBe(original.id);+ expect(restarted.status().blockers).toHaveLength(1);+ await recovered.finish();+ expect(admission.status().state).toBe('ready');+ });++ it('a second process sees the same fence and restart never discards old ownership', async () => {+ const { root, admission } = gate();+ const owner = admission.admit('agent', 'agent-fixture');+ const restarted = createMaintenanceAdmission(root);+ const held = restarted.begin({ reason: 'Service work', owner: 'Operator session' });+ expect(admission.tryAdmit('runner', 'new')).toBeNull();+ expect(createMaintenanceAdmission(root).status()).toMatchObject({ state: 'draining', hold: held.hold });+ await owner.finish();+ expect(restarted.status().state).toBe('ready');+ });++ it('rejects stale resume without clearing the current owner hold', () => {+ const { admission } = gate();+ const first = admission.begin({ reason: 'First', owner: 'Operator' }).hold;+ admission.resume({ id: first.id, revision: first.revision });+ const second = admission.begin({ reason: 'Second', owner: 'Operator' }).hold;+ expect(() => admission.resume({ id: first.id, revision: first.revision })).toThrowError(/changed/);+ expect(admission.status().hold).toEqual(second);+ expect(admission.resume({ id: second.id, revision: second.revision }).state).toBe('normal');+ });++ it('does not let a detached callback reuse a settled parent capability', async () => {+ const { admission } = gate();+ const parent = admission.admit('media', 'old');+ await parent.finish();+ admission.begin({ reason: 'Drain', owner: 'Operator' });+ expect(() => parent.run(() => admission.admit('provider', 'late', { continuation: true }))).toThrow();+ expect(admission.status().state).toBe('ready');+ });++ it('retries completion lock contention and keeps readiness closed until the write succeeds', async () => {+ vi.useFakeTimers();+ const { admission } = gate();+ const work = admission.admit('media', 'render');+ admission.begin({ reason: 'Drain', owner: 'Operator' });+ mkdirSync(join(admission.directory, 'transaction'));+ const finishing = work.finish();+ expect(admission.status().state).toBe('unavailable');+ rmSync(join(admission.directory, 'transaction'), { recursive: true });+ expect(admission.status().state).toBe('draining');+ await vi.advanceTimersByTimeAsync(50);+ expect(await finishing).toBe(true);+ expect(admission.status().state).toBe('ready');+ });++ it('keeps corrupt/future journals and failed terminal persistence fail-closed', async () => {+ const { root, admission } = gate();+ const render = admission.admit('media', 'render');+ render.markUnsettled();+ await render.finish();+ admission.begin({ reason: 'Drain', owner: 'Operator' });+ expect(admission.status()).toMatchObject({ state: 'draining', blockers: [{ unsettled: true }] });+ writeFileSync(join(admission.directory, 'state.json'), '{"version":999}');+ const restarted = createMaintenanceAdmission(root);+ expect(restarted.status().state).toBe('unavailable');+ expect(restarted.tryAdmit('agent', 'new')).toBeNull();+ expect(() => restarted.resume({ id: '00000000-0000-4000-8000-000000000000', revision: 1 })).toThrow();+ });+});diff --git a/server/lib/sidecarProcess.js b/server/lib/sidecarProcess.jsindex 0a6a77fcdc..5cd6e1d648 100644--- a/server/lib/sidecarProcess.js+++ b/server/lib/sidecarProcess.js@@ -65,6 +65,7 @@ export function runSidecarProcess({ bin, args, env, signal, onStage, onProcess }onProcess?.(proc);let stdoutTail = '';let stderrTail = '';+ let processError;let settled = false;const finish = (val) => {if (settled) return;@@ -96,8 +97,18 @@ export function runSidecarProcess({ bin, args, env, signal, onStage, onProcess }}}});- proc.on('error', (err) => finish({ ok: false, reason: `spawn failed: ${err.message}`, stdout: stdoutTail }));+ proc.on('error', (err) => {+ if (proc.pid && proc.exitCode == null && proc.signalCode == null) {+ processError = err;+ return;+ }+ finish({ ok: false, reason: `spawn failed: ${err.message}`, stdout: stdoutTail });+ });proc.on('close', (code, sig) => {+ if (processError) {+ finish({ ok: false, reason: `sidecar process failed: ${processError.message}`, stdout: stdoutTail });+ return;+ }if (sig === 'SIGTERM' || sig === 'SIGKILL') {finish({ ok: false, canceled: true, reason: `cancelled (${sig})`, stdout: stdoutTail });return;diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex adb83264d4..3a7f585146 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -53,6 +53,7 @@ vi.mock('../services/promptRunner.js', () => ({}));vi.mock('../services/mediaJobQueue/index.js', () => ({enqueueJob: vi.fn(async () => ({ jobId: 'media-export', position: 1, status: 'queued' })),+ listJobs: vi.fn(() => []),}));import { emitCodeAnimationChanged } from '../services/socket.js';diff --git a/server/routes/maintenance.js b/server/routes/maintenance.jsnew file mode 100644index 0000000000..f9cbc209c6--- /dev/null+++ b/server/routes/maintenance.js@@ -0,0 +1,19 @@+import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { maintenance, maintenanceBeginSchema, maintenanceResumeSchema } from '../lib/maintenanceAdmission.js';+import { requireHostControl } from '../services/authGate.js';+import { resumeMaintenance } from '../services/maintenanceControl.js';++const router = Router();+router.get('/maintenance', (req, res) => res.json(maintenance.status()));+router.post('/maintenance', requireHostControl, asyncHandler(async (req, res) => {+ const { reason } = validateRequest(maintenanceBeginSchema, req.body);+ const owner = req.portosAuthContext?.method === 'session' ? 'Operator session' : 'Local operator';+ res.json(maintenance.begin({ reason, owner }));+}));+router.post('/maintenance/resume', requireHostControl, asyncHandler(async (req, res) => {+ const input = validateRequest(maintenanceResumeSchema, req.body);+ res.json(await resumeMaintenance(input));+}));+export default router;diff --git a/server/routes/maintenance.test.js b/server/routes/maintenance.test.jsnew file mode 100644index 0000000000..d63b256554--- /dev/null+++ b/server/routes/maintenance.test.js@@ -0,0 +1,36 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { maintenance } from '../lib/maintenanceAdmission.js';+vi.mock('../services/maintenanceControl.js', () => ({ resumeMaintenance: async input => maintenance.resume(input) }));+import router from './maintenance.js';+const session = { enabled: true, authenticated: true, method: 'session' };+const call = (method, path, body, auth = session, address = '192.0.2.10') => new Promise(resolve => {+ const req = { app: { get: () => null }, method, url: path, body, headers: {}, socket: { remoteAddress: address }, portosAuthContext: auth };+ const res = { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(value) { resolve({ status: this.statusCode, body: value }); } };+ router.handle(req, res, err => resolve({ status: err?.status || 404, error: err }));+});+afterEach(() => {+ const hold = maintenance.status().hold;+ if (hold) maintenance.resume({ id: hold.id, revision: hold.revision });+});+describe('maintenance authority and stale mutations', () => {+ it.each(['peer', 'basic'])('does not grant host control to %s credentials', async method => {+ const result = await call('POST', '/maintenance', { reason: 'Work' }, { ...session, method });+ expect(result.status).toBe(403);+ expect(maintenance.status().state).toBe('normal');+ });+ it('requires local transport for a password-free installation', async () => {+ expect((await call('POST', '/maintenance', { reason: 'Work' }, { enabled: false })).status).toBe(403);+ const result = await call('POST', '/maintenance', { reason: 'Work' }, { enabled: false }, '127.0.0.1');+ expect(result.body).toMatchObject({ state: 'ready', hold: { owner: 'Local operator' } });+ });+ it('derives owner from authenticated context and refuses stale resume', async () => {+ expect((await call('POST', '/maintenance', { reason: 'Work', owner: 'Forged' })).status).toBe(400);+ const first = (await call('POST', '/maintenance', { reason: 'Work' })).body.hold;+ expect(first.owner).toBe('Operator session');+ const token = { id: first.id, revision: first.revision };+ expect((await call('POST', '/maintenance/resume', token)).body.state).toBe('normal');+ await call('POST', '/maintenance', { reason: 'Next work' });+ expect((await call('POST', '/maintenance/resume', token)).status).toBe(409);+ expect(maintenance.status().hold.reason).toBe('Next work');+ });+});diff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex 21496365ff..825307b069 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -39,6 +39,7 @@ import { deriveAudioCues, preserveRenderedCues } from '../../services/pipeline/aimport { uploadSingle } from '../../lib/multipart.js';import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { mapServiceError } from './shared.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';const router = Router();@@ -380,7 +381,7 @@ const musicGenerateSchema = z.object({durationSec: z.number().min(1).max(MAX_ENGINE_DURATION).optional(),modelId: z.enum(ALL_MODEL_IDS).optional(),});-router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req, res) => {+router.post('/issues/:id/stages/audio/music/generate', asyncHandler((req, res) => maintenance.run('pipeline-audio', req.params.id, async () => {const body = validateRequest(musicGenerateSchema, req.body ?? {});// Guard the (expensive) generation behind a 404 check first — generating a// multi-second clip only to discover the issue is gone wastes GPU time and@@ -395,7 +396,8 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,}).catch((err) => { throw mapServiceError(err); });// The sidecar wrote the WAV in place and may still have been writing while a// cut ran. The row that first names it waits for any open cut, so a dump can- // never name a track its file copy did not reach (#9982).+ // never name a track its file copy did not reach (#9982). The shared publication+ // boundary retains maintenance settlement through that wait and the row save.const { issue: updatedIssue, stage } = await withBackupAssetPublication(() => issuesSvc.updateStageWithLatest(req.params.id,'audio',@@ -407,7 +409,7 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,}),)).catch((err) => { throw mapServiceError(err); });res.json({ issue: updatedIssue, stage, music: stage.music, durationSec: gen.durationSec, modelId: gen.modelId, engine: gen.engine });-}));+})));router.post('/issues/:id/stages/audio/music/upload', musicUpload, asyncHandler(async (req, res) => {if (!req.file) {@@ -549,7 +551,7 @@ const cueRenderSchema = z.object({durationSec: z.number().min(1).max(MAX_ENGINE_DURATION).optional(),modelId: z.enum(ALL_MODEL_IDS).optional(),});-router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler(async (req, res) => {+router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler((req, res) => maintenance.run('pipeline-audio', req.params.id, async () => {const cueIdx = Number(req.params.cueIdx);if (!Number.isInteger(cueIdx) || cueIdx < 0) {throw new ServerError('cueIdx must be a non-negative integer', {@@ -590,6 +592,7 @@ router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler(async (// Merge against the freshest persisted cue inside the write queue so a// concurrent re-derive can't clobber the render (the cue list is re-read here).// The row that first names the WAV waits for any open backup cut (#9982).+ // The shared publication boundary also owns its maintenance settlement.const { issue: updatedIssue, stage } = await withBackupAssetPublication(() => issuesSvc.updateStageWithLatest(req.params.id,'audio',@@ -615,7 +618,7 @@ router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler(async (engine: gen.engine,modelId: gen.modelId,});-}));+})));// Deleting from the library leaves stale `music.trackFilename` pointers on// issues so the user sees the broken playback and re-picks. Auto-purgingdiff --git a/server/routes/pipeline/audio.maintenance.test.js b/server/routes/pipeline/audio.maintenance.test.jsnew file mode 100644index 0000000000..f517bdc06f--- /dev/null+++ b/server/routes/pipeline/audio.maintenance.test.js@@ -0,0 +1,153 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { request } from '../../lib/testHelper.js';+import { errorMiddleware } from '../../lib/errorHandler.js';++const fixture = vi.hoisted(() => ({ admission: null, issue: null, generate: vi.fn(), save: vi.fn() }));+vi.mock('../../lib/maintenanceAdmission.js', async importOriginal => ({+ ...await importOriginal(),+ maintenance: new Proxy({}, { get: (_target, property) => fixture.admission[property] }),+}));+vi.mock('../../services/pipeline/series.js', () => ({}));+vi.mock('../../services/pipeline/issues.js', () => ({+ getIssue: async () => fixture.issue,+ assertStageUnlocked: () => {},+ updateStageWithLatest: (...args) => fixture.save(...args),+}));+vi.mock('../../services/pipeline/seriesCanon.js', () => ({ getSeriesCanon: vi.fn() }));+vi.mock('../../lib/seriesLlmOverride.js', () => ({ resolveSeriesLlmOverride: vi.fn() }));+vi.mock('../../services/pipeline/audio.js', () => ({+ listAllVoices: vi.fn(), synthesizeToFile: vi.fn(), parseVoiceId: vi.fn(),+ extractDialogueLines: vi.fn(), resolveVoiceForLine: vi.fn(),+}));+vi.mock('../../services/pipeline/manuscriptNarration.js', () => ({ narrateProse: vi.fn() }));+vi.mock('../../services/voice/tts.js', () => ({ synthesize: vi.fn() }));+vi.mock('../../services/voice/profiles.js', () => ({+ clearVoiceProfileRender: vi.fn(), recordVoiceProfileRender: vi.fn(), resolveCharacterVoice: vi.fn(),+}));+vi.mock('../../services/pipeline/musicLibrary.js', () => ({+ listMusicLibrary: vi.fn(), importUploadedTrack: vi.fn(), deleteMusicTrack: vi.fn(),+ statMusicTrack: vi.fn(), isSupportedMusicUpload: vi.fn(), MUSIC_UPLOAD_MAX_BYTES: 1024,+ MUSIC_SOURCE: { NONE: 'none', UPLOAD: 'upload', GEN: 'gen' },+}));+vi.mock('../../services/pipeline/musicGen.js', () => ({+ generateMusic: (...args) => fixture.generate(...args),+ ENGINES: { musicgen: { models: [{ id: 'example-model' }], maxDurationSec: 30 } },+ DEFAULT_ENGINE_ID: 'musicgen', isEngineHealthy: async () => true,+}));+vi.mock('../../services/pipeline/audioCues.js', () => ({ deriveAudioCues: vi.fn(), preserveRenderedCues: vi.fn() }));+vi.mock('../../lib/multipart.js', () => ({ uploadSingle: () => (_req, _res, next) => next() }));+vi.mock('./shared.js', () => ({ mapServiceError: error => error }));++import router from './audio.js';+import { createMaintenanceAdmission } from '../../lib/maintenanceAdmission.js';+import { acquireBackupSnapshotCut } from '../../lib/backupSnapshotBoundary.js';++const generated = { filename: 'synthetic.wav', durationSec: 12, engine: 'musicgen', modelId: 'example-model', model: 'Example' };+const endpoint = kind => `/api/pipeline/issues/example/stages/audio/${kind === 'music' ? 'music/generate' : 'cues/0/render'}`;+let root;+let app;+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'pipeline-audio-maintenance-'));+ fixture.admission = createMaintenanceAdmission(root);+ fixture.issue = { id: 'example', stages: { audio: { cues: [{ prompt: 'Synthetic audio', engine: 'musicgen' }] } } };+ fixture.generate.mockReset().mockResolvedValue(generated);+ fixture.save.mockReset().mockImplementation(async (_id, _stage, update) => {+ const stage = { ...fixture.issue.stages.audio, ...update(fixture.issue.stages.audio) };+ fixture.issue.stages.audio = stage;+ return { issue: fixture.issue, stage };+ });+ app = express();+ app.use(express.json());+ app.use('/api/pipeline', router);+ app.use(errorMiddleware);+});+afterEach(() => rmSync(root, { recursive: true, force: true }));++describe.each(['music', 'cue'])('direct pipeline %s rendering maintenance', kind => {+ const send = () => request(app).post(endpoint(kind)).send({ prompt: 'Synthetic audio' });++ it('rejects a manual render during Ready before generation or persistence', async () => {+ fixture.admission.begin({ reason: 'Hold new renders', owner: 'Operator' });+ expect(fixture.admission.status().state).toBe('ready');+ const response = await send();+ expect(response.status).toBe(503);+ expect(response.body.code).toBe('MAINTENANCE_HELD');+ expect(fixture.generate).not.toHaveBeenCalled();+ expect(fixture.save).not.toHaveBeenCalled();+ });++ it('keeps an admitted render owned through generation and the final stage save', async () => {+ const rendering = Promise.withResolvers();+ const saving = Promise.withResolvers();+ fixture.generate.mockReturnValue(rendering.promise);+ const save = fixture.save.getMockImplementation();+ fixture.save.mockImplementation(async (...args) => { await saving.promise; return save(...args); });+ const response = send().then(value => value);+ try {+ await vi.waitFor(() => expect(fixture.generate).toHaveBeenCalledTimes(1));+ fixture.admission.begin({ reason: 'Drain this render', owner: 'Operator' });+ expect(fixture.admission.status().state).toBe('draining');+ rendering.resolve(generated);+ await vi.waitFor(() => expect(fixture.save).toHaveBeenCalledTimes(1));+ expect(fixture.admission.status().state).toBe('draining');+ saving.resolve();+ expect((await response).status).toBe(200);+ expect(fixture.admission.status().state).toBe('ready');+ const audio = fixture.issue.stages.audio;+ expect(kind === 'music' ? audio.music.trackFilename : audio.cues[0].trackFilename).toBe('synthetic.wav');+ } finally {+ rendering.resolve(generated);+ saving.resolve();+ await response;+ }+ });++ it('retains a recovery blocker when the rendered track cannot be saved to its stage', async () => {+ fixture.save.mockImplementation(async () => {+ fixture.admission.begin({ reason: 'Drain during save', owner: 'Operator' });+ throw new Error('Stage storage unavailable');+ });+ expect((await send()).status).toBe(500);+ expect(fixture.admission.status()).toMatchObject({+ state: 'draining', blockers: [expect.objectContaining({ kind: 'settlement', unsettled: true })],+ });+ });++ it('keeps maintenance draining while an admitted render waits for the backup cut and final row save', async () => {+ const rendering = Promise.withResolvers();+ const saving = Promise.withResolvers();+ fixture.generate.mockReturnValue(rendering.promise);+ const save = fixture.save.getMockImplementation();+ fixture.save.mockImplementation(async (...args) => { await saving.promise; return save(...args); });+ const response = send().then(value => value);+ let releaseCut;+ try {+ await vi.waitFor(() => expect(fixture.generate).toHaveBeenCalledTimes(1));+ releaseCut = await acquireBackupSnapshotCut();+ fixture.admission.begin({ reason: 'Drain during backup cut', owner: 'Operator' });+ rendering.resolve(generated);+ await vi.waitFor(() => expect(fixture.admission.status().blockers).toEqual(expect.arrayContaining([+ expect.objectContaining({ kind: 'settlement' }),+ ])));+ expect(fixture.save).not.toHaveBeenCalled();+ expect(fixture.admission.status().state).toBe('draining');+ releaseCut();+ await vi.waitFor(() => expect(fixture.save).toHaveBeenCalledTimes(1));+ expect(fixture.admission.status().state).toBe('draining');+ saving.resolve();+ expect((await response).status).toBe(200);+ expect(fixture.admission.status().state).toBe('ready');+ const audio = fixture.issue.stages.audio;+ expect(kind === 'music' ? audio.music.trackFilename : audio.cues[0].trackFilename).toBe('synthetic.wav');+ } finally {+ rendering.resolve(generated);+ releaseCut?.();+ saving.resolve();+ await response;+ }+ });+});diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex d252b9a338..0d09b11d1c 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';/*** Agent CLI Spawning@@ -519,7 +520,10 @@ export async function spawnDirectly({const lines = streamParser.processChunk(text);for (const line of lines) outputBuffer += line + '\n';outputBatcher.push(lines);- await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => {+ maintenance.markResourceUnsettled('agent', agentId);+ transcriptWriteReporter.report('output.txt', err);+ });} else {// Non-stream providers: emit stdout as-is once decolored. A chunk that// was purely terminal control has nothing left to show. Unlike stderr@@ -527,7 +531,10 @@ export async function spawnDirectly({// formatting when it isn't wearing an `[stderr]` tag.if (!text) return;outputBuffer += text;- await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => {+ maintenance.markResourceUnsettled('agent', agentId);+ transcriptWriteReporter.report('output.txt', err);+ });outputBatcher.push(text);}});@@ -549,7 +556,10 @@ export async function spawnDirectly({const lines = codexStderrFormatter.processChunk(text);for (const line of lines) outputBuffer += line + '\n';outputBatcher.push(lines);- await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => {+ maintenance.markResourceUnsettled('agent', agentId);+ transcriptWriteReporter.report('output.txt', err);+ });return;}// A chunk that decolors down to whitespace was pure terminal control@@ -558,7 +568,10 @@ export async function spawnDirectly({const trimmed = text.trim();if (!trimmed || isKnownCliStderrNoise(trimmed)) return;outputBuffer += `[stderr] ${text}`;- await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => {+ maintenance.markResourceUnsettled('agent', agentId);+ transcriptWriteReporter.report('output.txt', err);+ });outputBatcher.push(`[stderr] ${text}`);});} catch (err) {@@ -601,7 +614,9 @@ export async function spawnDirectly({await completeAgentRun(runId, isPrivateSecurityTask(task) ? 'Private security assessment failed; inspect its local assessment archive.' : outputBuffer, 1, 0, { message: err.message, category: 'spawn-error' });unregisterSpawnedAgent(claudeProcess.pid);activeAgents.delete(agentId);+ if (!claudeProcess.pid) await maintenance.finishResource('agent', agentId);} catch (handlerErr) {+ maintenance.markResourceUnsettled('agent', agentId);console.error(`❌ Agent ${agentId} error handler failed: ${handlerErr.message}`);activeAgents.delete(agentId);}@@ -721,7 +736,10 @@ export async function spawnDirectly({// below too, since output.txt is written next).await outputBatcher.flush();- await writeFileGuarded(outputFile, outputBuffer).catch((err) => transcriptWriteReporter.report('output.txt', err));+ await writeFileGuarded(outputFile, outputBuffer).catch((err) => {+ maintenance.markResourceUnsettled('agent', agentId);+ transcriptWriteReporter.report('output.txt', err);+ });// The teardown both in-process spawners share: paused early return, then// the host-shutdown abandon gate, the user-termination consume, the@@ -741,7 +759,7 @@ export async function spawnDirectly({sentinelPresent: completionSentinelPresent,});- if (finalizeOutcome.outcome === 'paused') return;+ if (finalizeOutcome.outcome === 'paused') { await maintenance.finishResource('agent', agentId); return; }if (finalizeOutcome.outcome === 'abandoned') {outputBatcher.push('🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.');@@ -826,12 +844,17 @@ export async function spawnDirectly({prClaimVerified,branchProvenEmpty,outputBuffer,- }).catch(err => console.error(`❌ CLI completion cleanup failed for ${agentId}: ${err.message}`));+ }).catch(err => {+ maintenance.markResourceUnsettled('agent', agentId);+ console.error(`❌ CLI completion cleanup failed for ${agentId}: ${err.message}`);+ });unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);activeAgents.delete(agentId);}+ maintenance.finishResource('agent', agentId);} catch (handlerErr) {+ maintenance.markResourceUnsettled('agent', agentId);await recoverFromCloseHandlerFailure(handlerErr, { code, laneReleased, outputBuffer });}};diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex df0a1eecd3..93ff4112e2 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';/*** Agent Lifecycle@@ -103,11 +104,19 @@ export async function spawnAgentForTask(task) {* early `return null` and any throw is covered by the wrapper's release.*/async function runAgentSpawn(task) {+ const permit = maintenance.admit('agent', task.id);+ return permit.run(() => runAdmittedAgentSpawn(task, permit));+}++async function runAdmittedAgentSpawn(task, permit) {const context = createAgentSpawnContext(task);try {const prepared = await prepareAgentSpawn(task, context);if (!prepared) return null;- return await dispatchAgentRun(prepared, { spawnViaRunner });+ permit.identify(context.agentId);+ const result = await dispatchAgentRun(prepared, { spawnViaRunner });+ if (!result) permit.finish();+ return result;} catch (err) {if (!context.setupCatchArmed || context.handedOff) throw err;const privateSecurity = isPrivateSecurityTask(task);@@ -124,6 +133,8 @@ async function runAgentSpawn(task) {cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });}return null;+ } finally {+ if (!context.handedOff) permit.finish();}}@@ -477,6 +488,7 @@ async function completeUntrackedAgentFromCosState(agentId, exitCode, success, duawait handleOrphanedTask(cosAgent.taskId, agentId, getTaskById, { agentMetadata: cosAgent.metadata, agentStartedAt: cosAgent.startedAt });}}+ await maintenance.finishResource('agent', agentId);}/**@@ -487,12 +499,20 @@ async function completeUntrackedAgentFromCosState(agentId, exitCode, success, du* finalization runs against a live agent.*/export async function handleAgentCompletion(agentId, exitCode, success, duration) {+ return maintenance.withResource('agent', agentId, async () => {+ try { return await handleAdmittedAgentCompletion(agentId, exitCode, success, duration); }+ catch (err) { maintenance.markResourceUnsettled('agent', agentId); throw err; }+ });+}++async function handleAdmittedAgentCompletion(agentId, exitCode, success, duration) {// Paused agents are finalized by markAgentPaused, not here — skip so a stray// completion event can't clean the worktree / complete the task out from// under a later resume. Mirrors the CLI/TUI close-handler pause guards.if (pausedAgents.has(agentId)) {consumePausedAgentExit(agentId);runnerAgents.delete(agentId);+ await maintenance.finishResource('agent', agentId);return;}const agent = runnerAgents.get(agentId);@@ -681,5 +701,6 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// cleanup completed — without this the runner harness would never see// the failure and couldn't requeue or alert.if (finalizeError) throw finalizeError;+ maintenance.finishResource('agent', agentId);});}diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 40ecdadf4c..7914c6949d 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Agent Management*@@ -238,6 +239,11 @@ async function markAgentPaused(agentId, agentInfo, pausedAt, reason) {* so a later resume task can use the same workspace/change context.*/export async function pauseAgent(agentId, reason = null) {+ return maintenance.withResource('agent', agentId, () =>+ maintenance.continueSettlement(() => pauseAdmittedAgent(agentId, reason)));+}++async function pauseAdmittedAgent(agentId, reason) {const pausedAt = new Date().toISOString();if (runnerAgents.has(agentId)) {@@ -372,6 +378,7 @@ function classifyResume(task, agentId) {* @returns {Promise<{success: true, agentId: string, taskId: string|null, mode: 'requeued'|'already-active'|'superseded'|'new-task', created: boolean, branchName: string|null}>}*/export async function resumeAgent(agentId, overrides = {}) {+ maintenance.assertOpen();const agent = await getAgentRecord(agentId);if (!agent) {throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });@@ -535,6 +542,7 @@ const RELAUNCH_EXIT_TIMEOUT_MS = 15000;* @param {{context?: string, provider?: string, model?: string, effort?: string, app?: string, reason?: string}} overrides*/export async function relaunchAgent(agentId, overrides = {}) {+ maintenance.assertOpen();const agent = await getAgentRecord(agentId);if (!agent) {throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 86f2f562e6..75f73b47fa 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -1645,7 +1645,7 @@ describe('close-handler skip-finalization — source contract', () => {// which moved into `completeUntrackedAgentFromCosState` in #3872 and would// silently make this test vacuous (indexOf → -1) if it were still named here.it('runner handleAgentCompletion guards with pausedAgents.has and returns before either completion path', () => {- const fnBody = extractFunctionBody(AGENT_LIFECYCLE_SRC, 'export async function handleAgentCompletion');+ const fnBody = extractFunctionBody(AGENT_LIFECYCLE_SRC, 'async function handleAdmittedAgentCompletion');expect(fnBody, 'handleAgentCompletion must exist and be extractable').toBeTruthy();// Guard present@@ -1666,7 +1666,7 @@ describe('close-handler skip-finalization — source contract', () => {it('runner pause guard also cleans up runnerAgents entry before returning', () => {// After returning early, the runner agent map entry must not be leaked.- const fnBody = extractFunctionBody(AGENT_LIFECYCLE_SRC, 'export async function handleAgentCompletion');+ const fnBody = extractFunctionBody(AGENT_LIFECYCLE_SRC, 'async function handleAdmittedAgentCompletion');const guardPos = fnBody.indexOf('pausedAgents.has(agentId)');const returnAfterGuard = fnBody.indexOf('return', guardPos);diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex a5e22d2051..4c5cd16531 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Runner agent recovery.*@@ -70,6 +71,7 @@ export async function syncRunnerAgents() {// re-adopt — adopting it would put it in runnerAgents and the orphan// sweep would treat that local map as ownership. Live rows still sync.if (!(await runnerEntryShieldsRunningRecord(agent))) continue;+ maintenance.recoverOwned('agent', agent.id);// Only sync if this process isn't already driving itif (!isAgentOwnedLocally(agent.id)) {const task = taskMap.get(agent.taskId);diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 99c458bff9..c8059f2cce 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Agent TUI Spawning*@@ -348,6 +349,11 @@ export async function spawnTuiAgent({// the SERVICE layer is threaded in here — that is what keeps// `sessionController.js` a leaf with no edge back into this cluster, and what// makes the state machine drivable without a live PTY in a test.+ let maintenanceExited = false;+ let maintenanceCleaned = false;+ const settleMaintenance = () => {+ if (maintenanceExited && maintenanceCleaned) maintenance.finishResource('agent', agentId);+ };const controller = createTuiSessionController({agentId,task,@@ -372,12 +378,15 @@ export async function spawnTuiAgent({hasLiveChild: (pid) => shellHasLiveChild(pid),},persistence: {+ markUnsettled: () => maintenance.markResourceUnsettled('agent', agentId),updateAgent,appendRunEvent,readRunRecord: () => activeAgents.get(agentId),releaseRunRecord: (pid) => {if (pid) unregisterSpawnedAgent(pid);activeAgents.delete(agentId);+ maintenanceCleaned = true;+ settleMaintenance();},},sentinel: {@@ -466,10 +475,18 @@ export async function spawnTuiAgent({doneSentinelPath,launchShape,safetyProfile,- onData: controller.handleData,- onExit: controller.handleExit,+ onData: (...args) => maintenance.withResource('agent', agentId, () => controller.handleData(...args)),+ onExit: (...args) => {+ if (args[0]?.killed !== true) maintenanceExited = true;+ const result = maintenance.withResource('agent', agentId, () => controller.handleExit(...args));+ settleMaintenance();+ return result;+ },onInitialCommandSent: controller.markCommandInjected,});+ // killSession removes the UI record and reports a synthetic exit. Readiness+ // additionally waits for node-pty/the runner to confirm physical exit.+ session.ptyProcess?.onExit?.(() => { maintenanceExited = true; settleMaintenance(); });} catch (err) {const message = err?.message || String(err);appendLine(`❌ Failed to start ${provider.name || provider.id} TUI: ${message}`);diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex b5c04b8396..85f656b9bd 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -886,9 +886,15 @@ export function createTuiSessionController({prClaimVerified,branchProvenEmpty,outputBuffer: getOutputBuffer(),- }).catch(err => emitLog('warn', `TUI completion cleanup failed for ${agentId}: ${err.message}`, { agentId }));+ }).catch(err => {+ persistence.markUnsettled?.();+ emitLog('warn', `TUI completion cleanup failed for ${agentId}: ${err.message}`, { agentId });+ });if (sentinel.cleanup) {- await sentinel.cleanup().catch(err => emitLog('warn', `TUI recovery sentinel cleanup failed for ${agentId}: ${err.message}`, { agentId }));+ await sentinel.cleanup().catch(err => {+ persistence.markUnsettled?.();+ emitLog('warn', `TUI recovery sentinel cleanup failed for ${agentId}: ${err.message}`, { agentId });+ });}persistence.releaseRunRecord(agentData?.pid ?? null);@@ -1048,7 +1054,7 @@ export function createTuiSessionController({errorExecutionFallback: `TUI agent ended: ${reason}`,});- if (finalizeOutcome.outcome === 'paused') return;+ if (finalizeOutcome.outcome === 'paused') { persistence.releaseRunRecord(agentData?.pid ?? null); return; }if (finalizeOutcome.outcome === 'abandoned') {await abandonForHostShutdown();@@ -1151,6 +1157,9 @@ export function createTuiSessionController({if (finalizeVerdict && typeof finalizeVerdict.success === 'boolean') cleanupSuccess = finalizeVerdict.success;if (finalizeVerdict?.prClaimVerified === true) prClaimVerified = true;if (finalizeVerdict?.branchProvenEmpty === true) branchProvenEmpty = true;+ } catch (err) {+ persistence.markUnsettled?.();+ throw err;} finally {await releaseRunResources({ agentData, cleanupSuccess, prClaimVerified, branchProvenEmpty });}diff --git a/server/services/audioGen/remote.test.js b/server/services/audioGen/remote.test.jsindex 156aadba08..bc7a06e2c8 100644--- a/server/services/audioGen/remote.test.js+++ b/server/services/audioGen/remote.test.js@@ -150,6 +150,29 @@ afterEach(() => {});describe('federated audio consumer adapter', () => {+ it('keeps invalid recovered routing metadata unresolved without contacting the peer', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const owner = maintenance.admit('media', 'invalid-recovered-peer');+ await owner.run(() => generateAudio(params({ remoteMedia: { reconcile: true } })));+ await owner.finish();+ expect(transport.fetch).not.toHaveBeenCalled();+ expect(maintenance.status().blockers).toContainEqual(expect.objectContaining({ resource: 'invalid-recovered-peer', unsettled: true }));+ });++ it.each(['running', 'failed'])('distinguishes peer access loss from a confirmed %s outcome', async remoteStatus => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const owner = maintenance.admit('media', `peer-${remoteStatus}`);+ transport.fetch.mockImplementation(async (url, options) => {+ if (url.endsWith('/jobs') && options.method === 'POST') return jsonResponse(providerJob(remoteStatus), 202);+ return jsonResponse({ code: 'ACCESS_REVOKED' }, 403);+ });+ await owner.run(() => generateAudio(params()));+ await owner.finish();+ const blocker = maintenance.status().blockers.find(entry => entry.resource === `peer-${remoteStatus}`);+ if (remoteStatus === 'running') expect(blocker).toMatchObject({ unsettled: true });+ else expect(blocker).toBeUndefined();+ });+it('reconciles a queued provider job and atomically imports a verified WAV', async () => {const wav = Buffer.from('RIFF-example-wave-bytes');const digest = sha256(wav);diff --git a/server/services/autonomousJobs/execution.js b/server/services/autonomousJobs/execution.jsindex d722929052..04ce1f1d64 100644--- a/server/services/autonomousJobs/execution.js+++ b/server/services/autonomousJobs/execution.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Autonomous Jobs — direct execution paths.*@@ -33,7 +34,11 @@ function isScriptJob(job) {* @param {Object} job - The script job to execute* @returns {Promise<Object>} Result of the script execution*/-async function executeScriptJob(job, { manual = false } = {}) {+async function executeScriptJob(job, options) {+ return maintenance.run('script-job', job.id, () => executeScriptJobAdmitted(job, options));+}++async function executeScriptJobAdmitted(job, { manual = false } = {}) {if (!isScriptJob(job)) {throw new Error(`Job ${job.id} is not a script job`)}@@ -49,7 +54,7 @@ async function executeScriptJob(job, { manual = false } = {}) {const result = await handler({ background: !manual })// Record the job execution- await recordJobExecution(job.id)+ await recordJobExecution(job.id).catch(err => { maintenance.markCurrentUnsettled(); throw err })console.log(`✅ Script job completed: ${job.name}`)cosEvents.emit('jobs:script-executed', { id: job.id, result })@@ -61,6 +66,10 @@ async function executeScriptJob(job, { manual = false } = {}) {* Execute a shell job directly (no AI agent needed)*/async function executeShellJob(job) {+ return maintenance.run('shell-job', job.id, () => executeShellJobAdmitted(job));+}++async function executeShellJobAdmitted(job) {const validation = validateCommand(job.command)if (!validation.valid) {throw new Error(`Invalid shell command: ${validation.error}`)@@ -115,41 +124,19 @@ async function executeShellJob(job) {if (errBytes < MAX_OUTPUT_BYTES) { errChunks.push(data.toString()); errBytes += data.length }})- child.on('close', (rawCode, signal) => {- const code = rawCode ?? (signal ? 128 : 1)+ let spawnError = null+ child.on('error', err => {+ spawnError = err+ console.error(`❌ Shell job ${job.name} error: ${err.message}`)+ })+ child.once('close', (rawCode, signal) => {clearTimeout(timer)- if (killed) {- const persistTimeout = async () => {- await withLock(async () => {- const data = await loadJobs()- const j = data.jobs.find(x => x.id === job.id)- if (j) {- j.lastOutput = `Process killed after ${timeoutMs}ms timeout`- j.lastExitCode = -1- j.lastResult = 'timeout'- await saveJobs(data)- }- })- await recordJobExecution(job.id)- }- persistTimeout().then(() => {- const err = new Error(`Shell job "${job.name}" timed out after ${timeoutMs}ms`)- err.exitCode = -1- reject(err)- }).catch((persistErr) => {- console.error(`❌ Shell job ${job.name} failed to persist timeout state: ${persistErr.message}`)- const err = new Error(`Shell job "${job.name}" timed out after ${timeoutMs}ms`)- err.exitCode = -1- reject(err)- })- return- }+ const code = killed || spawnError ? -1 : rawCode ?? (signal ? 128 : 1)const output = outChunks.join('')- const error = errChunks.join('')- const fullOutput = output + (error ? `\n[stderr]\n${error}` : '')- const redactedOutput = redactOutput(fullOutput)-- // Persist output/exit code and record execution in a single lock cycle+ const stderr = errChunks.join('')+ const redactedOutput = redactOutput(killed+ ? `Process killed after ${timeoutMs}ms timeout`+ : spawnError?.message || output + (stderr ? `\n[stderr]\n${stderr}` : ''))const persist = async () => {await withLock(async () => {const data = await loadJobs()@@ -158,59 +145,30 @@ async function executeShellJob(job) {j.lastOutput = redactedOutput.substring(0, 10000)j.lastExitCode = codej.lastRun = new Date().toISOString()- j.lastResult = code === 0 ? 'success' : 'failure'+ j.lastResult = killed ? 'timeout' : spawnError ? 'error' : code === 0 ? 'success' : 'failure'j.runCount = (j.runCount || 0) + 1j.updatedAt = j.lastRunawait saveJobs(data)- console.log(`🤖 Shell job executed: ${j.name} (run #${j.runCount})`)cosEvents.emit('jobs:executed', { id: job.id, runCount: j.runCount })}})}-persist().then(() => {+ cosEvents.emit('jobs:shell-executed', { id: job.id, exitCode: code })if (code !== 0) {- console.error(`❌ Shell job failed: ${job.name} (exit ${code})`)- cosEvents.emit('jobs:shell-executed', { id: job.id, exitCode: code })- const err = new Error(`Shell job "${job.name}" exited with code ${code}: ${redactedOutput.substring(0, 500)}`)- err.exitCode = code- reject(err)+ const message = killed ? `timed out after ${timeoutMs}ms`+ : spawnError ? `spawn error: ${spawnError.message}` : `exited with code ${code}: ${redactedOutput.substring(0, 500)}`+ reject(Object.assign(new Error(`Shell job "${job.name}" ${message}`), { exitCode: code }))return}-console.log(`✅ Shell job completed: ${job.name} (exit ${code})`)- cosEvents.emit('jobs:shell-executed', { id: job.id, exitCode: code })resolve({ success: true, exitCode: code, output: redactedOutput })- }).catch((persistErr) => {+ }).catch(persistErr => {+ maintenance.markCurrentUnsettled()console.error(`❌ Shell job ${job.name} failed to persist state: ${persistErr.message}`)reject(persistErr)})})-- child.on('error', (err) => {- clearTimeout(timer)- console.error(`❌ Shell job ${job.name} error: ${err.message}`)- const persistError = async () => {- await withLock(async () => {- const data = await loadJobs()- const j = data.jobs.find(x => x.id === job.id)- if (j) {- j.lastOutput = err.message- j.lastExitCode = -1- j.lastRun = new Date().toISOString()- j.lastResult = 'error'- await saveJobs(data)- }- })- await recordJobExecution(job.id)- }- persistError().then(() => {- reject(new Error(`Shell job "${job.name}" spawn error: ${err.message}`))- }).catch((persistErr) => {- console.error(`❌ Shell job ${job.name} failed to persist error state: ${persistErr.message}`)- reject(new Error(`Shell job "${job.name}" spawn error: ${err.message}`))- })- })})}diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 888c982424..c18bdba38a 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -1,3 +1,5 @@+import { bindMaintenanceIo } from './maintenanceControl.js';+import { maintenance } from '../lib/maintenanceAdmission.js';import { noteReadinessChanged } from './readinessNotify.js';/*** Server boot orchestration.@@ -189,6 +191,7 @@ import { logFailureWithStack as logBootstrapFailure } from '../lib/failureLoggin* `runBootSequence` below.*/export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverDir }) => {+ bindMaintenanceIo(io);// Lifecycle hooks shared between AI Toolkit and PortOS runner shimconst aiToolkitHooks = attachLlmActivityHooks({ensureProviderReady: (provider) => ensureProviderReadyForExecution(provider),@@ -202,7 +205,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// the prompt-cache tiers that dominate cost), falling back to the// prompt-length/stdout estimate when none is found. Owns its own error// handling — a usage-accounting failure must not fail the run.- recordCompletedRunUsage(metadata, output);+ return recordCompletedRunUsage(metadata, output);},onRunFailed: (metadata, error) => {const errorMessage = error?.message ?? String(error);@@ -290,6 +293,7 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverDsampleProvidersFile: join(dataReferenceDir, 'providers.json'),io,asyncHandler,+ withRunAdmission: handler => (req, res) => maintenance.run('manual-run', 'Runs', () => handler(req, res)),// Inject PortOS's ServerError so toolkit route errors normalize into the// canonical `{ error, code, timestamp, context? }` envelope (issue #1084).ServerError,@@ -371,6 +375,14 @@ export const bootstrapServices = async ({ io, dataDir, dataReferenceDir, serverD// toolkit's external-run registry, so the toolkit's own stopRun/isRunActive/// deleteRun account for live runs without any sibling-method monkey-patching.registerRunners: (aiToolkit) => {+ const executeApi = aiToolkit.services.runner.executeApiRun.bind(aiToolkit.services.runner);+ aiToolkit.services.runner.executeApiRun = options => {+ const permit = maintenance.admit('api-run', options.runId, { continuation: true });+ return permit.run(() => executeApi({ ...options,+ onPersistenceFailure: () => permit.markUnsettled(),+ onSettled: () => permit.finish(),+ })).catch(err => { permit.markUnsettled(); throw err; });+ };aiToolkit.services.runner.setCliRunner(executeCliRunFixed);aiToolkit.services.runner.setTuiRunner(executeTuiRunFixed);},diff --git a/server/services/codeAnimation/export.js b/server/services/codeAnimation/export.jsindex f2d0d75549..b84b3f0e26 100644--- a/server/services/codeAnimation/export.js+++ b/server/services/codeAnimation/export.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Frame-exact MP4 export for a generated Code Animation (#9078).*@@ -32,12 +33,15 @@ const STALE_STAGING_MS = 24 * 60 * 60 * 1000;// Remove this animation's earlier stagings, keeping any a queued render may// not have snapshotted yet.async function sweepStaleStagings(parent) {+ const { listJobs } = await import('../mediaJobQueue/index.js');+ const referenced = new Set(listJobs().filter(job => ['queued', 'running'].includes(job.status))+ .map(job => job.params?.directory).filter(Boolean).map(directory => join(PATHS.data, directory)));const entries = await readdir(parent).catch(() => []);const cutoff = Date.now() - STALE_STAGING_MS;for (const name of entries) {const path = join(parent, name);const info = await stat(path).catch(() => null);- if (info && info.mtimeMs < cutoff) await rm(path, { recursive: true, force: true });+ if (!referenced.has(path) && info && info.mtimeMs < cutoff) await rm(path, { recursive: true, force: true });}}@@ -113,6 +117,10 @@ function musicTrackOf(job) {* composition render. Returns the queued media job plus any export notes.*/export async function startCodeAnimationExport(id, deps = {}) {+ return maintenance.run('export-preparation', id, () => startAdmittedExport(id, deps));+}++async function startAdmittedExport(id, deps) {const {enqueueJob = (await import('../mediaJobQueue/index.js')).enqueueJob,beatGrid = async (track) => {diff --git a/server/services/cos.js b/server/services/cos.jsindex 637da0341e..dde66b645c 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';import { getPendingTaskIds as readPendingTaskIds } from './cosTaskStore.js';import { mergePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';/**@@ -698,6 +699,7 @@ export async function isPaused() {* Force-spawn a pending task by ID, bypassing cooldowns and evaluation intervals.*/export async function forceSpawnTask(taskId) {+ maintenance.assertOpen();const task = await getTaskById(taskId);if (!task) return { error: 'Task not found' };if (task.status !== 'pending') return { error: `Task is ${task.status}, not pending` };@@ -1204,6 +1206,7 @@ const scheduleDequeue = (options = {}) => setImmediate(() => {* other caller runs outside that window and correctly leaves it null.*/export async function dequeueNextTask({ ignoreTaskId = null } = {}) {+ if (maintenance.held()) return;if (!isDaemonRunning()) return;// In runner mode the cos-runner app owns every agent process, so a cycle rundiff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.jsindex 93429189a6..fc3d53a7c8 100644--- a/server/services/cosJobScheduler.js+++ b/server/services/cosJobScheduler.js@@ -1,3 +1,4 @@+import { maintenance, isMaintenanceHold } from '../lib/maintenanceAdmission.js';/*** CoS Job Scheduler Module*@@ -218,6 +219,10 @@ export function clearSpawningJob(jobId) {* Execute a scheduled autonomous job and re-register its timer.*/export async function executeScheduledJob(jobId) {+ if (maintenance.held()) {+ scheduleEvent({ id: `job:${jobId}`, type: 'once', delayMs: 60000, handler: () => executeScheduledJob(jobId), metadata: { jobId, description: 'Maintenance hold' } });+ return;+ }if (!isDaemonRunning()) return;const paused = (await loadState()).paused || false;@@ -330,9 +335,14 @@ export async function executeScheduledJob(jobId) {if (isScriptJob(job)) {const startedAt = Date.now();const scriptOk = await executeScriptJob(job).then(() => true, err => {+ if (isMaintenanceHold(err)) return null;emitLog('error', `Script job failed: ${job.name} - ${err.message}`, { jobId: job.id });return false;});+ if (scriptOk === null) {+ scheduleEvent({ id: `job:${jobId}`, type: 'once', delayMs: 60000, handler: () => executeScheduledJob(jobId), metadata: { jobId } });+ return;+ }// Count the fired attempt against the budget whether it succeeded or failed —// a failing/looping scheduled job still consumes autonomous work + wall-clock,// and must not be able to bypass the daily cap.@@ -343,9 +353,14 @@ export async function executeScheduledJob(jobId) {} else if (isShellJob(job)) {const startedAt = Date.now();const shellOk = await executeShellJob(job).then(() => true, err => {+ if (isMaintenanceHold(err)) return null;emitLog('error', `Shell job failed: ${job.name} - ${err.message}`, { jobId: job.id });return false;});+ if (shellOk === null) {+ scheduleEvent({ id: `job:${jobId}`, type: 'once', delayMs: 60000, handler: () => executeScheduledJob(jobId), metadata: { jobId } });+ return;+ }await recordDomainUsage('cos', { actions: 1, ms: Date.now() - startedAt }).catch(err => console.error(`❌ Failed to record CoS budget usage for shell job ${job.id}: ${err.message}`));releaseReservation(); // recorded usage now owns the in-flight count for this actiondiff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 6690395e64..5cfbabe69c 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** CoS Runner Client*@@ -214,7 +215,7 @@ const postSpawn = (path, body) =>fetchWithTimeout(`${COS_RUNNER_URL}${path}`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(body),+ body: JSON.stringify({ ...body, maintenanceParentId: maintenance.currentId() }),}, 60000).then(response => ({ response }),err => ({ transportError: ambiguousSpawn(err) })diff --git a/server/services/creativeDirector/planAdvance.js b/server/services/creativeDirector/planAdvance.jsindex a0bec49dcf..93b2487e7e 100644--- a/server/services/creativeDirector/planAdvance.js+++ b/server/services/creativeDirector/planAdvance.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Creative Director — production-plan advance loop (CDO Phase 2, #2184).*@@ -536,7 +537,7 @@ function armPlanJobListener(projectId, stepId, jobId, runId, expectedProductionRteardown();const success = job.status === 'completed';// Runs outside the request lifecycle (media-queue emitter) — never throw out.- (async () => {+ maintenance.continueSettlement(async () => {await finishRun(projectId, runId, success ? 'completed' : 'failed', success ? undefined : `job ${job.status}`);if (success) {await updatePlanStep(projectId, stepId, { ...(expectedProductionRevision === undefined ? {} : { expectedProductionRevision }), status: 'done', result: { jobId } });@@ -545,7 +546,7 @@ function armPlanJobListener(projectId, stepId, jobId, runId, expectedProductionRawait updatePlanStep(projectId, stepId, { ...(expectedProductionRevision === undefined ? {} : { expectedProductionRevision }), status: 'failed', result: { jobId, jobStatus: job.status } });await handlePlanStepFailure(projectId, { stepId, toolName: '(long-running job)', retryCount: 0 });}- })().catch((e) => console.log(`⚠️ CD plan ${projectId} job settle for ${stepId} failed: ${e.message}`));+ }).catch((e) => console.log(`⚠️ CD plan ${projectId} job settle for ${stepId} failed: ${e.message}`));}mediaJobEvents.on('completed', settle);mediaJobEvents.on('failed', settle);diff --git a/server/services/creativeDirector/sceneRunner.js b/server/services/creativeDirector/sceneRunner.jsindex 50b7c5af77..08a8865563 100644--- a/server/services/creativeDirector/sceneRunner.js+++ b/server/services/creativeDirector/sceneRunner.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Creative Director — server-side scene render orchestrator.*@@ -296,14 +297,14 @@ export async function runSceneRender(project, scene) {if (settled || job.id !== jobId) return;settled = true;cleanup();- settleReceipt('completed').then(() => handleRenderCompleted(project.id, scene.sceneId, jobId, { continuationFellBack, workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined }))+ maintenance.continueSettlement(() => settleReceipt('completed').then(() => handleRenderCompleted(project.id, scene.sceneId, jobId, { continuationFellBack, workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined }))).catch(error => console.error(`❌ CD render completion failed: ${error.message}`));};const onFailed = (job) => {if (settled || job.id !== jobId) return;settled = true;cleanup();- settleReceipt(/timeout|timed out|interrupted/i.test(job.error || '') ? 'uncertain' : 'failed').then(() => handleRenderFailed(project.id, scene.sceneId, job.error || 'render failed', { workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined }))+ maintenance.continueSettlement(() => settleReceipt(/timeout|timed out|interrupted/i.test(job.error || '') ? 'uncertain' : 'failed').then(() => handleRenderFailed(project.id, scene.sceneId, job.error || 'render failed', { workRevision: project.workspace === 'video' ? scene.workRevision || 0 : undefined }))).catch(error => console.error(`❌ CD render failure handling failed: ${error.message}`));};const onCanceled = (job) => {@@ -315,7 +316,7 @@ export async function runSceneRender(project, scene) {// CD_MAX_SCENE_RETRIES); the user explicitly stopped this. Mark the scene// failed and let the completionHook flag the project so the user can// resume from the UI.- settleReceipt(job.params?.videoProduction?.submissionUncertain ? 'uncertain' : 'canceled').then(() => handleRenderCanceled(project.id, scene.sceneId, project.workspace === 'video' ? scene.workRevision || 0 : undefined))+ maintenance.continueSettlement(() => settleReceipt(job.params?.videoProduction?.submissionUncertain ? 'uncertain' : 'canceled').then(() => handleRenderCanceled(project.id, scene.sceneId, project.workspace === 'video' ? scene.workRevision || 0 : undefined))).catch(error => console.error(`❌ CD render cancellation handling failed: ${error.message}`));};function cleanup() {diff --git a/server/services/falQueue.js b/server/services/falQueue.jsindex df0f0cdab0..d95d270e97 100644--- a/server/services/falQueue.js+++ b/server/services/falQueue.js@@ -15,6 +15,7 @@*/import { readFile } from 'fs/promises';+import { maintenance } from '../lib/maintenanceAdmission.js';import { ServerError } from '../lib/errorHandler.js';import { describeFetchError } from '../lib/fetchErrorChain.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';@@ -72,7 +73,18 @@ export const createFalRequestEntry = (apiKey) => ({// never fires once the remote request already reached a fal-reported// terminal state (COMPLETED/ERROR) — there is nothing left to cancel there.export async function cancelFalRequest(entry) {- if (!entry || entry.canceledRemote || entry.remoteTerminal || !entry.cancelUrl || !entry.apiKey) return;+ if (!entry) return;+ if (entry.cancelPromise) await entry.cancelPromise;+ else {+ if (entry.remoteTerminal || !entry.cancelUrl || !entry.apiKey) return;+ entry.cancelPromise = sendFalCancel(entry);+ await entry.cancelPromise;+ }+ // An accepted cancel request does not prove the paid remote render stopped.+ if (!entry.remoteTerminal) maintenance.markCurrentUnsettled();+}++async function sendFalCancel(entry) {entry.canceledRemote = true;try {const res = await fetchWithTimeout(entry.cancelUrl, {@@ -80,6 +92,7 @@ export async function cancelFalRequest(entry) {headers: { Authorization: `Key ${entry.apiKey}` },}, FAL_POLL_TIMEOUT_MS);if (!res.ok) console.error(`❌ fal.ai cancellation request failed: HTTP ${res.status}`);+ await res.body?.cancel?.();} catch (err) {console.error(`❌ fal.ai cancellation request failed: ${err?.message || err}`);}@@ -95,9 +108,14 @@ export async function submitFalRequest({ apiKey, modelId, body }) {method: 'POST',headers: { Authorization: `Key ${apiKey}`, 'Content-Type': 'application/json' },body: JSON.stringify(body),- }, FAL_SUBMIT_TIMEOUT_MS);+ }, FAL_SUBMIT_TIMEOUT_MS).catch(err => {+ // A lost POST response is not proof that the paid request was rejected.+ maintenance.markCurrentUnsettled();+ throw err;+ });const payload = await res.json().catch(() => null);if (!res.ok || !payload?.request_id) {+ if (res.ok || res.status >= 500) maintenance.markCurrentUnsettled();const reason = payload?.detail ? JSON.stringify(payload.detail) : `HTTP ${res.status}`;throw new ServerError(`fal.ai rejected the request: ${reason}`, { status: 502, code: 'FAL_SUBMIT_FAILED' });}@@ -161,12 +179,16 @@ export async function awaitFalCompletion({}if (status.status === 'ERROR') {entry.remoteTerminal = true;+ await cancelFalRequest(entry);return { outcome: 'failed', reason: `fal.ai render failed: ${status.error || 'unknown error'}` };}onStatus(status.status);await new Promise((r) => setTimeout(r, FAL_POLL_INTERVAL_MS));}- if (entry.aborted) return { outcome: 'canceled' };+ if (entry.aborted) {+ await cancelFalRequest(entry);+ return { outcome: 'canceled' };+ }if (Date.now() >= deadline) {await cancelFalRequest(entry);return { outcome: 'failed', reason: `fal.ai did not finish within ${Math.round(timeoutMs / 1000)}s` };diff --git a/server/services/falQueue.test.js b/server/services/falQueue.test.jsindex 8f45c6caab..b690d6f9d8 100644--- a/server/services/falQueue.test.js+++ b/server/services/falQueue.test.js@@ -1,9 +1,72 @@import { describe, it, expect, vi, afterEach } from 'vitest';-import { awaitFalCompletion, createFalRequestEntry } from './falQueue.js';+import { cancelFalRequest, submitFalRequest, awaitFalCompletion, createFalRequestEntry } from './falQueue.js';afterEach(() => vi.unstubAllGlobals());describe('awaitFalCompletion', () => {+ it.each(['COMPLETED', 'ERROR'])('waits for cancellation transport when concurrent status reports %s', async remoteStatus => {+ let completeStatus;+ let completeCancel;+ vi.stubGlobal('fetch', vi.fn((_url, options) => new Promise(resolve => {+ if (options.method === 'PUT') completeCancel = resolve;+ else completeStatus = resolve;+ })));+ const entry = createFalRequestEntry('test-key');+ entry.cancelUrl = 'https://queue.fal.run/example/requests/abc/cancel';+ let settled = false;+ const poll = awaitFalCompletion({ entry, statusUrl: 'https://queue.fal.run/example/status',+ apiKey: 'test-key', deadline: Date.now() + 60_000, timeoutMs: 60_000,+ }).then(result => { settled = true; return result; });+ entry.aborted = true;+ const canceling = cancelFalRequest(entry);+ completeStatus({ ok: true, json: async () => ({ status: remoteStatus }) });+ await vi.waitFor(() => expect(entry.remoteTerminal).toBe(true));+ expect(settled).toBe(false);+ completeCancel({ ok: true });+ expect(await poll).toMatchObject({ outcome: remoteStatus === 'ERROR' ? 'failed' : 'canceled' });+ await canceling;+ });++ it.each(['lost response', 'missing receipt'])('retains an ambiguous paid submission: %s', async failure => {+ const { maintenance } = await import('../lib/maintenanceAdmission.js');+ const owner = maintenance.admit('media', failure);+ vi.stubGlobal('fetch', vi.fn(async () => {+ if (failure === 'lost response') throw new Error('Connection lost');+ return { ok: true, status: 200, json: async () => ({}) };+ }));+ await expect(owner.run(() => submitFalRequest({ apiKey: 'test-key', modelId: 'example', body: {} }))).rejects.toThrow();+ await owner.finish();+ expect(maintenance.status().blockers).toContainEqual(expect.objectContaining({ resource: failure, unsettled: true }));+ });++ it('joins an in-flight cancel and retains uncertain remote ownership', async () => {+ const { maintenance } = await import('../lib/maintenanceAdmission.js');+ let completeCancel;+ const transport = new Promise(resolve => { completeCancel = resolve; });+ const fetchMock = vi.fn(() => transport);+ vi.stubGlobal('fetch', fetchMock);+ const owner = maintenance.admit('media', 'fal-cancel-test');+ const entry = createFalRequestEntry('test-key');+ entry.cancelUrl = 'https://queue.fal.run/example/requests/abc/cancel';+ entry.aborted = true;+ const canceling = cancelFalRequest(entry);+ let settled = false;+ const poll = owner.run(() => awaitFalCompletion({+ entry, statusUrl: 'unused', apiKey: 'test-key',+ deadline: Date.now() + 60_000, timeoutMs: 60_000,+ })).then(() => { settled = true; });+ const status = maintenance.begin({ reason: 'cancel transport test', owner: 'test' });+ await Promise.resolve();+ expect(settled).toBe(false);+ expect(status.state).toBe('draining');+ completeCancel({ ok: true });+ await Promise.all([canceling, poll]);+ await owner.finish();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(maintenance.status().blockers).toContainEqual(expect.objectContaining({ resource: 'fal-cancel-test', unsettled: true }));+ maintenance.resume({ id: status.hold.id, revision: status.hold.revision });+ });+// A cancel that lands while submit is in flight finds no cancel_url, so the// remote cancel is a no-op; the receipt arrives afterwards. The paid render// must still be cancelled remotely instead of left queued at fal.ai.diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.jsindex 519a269309..854f0901b5 100644--- a/server/services/federatedMedia/remoteExecutor.js+++ b/server/services/federatedMedia/remoteExecutor.js@@ -23,6 +23,7 @@* federatedMedia/inputAssets.js.*/+import { maintenance } from '../../lib/maintenanceAdmission.js';import { createWriteStream } from 'node:fs';import { mkdir, rename, stat, unlink } from 'node:fs/promises';import { createHash } from 'node:crypto';@@ -306,8 +307,10 @@ export function createRemoteMediaExecutor({async function pollProviderJob(state, initial) {let current = initial;while (true) {+ if (['completed', 'failed', 'canceled'].includes(current.status)) state.remoteTerminal = true;if (state.cancelRequested && !state.cancelSent) {current = await sendRemoteCancel(state, current.id);+ if (['completed', 'failed', 'canceled'].includes(current.status)) state.remoteTerminal = true;}if (state.cancelRequested && ['completed', 'failed', 'canceled'].includes(current.status)) {throw canceledError();@@ -367,7 +370,7 @@ export function createRemoteMediaExecutor({const partialPath = join(dir, `.${filename}.partial`);await mkdir(dir, { recursive: true });if (await existingResultMatches(finalPath, metadata)) return { filename, dir, path: finalPath };- await unlink(partialPath).catch(() => {});+ await unlink(partialPath).catch((error) => { if (error.code !== 'ENOENT') maintenance.markCurrentUnsettled(); });const peer = await findPeer(state.peerId, { standingRoute: state.standingRoute });// Keep the controller live for the body stream so cancel()/the queue@@ -430,7 +433,7 @@ export function createRemoteMediaExecutor({await rename(partialPath, finalPath);return { filename, dir, path: finalPath };} finally {- await unlink(partialPath).catch(() => {});+ await unlink(partialPath).catch((error) => { if (error.code !== 'ENOENT') maintenance.markCurrentUnsettled(); });}}, { timeoutMs: null });}@@ -469,6 +472,7 @@ export function createRemoteMediaExecutor({const submitted = await submitOrRecover(state, request);const completed = await pollProviderJob(state, submitted);const downloaded = await downloadResult(state, completed);+ state.finalizing = true;const local = await finalize({jobId: state.jobId,peerId: state.peerId,@@ -483,6 +487,7 @@ export function createRemoteMediaExecutor({renderStartedAtMs: state.renderStartedAtMs,...downloaded,});+ state.finalizing = false;return {...local,federatedMedia: {@@ -497,6 +502,7 @@ export function createRemoteMediaExecutor({async function run(params) {const marker = markerSchema.safeParse(params?.remoteMedia);if (!marker.success) {+ if (params?.remoteMedia?.reconcile === true) maintenance.markCurrentUnsettled();events.emit('failed', {generationId: params?.jobId,error: `Remote ${label} job has invalid persisted routing metadata`,@@ -532,6 +538,9 @@ export function createRemoteMediaExecutor({const result = await runRemote(state, marker.data);events.emit('completed', { generationId: params.jobId, ...result });} catch (error) {+ // An unreachable/revoked peer is not proof that its admitted render+ // stopped. Keep local ownership until completion can be reconciled.+ if ((state.submissionMayExist && !state.remoteTerminal) || state.finalizing) maintenance.markCurrentUnsettled();events.emit('failed', {generationId: params.jobId,error: error?.canceleddiff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.jsindex 84b08ec59d..5633ff7ea0 100644--- a/server/services/htmlComposition/index.js+++ b/server/services/htmlComposition/index.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { cp, lstat, mkdtemp, open, realpath, rm, stat, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';@@ -81,7 +82,10 @@ export async function stageMusicVideoComposition(sourceDirectory, jobId, song, {if (prepare) await prepare(compositionDir);return { directory: `${MUSIC_VIDEO_SCRATCH_DIR}/${jobId}/composition`, scratchRoot };} catch (error) {- await rm(scratchRoot, { recursive: true, force: true });+ await rm(scratchRoot, { recursive: true, force: true }).catch(cleanupError => {+ maintenance.markCurrentUnsettled();+ throw cleanupError;+ });throw error;}}@@ -130,7 +134,11 @@ function deliveryNames(targets) {return names;}-export async function renderComposition({ jobId, owner, audio, maxDurationSec, song, ...input }) {+export async function renderComposition(options) {+ return maintenance.run('composition', options.jobId, () => renderCompositionAdmitted(options), { continuation: true });+}++async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec, song, ...input }) {const job = { controller: new AbortController(), committing: false };active.set(jobId, job);const { signal } = job.controller;@@ -336,17 +344,23 @@ export async function renderComposition({ jobId, owner, audio, maxDurationSec, s...(formats ? { videos: rendered.map(video => ({ format: video.format, ...summary(video) })) } : {}) };}} catch (error) {+ if (job.committing) maintenance.markCurrentUnsettled();failure = error;} finally {- await page?.close();+ if (page) await page.close().catch(error => {+ maintenance.markCurrentUnsettled();+ failure ||= error;+ });if (audioDirectory) await rm(audioDirectory, { recursive: true, force: true }).catch(() => {+ maintenance.markCurrentUnsettled();console.warn('⚠️ Could not remove temporary composition audio');});if (scratchRoot) await rm(scratchRoot, { recursive: true, force: true }).catch(() => {+ maintenance.markCurrentUnsettled();console.warn('⚠️ Could not remove temporary music-video composition');});if (!success) {- for (const path of ownedPaths) await unlinkGuarded(path).catch(() => {});+ for (const path of ownedPaths) await unlinkGuarded(path).catch(error => { if (error.code !== 'ENOENT') maintenance.markCurrentUnsettled(); });}active.delete(jobId);}diff --git a/server/services/htmlComposition/renderComposition.preflight.test.js b/server/services/htmlComposition/renderComposition.preflight.test.jsindex 39ae41c8fc..7dc0354a6c 100644--- a/server/services/htmlComposition/renderComposition.preflight.test.js+++ b/server/services/htmlComposition/renderComposition.preflight.test.js@@ -13,6 +13,7 @@ vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await idataRoot: () => lazyTempDataRoot('portos-html-composition-preflight-'),}));+const closeComposition = vi.fn(async () => {});const CONTRACT = { durationSec: 15, fps: 12, width: 1280, height: 720, motionBlur: 1, layout: false };vi.mock('./browser.js', () => ({@@ -23,7 +24,7 @@ vi.mock('./browser.js', () => ({['/caption.txt', Buffer.from('Make a clear plan.')],['/storyboard.json', Buffer.from(JSON.stringify({ posterSec: 11, scenes: [{ durationSec: 15, lines: [] }] }))],]));- return { evaluate: async () => CONTRACT, check: () => {}, close: async () => {} };+ return { evaluate: async () => CONTRACT, check: () => {}, close: closeComposition };},}));@@ -36,6 +37,30 @@ const { PATHS } = await import('../../lib/fileUtils.js');const { renderComposition } = await import('./index.js');describe('renderComposition delivery preflight', () => {+ it('releases ownership after an ordinary render failure finishes cleanup', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const jobId = randomUUID();+ const directory = `compositions/${jobId}`;+ await mkdir(join(PATHS.data, directory), { recursive: true });+ await writeFile(join(PATHS.data, directory, 'index.html'), '<html></html>');+ await expect(renderComposition({ directory, jobId })).rejects.toThrow('encodeComposition must not run');+ expect(closeComposition).toHaveBeenLastCalledWith();+ expect(maintenance.status().blockers).not.toContainEqual(expect.objectContaining({ resource: jobId }));+ encodeComposition.mockClear();+ });++ it('retains ownership when a failed render cannot finish browser cleanup', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const jobId = randomUUID();+ const directory = `compositions/${jobId}`;+ await mkdir(join(PATHS.data, directory), { recursive: true });+ await writeFile(join(PATHS.data, directory, 'index.html'), '<html></html>');+ closeComposition.mockRejectedValueOnce(new Error('Context cleanup failed'));+ await expect(renderComposition({ directory, jobId })).rejects.toThrow();+ expect(maintenance.status().blockers).toContainEqual(expect.objectContaining({ kind: 'composition', resource: jobId, unsettled: true }));+ encodeComposition.mockClear();+ });+it('refuses with EEXIST before encoding when a delivery file already exists', async () => {const runId = randomUUID();const directory = `launch-videos/example/${runId}/composition`;diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex 486d5f4bcf..c2e916ac01 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — Antigravity (`agy`) CLI provider.*@@ -378,7 +379,12 @@ async function runAgy(job, jobId, bin, args, {// scratch-dir spawn telling the child one consistent story about where it is.const proc = spawn(command, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });activeProcs.set(jobId, proc);- const removeScratch = () => rmGuarded(scratchDir, { recursive: true, force: true }).catch(() => {});+ const removeScratch = () => maintenance.continueSettlement(+ () => rmGuarded(scratchDir, { recursive: true, force: true }),+ ).catch((err) => {+ maintenance.markCurrentUnsettled();+ console.error(`❌ agy scratch cleanup failed: ${err.message}`);+ });let stdoutTail = '';let stderrTail = '';const timeoutTimer = setTimeout(() => {@@ -395,7 +401,11 @@ async function runAgy(job, jobId, bin, args, {proc.stderr.on('data', (chunk) => {stderrTail = `${stderrTail}${chunk}`.slice(-32768);});+ let processError;proc.on('error', (err) => {+ processError = err;+ // A failed kill/send on a live child is not physical exit.+ if (proc.pid) return;clearTimeout(timeoutTimer);removeScratch();finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);@@ -403,9 +413,9 @@ async function runAgy(job, jobId, bin, args, {proc.on('close', async (code, signal) => {clearTimeout(timeoutTimer);try {- if (code !== 0) {+ if (code !== 0 || processError) {removeScratch();- const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);return finalizeJobFailure(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);}const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);@@ -442,7 +452,7 @@ async function runAgy(job, jobId, bin, args, {// `job.renderStartedAtMs` is the queue-ingestion instant generateImage// captured, so the spread measures the render itself — not the time the// job spent queued behind other renders.- await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => {});+ await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => maintenance.markCurrentUnsettled());await autoCleanGeneratedImage({cleanC2PA,denoise,diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex b961993b28..83acc29045 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — Codex CLI provider.*@@ -367,7 +368,11 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleif (bannerBuf.length > BANNER_BUF_MAX) bannerBuf = bannerBuf.slice(-BANNER_BUF_MAX);};+ let processError;proc.on('error', (err) => {+ processError = err;+ // A failed kill/send on a live child is not physical exit.+ if (proc.pid) return;clearTimeout(timeoutTimer);finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);});@@ -404,8 +409,8 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle// unhandled rejection (process-killing on Node ≥15) and the job would// be stuck in 'running' forever with no SSE error to the client.try {- if (code !== 0) {- const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ if (code !== 0 || processError) {+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);const tail = stderrTail.trim().split('\n').slice(-6).join('\n');return finalizeJobFailure(job, jobId, proc, `Codex generation failed: ${reason}\n${tail}`);}@@ -438,7 +443,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle// `job.renderStartedAtMs` is the queue-ingestion instant generateImage// captured, so the spread measures the render itself — not the time the// job spent queued behind other renders.- await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => {});+ await atomicWrite(sidecar, { ...meta, codexSessionId: sessionId, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => maintenance.markCurrentUnsettled());// Cleaners run BEFORE the SSE complete + completed events so subscribers// see the cleaned bytes. codex output is the highest-value target for// C2PA stripping because gpt-image is the one provider that embedsdiff --git a/server/services/imageGen/fal.js b/server/services/imageGen/fal.jsindex 38adee43b8..9779846287 100644--- a/server/services/imageGen/fal.js+++ b/server/services/imageGen/fal.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — fal.ai queue REST API provider.*@@ -367,7 +368,7 @@ async function runFal(job, jobId, {// account; this only lets a gallery record say roughly what it cost.estimatedCostUsd: request.estimatedCostUsd,...renderTimingFields(job.renderStartedAtMs),- }).catch(() => {});+ }).catch(() => maintenance.markCurrentUnsettled());// Cleaners run BEFORE the SSE complete + completed events so subscribers// see the cleaned bytes.await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: MODE });diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex 7b30497335..2c32083f0a 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — xAI Grok Build CLI provider.*@@ -320,7 +321,12 @@ async function runGrok(job, jobId, bin, args, {// scratch-dir spawn telling the child one consistent story about where it is.const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });activeProcs.set(jobId, proc);- const removeScratch = () => rmGuarded(scratchDir, { recursive: true, force: true }).catch(() => {});+ const removeScratch = () => maintenance.continueSettlement(+ () => rmGuarded(scratchDir, { recursive: true, force: true }),+ ).catch((err) => {+ maintenance.markCurrentUnsettled();+ console.error(`❌ grok scratch cleanup failed: ${err.message}`);+ });if (useStdin) {// POSIX: grok reads the prompt via --prompt-file /dev/stdin. EPIPE fires@@ -342,7 +348,11 @@ async function runGrok(job, jobId, bin, args, {}}, GROK_TIMEOUT_MS);+ let processError;proc.on('error', (err) => {+ processError = err;+ // A failed kill/send on a live child is not physical exit.+ if (proc.pid) return;clearTimeout(timeoutTimer);cleanupPromptFile();removeScratch();@@ -367,8 +377,8 @@ async function runGrok(job, jobId, bin, args, {// a throw from the harvest/copy would surface as an unhandled rejection// and the job would be stuck in 'running' forever with no SSE error.try {- if (code !== 0) {- const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ if (code !== 0 || processError) {+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);const tail = stderrTail.trim().split('\n').slice(-6).join('\n');removeScratch();return finalizeJobFailure(job, jobId, proc, `Grok generation failed: ${reason}\n${tail}`);@@ -414,7 +424,7 @@ async function runGrok(job, jobId, bin, args, {// `job.renderStartedAtMs` is the queue-ingestion instant generateImage// captured, so the spread measures the render itself — not the time the// job spent queued behind other renders.- await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => {});+ await atomicWrite(sidecar, { ...meta, ...renderTimingFields(job.renderStartedAtMs) }).catch(() => maintenance.markCurrentUnsettled());// Cleaners run BEFORE the SSE complete + completed events so// subscribers see the cleaned bytes.await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.GROK });diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex b96c69e058..605d4b287d 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -94,6 +94,19 @@ afterEach(async () => {});describe('grok provider — deriveAspectRatio', () => {+ it('does not signal a live-child error as settled before physical close', async () => {+ const failed = vi.fn();+ imageGenEvents.on('failed', failed);+ await grok.generateImage({ prompt: 'a fox' });+ const child = spawnCalls[0].child;+ child.pid = 9876;+ child.emit('error', new Error('signal delivery failed'));+ await flush();+ expect(failed).not.toHaveBeenCalled();+ await closeChild(0, 1);+ expect(failed).toHaveBeenCalledTimes(1);+ });+it('maps common dimension pairs to the closest supported ratio', () => {expect(grok.deriveAspectRatio(1024, 1024)).toBe('1:1');expect(grok.deriveAspectRatio(1920, 1080)).toBe('16:9');diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 6fd33b90d9..7580ad406a 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -1,3 +1,6 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';+import { randomUUID } from 'node:crypto';+import { imageGenEvents } from '../imageGenEvents.js';/*** Image Gen — Mode-aware dispatcher.*@@ -124,6 +127,24 @@ export async function checkConnection({ mode: modeOverride, modelId: modelIdOver}export async function generateImage(params) {+ const jobId = params?.jobId || randomUUID();+ const permit = maintenance.admit('image', jobId);+ const terminal = payload => {+ if (payload?.generationId !== jobId) return;+ detach();+ queueMicrotask(() => permit.finish());+ };+ const detach = () => { for (const event of ['completed', 'failed', 'canceled']) imageGenEvents.off(event, terminal); };+ for (const event of ['completed', 'failed', 'canceled']) imageGenEvents.on(event, terminal);+ try {+ const result = await permit.run(() => generateAdmittedImage({ ...params, jobId }));+ // External SD-API is awaited; CLI/local providers return a live job id.+ if (!result?.jobId) { detach(); permit.finish(); }+ return result;+ } catch (err) { detach(); permit.finish(); throw err; }+}++async function generateAdmittedImage(params) {const s = await getSettings();const requestedMode = params?.mode;const mode = requestedMode || cfg(s).mode || DEFAULT_MODE;diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex b0f72fb601..cf8fa2d552 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image Gen — Local provider (mflux, diffusers, and platform-specific runners).*@@ -697,8 +698,17 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =await rmGuarded(stepwiseDir, { recursive: true, force: true });throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });}- const releaseHeavyClaim = () => heavyClaim.release()- .catch((err) => console.error(`❌ Image generation claim release [${jobId.slice(0, 8)}]: ${err.message}`));+ const releaseHeavyClaim = () => maintenance.continueSettlement(() => heavyClaim.release())+ .catch((err) => {+ maintenance.markCurrentUnsettled();+ console.error(`❌ Image generation claim release [${jobId.slice(0, 8)}]: ${err.message}`);+ });+ const removeStepwise = () => maintenance.continueSettlement(+ () => rmGuarded(stepwiseDir, { recursive: true, force: true }),+ ).catch((err) => {+ maintenance.markCurrentUnsettled();+ console.error(`❌ Image generation scratch cleanup [${jobId.slice(0, 8)}]: ${err.message}`);+ });let proc;let claimHandedOff = false;try {@@ -725,9 +735,10 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// event — unwind it exactly the way the busy branch above does, or a refusal// strands a `running` entry and its stepwise dir every time.if (!claimHandedOff) {+ if (proc?.pid) maintenance.markCurrentUnsettled();await releaseHeavyClaim();jobs.delete(jobId);- await rmGuarded(stepwiseDir, { recursive: true, force: true }).catch(() => {});+ await removeStepwise();}throw err;}@@ -739,12 +750,16 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// whether we've finalized so the close handler can detect "already// handled" and skip the second emit.let finalized = false;+ let processError;proc.on('error', (err) => {- if (finalized) return;+ processError = err;+ if (finalized || proc.pid) return;finalized = true;job.status = 'error';const reason = `Failed to spawn ${bin}: ${err.message}`;console.error(`❌ Image generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);+ void releaseHeavyClaim();+ void removeStepwise();dispatchTerminalEvent(jobId,() => broadcastSse(job, { type: 'error', error: reason }),@@ -752,8 +767,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =);activeProcess = null;activeJob = null;- void releaseHeavyClaim();- rmGuarded(stepwiseDir, { recursive: true, force: true }).catch(() => {});+closeJobAfterDelay(jobs, jobId);});@@ -938,7 +952,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =activeJob = null;void releaseHeavyClaim();if (watcher) { try { watcher.close(); } catch { /* ignore */ } }- rmGuarded(stepwiseDir, { recursive: true, force: true }).catch(() => {});+ void removeStepwise();// EventEmitter doesn't await async listeners — without this try/catch, a// throw from any of the post-exit work below (rejectDegenerateFrame,// sharp, atomicWrite, autoCleanGeneratedImage) would surface as an@@ -975,9 +989,9 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =);return;}- if (code !== 0) {+ if (code !== 0 || processError) {job.status = 'error';- const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);// Extract a structured user-error if the runner emitted one// (USER_ERROR:gated_repo:black-forest-labs/FLUX.2-klein-9B), and find// the matching `❌ …` prose line that follows it. Fall back to the last@@ -1076,7 +1090,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =.toBuffer().catch((err) => { console.warn(`⚠️ Regen upscale failed for ${filename}: ${err?.message || err}`); return null; });if (resized) {- await atomicWrite(outputPath, resized).catch(() => {});+ await atomicWrite(outputPath, resized).catch(() => maintenance.markCurrentUnsettled());meta.renderWidth = meta.width;meta.renderHeight = meta.height;meta.width = targetW;@@ -1110,7 +1124,7 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =// Render timing is stamped onto `meta` (not spread at the write) so the// sidecar and the `autoCleanGeneratedImage` rewrite below agree on it.Object.assign(meta, renderTimingFields(job.renderStartedAtMs));- await atomicWrite(sidecar, meta).catch(() => {});+ await atomicWrite(sidecar, meta).catch(() => maintenance.markCurrentUnsettled());// Cleaners run BEFORE the SSE complete + completed events so subscribers// see the cleaned bytes. Local FLUX renders never carry C2PA chunks so// cleanC2PA is a no-op on local — denoise is the only mode that doesdiff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.jsindex 16c41dc3b1..b2d5d89b79 100644--- a/server/services/imageTo3d/models.js+++ b/server/services/imageTo3d/models.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Image-to-3D model orchestration (issue #2952) — gallery-image lineage, target* dispatch, guarded local render, persistence, and GLB export.@@ -107,7 +108,7 @@ const usdzDiskPath = (id) => join(recordDir(id), 'model.usdz');*/async function cleanupRenderDir(id) {await rmGuarded(recordDir(id), { recursive: true, force: true })- .catch((err) => console.error(`❌ Image-to-3D cleanup failed for ${id}: ${err.message}`));+ .catch((err) => { maintenance.markCurrentUnsettled(); console.error(`❌ Image-to-3D cleanup failed for ${id}: ${err.message}`); });}/**@@ -177,6 +178,7 @@ async function failGeneration(id, operationId, error) {}),};}, { includeDeleted: true }).catch((persistError) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Image-to-3D model ${id} failure could not be persisted: ${persistError.message}`);return null;});@@ -399,6 +401,12 @@ export async function startGeneration(id, { caps, options } = {}) {* values the subprocess receives — the truthful, reproducible record.*/async function beginRender(record, adapter, sourcePath, caps, requestOptions) {+ const permit = maintenance.admit('image-to-3d', record.id);+ try { return await permit.run(() => beginAdmittedRender(record, adapter, sourcePath, caps, requestOptions, permit)); }+ catch (err) { permit.finish(); throw err; }+}++async function beginAdmittedRender(record, adapter, sourcePath, caps, requestOptions, permit) {const { id } = record;const operationId = randomUUID();const startedAt = new Date().toISOString();@@ -448,7 +456,8 @@ async function beginRender(record, adapter, sourcePath, caps, requestOptions) {if (next?.status === 'generating') noteImageTo3d('start');activeOperations.add(operationId);setImmediate(() => {- void executeRender({ id, operationId, adapter, sourcePath, caps, options });+ void executeRender({ id, operationId, adapter, sourcePath, caps, options }).then(() => permit.finish())+ .catch(err => console.error(`❌ Image-to-3D maintenance settlement pending: ${err.message}`));});return next;}diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 2140c1313a..d7cd8f0982 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -19,6 +19,7 @@ import { join, basename, dirname } from 'path';import { platform } from 'os';import { PATHS, ensureDir, atomicWrite, shortId, copyFileGuarded, writeFileGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';import { v4 as uuidv4 } from '../../lib/uuid.js';import { hfChildEnv } from '../hfToken.js';import { spawnDetached, reapDetached, reattachDetached, isReattachable } from '../../lib/detachedSpawn.js';@@ -404,7 +405,7 @@ const flipDatasetAfterRun = (run, { trained, loraFilename = null }) => {...(trained ? { loraFilename, completedAt: new Date().toISOString() } : {}),},};- }).catch((err) => console.error(`❌ dataset post-run stamp failed: ${err?.message}`));+ });};// When a trained LoRA artifact is deleted (DELETE /runs/:id?deleteLora=true),@@ -451,6 +452,15 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckconst settings = await getSettings();const dir = runDir(runId);let heavyClaim = null;+ const retainOwnership = () => {+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ };+ let claimRelease;+ const releaseClaim = () => claimRelease ||= Promise.resolve().then(() => heavyClaim?.release()).catch(err => {+ retainOwnership();+ console.error(`❌ training [${shortId(jobId)}] claim release failed: ${err.message}`);+ });// Terminal failure BEFORE the child spawns: flip the run record to failed// AND release the dataset's `training` status, then emit the failed event.@@ -458,11 +468,11 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck// stuck `running` (lingering until the next boot reconcile) or the dataset// stuck on its `training` chip.const failBeforeSpawn = async (message) => {- await heavyClaim?.release().catch((err) => console.error(`❌ training [${shortId(jobId)}] claim release failed: ${err.message}`));+ await releaseClaim();await runsDb.updateRun(runId, {status: 'failed', error: message, completedAt: new Date().toISOString(),- }).catch(() => {});- await flipDatasetAfterRun(run, { trained: false });+ }).catch(retainOwnership);+ await flipDatasetAfterRun(run, { trained: false }).catch(retainOwnership);return fail(message);};@@ -853,13 +863,18 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckstallTimer.unref?.();}+ let terminalStarted = false;+ let processError;proc.on('error', (err) => {+ if (terminalStarted) return;+ processError = err;+ // Detached handles can report failed signals while their trainer is live.+ // Preserve its cancel handle and claim until physical close.+ if (proc.pid) return;+ terminalStarted = true;stopStallWatchdog();if (activeProcess === proc) { activeProcess = null; activeJobId = null; }- // Terminal too (no 'close' follows an 'error'), so wake the display here as- // well — no-op unless we actually slept it (proc.pid was set). Without this,- // a pid-bearing process that errors instead of closing would leave the- // display asleep.+ // A no-PID launch failure owns no running trainer.wakeDisplay(settings);// A launch failure after the run was marked `running` — a genuine spawn// error, or (with spawnDetached) the control dir failing to create/clear.@@ -868,10 +883,15 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck// released; `fail()` alone only logs + emits. Async + guarded since this// runs outside the request lifecycle.Promise.resolve(failBeforeSpawn(`trainer spawn failed: ${err.message}`))- .catch((e) => console.error(`❌ training [${shortId(jobId)}] failure cleanup failed: ${e?.message}`));+ .catch((e) => {+ retainOwnership();+ console.error(`❌ training [${shortId(jobId)}] failure cleanup failed: ${e?.message}`);+ });});proc.on('close', (code, signal) => {+ if (terminalStarted) return;+ terminalStarted = true;stopStallWatchdog();if (activeProcess === proc) { activeProcess = null; activeJobId = null; }// Flush the debounced progress (final checkpoint + last sample) BEFORE@@ -880,10 +900,11 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck// escape the event handler (unhandled rejection kills the process on Node ≥15).// The trainer has exited, so release before finalization can enqueue an// automatic checkpoint resume; that successor must acquire a fresh claim.- Promise.resolve(heavyClaim?.release())- .catch((err) => console.error(`❌ training [${shortId(jobId)}] claim release failed: ${err.message}`))+ releaseClaim().then(() => flushProgress())- .then(() => finalizeTraining({ jobId, runId, code, signal, state: getState(), stallKilled }))+ .then(() => processError+ ? failBeforeSpawn(`trainer process failed: ${processError.message}`)+ : finalizeTraining({ jobId, runId, code, signal, state: getState(), stallKilled })).then((resumed) => {// Wake the display now the run is over so the user sees the result —// but NOT when finalize actually enqueued a stall-watchdog auto-resume@@ -894,6 +915,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckif (!resumed) wakeDisplay(settings);}).catch((err) => {+ retainOwnership();// A finalize/flush rejection is still a terminal end with no auto-resume// enqueued, so wake the display here too — otherwise this error path// would leave it asleep (no .then ran). No-op unless we slept it.@@ -992,8 +1014,7 @@ async function finalizeTraining({ jobId, runId, code, signal, state, stallKilledif (canceled) {// Queue's cancelRequested flips the failed event into a clean cancel;// record keeps the checkpoint lineage for a future resume.- await runsDb.updateRun(runId, { status: 'canceled', completedAt: new Date().toISOString(), error: 'Canceled' })- .catch(() => {});+ await runsDb.updateRun(runId, { status: 'canceled', completedAt: new Date().toISOString(), error: 'Canceled' });await flipDatasetAfterRun(run, { trained: false });trainingEvents.emit('failed', { generationId: jobId, error: 'Canceled' });return;@@ -1009,7 +1030,7 @@ async function finalizeTraining({ jobId, runId, code, signal, state, stallKilledawait runsDb.updateRun(runId, {status: 'failed', completedAt: new Date().toISOString(),error: message, errorCode: state.userError?.kind || 'NO_RESULT',- }).catch(() => {});+ });await flipDatasetAfterRun(run, { trained: false });console.error(`❌ training [${shortId(jobId)}] no-result: ${message}`);trainingEvents.emit('failed', { generationId: jobId, error: message });@@ -1023,7 +1044,7 @@ async function finalizeTraining({ jobId, runId, code, signal, state, stallKilledstatus: 'failed', completedAt: new Date().toISOString(), error: message, errorCode: failCode,// Gated-repo deep-link target for the UI banner (HF_AUTH only); null otherwise.errorRepo: failRepo,- }).catch(() => {});+ });await flipDatasetAfterRun(run, { trained: false });console.error(`❌ training [${shortId(jobId)}] ${failCode}: ${message}`);trainingEvents.emit('failed', { generationId: jobId, error: message, code: failCode, repo: failRepo });diff --git a/server/services/loraTraining/lifecycle.maintenance.test.js b/server/services/loraTraining/lifecycle.maintenance.test.jsnew file mode 100644index 0000000000..7fbe2eccf5--- /dev/null+++ b/server/services/loraTraining/lifecycle.maintenance.test.js@@ -0,0 +1,170 @@+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++const fixture = vi.hoisted(() => ({+ admission: null, child: null, run: null, queueJob: null,+ release: vi.fn(), save: vi.fn(), saveDataset: vi.fn(),+}));+vi.mock('../../lib/fileUtils.js', async importOriginal =>+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('training-maintenance-') }));+vi.mock('../../lib/maintenanceAdmission.js', async importOriginal => ({+ ...await importOriginal(),+ maintenance: new Proxy({}, { get: (_target, property) => fixture.admission[property] }),+}));+vi.mock('os', async importOriginal => ({ ...await importOriginal(), platform: () => 'linux' }));+vi.mock('../../lib/childProcess.js', async importOriginal => ({+ ...await importOriginal(), spawn: vi.fn(() => { throw new Error('Unexpected real child launch'); }),+}));+vi.mock('../../lib/detachedSpawn.js', () => ({+ reattachDetached: async () => fixture.child, spawnDetached: vi.fn(), reapDetached: vi.fn(), isReattachable: vi.fn(),+}));+vi.mock('../../lib/heavyJobClaim.js', () => ({+ adoptHeavyLocalJob: async () => ({ ok: true, holder: { pid: fixture.child.pid },+ handoffTo: async () => {}, release: () => fixture.release() }),+ claimHeavyLocalJob: vi.fn(),+}));+vi.mock('./db.js', () => ({+ getRun: async () => fixture.run,+ updateRun: (...args) => fixture.save(...args), getRunRequired: vi.fn(), listRuns: vi.fn(), deleteRun: vi.fn(),+}));+vi.mock('../settings.js', () => ({ getSettings: async () => ({ loraTraining: { stallWatchdog: false } }) }));+vi.mock('../loraDatasets.js', () => ({ updateDataset: (...args) => fixture.saveDataset(...args) }));+vi.mock('../mediaJobQueue/index.js', () => ({+ assertMediaQueueRoom: vi.fn(), enqueueJob: vi.fn(), getJob: () => fixture.queueJob, mediaJobEvents: new EventEmitter(),+}));+vi.mock('./displayPower.js', () => ({ sleepDisplayForTraining: vi.fn(), wakeDisplay: vi.fn() }));++const { runTraining, cancel, trainingEvents } = await import('./index.js');+const { createMaintenanceAdmission } = await import('../../lib/maintenanceAdmission.js');+const { PATHS } = await import('../../lib/fileUtils.js');+let fixtureNumber = 0;+beforeEach(() => {+ fixture.admission = createMaintenanceAdmission(join(PATHS.data, 'admission-fixtures', String(fixtureNumber++)));+ fixture.child = new EventEmitter();+ Object.assign(fixture.child, { pid: 101, exitCode: null, signalCode: null,+ stdout: new EventEmitter(), stderr: new EventEmitter(), kill: vi.fn() });+ fixture.run = { id: 'example-run', jobId: 'example-job', datasetId: 'example-dataset', params: { steps: 10 }, runtime: 'mflux' };+ fixture.queueJob = {};+ fixture.release.mockReset().mockResolvedValue();+ fixture.save.mockReset().mockResolvedValue();+ fixture.saveDataset.mockReset().mockResolvedValue();+});+afterEach(() => { vi.useRealTimers(); trainingEvents.removeAllListeners(); });+afterAll(cleanupTempDataRoots);++describe('training physical settlement under maintenance', () => {+ it.each([+ { terminal: 'canceled', code: 1, canceled: true, persistence: 'run' },+ { terminal: 'no result', code: 0, canceled: false, persistence: 'run' },+ { terminal: 'nonzero exit', code: 1, canceled: false, persistence: 'run' },+ { terminal: 'dataset reset', code: 0, canceled: false, persistence: 'dataset' },+ ])('retains a blocker when $terminal persistence fails after physical close', async ({ code, canceled, persistence }) => {+ fixture.queueJob.cancelRequested = canceled;+ const save = persistence === 'run' ? fixture.save : fixture.saveDataset;+ save.mockRejectedValueOnce(new Error('Terminal storage unavailable'));+ const permit = fixture.admission.admit('media', 'example-job');+ let settlement;+ const failed = vi.fn(() => { settlement = permit.finish(); });+ trainingEvents.on('failed', failed);+ await permit.run(() => runTraining({ jobId: 'example-job', runId: 'example-run', reattach: true }));+ fixture.admission.begin({ reason: 'Drain trainer', owner: 'Operator' });+ fixture.child.exitCode = code;+ fixture.child.emit('close', code, null);+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ await settlement;+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ error: 'finalize failed: Terminal storage unavailable' }));+ expect(fixture.admission.status()).toMatchObject({+ state: 'draining', blockers: [expect.objectContaining({ resource: 'example-job', unsettled: true })],+ });+ if (persistence === 'run') expect(fixture.saveDataset).not.toHaveBeenCalled();+ else expect(fixture.save).toHaveBeenCalledWith('example-run', expect.objectContaining({ status: 'failed' }));+ expect(cancel('example-job')).toBe(false);+ });++ it('waits for the dataset terminal write before releasing maintenance', async () => {+ const save = Promise.withResolvers();+ fixture.saveDataset.mockReturnValueOnce(save.promise);+ const permit = fixture.admission.admit('media', 'example-job');+ let settlement;+ const failed = vi.fn(() => { settlement = permit.finish(); });+ trainingEvents.on('failed', failed);+ await permit.run(() => runTraining({ jobId: 'example-job', runId: 'example-run', reattach: true }));+ fixture.admission.begin({ reason: 'Drain trainer', owner: 'Operator' });+ fixture.child.exitCode = 0;+ fixture.child.emit('close', 0, null);+ try {+ await vi.waitFor(() => expect(fixture.saveDataset).toHaveBeenCalledTimes(1));+ expect(failed).not.toHaveBeenCalled();+ expect(fixture.admission.status().state).toBe('draining');+ } finally {+ save.resolve();+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ await settlement;+ }+ expect(fixture.admission.status().state).toBe('ready');+ });++ it('retains a blocker and emits failure when a pre-spawn dataset reset cannot persist', async () => {+ fixture.child = null;+ fixture.saveDataset.mockRejectedValueOnce(new Error('Dataset storage unavailable'));+ const permit = fixture.admission.admit('media', 'example-job');+ const failed = vi.fn();+ trainingEvents.on('failed', failed);+ fixture.admission.begin({ reason: 'Drain trainer', owner: 'Operator' });+ await permit.run(() => runTraining({ jobId: 'example-job', runId: 'example-run', reattach: true }));+ await permit.finish();+ expect(failed).toHaveBeenCalledTimes(1);+ expect(fixture.admission.status()).toMatchObject({+ state: 'draining', blockers: [expect.objectContaining({ resource: 'example-job', unsettled: true })],+ });+ });++ it.each([false, true])('waits for physical close and claim cleanup after a live error (cleanup fails: %s)', async cleanupFails => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const cleanup = Promise.withResolvers();+ fixture.release.mockImplementation(async () => {+ await cleanup.promise;+ if (cleanupFails) throw new Error('Claim storage unavailable');+ });+ const permit = fixture.admission.admit('media', 'example-job');+ let settlement;+ const failed = vi.fn(() => { settlement = permit.finish(); });+ trainingEvents.on('failed', failed);+ const close = () => {+ fixture.child.exitCode = 1;+ fixture.child.emit('close', 1, null);+ };+ try {+ await permit.run(() => runTraining({ jobId: 'example-job', runId: 'example-run', reattach: true }));+ fixture.admission.begin({ reason: 'Drain trainer', owner: 'Operator' });+ fixture.child.emit('error', new Error('Signal transport failed'));+ expect(failed).not.toHaveBeenCalled();+ expect(fixture.release).not.toHaveBeenCalled();+ expect(cancel('example-job')).toBe(true);+ await vi.advanceTimersByTimeAsync(8000);+ expect(fixture.child.kill).toHaveBeenCalledWith('SIGKILL');+ close();+ await vi.waitFor(() => expect(fixture.release).toHaveBeenCalledTimes(1));+ expect(failed).not.toHaveBeenCalled();+ expect(fixture.admission.status().state).toBe('draining');+ cleanup.resolve();+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ await settlement;+ expect(fixture.save).toHaveBeenCalledWith('example-run', expect.objectContaining({+ status: 'failed', error: 'trainer process failed: Signal transport failed',+ }));+ expect(fixture.admission.status().state).toBe(cleanupFails ? 'draining' : 'ready');+ if (cleanupFails) expect(fixture.admission.status().blockers[0].unsettled).toBe(true);+ close();+ expect(failed).toHaveBeenCalledTimes(1);+ expect(cancel('example-job')).toBe(false);+ } finally {+ cleanup.resolve();+ close();+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ await permit.finish();+ }+ });+});diff --git a/server/services/maintenanceControl.js b/server/services/maintenanceControl.jsnew file mode 100644index 0000000000..8e69a2e37d--- /dev/null+++ b/server/services/maintenanceControl.js@@ -0,0 +1,32 @@+import { watch, mkdirSync } from 'node:fs';+import { maintenance } from '../lib/maintenanceAdmission.js';+import { assertNotRealDataWrite } from '../lib/testDataIsolation.js';++let watcher;+let timer;+let boundIo;+export function bindMaintenanceIo(io) {+ boundIo = io;+ if (watcher) return;+ assertNotRealDataWrite(maintenance.directory, 'maintenance notifications');+ mkdirSync(maintenance.directory, { recursive: true, mode: 0o700 });+ // Cross-process runner settlements also invalidate the UI. Payload contains+ // no operation capability or private resource identity; GET remains auth gated.+ watcher = watch(maintenance.directory, () => {+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => { timer = null; boundIo?.emit('maintenance:changed'); }, 100);+ timer.unref?.();+ });+ watcher.unref?.();+}++export async function resumeMaintenance(input) {+ const status = maintenance.resume(input);+ // Re-evaluate saved policies. These functions retain their daemon, pause,+ // domain, budget and quota gates; do not call CoS.resume or mind.resume.+ const [{ dequeueNextTask }, { recheckPersistentMindSchedule }] = await Promise.all([+ import('./cos.js'), import('./persistentMindSupervisor.js'),+ ]);+ await Promise.allSettled([dequeueNextTask(), recheckPersistentMindSchedule()]);+ return status;+}diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex cdb19d9d95..9b7984a553 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Media Job Queue — lane-aware FIFO for media generation jobs.*@@ -626,9 +627,22 @@ export async function initMediaJobQueue() {// re-attached (#1332), and only a genuinely-dead one is reaped+failed in// initLoraTraining.) This runs before the worker starts, so every dir// present is an orphan from the prior process.- const videoReap = await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));+ const videoReap = maintenance.held() ? { reaped: 0 }+ : await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));if (videoReap.reaped) console.log(`🧹 reaped ${videoReap.reaped} surviving render(s) on boot`);for (const j of persistedJobs) {+ if (j.status === 'running' && maintenance.held()) {+ maintenance.recoverOwned('media', j.id);+ if (j.kind === 'training' && j.params?.runId && await jobHasSurvivingTrainer(j.params.runId)) {+ recoveringJobs.add(j.id);+ reattachJobs.push({ ...j, status: 'queued', params: { ...j.params, reattach: true } });+ } else {+ // Preserve uncertain work and staged inputs; no paid replay or orphan+ // kill is safe merely because the observer process restarted.+ archive.push({ ...j, params: restoredParams(j) });+ }+ continue;+ }// Explicit Video Start grants one process lifetime. Restored jobs wait for// project reconciliation; replaying an unknown paid submit could charge twice.if (j.params?.videoProduction && ['queued', 'running'].includes(j.status)) {@@ -643,6 +657,7 @@ export async function initMediaJobQueue() {// the remote adapter replay the submission, recover the provider job,// and continue polling (or deliver a persisted cancellation intent).if (isRemoteMediaJob(j)) {+ maintenance.recoverOwned('media', j.id);const marker = j.params?.remoteMedia;queue.push({...j,@@ -778,6 +793,10 @@ function startLaneJob(job, { lane }) {console.log(`⚠️ media-job [${job.id.slice(0, 8)}] startLaneJob: already removed from queue, skipping`);return false;}+ const permit = recoveringJobs.has(job.id)+ ? maintenance.recoverOwned('media', job.id)+ : maintenance.tryAdmit('media', job.id, { reconnect: isRemoteMediaJob(job) && job.params?.remoteMedia?.reconcile === true });+ if (!permit) return false;queue.splice(idx, 1);job.status = 'running';job.startedAt = new Date().toISOString();@@ -796,8 +815,9 @@ function startLaneJob(job, { lane }) {? (job.params?.mode || 'cloud'): lane === 'remote' ? `remote ${job.kind}` : job.kind;let finalized = false;+ let archiveWrite;function finalizeLane() {- if (finalized) return;+ if (finalized) return archiveWrite;finalized = true;// Count once, after every terminal path (including pre-dispatch throws),// and before releasing the lane. Boot reconciliation never comes here.@@ -817,11 +837,13 @@ function startLaneJob(job, { lane }) {// the UI's recent-reel cap (recentLimit) handles in-memory display.archive.push(job);recomputeQueuePositions();- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} done failed: ${e.message}`));+ archiveWrite = persist();+ archiveWrite.catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} done failed: ${e.message}`));+ return archiveWrite;}let markRunning;trackOperation(dispatchOperations, new Promise((resolve) => { markRunning = resolve; }));- (async () => {+ permit.run(async () => {try {await persist();// Cancellation can win while the running snapshot is blocked.@@ -853,8 +875,12 @@ function startLaneJob(job, { lane }) {await trackTerminalOperation(persistTerminalTransition(job));}}- finalizeLane();- })().catch((error) => console.error(`❌ media-job [${job.id.slice(0, 8)}] storage settlement pending: ${error.message}`));+ await finalizeLane();+ const settled = await flushMediaJobQueue();+ recoveringJobs.delete(job.id);+ if (settled.ok) permit.finish();+ else permit.markUnsettled();+ }).catch((error) => console.error(`❌ media-job [${job.id.slice(0, 8)}] storage settlement pending: ${error.message}`));return true;}@@ -899,9 +925,14 @@ async function prepareQueuedVideos(jobs = queue.filter((job) => !job.admitting))}}+// IDs proven by the boot probe to have an existing trainer; request params cannot grant this.+const recoveringJobs = new Set();+async function drainLoop() {while (!dispatchQuiesced) {- const candidates = queue.filter((job) => !job.admitting);+ const held = maintenance.held();+ const candidates = queue.filter((job) => !job.admitting && (!held || recoveringJobs.has(job.id)));+ if (held && !candidates.length) { await sleep(150); continue; }await prepareQueuedVideos(candidates);// Shutdown may have begun while cohorts resolved; exit without promoting.if (dispatchQuiesced) break;@@ -971,7 +1002,9 @@ export function runJobNow(jobId) {if (dispatchQuiesced) {return { ok: false, code: MEDIA_QUEUE_SHUTTING_DOWN, error: 'The server is shutting down; the job stays queued and resumes after restart' };}- startLaneJob(job, { lane: 'cloud' });+ if (!startLaneJob(job, { lane: 'cloud' })) {+ return { ok: false, code: 'MAINTENANCE_HELD', error: 'Maintenance is holding new renders; this job stays queued' };+ }return { ok: true, status: 'running' };}@@ -1125,6 +1158,9 @@ async function runJobLifecycle(job, markDispatched) {const sseEntry = ensureSseEntry(job.id);let resolveTerminalState;const terminalState = new Promise((resolve) => { resolveTerminalState = resolve; });+ let resolveProviderSettlement;+ const providerSettlement = new Promise(resolve => { resolveProviderSettlement = resolve; });+ let watchdogNeedsProviderSettlement = false;let progressPersistDirty = false;let progressPersistTimer = null;let progressPersisting = null;@@ -1308,7 +1344,14 @@ async function runJobLifecycle(job, markDispatched) {: job.kind === 'training' ? trainingEvents: job.kind === 'audio' || job.kind === 'supercollider' ? audioGenEvents: imageGenEvents;- const dispatcher = makeGenDispatcher(emitter, job, handlers);+ // A watchdog outcome records why the job failed; it does not prove that+ // cancellation has reached physical exit and provider cleanup. Only a real+ // provider terminal event can release that additional wait.+ const dispatcher = makeGenDispatcher(emitter, job, {+ ...handlers,+ completed: payload => { resolveProviderSettlement(); handlers.completed(payload); },+ failed: payload => { resolveProviderSettlement(); handlers.failed(payload); },+ });dispatcher.attach();// Thread #2: per-job idle watchdog — fires when the gen has been silent@@ -1371,7 +1414,8 @@ async function runJobLifecycle(job, markDispatched) {// draining to disk with job.status still 'running') during the import.if (!canRequestCancellation(job)) return;console.log(`⏱️ media-job [${job.id.slice(0, 8)}] watchdog fired after ${idleFor}ms idle (limit ${idleTimeoutMs}ms) — marking failed`);- if (mod?.cancel) mod.cancel(job.id);+ watchdogNeedsProviderSettlement ||= job.providerInvoked === true;+ if (mod?.cancel) await mod.cancel(job.id);handlers.failed({ error: `watchdog timeout: no runner output for ${Math.round(idleFor / 1000)}s (limit ${Math.round(idleTimeoutMs / 1000)}s)` });} catch (err) {// Don't take down the server over a watchdog tick that couldn't@@ -1421,6 +1465,9 @@ async function runJobLifecycle(job, markDispatched) {if (job.cancelRequested && !isRemoteMediaJob(job)) {throw new Error('Canceled before provider dispatch');}+ // A watchdog can win during the awaited policy/module preparation above.+ // Its terminal outcome must prevent that delayed provider from starting.+ if (!canRequestCancellation(job)) throw new Error('Provider dispatch stopped after the job reached a terminal outcome');// Transient, like terminating: no await between this flag and invocation.job.providerInvoked = true;const request = { ...safeParams, jobId: job.id };@@ -1435,6 +1482,9 @@ async function runJobLifecycle(job, markDispatched) {markDispatched();await kickoff;} catch (err) {+ // Policy/auth refusal still stands, but it cannot prove a previously+ // admitted peer render finished before this recovery attempt.+ if (isRemoteMediaJob(job) && job.params?.remoteMedia?.reconcile === true) maintenance.markCurrentUnsettled();// generateVideo / generateChainedVideo / generateImage threw before// reaching their proc.on cleanup hooks (e.g. PYTHON not configured,// validation fail). Clean up multipart upload temp files the route@@ -1458,6 +1508,7 @@ async function runJobLifecycle(job, markDispatched) {// the explicit terminal signal rather than polling every 100ms; this makes// lane release immediate and gives tests a deterministic lifecycle to drain.await terminalState;+ if (watchdogNeedsProviderSettlement) await providerSettlement;dispatcher.detach();}diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 69de78d9e0..092f675b6f 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -216,6 +216,12 @@ const remoteVideoMediaParams = () => ({beforeEach(async () => {tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));+ // Queue fixtures deliberately abandon active work when simulating a crash.+ // Give each test its own real journal, retaining it across importFresh()+ // within that test so restart recovery still exercises durable ownership.+ const admissionModule = await vi.importActual('../../lib/maintenanceAdmission.js');+ const admission = admissionModule.createMaintenanceAdmission(tempDataDir);+ vi.doMock('../../lib/maintenanceAdmission.js', () => ({ ...admissionModule, maintenance: admission }));Object.values(stubs).forEach((fn) => fn.mockReset());const { getDefaultVideoModelId } = await import('../../lib/mediaModels.js');getDefaultVideoModelId.mockImplementation(() => 'example-mlx');@@ -286,6 +292,72 @@ describe('mediaJobQueue', () => {mediaJobQueue.mediaJobEvents.off('changed', changed);});+ it('maintenance preserves queued work and refuses Run now while active work finishes', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const first = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'first' } });+ await waitFor(() => stubs.generateVideo.mock.calls.length === 1);+ const { hold } = maintenance.begin({ reason: 'Work', owner: 'Operator' });+ try {+ const second = await mediaJobQueue.enqueueJob({ kind: 'image', params: { mode: 'codex', prompt: 'next' } });+ expect(mediaJobQueue.runJobNow(second.jobId)).toMatchObject({ ok: false, code: 'MAINTENANCE_HELD' });+ expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');+ expect(maintenance.status().state).toBe('draining');+ videoGenEvents.emit('completed', { generationId: first.jobId, filename: 'example.mp4' });+ await waitFor(() => maintenance.status().state === 'ready');+ expect(stubs.generateImageCodex).not.toHaveBeenCalled();+ expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');+ } finally { maintenance.resume({ id: hold.id, revision: hold.revision }); }+ });++ it.each(['local', 'remote'])('keeps maintenance draining through terminal and archive writes for a %s render', async (route) => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const generate = route === 'remote' ? stubs.generateVideoRemote : stubs.generateVideo;+ generate.mockResolvedValueOnce({});+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: {+ prompt: 'Synthetic settlement', ...(route === 'remote' ? { remoteMedia: remoteVideoMediaParams() } : {}),+ } });+ await waitFor(() => generate.mock.calls.length === 1);+ await flush();+ const { hold } = maintenance.begin({ reason: 'Verify durable settlement', owner: 'Operator' });+ const realWrite = atomicWriteSpy.getMockImplementation();+ let releaseTerminal;+ let releaseArchive;+ const terminalWrite = new Promise(resolve => { releaseTerminal = resolve; });+ const archiveWrite = new Promise(resolve => { releaseArchive = resolve; });+ let completedWrites = 0;+ atomicWriteSpy.mockImplementation(async (path, data) => {+ if (data?.jobs?.some(job => job.id === jobId && job.status === 'completed')) {+ completedWrites += 1;+ if (completedWrites === 1) await terminalWrite;+ if (completedWrites === 2) await archiveWrite;+ }+ return realWrite(path, data);+ });+ try {+ videoGenEvents.emit('completed', { generationId: jobId, filename: 'example.mp4' });+ await waitFor(() => completedWrites === 1);+ expect(maintenance.status()).toMatchObject({ state: 'draining', blockers: [expect.objectContaining({ kind: 'media', resource: jobId })] });+ expect(mediaJobQueue.getJob(jobId).status).toBe('running');+ expect(persistedJobs().find(job => job.id === jobId).status).toBe('running');++ releaseTerminal();+ await waitFor(() => completedWrites === 2);+ expect(mediaJobQueue.getJob(jobId).status).toBe('completed');+ expect(persistedJobs().find(job => job.id === jobId).status).toBe('completed');+ expect(maintenance.status().state).toBe('draining');++ releaseArchive();+ await waitFor(() => maintenance.status().state === 'ready');+ expect(generate).toHaveBeenCalledTimes(1);+ } finally {+ releaseTerminal();+ releaseArchive();+ atomicWriteSpy.mockImplementation(realWrite);+ await flush();+ maintenance.resume({ id: hold.id, revision: hold.revision });+ }+ });+it('enqueueJob returns jobId + queued status + position', async () => {// Block the worker so the second enqueue lands behind the first in the// pipeline rather than entering an empty queue after the first ran.@@ -1160,25 +1232,78 @@ describe('mediaJobQueue', () => {await waitFor(() => mediaJobQueue.getJob(job.jobId).status === 'completed');});- it('watchdog fires and marks the job failed when gen never emits a terminal event', async () => {- // Use a very short watchdog for this test by overriding the env var before- // the module is loaded. Re-import the module with MEDIA_JOB_WATCHDOG_VIDEO_MS=50.+ it('keeps maintenance and the lane owned after watchdog cancellation until provider teardown settles', async () => {+ vi.useFakeTimers();process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS = '50';await importFresh();- // generateVideo hangs forever — never emits completed/failed.- stubs.generateVideo.mockImplementation(() => new Promise(() => {}));-+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ // A real local provider returns its job id after spawn, before child exit.+ stubs.generateVideo.mockResolvedValue({ jobId: 'provider-started' });const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'hang' } });- await waitFor(() => stubs.generateVideo.mock.calls.length === 1);-- // The watchdog should fire within 50 ms and fail the job.- await waitFor(() => mediaJobQueue.getJob(job.jobId)?.status === 'failed', { timeoutMs: 2000 });-- const failed = mediaJobQueue.getJob(job.jobId);- expect(failed.status).toBe('failed');- expect(failed.error).toMatch(/watchdog timeout/);+ let hold;+ try {+ await vi.waitFor(() => expect(stubs.generateVideo).toHaveBeenCalledTimes(1), { interval: 1 });+ ({ hold } = maintenance.begin({ reason: 'Wait for physical teardown', owner: 'Operator' }));+ await vi.advanceTimersByTimeAsync(100);+ await flush();+ await vi.waitFor(() => expect(stubs.cancelVideo).toHaveBeenCalledTimes(1));+ await flush();+ expect(mediaJobQueue.getJob(job.jobId)).toMatchObject({ status: 'failed', error: expect.stringMatching(/watchdog timeout/) });+ expect(maintenance.status()).toMatchObject({ state: 'draining', blockers: [expect.objectContaining({ resource: job.jobId })] });+ expect(mediaJobQueue.getQueueCapacity().lanes.gpu.running).toBe(1);++ // A cancel acknowledgment/time passing is no proof of exit or cleanup.+ await vi.advanceTimersByTimeAsync(8000);+ expect(maintenance.status().state).toBe('draining');+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Child closed and cleanup finished' });+ await flush();+ await vi.waitFor(() => expect(maintenance.status().state).toBe('ready'));+ expect(mediaJobQueue.getQueueCapacity().lanes.gpu.running).toBe(0);+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);+ } finally {+ videoGenEvents.emit('failed', { generationId: job.jobId, error: 'Fixture teardown' });+ await flush();+ if (hold) maintenance.resume({ id: hold.id, revision: hold.revision });+ delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ vi.clearAllTimers();+ vi.useRealTimers();+ }+ });- delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ it('does not start a provider after its watchdog wins during asynchronous dispatch checks', async () => {+ vi.useFakeTimers();+ process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS = '50';+ await importFresh();+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const { assertVideoAttemptDispatch } = await import('../creativeDirector/videoExecution.js');+ const dispatchCheck = Promise.withResolvers();+ let checkEntered = false;+ assertVideoAttemptDispatch.mockImplementationOnce(() => {+ checkEntered = true;+ return dispatchCheck.promise;+ });+ const job = await mediaJobQueue.enqueueJob({ kind: 'video', params: {+ prompt: 'delayed dispatch', videoProduction: { projectId: 'example', attemptId: 'example-attempt' },+ } });+ let hold;+ try {+ await vi.waitFor(() => expect(checkEntered).toBe(true), { interval: 1 });+ ({ hold } = maintenance.begin({ reason: 'Drain pending preparation', owner: 'Operator' }));+ await vi.advanceTimersByTimeAsync(100);+ await vi.waitFor(() => expect(mediaJobQueue.getJob(job.jobId).status).toBe('failed'));+ expect(maintenance.status().state).toBe('draining');+ dispatchCheck.resolve();+ await vi.waitFor(() => expect(maintenance.status().state).toBe('ready'));+ expect(stubs.generateVideo).not.toHaveBeenCalled();+ expect(mediaJobQueue.getQueueCapacity().lanes.gpu.running).toBe(0);+ } finally {+ dispatchCheck.resolve();+ await flush();+ if (hold) maintenance.resume({ id: hold.id, revision: hold.revision });+ delete process.env.MEDIA_JOB_WATCHDOG_VIDEO_MS;+ vi.clearAllTimers();+ vi.useRealTimers();+ }});it('terminal handlers are idempotent: watchdog then gen emit causes only one mediaJobEvents.failed', async () => {@@ -1331,6 +1456,25 @@ describe('mediaJobQueue', () => {});describe('Audio kind (#1928)', () => {+ it('holds new peer dispatch while an admitted remote render settles locally', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ let reconcileRemote;+ stubs.generateAudioRemote.mockImplementationOnce(() => new Promise(resolve => { reconcileRemote = resolve; }));+ const active = await mediaJobQueue.enqueueJob({ kind: 'audio', params: { remoteMedia: remoteMediaParams() } });+ await waitFor(() => stubs.generateAudioRemote.mock.calls.length === 1);+ const { hold } = maintenance.begin({ reason: 'Peer drain', owner: 'Operator' });+ try {+ const queued = await mediaJobQueue.enqueueJob({ kind: 'audio', params: { remoteMedia: remoteMediaParams() } });+ audioGenEvents.emit('completed', { generationId: active.jobId, filename: `${active.jobId}.wav` });+ await waitFor(() => mediaJobQueue.getJob(active.jobId)?.status === 'completed');+ expect(maintenance.status().state).toBe('draining');+ expect(stubs.generateAudioRemote).toHaveBeenCalledTimes(1);+ reconcileRemote();+ await waitFor(() => !maintenance.status().blockers.some(blocker => blocker.resource === active.jobId));+ expect(mediaJobQueue.getJob(queued.jobId).status).toBe('queued');+ } finally { maintenance.resume({ id: hold.id, revision: hold.revision }); }+ });+it('dispatches an audio job to audioGen/local.js#generateAudio and completes', async () => {const job = await mediaJobQueue.enqueueJob({kind: 'audio',@@ -2932,24 +3076,33 @@ describe('durable execution and terminal settlement', () => {});it('withholds completion and its result until storage recovers without generating again', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-cuda' } });await vi.advanceTimersByTimeAsync(200);await flush();const completed = vi.fn();mediaJobQueue.mediaJobEvents.on('completed', completed);const realWrite = atomicWriteSpy.getMockImplementation();- atomicWriteSpy.mockRejectedValue(new Error('disk full'));- videoGenEvents.emit('completed', { generationId: jobId, output: 'example.mp4' });- await flush();- expect(completed).not.toHaveBeenCalled();- expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'running' });- expect(mediaJobQueue.getJob(jobId).result).toBeUndefined();- expect(persistedJobs().find((j) => j.id === jobId).status).toBe('running');- atomicWriteSpy.mockImplementation(realWrite);- await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });- expect(completed).toHaveBeenCalledTimes(1);- expect(stubs.generateVideo).toHaveBeenCalledTimes(1);- expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'completed', result: { output: 'example.mp4' } });+ const { hold } = maintenance.begin({ reason: 'Storage recovery', owner: 'Operator' });+ try {+ atomicWriteSpy.mockRejectedValue(new Error('disk full'));+ videoGenEvents.emit('completed', { generationId: jobId, output: 'example.mp4' });+ await flush();+ expect(completed).not.toHaveBeenCalled();+ expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'running' });+ expect(mediaJobQueue.getJob(jobId).result).toBeUndefined();+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('running');+ expect(maintenance.status()).toMatchObject({ state: 'draining', blockers: [expect.objectContaining({ resource: jobId })] });+ atomicWriteSpy.mockImplementation(realWrite);+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });+ expect(completed).toHaveBeenCalledTimes(1);+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);+ expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'completed', result: { output: 'example.mp4' } });+ await vi.waitFor(() => expect(maintenance.status().state).toBe('ready'));+ } finally {+ atomicWriteSpy.mockImplementation(realWrite);+ maintenance.resume({ id: hold.id, revision: hold.revision });+ }vi.clearAllTimers();mediaJobQueue.__resetForTests();await importFresh();diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex eca29c7ba7..cd63964bf1 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';import { assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';import { assertProductionApproval, productionReviewBasis } from './productionReview.js';import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';@@ -713,6 +714,7 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =handOff();const priorStatus = project.status && project.status !== 'rendering' ? project.status : 'ready';await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename, renderError: null }).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→rendering write failed: ${err.message}`);});console.log(`🎬 Rendering ${renderer.label} music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} frames=${Math.round(plan.durationSec * plan.fps)} footage=off`);@@ -720,11 +722,13 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =const finish = async (patch) => {projectRenders.delete(projectId);await updateProject(projectId, settledRender(patch.status, { renderError: patch.status === 'failed' ? job.lastError?.slice(0, 2000) || 'Render failed' : null, ...patch.extra })).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);});emitRenderSettled(projectId, job);if (options.productionRunId) musicVideoEvents.emit('document-render', { projectId, runId: options.productionRunId, attemptId: options.productionRenderAttemptId, jobId, status: patch.status === 'complete' ? 'completed' : 'failed', error: job.lastError || null });closeJobAfterDelay(jobs, jobId);+ options.maintenancePermit?.finish();};Promise.resolve().then(async () => {await assertCurrentRenderApproval(projectId, project, options);@@ -788,6 +792,12 @@ async function assertCurrentRenderApproval(projectId, preparedProject, options)}export async function renderMusicVideo(projectId, options = {}) {+ const permit = maintenance.admit('music-video', projectId, { continuation: true, parentKinds: ['media'] });+ try { return await permit.run(() => renderAdmittedMusicVideo(projectId, options, permit)); }+ catch (err) { permit.finish(); throw err; }+}++async function renderAdmittedMusicVideo(projectId, options, permit) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });assertProductionApproval(project);@@ -809,7 +819,7 @@ export async function renderMusicVideo(projectId, options = {}) {try {const seeked = seekedRendererFor(project);if (seeked) {- return await renderSeekedMode(projectId, project, () => { handedOff = true; }, seeked, options);+ return await renderSeekedMode(projectId, project, () => { handedOff = true; }, seeked, { ...options, maintenancePermit: permit });}const { ffmpeg, audioPath, composed, clips, audioDurationSec, soundBed } = await planMusicVideoRender(project);await ensureDir(PATHS.videos);@@ -844,12 +854,14 @@ export async function renderMusicVideo(projectId, options = {}) {// it alone, and record the output file so OUR boot recovery can delete the// partial a restart mid-encode leaves behind.await updateProject(projectId, { status: 'rendering', renderingOn, renderPartialFilename: filename, renderError: null }).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→rendering write failed: ${err.message}`);});console.log(`🎬 Rendering music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} clips=${clips.length} cues=${cues.length} duration=${totalDuration.toFixed(2)}s`);const releaseScratch = () => (composition ? removeCompositionScratch(jobId).catch((err) => {+ maintenance.markCurrentUnsettled();console.warn(`⚠️ Music-video render [${jobId.slice(0, 8)}] could not remove its overlay scratch: ${err.message}`);}) : null);@@ -905,11 +917,13 @@ export async function renderMusicVideo(projectId, options = {}) {broadcastSse(job, { type: 'error', error: reason });projectRenders.delete(projectId);await updateProject(projectId, settledRender('failed')).catch((updateErr) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);});emitRenderSettled(projectId, job);await releaseScratch();closeJobAfterDelay(jobs, jobId);+ permit.finish();},onClose: async (code, signal) => {job.process = null;@@ -928,11 +942,13 @@ export async function renderMusicVideo(projectId, options = {}) {// 'complete' project stays 'complete'); a real failure marks it 'failed'.const targetStatus = canceled ? priorStatus : 'failed';await updateProject(projectId, settledRender(targetStatus)).catch((updateErr) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);});emitRenderSettled(projectId, job);await releaseScratch();closeJobAfterDelay(jobs, jobId);+ permit.finish();return;}// Success finalization runs in an event callback (no request to bubble@@ -966,17 +982,20 @@ export async function renderMusicVideo(projectId, options = {}) {};await appendToVideoHistory(meta);await updateProject(projectId, settledRender('complete', { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) })).catch((updateErr) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);});emitRenderSettled(projectId, job);console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });} catch (err) {+ permit.markUnsettled();job.status = 'error';job.lastError = `Finalize failed: ${err.message}`;console.error(`❌ Music-video render finalize failed [${jobId.slice(0, 8)}]: ${err.message}`);broadcastSse(job, { type: 'error', error: 'Render finalize failed' });await updateProject(projectId, settledRender('failed')).catch((updateErr) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→failed write failed: ${updateErr.message}`);});emitRenderSettled(projectId, job);@@ -984,6 +1003,7 @@ export async function renderMusicVideo(projectId, options = {}) {projectRenders.delete(projectId);await releaseScratch();closeJobAfterDelay(jobs, jobId);+ permit.finish();}},});@@ -1021,18 +1041,20 @@ export async function renderMusicVideo(projectId, options = {}) {projectRenders.delete(projectId);const targetStatus = canceled ? priorStatus : 'failed';await updateProject(projectId, settledRender(targetStatus)).catch((updateErr) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${targetStatus} write failed: ${updateErr.message}`);});emitRenderSettled(projectId, job);await releaseScratch();closeJobAfterDelay(jobs, jobId);+ permit.finish();});return { jobId };} finally {// Prep threw (or we never handed off to the job lifecycle) — release the// reserved slot so a stale PENDING can't 409 every future render.- if (!handedOff) projectRenders.delete(projectId);+ if (!handedOff) { projectRenders.delete(projectId); permit.finish(); }}}diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex d141c8761a..2903cea1fe 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Persistent CoS mind supervisor.*@@ -187,6 +188,7 @@ function armWatchdog() {}async function scheduleNextWake() {+ if (maintenance.held()) return;const root = await loadState();const state = normalizePersistentMindState(root.persistentMind);cancel(PERSISTENT_MIND_WAKE_EVENT_ID);@@ -678,6 +680,14 @@ function resolveTurnProfile({ selfThinkingRequest, thinkingPresetId, thinkingSel}async function runOnePersistentMindTurn() {+ const permit = maintenance.tryAdmit('mind-turn', 'persistent-mind');+ if (!permit) return;+ try { return await permit.run(runAdmittedPersistentMindTurn); }+ catch (err) { permit.markUnsettled(); throw err; }+ finally { await permit.finish(); }+}++async function runAdmittedPersistentMindTurn() {if (supervisorStopping || !isDaemonRunning()) return;if (!turnAdapter) {return deferUnclaimedWake({@@ -1166,6 +1176,7 @@ export async function setPersistentMindEnabled(enabled) {}export async function startPersistentMind() {+ maintenance.assertOpen();const result = await mutateMindState((mind) => {if (mind.started) return { mind, value: { success: true, alreadyStarted: true } };return {@@ -1191,6 +1202,7 @@ export async function startPersistentMind() {/** A deliberate user wake retries now through the normal admission gates. */export async function wakePersistentMind() {+ maintenance.assertOpen();const result = await mutateMindState((mind) => {// A running turn already satisfies this request; never interrupt or queue// an extra billable turn for repeated clicks while it is thinking.@@ -1234,6 +1246,7 @@ export async function pausePersistentMind(reason = 'Paused by user') {}export async function resumePersistentMind() {+ maintenance.assertOpen();const result = await mutateMindState((mind) => {if (!mind.enabled || !mind.started) return { mind, value: { success: false, error: 'Persistent mind is not started' } };if (mind.status !== 'paused') return { mind, value: { success: true, alreadyRunning: true } };@@ -1684,3 +1697,5 @@ export function __resetPersistentMindSupervisorForTests() {cancel(PERSISTENT_MIND_WATCHDOG_EVENT_ID);cancel(PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID);}++export const recheckPersistentMindSchedule = () => scheduleNextWake();diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 8a734e11e2..57f5bd6abb 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -117,6 +117,7 @@ vi.mock('./persistentMindMaintainerInference.js', async (importOriginal) => {};});+const { maintenance } = await import('../lib/maintenanceAdmission.js');const supervisor = await import('./persistentMindSupervisor.js');const makeRoot = () => ({@@ -179,6 +180,23 @@ describe('persistent mind supervisor', () => {supervisor.__resetPersistentMindSupervisorForTests();});+ it('maintenance rejects manual wakes without changing the saved paused policy', async () => {+ const prepare = vi.fn(); const run = vi.fn();+ await supervisor.registerPersistentMindTurnAdapter({ prepare, run });+ await supervisor.startPersistentMind();+ await supervisor.pausePersistentMind();+ const saved = structuredClone(mock.root.persistentMind);+ const { hold } = maintenance.begin({ reason: 'Work', owner: 'Operator' });+ try {+ await expect(supervisor.wakePersistentMind()).rejects.toMatchObject({ code: 'MAINTENANCE_HELD' });+ await expect(supervisor.resumePersistentMind()).rejects.toMatchObject({ code: 'MAINTENANCE_HELD' });+ expect(mock.root.persistentMind).toEqual(saved);+ expect(run).not.toHaveBeenCalled();+ } finally { maintenance.resume({ id: hold.id, revision: hold.revision }); }+ await supervisor.recheckPersistentMindSchedule();+ expect(mock.root.persistentMind).toEqual(saved);+ });+it('is silent on boot and enables the runtime only when explicitly started', async () => {const prepare = vi.fn();const run = vi.fn();diff --git a/server/services/pipeline/filenameHookFactory.js b/server/services/pipeline/filenameHookFactory.jsindex 769eda8da9..aaba2d5bc0 100644--- a/server/services/pipeline/filenameHookFactory.js+++ b/server/services/pipeline/filenameHookFactory.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Factory for pipeline media-job filename hooks.*@@ -87,6 +88,7 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,return result.patch || {};},).then(() => { writeOk = true; }).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ ${name} filename hook failed for job ${shortId}: ${err?.message || err}`);});@@ -94,11 +96,13 @@ export function createFilenameHook({ name, stageId, kind = 'image', parseOwner,console.log(`📎 ${name} filename stamped — issue=${parsed.issueId.slice(0, 8)} ${stampedLabel} ← ${filename}`);if (onStamped) {await onStamped({ parsed, job, filename, label: stampedLabel }).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ ${name} onStamped hook failed for job ${shortId}: ${err?.message || err}`);});}}}).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ ${name} filename hook crashed: ${err?.message || err}`);}));};diff --git a/server/services/pipeline/musicGen.js b/server/services/pipeline/musicGen.jsindex 33401914c7..645e40ffb0 100644--- a/server/services/pipeline/musicGen.js+++ b/server/services/pipeline/musicGen.js@@ -60,6 +60,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { stripMarkdownEmphasis } from '../../lib/markdownText.js';import { recommendMinimaxDurationSec } from '../../lib/musicDuration.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';const execFileAsync = promisify(execFile);@@ -674,10 +675,15 @@ export function buildMusicGenArgs({ pythonPath, scriptPath = SIDECAR_SCRIPT, run* generic idle watchdog resets its timer off it via the audio job-kind* adapter (server/services/audioGen/local.js), the same way the image/video* sidecars' stderr lines do, so a slow first-run model download doesn't trip a- * flat timeout. Callers outside the queue (the Pipeline Audio routes) omit it- * and behave exactly as before.+ * flat timeout. Callers outside the queue (the Pipeline Audio routes) omit it.+ * All callers honor maintenance admission; already-admitted work may continue.*/-export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, durationMode, modelId, repo, provenance, signal, onActivity } = {}) {+export async function generateMusic(options = {}) {+ return maintenance.run('music-render', options.engine || DEFAULT_ENGINE_ID,+ () => generateMusicAdmitted(options), { continuation: true });+}++async function generateMusicAdmitted({ prompt, lyrics, engine: engineId = DEFAULT_ENGINE_ID, durationSec, durationMode, modelId, repo, provenance, signal, onActivity }) {const text = (prompt || '').trim();if (!text) {throw new ServerError('prompt is required', { status: 400, code: 'PIPELINE_MUSIC_EMPTY_PROMPT' });@@ -769,7 +775,7 @@ export async function generateMusic({ prompt, lyrics, engine: engineId = DEFAULT? parsed.executionProfile: null;if (!result.ok || !parsed || !wroteFile) {- await unlink(outputPath).catch(() => {});+ await unlink(outputPath).catch(error => { if (error.code !== 'ENOENT') maintenance.markCurrentUnsettled(); });const reason = !result.ok ? result.reason : (!wroteFile ? 'sidecar wrote no audio' : 'sidecar returned no result');throw new ServerError(`Music generation failed: ${reason}`, {status: 500, code: 'PIPELINE_MUSIC_GEN_FAILED',diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.jsindex de191ec505..804381ba32 100644--- a/server/services/pipeline/musicGen.test.js+++ b/server/services/pipeline/musicGen.test.js@@ -406,6 +406,9 @@ const h = vi.hoisted(() => ({mockExitCode: 0,mockStdout: '',mockWriteOutput: true,+ deferClose: false,+ child: null,+ finishChild: null,musicgenPython: '/fake/venv-musicgen/bin/python3',audioldm2Python: '/fake/venv-audioldm2/bin/python3',minimaxMusic3Python: '/fake/venv-minimax-music3/bin/python3',@@ -450,18 +453,26 @@ vi.mock('../../lib/childProcess.js', async () => {h.spawnCalls.push({ bin, args });const listeners = {};const proc = {+ pid: 101, exitCode: null, signalCode: null,stdout: { on: (event, cb) => { if (event === 'data' && h.mockStdout) cb(Buffer.from(h.mockStdout)); } },stderr: { on: (event, cb) => { if (event === 'data') cb(Buffer.from('STAGE:generate\n')); } },on: (event, cb) => { listeners[event] = cb; },+ emit: (event, ...args) => listeners[event]?.(...args),kill: () => {},};- Promise.resolve().then(() => {+ let finished = false;+ h.child = proc;+ h.finishChild = () => {+ if (finished) return;+ finished = true;if (h.mockExitCode === 0 && h.mockWriteOutput) {const outPath = args[args.indexOf('--output') + 1];writeFileSync(outPath, Buffer.from('fake-wav-bytes'));}+ proc.exitCode = h.mockExitCode;listeners.close?.(h.mockExitCode, null);- });+ };+ if (!h.deferClose) Promise.resolve().then(h.finishChild);return proc;},};@@ -501,6 +512,9 @@ beforeEach(() => {h.spawnCalls.length = 0;h.mockExitCode = 0;h.mockWriteOutput = true;+ h.deferClose = false;+ h.child = null;+ h.finishChild = null;h.mockStdout = 'STAGE:done\nRESULT:{"output":"x","durationSec":12.5,"sampleRate":32000}\n';h.musicgenPython = '/fake/venv-musicgen/bin/python3';h.audioldm2Python = '/fake/venv-audioldm2/bin/python3';@@ -529,6 +543,45 @@ afterAll(async () => {});describe('generateMusic backend selection', () => {+ it('keeps music ownership through a live sidecar error until close and partial-file cleanup', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ h.deferClose = true;+ const outcome = generateMusic({ prompt: 'in-flight audio' }).catch(error => error);+ await vi.waitFor(() => expect(h.child).not.toBeNull());+ const { hold } = maintenance.begin({ reason: 'Drain live audio', owner: 'Operator' });+ try {+ h.child.emit('error', new Error('signal transport failed'));+ await Promise.resolve();+ expect(maintenance.status().state).toBe('draining');+ h.finishChild();+ expect(await outcome).toMatchObject({ code: 'PIPELINE_MUSIC_GEN_FAILED' });+ expect(await readdir(TEST_DIR)).toHaveLength(0);+ expect(maintenance.status().state).toBe('ready');+ } finally {+ h.finishChild();+ await outcome;+ maintenance.resume({ id: hold.id, revision: hold.revision });+ }+ });++ it('holds new music renders before probes or spawn while an admitted render can continue', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const parent = maintenance.admit('media', 'admitted-audio');+ const { hold } = maintenance.begin({ reason: 'Drain audio', owner: 'Operator' });+ try {+ await expect(generateMusic({ prompt: 'new render' })).rejects.toMatchObject({ code: 'MAINTENANCE_HELD' });+ expect(h.probeCalls).toEqual([]);+ expect(spawnCalls).toEqual([]);+ await expect(parent.run(() => generateMusic({ prompt: 'already admitted' }))).resolves.toMatchObject({ engine: 'musicgen' });+ expect(maintenance.status().state).toBe('draining');+ await parent.finish();+ expect(maintenance.status().state).toBe('ready');+ } finally {+ await parent.finish();+ maintenance.resume({ id: hold.id, revision: hold.revision });+ }+ });+it('defaults to the musicgen sidecar', async () => {const res = await generateMusic({ prompt: 'calm piano' });expect(spawnCalls).toHaveLength(1);diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.jsindex cf2792da09..6b5c093e01 100644--- a/server/services/pipeline/seasonCoverFilenameHook.js+++ b/server/services/pipeline/seasonCoverFilenameHook.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Pipeline season (volume) cover — filename hook.*@@ -66,6 +67,7 @@ const handler = (job) => {},};}).then(() => { writeOk = true; }).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ seasonCover filename hook failed for job ${shortId}: ${err?.message || err}`);});@@ -77,6 +79,7 @@ const handler = (job) => {if (target === 'cover') await refreshSeriesCoverImage(seriesId);}}).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);}));};diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex aa3252ff22..4f1ca68b72 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Shared LLM runner wrapper.*@@ -772,6 +773,10 @@ function createRecoveryInvestigationScope({ failed, failedModel, firstError }) {* log/attribute the deterministic recovery path.*/export async function runPromptThroughProvider(rawArgs) {+ return maintenance.run('provider', rawArgs?.source ?? 'prompt', () => runPromptThroughProviderAdmitted(rawArgs), { continuation: true });+}++async function runPromptThroughProviderAdmitted(rawArgs) {// Validate inputs up front so an accidentally-null `provider` (or one// missing `id`/`type`) surfaces a clear error here instead of throwing// a downstream TypeError on `provider.id` inside createRun or on thediff --git a/server/services/runner.js b/server/services/runner.jsindex 876fc9ac75..823a1bd9a0 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Compatibility shim for PortOS services that import from runner.js* Re-exports toolkit runner service functions with local overrides@@ -65,6 +66,8 @@ function safeSettle(fn, label) {}}+const settleCompletion = (fn, label) => safeSettle(() => maintenance.continueSettlement(fn), label);+export async function createRun(options) {// The toolkit's runner emits its own "🤖 AI run [source]: provider/model"// line — don't duplicate it here.@@ -112,7 +115,7 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erroconst outputPath = join(runDir, 'output.txt');const metadataPath = join(runDir, 'metadata.json');- await writeFileGuarded(outputPath, output).catch(() => {});+ await writeFileGuarded(outputPath, output).catch(() => maintenance.markCurrentUnsettled());const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');let metadata = {};@@ -173,7 +176,7 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, errometadata.errorAnalysis = errorAnalysis;}- await atomicWrite(metadataPath, metadata).catch(() => {});+ await atomicWrite(metadataPath, metadata).catch(() => maintenance.markCurrentUnsettled());// Guarded: these hooks are host-supplied, and every caller of this function// runs outside the request lifecycle — the /runs route never awaits its@@ -182,13 +185,13 @@ export async function finalizeRunRecord({ runId, output, exitCode, success, erro// unhandled rejection with the run stuck looking in-flight. The metadata is// already persisted by this point, so a failing hook must not un-finalize it.if (success) {- safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), 'onRunCompleted');+ settleCompletion(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), 'onRunCompleted');} else if (canceled) {// A Stop is not a provider failure. The hook still has to fire so the// shared activity snapshot drops the run; `onRunFailed` stays silent.- safeSettle(() => runnerConfig.hooks?.onRunCanceled?.({ runId: metadata.id }), 'onRunCanceled');+ settleCompletion(() => runnerConfig.hooks?.onRunCanceled?.({ runId: metadata.id }), 'onRunCanceled');} else if (reportFailure) {- safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), 'onRunFailed');+ settleCompletion(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), 'onRunFailed');}return metadata;@@ -215,7 +218,7 @@ export async function failRunRecord({ runId, error, exitCode = null, startTime =const failure = await finalizeRunRecord({runId, output: message, exitCode, success: false, error, startTime, identity, reportFailure,});- safeSettle(() => onComplete?.(failure), 'onComplete');+ settleCompletion(() => onComplete?.(failure), 'onComplete');return failure;}@@ -323,7 +326,13 @@ const describeSpawnFailure = (spawnError, command) =>* `.cmd`/`.bat` spawn under `shell:false` fails outright post-CVE-2024-27980,* and why the `cmd.exe` wrapper avoids DEP0190's unescaped-join hazard).*/-export async function executeCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout, toolFree = false, beforeExecute }) {+export async function executeCliRun(options) {+ const permit = maintenance.admit('cli-run', options.runId, { continuation: true });+ try { return await permit.run(() => executeAdmittedCliRun(options, permit)); }+ catch (err) { permit.finish(); throw err; }+}++async function executeAdmittedCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout, toolFree = false, beforeExecute }, permit) {const toolkit = requireToolkit();const runsPath = join(runnerConfig.dataDir, 'runs');@@ -367,7 +376,7 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, scconst { cwd: effectiveCwd, failure } = await resolveRunCwd({runId, workspacePath, label: `Run ${runId}`, startTime, onData, onComplete,});- if (failure) return;+ if (failure) { await permit.finish(); return; }const prepareVision = screenshots.length > 0 ? await import('./visionCli.js') : null;const vision = prepareVision@@ -624,13 +633,14 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc// Isolate lifecycle hooks from onComplete so a hook failure never changes// the terminal result or prevents the caller from settling.if (metadata.success) {- safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);+ settleCompletion(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);} else if (canceled) {- safeSettle(() => runnerConfig.hooks?.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);+ settleCompletion(() => runnerConfig.hooks?.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);} else {- safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);+ settleCompletion(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);}- safeSettle(() => onComplete?.(stdoutIsResponse && metadata.success ? { ...metadata, text: assistantOutput } : metadata), `Run ${runId} onComplete`);+ settleCompletion(() => onComplete?.(stdoutIsResponse && metadata.success ? { ...metadata, text: assistantOutput } : metadata), `Run ${runId} onComplete`);+ permit.finish();return metadata;} catch (err) {const handler = spawnError ? 'error' : 'close';@@ -647,11 +657,11 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc...(canceled ? { canceled: true, completionReason: hostInterrupted ? 'host-shutdown' : 'canceled' } : {}),};if (canceled) {- safeSettle(() => runnerConfig.hooks?.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);+ settleCompletion(() => runnerConfig.hooks?.onRunCanceled?.({ runId }), `Run ${runId} onRunCanceled hook`);} else {- safeSettle(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);+ settleCompletion(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);}- safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);+ settleCompletion(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);return failMetadata;}};@@ -660,12 +670,15 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, screturn finalizationPromise;};+ let terminalSpawnError = null;handleSpawnError = (err) => {- void finalizeOnce({ exitCode: -1, spawnError: err });+ terminalSpawnError = err;+ // With no pid there was no child. Otherwise close owns physical exit.+ if (!childProcess.pid) void finalizeOnce({ exitCode: -1, spawnError: err });};childProcess.on('close', (code, signal) => {- void finalizeOnce({ exitCode: code, signal });+ void finalizeOnce({ exitCode: code, signal, spawnError: terminalSpawnError });});// A failed spawn emits 'error' and commonly 'close' after it; finalizeOncediff --git a/server/services/sprites/localAnimationJobHook.js b/server/services/sprites/localAnimationJobHook.jsindex af8daaab0d..aa2f7efa8e 100644--- a/server/services/sprites/localAnimationJobHook.js+++ b/server/services/sprites/localAnimationJobHook.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Sprite local-render completion hook (#4876).*@@ -144,14 +145,18 @@ async function reconcileSettledSpriteJobs() {.filter((job) => ['completed', 'failed', 'canceled'].includes(job.status)).filter(decodeSpriteAnimationJob);if (!jobs.length) return 0;+ // Register the whole recovery batch before yielding, so readiness cannot+ // flicker between two archived jobs. Recovery starts no new provider work.+ const pending = jobs.map(job => ({ job, permit: maintenance.recoverOwned('settlement', `sprite:${job.id}`) }));let settled = 0;- for (const job of jobs) {+ for (const { job, permit } of pending) {// Serialized on purpose: these share the per-record write tail anyway, and a// boot sweep has no reason to contend with the requests now arriving.// eslint-disable-next-line no-await-in-loop- await settleSpriteAnimationJob(job).then(() => { settled += 1; }).catch((err) => (- console.error(`❌ sprite local render boot reconcile failed for job ${job.id.slice(0, 8)}: ${err?.message || err}`)- ));+ await permit.run(() => settleSpriteAnimationJob(job)).then(() => { settled += 1; }).catch((err) => {+ permit.markUnsettled();+ console.error(`❌ sprite local render boot reconcile failed for job ${job.id.slice(0, 8)}: ${err?.message || err}`);+ }).finally(() => permit.finish());}console.log(`🎞️ sprite local renders: reconciled ${settled} settled job(s) on boot`);return settled;@@ -166,7 +171,7 @@ export function initSpriteLocalAnimationHook() {terminalHandler = (job) => {// Outside the request lifecycle, so a throw here would take the process// down rather than reaching error middleware (AGENTS.md boundary exception).- void settleSpriteAnimationJob(job).catch((err) => (+ void maintenance.continueSettlement(() => settleSpriteAnimationJob(job)).catch((err) => (console.error(`❌ sprite local render hook failed for job ${job?.id?.slice(0, 8)}: ${err?.message || err}`)));};diff --git a/server/services/sprites/localAnimationJobHook.test.js b/server/services/sprites/localAnimationJobHook.test.jsindex 92da4bfc98..eb556c365c 100644--- a/server/services/sprites/localAnimationJobHook.test.js+++ b/server/services/sprites/localAnimationJobHook.test.js@@ -387,6 +387,21 @@ describe('backup admission', () => {});describe('reconcileSettledSpriteJobs (boot pass)', () => {+ it('counts recovered publication before its first await under a persisted hold', async () => {+ const { maintenance } = await import('../../lib/maintenanceAdmission.js');+ const status = maintenance.begin({ reason: 'sprite recovery test', owner: 'test' });+ let finishAttach;+ attachTuiWalkResult.mockImplementationOnce(() => new Promise(resolve => { finishAttach = resolve; }));+ queuedJobs = [walkJob()];+ const reconciliation = reconcileSettledSpriteJobs();+ expect(maintenance.status().state).toBe('draining');+ await vi.waitFor(() => expect(finishAttach).toBeTypeOf('function'));+ finishAttach();+ await reconciliation;+ expect(maintenance.status().state).toBe('ready');+ maintenance.resume({ id: status.hold.id, revision: status.hold.revision });+ });+it('files jobs that reached a terminal state while the process was DOWN', async () => {// These emit nothing — they are simply sitting in the restored archive. The// live subscription can never see them, so without this pass the run is onlydiff --git a/server/services/subAgentSpawner.dispatchHolds.test.js b/server/services/subAgentSpawner.dispatchHolds.test.jsindex a8ee9269ff..d45153cd3c 100644--- a/server/services/subAgentSpawner.dispatchHolds.test.js+++ b/server/services/subAgentSpawner.dispatchHolds.test.js@@ -88,6 +88,7 @@ import { cosEvents, emitLog } from './cosEvents.js';import { isRunnerReachable } from './cosRunnerClient.js';import { spawnAgentForTask } from './agentOrchestrator.js';import { releaseAppReviewMarker } from './appActivity.js';+import { maintenance } from '../lib/maintenanceAdmission.js';import { isUpdateInProgress } from './updateChecker.js';import { setUseRunner } from './agentState.js';import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';@@ -105,6 +106,22 @@ describe('subAgentSpawner — runner-down hold', () => {isUpdateInProgress.mockReturnValue(false);});+ it('keeps task reservations recoverable when maintenance wins during spawn preparation', async () => {+ spawnAgentForTask.mockRejectedValueOnce(Object.assign(new Error('Held'), { code: 'MAINTENANCE_HELD' }));+ await dispatch({ id: 'held-task', metadata: { app: 'example-app', jobId: 'example-job' } });+ expect(releaseAppReviewMarker).toHaveBeenCalledWith('example-app');+ expect(cosEvents.emit).toHaveBeenCalledWith('job:spawn-failed', { jobId: 'example-job' });+ });++ it('holds a manual/automatic task-ready event before runner preparation', async () => {+ const { hold } = maintenance.begin({ reason: 'Work', owner: 'Operator' });+ try {+ await dispatch({ id: 'held-task', metadata: {} });+ expect(spawnAgentForTask).not.toHaveBeenCalled();+ expect(isRunnerReachable).not.toHaveBeenCalled();+ } finally { maintenance.resume({ id: hold.id, revision: hold.revision }); }+ });+it('spawns normally while the runner is up', async () => {await dispatch({ id: 'cos-1', metadata: {} });diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex a8ca86dbbb..444c3ca521 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -1,3 +1,4 @@+import { maintenance, isMaintenanceHold } from '../lib/maintenanceAdmission.js';/*** Sub-Agent Spawner Service — the agent cluster's EVENT WIRING.*@@ -168,6 +169,7 @@ async function handleTaskReady(task) {// by the restart (its PTY/child process is a child of this server). The// flag reads synchronously, so nothing can slip between the check and the// spawn; the task runs on the other side of the restart.+ if (maintenance.held()) return holdTask(task, 'maintenance is holding new work');if (isUpdateInProgress()) {return holdTask(task, 'a PortOS self-update is in progress');}@@ -215,6 +217,7 @@ async function handleTaskReady(task) {try {await spawnAgentForTask(task);} catch (err) {+ if (isMaintenanceHold(err)) return holdTask(task, 'maintenance is holding new work');emitLog('error', `Failed to spawn agent for task ${task.id}: ${err?.message || err}`, { taskId: task.id });const jobId = task.metadata?.jobId;if (jobId) {diff --git a/server/services/superColliderRender.js b/server/services/superColliderRender.jsindex f2203c48b0..542c6326f4 100644--- a/server/services/superColliderRender.js+++ b/server/services/superColliderRender.js@@ -31,6 +31,7 @@ import { createHash } from 'crypto';import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'fs/promises';import { join } from 'path';import { ServerError } from '../lib/errorHandler.js';+import { maintenance } from '../lib/maintenanceAdmission.js';import { PATHS } from '../lib/paths.js';import { measureWavAudio } from '../lib/wavAudioFile.js';import {@@ -191,6 +192,8 @@ export async function renderSuperColliderSource({if (signal?.aborted) stop.abort();const diagnostics = [];let quotaTimer = null;+ let containerInvoked = false;+ let containerSettled = false;try {// Exclusive: two jobs can never share a directory, and a stale one with// this id (an earlier process's scratch) is replaced rather than reused.@@ -216,6 +219,7 @@ export async function renderSuperColliderSource({onPhase({ phase: 'starting', message: 'Starting the SuperCollider container', progress: 0.05 });const { input, output } = SUPERCOLLIDER_CONTAINER_PATHS;+ containerInvoked = true;const run = await runSuperColliderContainer({docker,image: status.image.id,@@ -244,6 +248,7 @@ export async function renderSuperColliderSource({}},});+ containerSettled = run.cleanupComplete === true;clearInterval(quotaTimer);quotaTimer = null;@@ -306,8 +311,18 @@ export async function renderSuperColliderSource({} finally {if (quotaTimer) clearInterval(quotaTimer);signal?.removeEventListener('abort', forwardAbort);+ // A rejected runner or failed Docker removal cannot prove physical exit.+ // Keep recovery ownership before the adapter emits its terminal event.+ if (containerInvoked && !containerSettled) {+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ }await rm(jobDir, { recursive: true, force: true })- .catch((err) => console.error(`❌ SuperCollider job scratch ${jobId.slice(0, 8)} not removed: ${err.message}`));+ .catch((err) => {+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ console.error(`❌ SuperCollider job scratch ${jobId.slice(0, 8)} not removed: ${err.message}`);+ });}}@@ -319,29 +334,29 @@ export function presentSuperColliderPreview(preview) {/*** Media-queue entry point for `kind: 'supercollider'` jobs: renders, then- * announces the outcome on the audio event bus the queue listens to. Throws- * on failure (the queue turns that into failed, or canceled after a cancel).+ * announces the outcome on the audio event bus after teardown. Also rejects+ * on failure; the terminal event releases the queue's watchdog settlement wait.*/export async function renderSuperCollider({ jobId, source, durationSec, seed }) {const job = { controller: new AbortController(), committing: false };active.set(jobId, job);- let preview;- try {- preview = await renderSuperColliderSource({- jobId,- source,- durationSec,- seed,- signal: job.controller.signal,- onActivity: () => audioGenEvents.emit('activity', { generationId: jobId }),- onPhase: ({ phase, message, progress }) => {- if (typeof progress === 'number') audioGenEvents.emit('progress', { generationId: jobId, progress, message, phase });- else audioGenEvents.emit('status', { generationId: jobId, message, phase });- },- });- } finally {+ const preview = await renderSuperColliderSource({+ jobId,+ source,+ durationSec,+ seed,+ signal: job.controller.signal,+ onActivity: () => audioGenEvents.emit('activity', { generationId: jobId }),+ onPhase: ({ phase, message, progress }) => {+ if (typeof progress === 'number') audioGenEvents.emit('progress', { generationId: jobId, progress, message, phase });+ else audioGenEvents.emit('status', { generationId: jobId, message, phase });+ },+ }).finally(() => {active.delete(jobId);- }+ }).catch(err => {+ audioGenEvents.emit('failed', { generationId: jobId, error: err.message, code: err.code });+ throw err;+ });const result = { generationId: jobId, ...presentSuperColliderPreview(preview) };audioGenEvents.emit('completed', result);return result;diff --git a/server/services/superColliderRender.test.js b/server/services/superColliderRender.test.jsindex 820008d6a8..dcf2869213 100644--- a/server/services/superColliderRender.test.js+++ b/server/services/superColliderRender.test.js@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -7,7 +7,36 @@ import {SUPERCOLLIDER_RENDER_WRAPPER_SOURCE,} from '../lib/superColliderRuntime.js';import { setupSuperColliderRuntime } from './superColliderRuntime.js';-import { readSuperColliderPreview, renderSuperColliderSource } from './superColliderRender.js';+import { cancel, readSuperColliderPreview, renderSuperCollider, renderSuperColliderSource } from './superColliderRender.js';+import { audioGenEvents } from './audioGen/events.js';+import { createMaintenanceAdmission } from '../lib/maintenanceAdmission.js';++const fixture = vi.hoisted(() => ({ admission: null, failedCleanupPath: null, beforeRemove: null, docker: null, dataDir: null }));+vi.mock('../lib/paths.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, PATHS: new Proxy(actual.PATHS, {+ get: (target, property) => property === 'data' ? fixture.dataDir : target[property],+ }) };+});+vi.mock('./superColliderRuntime.js', async importOriginal => ({+ ...await importOriginal(),+ resolveDockerCli: async () => {+ if (!fixture.docker) throw new Error('Unexpected real Docker discovery');+ return fixture.docker;+ },+}));+vi.mock('../lib/maintenanceAdmission.js', async importOriginal => ({+ ...await importOriginal(),+ maintenance: new Proxy({}, { get: (_target, property) => fixture.admission[property] }),+}));+vi.mock('fs/promises', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, rm: async (path, options) => {+ await fixture.beforeRemove?.(path);+ if (path === fixture.failedCleanupPath) throw Object.assign(new Error('Cleanup denied'), { code: 'EACCES' });+ return actual.rm(path, options);+ } };+});// Interleaved IEEE-float WAV — the format the render wrapper asks scsynth for.function floatWav(seconds, amplitude, { channels = 2, sampleRate = 48000 } = {}) {@@ -90,7 +119,14 @@ describe('contained SuperCollider renders', () => {jobId: `job-${(jobSeq += 1)}`, source: STOCK_SOURCE, durationSec: 4, seed: 42, docker, dataDir, ...overrides,});- beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'portos-sc-render-')); });+ beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), 'portos-sc-render-'));+ fixture.dataDir = dataDir;+ fixture.docker = null;+ fixture.beforeRemove = null;+ fixture.admission = createMaintenanceAdmission(dataDir);+ fixture.failedCleanupPath = null;+ });afterEach(() => rmSync(dataDir, { recursive: true, force: true }));it('renders frozen source through the contained wrapper into a validated preview and leaves no scratch', async () => {@@ -129,6 +165,22 @@ describe('contained SuperCollider renders', () => {expect(wrapper).toBe(SUPERCOLLIDER_RENDER_WRAPPER_SOURCE);});+ it('retains a recovery blocker when render scratch cannot be removed', async () => {+ const jobId = 'job-cleanup-failed';+ const docker = await ready(fakeDocker({ render: run => {+ fixture.failedCleanupPath = join(jobsDir(), jobId);+ return defaultRender(run);+ } }));+ const permit = fixture.admission.admit('media', jobId);+ fixture.admission.begin({ reason: 'Drain audio render', owner: 'Operator' });+ await permit.run(() => render(docker, { jobId }));+ await permit.finish();+ expect(fixture.admission.status()).toMatchObject({+ state: 'draining', blockers: [expect.objectContaining({ resource: jobId, unsettled: true })],+ });+ expect(leftoverScratch()).toEqual([jobId]);+ });+it('reports a syntax error with sclang\'s location and publishes nothing', async () => {const docker = await ready(fakeDocker({ render: (run) => {run.onLine('PORTOS_PHASE compiling');@@ -172,6 +224,75 @@ describe('contained SuperCollider renders', () => {expect(leftoverScratch()).toEqual([]);});+ it.each(['complete', 'failed', 'rejected'])('emits cancellation settlement after awaited teardown (container removal: %s)', async removalOutcome => {+ const jobId = 'job-queue-cancel';+ const containerCleanup = Promise.withResolvers();+ const scratchCleanup = Promise.withResolvers();+ const removalStarted = Promise.withResolvers();+ const scratchStarted = Promise.withResolvers();+ fixture.docker = await ready(fakeDocker({ render: async run => {+ // Only delay terminal scratch cleanup, after the initial directory reset.+ fixture.beforeRemove = async path => {+ if (path !== join(jobsDir(), jobId)) return;+ scratchStarted.resolve();+ await scratchCleanup.promise;+ };+ await waitUntil(run.isCancelled);+ return { success: false, error: 'cancelled' };+ } }));+ const capture = fixture.docker.capture;+ fixture.docker.capture = async (args, ...rest) => {+ if (args[0] === 'rm' && args[2] === fixture.docker.calls.runs[0]?.name) {+ removalStarted.resolve();+ await containerCleanup.promise;+ if (removalOutcome === 'failed') return { success: false, stderr: 'Container removal unavailable' };+ if (removalOutcome === 'rejected') throw new Error('Container removal unavailable');+ }+ return capture(args, ...rest);+ };+ const permit = fixture.admission.admit('media', jobId);+ let settlement;+ let cancelAfterTerminal;+ const failed = vi.fn(() => {+ cancelAfterTerminal = cancel(jobId);+ settlement = permit.finish();+ });+ audioGenEvents.on('failed', failed);+ const pending = permit.run(() => renderSuperCollider({ jobId, source: STOCK_SOURCE, durationSec: 4, seed: 42 }));+ // Attach rejection handling immediately while teardown is deliberately held.+ const rejected = expect(pending).rejects.toMatchObject(removalOutcome === 'rejected'+ ? { message: 'Container removal unavailable' } : { code: 'SUPERCOLLIDER_CANCELED' });+ try {+ await waitUntil(() => fixture.docker.calls.runs.length === 1);+ fixture.admission.begin({ reason: 'Drain canceled render', owner: 'Operator' });+ expect(cancel(jobId)).toBe(true);+ await removalStarted.promise;+ expect(failed).not.toHaveBeenCalled();+ expect(fixture.admission.status().state).toBe('draining');+ containerCleanup.resolve();+ await scratchStarted.promise;+ expect(failed).not.toHaveBeenCalled();+ expect(leftoverScratch()).toEqual([jobId]);+ expect(fixture.admission.status().state).toBe('draining');+ scratchCleanup.resolve();+ await rejected;+ expect(failed).toHaveBeenCalledTimes(1);+ expect(failed).toHaveBeenCalledWith(expect.objectContaining({ generationId: jobId }));+ await settlement;+ expect(cancelAfterTerminal).toBe(false);+ expect(leftoverScratch()).toEqual([]);+ expect(fixture.admission.status().state).toBe(removalOutcome === 'complete' ? 'ready' : 'draining');+ if (removalOutcome !== 'complete') expect(fixture.admission.status().blockers[0]).toMatchObject({ resource: jobId, unsettled: true });+ } finally {+ cancel(jobId);+ containerCleanup.resolve();+ scratchCleanup.resolve();+ await pending.catch(() => {});+ audioGenEvents.off('failed', failed);+ await permit.finish();+ }+ });+it('stops a render that floods its output directory', async () => {const docker = await ready(fakeDocker({ render: async (run) => {for (let i = 0; i < 40; i += 1) writeFileSync(join(run.outputDir, `junk-${i}.bin`), 'x');diff --git a/server/services/superColliderRuntime.js b/server/services/superColliderRuntime.jsindex bd1b5b8bbd..2d8d7f50a9 100644--- a/server/services/superColliderRuntime.js+++ b/server/services/superColliderRuntime.js@@ -189,7 +189,8 @@ export async function runSuperColliderContainer({const args = buildSuperColliderRunArgs({ image, containerName, inputDir, outputDir, script, scriptArgs, user });const result = await docker.stream(args, onLine, { timeoutMs, isCancelled: () => Boolean(signal?.aborted) });const removal = await docker.capture(['rm', '--force', containerName], { timeoutMs: DOCKER_RM_TIMEOUT_MS });- if (!removal.success && !/no such container/i.test(`${removal.stderr}`)) {+ const cleanupComplete = removal.success || /no such container/i.test(`${removal.stderr}`);+ if (!cleanupComplete) {console.error(`❌ SuperCollider container ${containerName} cleanup failed: ${clipDiagnostic(spawnFailureDetail(removal, 'docker rm failed'))}`);}const error = result.success ? null : clipDiagnostic(result.error);@@ -199,6 +200,7 @@ export async function runSuperColliderContainer({timedOut: Boolean(error?.startsWith('timed out')),cancelled: error === 'cancelled',containerName,+ cleanupComplete,};}diff --git a/server/services/tuiPromptRunner.js b/server/services/tuiPromptRunner.jsindex c94549b4d3..4879fb5fc4 100644--- a/server/services/tuiPromptRunner.js+++ b/server/services/tuiPromptRunner.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** One-shot TUI prompt runner.*@@ -154,7 +155,16 @@ const PTY_ROWS = 50;* it reports itself, not a provider incident for the autofixer to escalate.* @returns {Promise<void>}*/-export async function executeTuiRun({ runId, provider, prompt, screenshots = [], workspacePath, onData, onComplete, onReady, timeout, idleMs, label, guard = false, reportFailure = true, beforeExecute }) {+export async function executeTuiRun(options) {+ const permit = maintenance.admit('tui-run', options.runId, { continuation: true });+ const lifecycle = { spawned: false, exited: false, cleaned: false,+ settle() { if (this.cleaned && (!this.spawned || this.exited)) return permit.finish(); } };+ try { return await permit.run(() => executeAdmittedTuiRun(options, lifecycle)); }+ catch (err) { if (lifecycle.spawned) permit.markUnsettled(); throw err; }+ finally { lifecycle.cleaned = true; await lifecycle.settle(); }+}++async function executeAdmittedTuiRun({ runId, provider, prompt, screenshots = [], workspacePath, onData, onComplete, onReady, timeout, idleMs, label, guard = false, reportFailure = true, beforeExecute }, maintenanceLifecycle) {if (!provider || typeof provider !== 'object') {throw new Error('executeTuiRun: provider is required');}@@ -328,9 +338,12 @@ ${prompt}`;// one exit event until finish() and the timers below are ready, then replay it// through the ordinary exit path. This is a startup/lifecycle guard, not an// output-idle timeout: a live but quiet model remains untouched.+ maintenanceLifecycle.spawned = true;let dispatchPtyExit = null;let pendingPtyExit = null;ptyProcess.onExit((event) => {+ maintenanceLifecycle.exited = true;+ maintenanceLifecycle.settle();if (dispatchPtyExit) {dispatchPtyExit(event);return;@@ -544,6 +557,7 @@ ${prompt}`;...(canceled ? { canceled: true } : {}),},}).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ TUI run ${runId} finalize failed: ${err.message}`);return {exitCode, success, error: error || err.message,@@ -554,6 +568,7 @@ ${prompt}`;onCompleteInvoked = true;onComplete?.({ ...metadata, text: responseText, usedResponseFile, outputTruncated: outputBufferTruncated });} catch (err) {+ maintenance.markCurrentUnsettled();console.error(`❌ TUI run ${runId} finish() failed: ${err?.message || err}`);// Ensure the original PTY is torn down even when a cleanup step BEFORE// the kill above threw (e.g. unregisterExternalSession). Otherwise thediff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.jsindex ee8517b92a..64f9248b1b 100644--- a/server/services/usageReconciler.js+++ b/server/services/usageReconciler.js@@ -1,3 +1,4 @@+import { maintenance } from '../lib/maintenanceAdmission.js';/*** Replace PortOS's estimated per-run token counts with the CLI's own measured* counts, read from the transcripts the coding CLIs already write to disk.@@ -893,6 +894,7 @@ export async function recordCompletedRunUsage(metadata, output, { home = homedirawait atomicWrite(metadataPath, persisted);}).catch((err) => {+ maintenance.markCurrentUnsettled();console.error(`❌ Failed to record usage: ${err.message}`);});}diff --git a/server/services/videoGen/conditioningMedia.js b/server/services/videoGen/conditioningMedia.jsindex a295daa5c7..a938f442d8 100644--- a/server/services/videoGen/conditioningMedia.js+++ b/server/services/videoGen/conditioningMedia.js@@ -4,6 +4,7 @@ import { join, basename } from 'path';import { tmpdir } from 'os';import { unlinkGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';import { safeChildProcessOptions } from '../../lib/processEnv.js';import { isIcLoraMode, icLoraSpecForMode } from '../../lib/icLoraWeights.js';@@ -152,7 +153,12 @@ export async function prepareVideoConditioningMedia({? [audioFilePath]: []),];- return Promise.all(paths.filter(Boolean).map((path) => unlinkGuarded(path).catch(() => {})));+ return Promise.all(paths.filter(Boolean).map((path) => unlinkGuarded(path).catch(error => {+ if (error.code !== 'ENOENT') {+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ }+ })));};const resolvedIcReferencePaths = await materializeIngredientsReferences({mode, icReferencePaths, ffmpeg, w, h, parsedFps, jobId,diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.jsindex f5ea612506..2ce69c1e43 100644--- a/server/services/videoGen/generateVideo.js+++ b/server/services/videoGen/generateVideo.js@@ -19,6 +19,7 @@ import { tmpdir } from 'os';import { randomUUID } from 'crypto';import { ensureDir, PATHS, rmGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';import { wan22FrameCountError } from './wan22Controls.js';import {isDefaultI2vReferenceMode, normalizeI2vReferenceMode, resolveI2vReferenceStrength,@@ -689,10 +690,16 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', mjob.status = 'error';const reason = err.message || 'Failed to prepare video generation';console.error(`❌ Video generation preparation error [${jobId.slice(0, 8)}]: ${reason}`);+ const cleanup = await Promise.allSettled([+ cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true }),+ rmGuarded(stepwiseDir, { recursive: true, force: true }),+ ]);+ if (cleanup.some(result => result.status === 'rejected')) {+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ }broadcastSse(job, { type: 'error', error: reason });videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [prompt, negativePrompt] }) });- void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });- void rmGuarded(stepwiseDir, { recursive: true, force: true });closeJobAfterDelay(videoJobState.jobs, jobId);throw err;}diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.jsindex 6453b0b7b5..da04a23c74 100644--- a/server/services/videoGen/grok.js+++ b/server/services/videoGen/grok.js@@ -38,6 +38,7 @@ import { mutateVideoHistory } from './history.js';import { noImageReason, deriveAspectRatio, GROK_ASPECT_RATIOS } from '../imageGen/grok.js';import { resolveGrokDuration } from '../../lib/grokVideoClip.js';import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';// 30 minutes — an image-first video turn is two sequential tool calls// (image_gen then image_to_video render + download), so it runs meaningfully@@ -209,12 +210,25 @@ async function runGrokVideo(job, jobId, bin, args, {// scratch-dir spawn telling the child one consistent story about where it is.const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, env: withSpawnCwdEnv(process.env, scratchDir), shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });activeProcs.set(jobId, proc);- const removeScratch = () => rmGuarded(scratchDir, { recursive: true, force: true }).catch(() => {});+ const retainOwnership = (error) => {+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ console.error(`❌ Grok video settlement failed [${jobId.slice(0, 8)}]: ${error?.message || error}`);+ };// The route stages a multipart source image into data/uploads and hands us// its path — the provider owns unlinking it on every terminal path (same// contract as videoGen/local.js; the queue only cleans up when the// provider throws before spawning, or on boot-restore of a dead job).- const removeUpload = () => { if (uploadedTempPath) unlinkGuarded(uploadedTempPath).catch(() => {}); };+ let cleanupPromise;+ const cleanup = () => cleanupPromise ||= Promise.allSettled([+ Promise.resolve().then(() => cleanupPromptFile({ throwOnError: true })),+ Promise.resolve().then(() => rmGuarded(scratchDir, { recursive: true, force: true })),+ Promise.resolve().then(() => uploadedTempPath && unlinkGuarded(uploadedTempPath)),+ ]).then(results => {+ for (const result of results) {+ if (result.status === 'rejected' && result.reason?.code !== 'ENOENT') retainOwnership(result.reason);+ }+ });if (useStdin) {proc.stdin.on('error', () => {});@@ -233,12 +247,19 @@ async function runGrokVideo(job, jobId, bin, args, {}}, GROK_VIDEO_TIMEOUT_MS);+ let terminalStarted = false;+ let processError;proc.on('error', (err) => {+ if (terminalStarted) return;+ processError = err;+ // A failed kill/send can report error while the child is still alive.+ // Keep its cancel handle (including SIGKILL escalation) until close.+ if (proc.pid) return;+ terminalStarted = true;clearTimeout(timeoutTimer);- cleanupPromptFile();- removeScratch();- removeUpload();- finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);+ cleanup().then(() => {+ finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);+ }).catch(retainOwnership);});proc.stdout.on('data', (chunk) => {@@ -259,27 +280,25 @@ async function runGrokVideo(job, jobId, bin, args, {});proc.on('close', async (code, signal) => {+ if (terminalStarted) return;+ terminalStarted = true;clearTimeout(timeoutTimer);- cleanupPromptFile();try {- if (code !== 0) {- const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;+ if (code !== 0 || processError) {+ const reason = processError?.message || (signal ? `Killed by signal ${signal}` : `Exit code ${code}`);const tail = stderrTail.trim().split('\n').slice(-6).join('\n');- removeScratch();- removeUpload();+ await cleanup();return finalizeJobFailure(job, jobId, proc, `Grok video generation failed: ${reason}\n${tail}`);}const harvested = await harvestStagedVideo(stagingPath, harvestTimeoutMs);if (!harvested.found) {- removeScratch();- removeUpload();+ await cleanup();const prefix = harvested.invalid ? 'Grok wrote a non-MP4 file at the directed path. ' : '';return finalizeJobFailure(job, jobId, proc, `${prefix}${noVideoReason(stdoutTail)}`);}await copyFileGuarded(stagingPath, outputPath);- await unlinkGuarded(stagingPath).catch(() => {});- removeScratch();- removeUpload();+ // Removing the scratch directory also removes the harvested staging file.+ await cleanup();if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);activeJobs.delete(jobId);// Shared finalizer: faststart optimization, thumbnail, history entry,@@ -289,8 +308,8 @@ async function runGrokVideo(job, jobId, bin, args, {await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });closeJobAfterDelay(jobs, jobId);} catch (err) {- removeScratch();- removeUpload();+ await cleanup();+ retainOwnership(err);// finalizeGeneratedVideo marks job.status='complete' BEFORE its async// post-processing (faststart/thumbnail/history) — a throw there must// still surface as a terminal failure or the queue's job staysdiff --git a/server/services/videoGen/grok.test.js b/server/services/videoGen/grok.test.jsindex 4b3c3425cc..f9f4a486c3 100644--- a/server/services/videoGen/grok.test.js+++ b/server/services/videoGen/grok.test.js@@ -1,9 +1,9 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { posixPath } from '../../lib/testHelper.js';+import { pinPlatform, posixPath } from '../../lib/testHelper.js';import { mkdir, writeFile, rm, readFile } from 'fs/promises';import { existsSync } from 'fs';-import { join } from 'path';+import { basename, join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'events';import { ChildProcess } from '../../lib/childProcess.js';@@ -30,7 +30,7 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => {const { readFileSync } = await import('fs');return {...actual,- spawn: vi.fn((bin, args) => {+ spawn: vi.fn((bin, args, options) => {const child = makeFakeChild();// On Windows grok cannot read /dev/stdin, so prepareGrokPromptFile writes// the prompt to a temp file and rewrites --prompt-file to point at it —@@ -44,7 +44,8 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => {if (pfPath && pfPath !== '/dev/stdin') {try { promptFromFile = readFileSync(pfPath, 'utf8'); } catch { promptFromFile = null; }}- spawnCalls.push({ bin, args, child, promptFromFile });+ const jobId = options?.cwd ? basename(options.cwd).replace(/^portos-grok-video-/, '') : null;+ spawnCalls.push({ bin, args, child, promptFromFile, jobId });return child;}),};@@ -55,6 +56,11 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => {const TEST_ROOT = join(tmpdir(), `portos-grok-video-test-${process.pid}-${Date.now()}`);const FAKE_VIDEOS_DIR = join(TEST_ROOT, 'data-videos');const FAKE_DATA_DIR = join(TEST_ROOT, 'data');+const fixture = vi.hoisted(() => ({ admission: null }));+vi.mock('../../lib/maintenanceAdmission.js', async importOriginal => ({+ ...await importOriginal(),+ maintenance: new Proxy({}, { get: (_target, property) => fixture.admission[property] }),+}));vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');actual.PATHS.videos = FAKE_VIDEOS_DIR;@@ -62,6 +68,8 @@ vi.mock('../../lib/fileUtils.js', async () => {return {...actual,ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),+ rmGuarded: vi.fn(actual.rmGuarded),+ unlinkGuarded: vi.fn(actual.unlinkGuarded),};});@@ -80,6 +88,9 @@ vi.mock('../../lib/ffmpeg.js', async () => {const grok = await import('./grok.js');const { videoGenEvents } = await import('./events.js');const { loadHistory } = await import('./history.js');+const { createMaintenanceAdmission } = await import('../../lib/maintenanceAdmission.js');+const { rmGuarded, unlinkGuarded } = await import('../../lib/fileUtils.js');+const realFiles = await vi.importActual('../../lib/fileUtils.js');const flush = () => new Promise((r) => setImmediate(r));const scratchDirFor = (jobId) => join(tmpdir(), `portos-grok-video-${jobId}`);@@ -87,9 +98,19 @@ const stagingPathFor = (jobId) => join(scratchDirFor(jobId), 'output.mp4');// Prefer the --prompt-file temp file (Windows) and fall back to stdin (POSIX).const promptOf = (i = 0) => spawnCalls[i].promptFromFile ?? spawnCalls[i].child.stdin.written;const closeChild = async (i = 0, code = 1) => {+ const terminal = new Promise(resolve => {+ const finish = payload => {+ if (payload.generationId !== spawnCalls[i].jobId) return;+ videoGenEvents.off('failed', finish);+ videoGenEvents.off('completed', finish);+ resolve();+ };+ videoGenEvents.on('failed', finish);+ videoGenEvents.on('completed', finish);+ });spawnCalls[i].child.exitCode = code;spawnCalls[i].child.emit('close', code, null);- await flush();+ await terminal;};// Minimal valid MP4 header: size box + `ftyp` at offset 4.const MP4_BYTES = Buffer.concat([@@ -103,6 +124,9 @@ beforeEach(async () => {grok._internals.setHarvestTimeoutForTests(10);await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});await mkdir(FAKE_DATA_DIR, { recursive: true });+ fixture.admission = createMaintenanceAdmission(FAKE_DATA_DIR);+ rmGuarded.mockReset().mockImplementation(realFiles.rmGuarded);+ unlinkGuarded.mockReset().mockImplementation(realFiles.unlinkGuarded);});afterEach(async () => {@@ -215,12 +239,7 @@ describe('videoGen/grok — harvest and finalize', () => {await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));expect(failed.mock.calls[0][0].error).toMatch(/non-MP4 file/);expect(existsSync(join(FAKE_VIDEOS_DIR, job.filename))).toBe(false);- // Scratch-dir removal is fire-and-forget alongside the 'failed' event- // (not awaited before it), so give it a moment to land on disk rather- // than racing it.- const scratchDir = scratchDirFor(job.jobId);- await vi.waitFor(() => expect(existsSync(scratchDir)).toBe(false));- expect(existsSync(scratchDir)).toBe(false);+ expect(existsSync(scratchDirFor(job.jobId))).toBe(false);});it('fails with the narration tail when grok exits 0 with no file', async () => {@@ -250,6 +269,111 @@ describe('videoGen/grok — harvest and finalize', () => {});describe('videoGen/grok — cancel', () => {+ it('retains cancel escalation and maintenance ownership after a live error until close and all cleanup finish', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ const scratchCleanup = Promise.withResolvers();+ const uploadCleanup = Promise.withResolvers();+ const jobId = 'grok-maintenance-live-error';+ const upload = join(TEST_ROOT, 'source.png');+ await writeFile(upload, 'synthetic reference');+ rmGuarded.mockImplementationOnce(async (...args) => {+ await scratchCleanup.promise;+ return realFiles.rmGuarded(...args);+ });+ unlinkGuarded.mockImplementationOnce(async (...args) => {+ await uploadCleanup.promise;+ return realFiles.unlinkGuarded(...args);+ });+ const permit = fixture.admission.admit('media', jobId);+ let settlement;+ const failed = vi.fn(() => { settlement = permit.finish(); });+ videoGenEvents.on('failed', failed);+ let closing;+ try {+ await permit.run(() => grok.generateVideo({ jobId, prompt: 'synthetic motion', uploadedTempPath: upload }));+ const child = spawnCalls[0].child;+ child.pid = 101;+ fixture.admission.begin({ reason: 'Drain renderer', owner: 'Operator' });+ child.emit('error', new Error('Signal transport failed'));+ expect(failed).not.toHaveBeenCalled();+ expect(grok.getActiveJob()).toMatchObject({ generationId: jobId });+ // Exercise POSIX escalation without changing the journal's native+ // filesystem behavior (Windows cannot fsync an opened directory).+ const restorePlatform = pinPlatform('darwin');+ try { expect(grok.cancel(jobId)).toBe(true); }+ finally { restorePlatform(); }+ await vi.advanceTimersByTimeAsync(5000);+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');+ expect(fixture.admission.status().state).toBe('draining');+ expect(rmGuarded).not.toHaveBeenCalled();++ closing = closeChild();+ await vi.waitFor(() => expect(unlinkGuarded).toHaveBeenCalledWith(upload));+ scratchCleanup.resolve();+ await vi.waitFor(() => expect(existsSync(scratchDirFor(jobId))).toBe(false));+ expect(failed).not.toHaveBeenCalled();+ expect(fixture.admission.status().state).toBe('draining');+ uploadCleanup.resolve();+ await closing;+ await settlement;+ expect(existsSync(upload)).toBe(false);+ expect(failed).toHaveBeenCalledTimes(1);+ expect(failed.mock.calls[0][0].error).toContain('Signal transport failed');+ expect(fixture.admission.status().state).toBe('ready');+ expect(grok.cancel(jobId)).toBe(false);+ child.emit('close', 1, null);+ expect(failed).toHaveBeenCalledTimes(1);+ } finally {+ scratchCleanup.resolve();+ uploadCleanup.resolve();+ if (!closing && spawnCalls[0] && failed.mock.calls.length === 0) closing = closeChild();+ await closing;+ await permit.finish();+ vi.useRealTimers();+ }+ });++ it('waits for cleanup once when a failed spawn emits both error and close', async () => {+ const cleanup = Promise.withResolvers();+ rmGuarded.mockImplementationOnce(async (...args) => {+ await cleanup.promise;+ return realFiles.rmGuarded(...args);+ });+ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const job = await grok.generateVideo({ prompt: 'synthetic motion' });+ const child = spawnCalls[0].child;+ try {+ child.emit('error', new Error('spawn ENOENT'));+ child.emit('close', -2, null);+ await flush();+ expect(failed).not.toHaveBeenCalled();+ cleanup.resolve();+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ expect(existsSync(scratchDirFor(job.jobId))).toBe(false);+ expect(rmGuarded).toHaveBeenCalledTimes(1);+ } finally {+ cleanup.resolve();+ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ }+ });++ it.each(['scratch', 'upload'])('retains a recovery blocker when %s cleanup fails', async target => {+ const jobId = `grok-maintenance-${target}-cleanup`;+ const upload = join(TEST_ROOT, 'source.png');+ await writeFile(upload, 'synthetic reference');+ (target === 'scratch' ? rmGuarded : unlinkGuarded).mockRejectedValueOnce(Object.assign(new Error('Cleanup denied'), { code: 'EACCES' }));+ const permit = fixture.admission.admit('media', jobId);+ await permit.run(() => grok.generateVideo({ jobId, prompt: 'synthetic motion', uploadedTempPath: upload }));+ fixture.admission.begin({ reason: 'Drain renderer', owner: 'Operator' });+ await closeChild();+ await permit.finish();+ expect(fixture.admission.status()).toMatchObject({+ state: 'draining', blockers: [expect.objectContaining({ resource: jobId, unsettled: true })],+ });+ await realFiles.rmGuarded(scratchDirFor(jobId), { recursive: true, force: true });+ });+it('cancel() requires a jobId; cancel(jobId) SIGTERMs; cancelAll() sweeps', async () => {expect(() => grok.cancel()).toThrow(/requires a jobId/);const a = await grok.generateVideo({ prompt: 'one' });diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 8f4e63c01e..97d53a9e1b 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -5561,7 +5561,7 @@ describe('generateVideo — first render child dies during the accelerator hando});it('reports a spawn error raised in the same window, which no exit status records', async () => {- const child = makeSilentProc(202);+ const child = makeSilentProc(undefined);await render('first-child-error-in-handoff', child, () => child.error(new Error('detached spawn produced no PID')));// exitCode/signalCode stay null on a spawn failure — only a subscriber sees it.diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.jsindex 83f58f705d..f8f22fa1d3 100644--- a/server/services/videoGen/spawnWatch.js+++ b/server/services/videoGen/spawnWatch.js@@ -1,6 +1,7 @@/** Render-child spawning, supervision, retry, and terminal finalization. */import { spawn } from '../../lib/childProcess.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';import { watch as fsWatch } from 'fs';import { readFile } from 'fs/promises';import { join } from 'path';@@ -71,6 +72,11 @@ export async function spawnAndWatchVideo({steps: actualSteps,videoGenSettings,}) {+ const retainOwnership = () => {+ // Chained renders use child job IDs; their ambient owner is the outer job.+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ };const heavyClaim = await claimHeavyLocalJob({ kind: 'local video generation', id: jobId });if (!heavyClaim.ok) {videoJobState.jobs.delete(jobId);@@ -78,8 +84,10 @@ export async function spawnAndWatchVideo({await rmGuarded(stepwiseDir, { recursive: true, force: true });throw new ServerError(heavyClaim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: heavyClaim.holder } });}- const releaseHeavyClaim = () => heavyClaim.release()- .catch((err) => console.error(`❌ Video generation claim release [${jobId.slice(0, 8)}]: ${err.message}`));+ const releaseHeavyClaim = () => heavyClaim.release().catch((err) => {+ retainOwnership();+ console.error(`❌ Video generation claim release [${jobId.slice(0, 8)}]: ${err.message}`);+ });// The first render child. Named apart from the `proc` each wireRenderChild()// call binds, so a relaunch cannot be confused with the original.let firstProc;@@ -101,14 +109,26 @@ export async function spawnAndWatchVideo({let previewReading = false;let previewPending = false;let previewClosed = false;+ let previewCleanup;const cleanupStepwisePreview = () => {- if (previewClosed) return;+ if (previewClosed) return previewCleanup;previewClosed = true;if (previewWatcher) {try { previewWatcher.close(); } catch { /* already closed */ }previewWatcher = null;}- void rmGuarded(stepwiseDir, { recursive: true, force: true });+ previewCleanup = Promise.resolve().then(() => rmGuarded(stepwiseDir, { recursive: true, force: true })).catch(error => {+ if (error.code !== 'ENOENT') retainOwnership();+ });+ return previewCleanup;+ };+ const cleanupFailedRender = async () => {+ const results = await Promise.allSettled([+ releaseHeavyClaim(),+ cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true }),+ cleanupStepwisePreview(),+ ]);+ if (results.some(result => result.status === 'rejected')) retainOwnership();};const processLatestPreview = async () => {if (previewClosed) return;@@ -228,30 +248,39 @@ export async function spawnAndWatchVideo({// double-release the accelerator claim, double-clean the temp files, or emit// two terminal events if the real event lands as well.let closeHandled = false;+ let childError;// Without an 'error' handler, a missing/non-executable pythonPath would// crash the server with an unhandled error event. Named (rather than an// inline arrow) so the caller can replay an 'error' this child emitted// before it was wired.const handleChildError = (err) => {if (closeHandled) return;+ // A failed signal/transport operation can emit error for a live child.+ // Keep ownership until close, rather than interpreting it as spawn failure.+ if (proc.pid && proc.exitCode == null && proc.signalCode == null) {+ childError = err;+ return;+ }closeHandled = true;clearCompletionWatchdog();job.status = 'error';const reason = `Failed to spawn ${bin}: ${err.message}`;console.error(`❌ Video generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);- broadcastSse(job, { type: 'error', error: reason });- videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });videoJobState.activeProcess = null;if (displaySlept) wakeDisplayForVideo(videoGenSettings, 'Video generation');- void releaseHeavyClaim();// Spawn failed, so proc.on('close') will never fire — clean up every// temp file we own here, including the multipart upload, otherwise// ENOENT/permission errors leak files in os.tmpdir().// Defensive cleanup includes audio passed directly without the route's// uploadedTempPaths tracking. Duplicate unlinks remain harmless.- void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });- cleanupStepwisePreview();- closeJobAfterDelay(videoJobState.jobs, jobId);+ return cleanupFailedRender().then(() => {+ broadcastSse(job, { type: 'error', error: reason });+ videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });+ closeJobAfterDelay(videoJobState.jobs, jobId);+ }).catch(error => {+ retainOwnership();+ console.error(`❌ Video spawn cleanup failed [${jobId.slice(0, 8)}]: ${error.message}`);+ });};let missingPyModule = null;@@ -389,7 +418,7 @@ export async function spawnAndWatchVideo({// before emitting the terminal completion event: an extend chain starts its// next child from that event and must be able to acquire the machine claim.await releaseHeavyClaim();- cleanupStepwisePreview();+ await cleanupStepwisePreview();// Wrap the whole teardown so a throw from finalizeGeneratedVideo (history// save, thumbnail, file move) can't leak as an unhandled rejection — on// Node ≥15 that kills the process AND strands the media job `running` with@@ -402,6 +431,7 @@ export async function spawnAndWatchVideo({// Cleanup internally generated resize/reference files, route-staged// uploads, and direct-call audio through the same ownership-aware helper.await cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });+ if (childError) throw childError;// A PortOS-fired completion-watchdog SIGKILL is a SUCCESS when the// output file is already on disk and non-empty: the render wrote its@@ -494,6 +524,7 @@ export async function spawnAndWatchVideo({}}} catch (err) {+ if (err !== childError) retainOwnership();// Finalize/teardown threw — fail the job loudly instead of crashing the// process. The job may already be partway through finalize, so force the// error state and emit the terminal event the client is waiting on.@@ -542,7 +573,7 @@ export async function spawnAndWatchVideo({if (!earlyExit) return;for (const { stream, chunk } of earlyExit.output || []) proc[stream].emit('data', chunk);console.log(`⚠️ video render child exited before it was wired [${jobId.slice(0, 8)}]`);- if (earlyExit.type === 'error') handleChildError(earlyExit.error);+ if (earlyExit.type === 'error') await handleChildError(earlyExit.error);else if (earlyExit.type === 'close') await handleChildClose(earlyExit.code, earlyExit.signal);};return replayEarlyExit;@@ -570,6 +601,9 @@ export async function spawnAndWatchVideo({// path and must not replace the real error with its own.const stopAbandonedChild = (child) => {if (!child) return;+ // This child has no completion listener. A kill request cannot certify+ // its physical exit, so only explicit recovery can clear this ownership.+ if (child.pid && child.exitCode == null && child.signalCode == null) retainOwnership();try {child.kill('SIGTERM');} catch (err) {@@ -676,14 +710,12 @@ export async function spawnAndWatchVideo({const abandonBeforeWiring = async (err) => {stopAbandonedChild(firstProc);if (videoJobState.activeProcess === firstProc) videoJobState.activeProcess = null;- await releaseHeavyClaim();+ await cleanupFailedRender();job.status = 'error';const reason = err.message || 'Video generation failed before the render child was wired';console.error(`❌ Video generation setup error [${jobId.slice(0, 8)}]: ${reason}`);broadcastSse(job, { type: 'error', error: reason });videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });- void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });- cleanupStepwisePreview();closeJobAfterDelay(videoJobState.jobs, jobId);};diff --git a/server/services/videoGen/spawnWatch.test.js b/server/services/videoGen/spawnWatch.test.jsindex c3143f6761..8fb5e5e20c 100644--- a/server/services/videoGen/spawnWatch.test.js+++ b/server/services/videoGen/spawnWatch.test.js@@ -191,14 +191,23 @@ describe('spawnAndWatchVideo claim lifecycle', () => {expect(mocks.history).toEqual([]);});- it('handles error followed by close exactly once, including upload and preview cleanup', async () => {+ it('waits for physical close and upload/preview cleanup after an error on a live child', async () => {+ const cleanup = Promise.withResolvers();+ params.cleanupTempFiles.mockReturnValue(cleanup.promise);await spawnAndWatchVideo(params);child.emit('error', new Error('renderer pipe failed'));+ await vi.advanceTimersByTimeAsync(0);+ expect(failed).not.toHaveBeenCalled();+ expect(mocks.release).not.toHaveBeenCalled();+ expect(videoJobState.activeProcess).toBe(child);await closeChild(1);+ expect(failed).not.toHaveBeenCalled();+ cleanup.resolve();+ await vi.advanceTimersByTimeAsync(0);expectCleanup();expect(job.status).toBe('error');- expect(failed).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ error: 'Failed to spawn python3: renderer pipe failed' }));+ expect(failed).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ error: 'renderer pipe failed' }));expect(completed).not.toHaveBeenCalled();expect(mocks.history).toEqual([]);});diff --git a/server/services/videoGen/upscaleJob.js b/server/services/videoGen/upscaleJob.jsindex 420f6917bd..158a6ae9e9 100644--- a/server/services/videoGen/upscaleJob.js+++ b/server/services/videoGen/upscaleJob.js@@ -25,6 +25,7 @@ import { join } from 'path';import { tmpdir } from 'os';import { PATHS, unlinkGuarded } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';+import { maintenance } from '../../lib/maintenanceAdmission.js';import {safeUnder, generateThumbnail, probeVideoStreamInfo, probeVideoDuration,} from '../../lib/ffmpeg.js';@@ -277,6 +278,7 @@ const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {proc.stderr.on('data', (c) => errReader.push(c));return new Promise((resolve) => {let settled = false;+ let processError;const settle = (result) => {if (settled) return;settled = true;@@ -284,8 +286,12 @@ const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {errReader.flush();resolve(result);};- proc.on('error', (err) => settle({ ok: false, reason: `spawn failed: ${err.message}` }));+ proc.on('error', (err) => {+ processError = err;+ if (!proc.pid) settle({ ok: false, reason: `spawn failed: ${err.message}` });+ });proc.on('close', (code, signal) => {+ if (processError) { settle({ ok: false, reason: `upscale process failed: ${processError.message}` }); return; }if (code === 0) { settle({ ok: true, ...provenance }); return; }const tail = stderrTail.slice(-4).join(' | ');const how = signal ? `killed (${signal})` : `exit ${code}`;@@ -313,6 +319,17 @@ export async function runVideoUpscale({const scratch = [];let deliverablePath = null;let thumbnailPath = null;+ let result = null;+ let failureReason;+ const removeOwnedFile = async path => {+ if (!path) return;+ await unlinkGuarded(path).catch(error => {+ if (error.code === 'ENOENT') return;+ maintenance.markCurrentUnsettled();+ maintenance.markResourceUnsettled('media', jobId);+ console.error(`❌ Video upscale cleanup failed [${jobId.slice(0, 8)}]: ${error.message}`);+ });+ };try {// Re-read the row rather than trusting the enqueue-time snapshot: a queued// job can wait behind a long render, and the user may have deleted or@@ -460,20 +477,21 @@ export async function runVideoUpscale({};await mutateVideoHistory((h) => { h.unshift(newEntry); return h; });console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height}, ${Math.round((newEntry.renderMs ?? 0) / 1000)}s)`);- videoGenEvents.emit('completed', { generationId: jobId, ...newEntry });- return newEntry;+ result = newEntry;} catch (err) {// The history row is written LAST, so nothing here can orphan one — only a// partial file can exist, and it is removed before the failure is reported.for (const path of [deliverablePath, thumbnailPath]) {- if (path) await unlinkGuarded(path).catch(() => {});+ await removeOwnedFile(path);}const reason = entry.canceled ? 'Canceled while running' : (err.message || 'Upscale failed');console.error(`❌ Video upscale ${entry.canceled ? 'canceled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);- videoGenEvents.emit('failed', { generationId: jobId, error: reason });- return null;+ failureReason = reason;} finally {- for (const path of scratch) await unlinkGuarded(path).catch(() => {});+ for (const path of scratch) await removeOwnedFile(path);activeUpscales.delete(jobId);}+ if (failureReason) videoGenEvents.emit('failed', { generationId: jobId, error: failureReason });+ else videoGenEvents.emit('completed', { generationId: jobId, ...result });+ return result;}diff --git a/server/services/videoGen/upscaleJob.test.js b/server/services/videoGen/upscaleJob.test.jsindex bb483d5983..055f11269d 100644--- a/server/services/videoGen/upscaleJob.test.js+++ b/server/services/videoGen/upscaleJob.test.js@@ -7,8 +7,11 @@ import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../../li// The lifecycle really creates and removes files, so PATHS must point at a temp// tree — the install's data/ is the developer's live gallery.-vi.mock('../../lib/fileUtils.js', async (importOriginal) =>- makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-upscale-job-') }));+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('portos-upscale-job-') }),+ unlinkGuarded: vi.fn(actual.unlinkGuarded) };+});afterAll(cleanupTempDataRoots);const state = vi.hoisted(() => ({@@ -24,6 +27,11 @@ const state = vi.hoisted(() => ({// Whether the fake runner writes the file it was told to produce.writesOutput: true,buildArgsCalls: [],+ admission: null,+}));+vi.mock('../../lib/maintenanceAdmission.js', async importOriginal => ({+ ...await importOriginal(),+ maintenance: new Proxy({}, { get: (_target, property) => state.admission[property] }),}));vi.mock('./upscaleVideo.js', () => ({@@ -86,7 +94,9 @@ const { enqueueJob } = await import('../mediaJobQueue/index.js');const { mutateVideoHistory } = await import('./history.js');const { padSourceForUpscale, finalizeUpscaleOutput } = await import('./upscaleFfmpeg.js');const { videoGenEvents } = await import('./events.js');-const { PATHS } = await import('../../lib/fileUtils.js');+const { PATHS, unlinkGuarded } = await import('../../lib/fileUtils.js');+const realFiles = await vi.importActual('../../lib/fileUtils.js');+const { createMaintenanceAdmission } = await import('../../lib/maintenanceAdmission.js');const { LTX_UPSCALE_JOB_KIND, LTX_PROVENANCE_FIELDS } = await import('./upscalePlan.js');const SOURCE_ID = '11111111-1111-4111-8111-111111111111';@@ -136,6 +146,9 @@ const makeChild = () => {const child = new EventEmitter();child.stdout = new EventEmitter();child.stderr = new EventEmitter();+ child.pid = 101;+ child.exitCode = null;+ child.signalCode = null;child.kill = vi.fn(() => { child.emit('close', null, 'SIGTERM'); return true; });return child;};@@ -164,6 +177,8 @@ const sourcePath = () => join(PATHS.videos, SOURCE_FILE);// Drive the fake runner: it writes the file the real one would, then exits.const finishChild = (code = 0, signal = null) => {if (state.writesOutput && code === 0) writeFileSync(renderOutputPath, 'rendered');+ state.child.exitCode = code;+ state.child.signalCode = signal;state.child.emit('close', code, signal);};@@ -175,7 +190,10 @@ const runWith = async (drive, params = {}) => {return run;};+let admissionFixture = 0;beforeEach(() => {+ state.admission = createMaintenanceAdmission(join(PATHS.data, 'admission-fixtures', String(admissionFixture++)));+ unlinkGuarded.mockReset().mockImplementation(realFiles.unlinkGuarded);mkdirSync(PATHS.videos, { recursive: true });writeFileSync(sourcePath(), 'source-bytes');state.history = [sourceRow()];@@ -491,6 +509,53 @@ describe('runVideoUpscale — failure and cancellation leave the source alone',expect(failures[0].error).toMatch(/exit 3/);});+ it('retains a live errored child and publishes failure only after close and scratch cleanup', async () => {+ const cleanup = Promise.withResolvers();+ unlinkGuarded.mockImplementationOnce(async (...args) => { await cleanup.promise; return realFiles.unlinkGuarded(...args); });+ state.child.kill.mockReturnValue(true);+ const permit = state.admission.admit('media', JOB_ID);+ const failed = vi.fn();+ videoGenEvents.on('failed', failed);+ const run = permit.run(() => runVideoUpscale(jobParams())).finally(() => permit.finish());+ try {+ await vi.waitFor(() => expect(state.child.listenerCount('close')).toBeGreaterThan(0));+ state.admission.begin({ reason: 'Drain upscale', owner: 'Operator' });+ state.child.emit('error', new Error('Signal transport failed'));+ await Promise.resolve();+ expect(failed).not.toHaveBeenCalled();+ expect(unlinkGuarded).not.toHaveBeenCalled();+ expect(cancel(JOB_ID)).toBe(true);+ finishChild(1);+ await vi.waitFor(() => expect(unlinkGuarded).toHaveBeenCalledWith(renderOutputPath));+ expect(failed).not.toHaveBeenCalled();+ expect(state.admission.status().state).toBe('draining');+ cleanup.resolve();+ await run;+ expect(failed).toHaveBeenCalledTimes(1);+ expect(state.admission.status().state).toBe('ready');+ expect(cancel(JOB_ID)).toBe(false);+ } finally {+ cleanup.resolve();+ finishChild(1);+ await run;+ videoGenEvents.off('failed', failed);+ }+ });++ it('keeps a recovery blocker when owned scratch cleanup fails', async () => {+ unlinkGuarded.mockRejectedValueOnce(Object.assign(new Error('Cleanup denied'), { code: 'EACCES' }));+ const permit = state.admission.admit('media', JOB_ID);+ const run = permit.run(() => runWith(() => {+ state.admission.begin({ reason: 'Drain upscale', owner: 'Operator' });+ finishChild(1);+ }));+ await run;+ await permit.finish();+ expect(state.admission.status()).toMatchObject({+ state: 'draining', blockers: [expect.objectContaining({ resource: JOB_ID, unsettled: true })],+ });+ });+it('fails when the runner exits clean but writes nothing', async () => {state.writesOutput = false;await runWith(() => finishChild(0));diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex 6349fd9293..b5e5a3472c 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -1,3 +1,4 @@+import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Video Timeline — non-linear editor backend.*@@ -593,7 +594,13 @@ export function cancelRender(jobId) {return true;}-export async function renderProject(projectId, { posterSec } = {}) {+export async function renderProject(projectId, options = {}) {+ const permit = maintenance.admit('timeline', projectId, { continuation: true, parentKinds: ['media'] });+ try { return await permit.run(() => renderAdmittedProject(projectId, options, permit)); }+ catch (err) { permit.finish(); throw err; }+}++async function renderAdmittedProject(projectId, { posterSec } = {}, permit) {const project = await getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });@@ -688,6 +695,7 @@ export async function renderProject(projectId, { posterSec } = {}) {broadcastSse(job, { type: 'error', error: reason });projectRenders.delete(projectId);closeJobAfterDelay(jobs, jobId);+ permit.finish();},onClose: async (code, signal) => {// Runs outside the request lifecycle — an uncaught throw from@@ -707,10 +715,11 @@ export async function renderProject(projectId, { posterSec } = {}) {// A cancel is a user action (stdout); a non-zero exit is a failure (#7945).const logClose = canceled ? console.log : console.error;logClose(`${canceled ? '🛑' : '❌'} Timeline render ${canceled ? 'cancelled' : 'failed'} [${jobId.slice(0, 8)}]: ${reason}`);- await unlink(outputPath).catch(() => {});+ await unlink(outputPath).catch((err) => { if (err.code !== 'ENOENT') maintenance.markCurrentUnsettled(); });broadcastSse(job, { type: canceled ? 'canceled' : 'error', error: reason });projectRenders.delete(projectId);closeJobAfterDelay(jobs, jobId);+ permit.finish();return;}job.status = 'complete';@@ -742,7 +751,9 @@ export async function renderProject(projectId, { posterSec } = {}) {broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });projectRenders.delete(projectId);closeJobAfterDelay(jobs, jobId);+ permit.finish();} catch (err) {+ permit.markUnsettled();const reason = `Post-render failed: ${err.message}`;job.status = 'error';job.lastError = reason;@@ -750,6 +761,7 @@ export async function renderProject(projectId, { posterSec } = {}) {broadcastSse(job, { type: 'error', error: reason });projectRenders.delete(projectId);closeJobAfterDelay(jobs, jobId);+ permit.finish();}},});diff --git a/server/vitest.setup.js b/server/vitest.setup.jsindex b36193ab91..a2ca2e0676 100644--- a/server/vitest.setup.js+++ b/server/vitest.setup.js@@ -52,6 +52,8 @@import { vi, afterAll } from 'vitest';import { rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';import { mockNoPeers } from './lib/mockPathsDataRoot.js';// The server intentionally logs expected error paths, lifecycle transitions,@@ -88,3 +90,26 @@ afterAll(() => {try { rmSync(dir, { recursive: true, force: true }); } catch { /* already gone */ }}});++// Exercise the real gate in workflow tests, with private test-owned journals.+// Register teardown in setup (not inside a lazy mock factory); resetModules can+// otherwise create a journal after the file's teardown hooks were collected.+const maintenanceTestRoots = [];+afterAll(() => {+ for (const entry of maintenanceTestRoots.splice(0)) {+ entry.closed = true;+ entry.io.rmSync(entry.root, { recursive: true, force: true });+ }+});+vi.mock('./lib/maintenanceAdmission.js', async (importOriginal) => {+ const actual = await importOriginal();+ const io = await vi.importActual('node:fs');+ const { randomUUID } = await vi.importActual('node:crypto');+ const root = io.mkdtempSync(join(tmpdir(), 'maintenance-workflow-'));+ const entry = { io, root, closed: false };+ maintenanceTestRoots.push(entry);+ return { ...actual, maintenance: actual.createMaintenanceAdmission(root, { io, makeId: randomUUID, assertWrite: path => {+ // Domain suites mock fs/UUIDs wholesale. Keep the journal private and real.+ if (entry.closed || path !== join(root, 'workflow-maintenance')) throw new Error('Unexpected maintenance test path');+ } }) };+});