Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: preserve and advance partial Deep audit checkpoints (#10603)
[._.]/41bcc45e70bd
diff --git a/docs/DEEP-AUDITS.md b/docs/DEEP-AUDITS.mdindex a601356abe..a0f06bfa69 100644--- a/docs/DEEP-AUDITS.md+++ b/docs/DEEP-AUDITS.md@@ -4,7 +4,7 @@ Deep is an audit depth, independent of **File issues** or **Audit and fix** deli## Run and resume-In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one server-assigned batch of one pass, not the whole audit. Batches contain at most 12 units and 96 distinct source paths; an indivisible larger unit is assigned alone and remains blocked if it cannot be substantively reviewed. Untouched units precede blocked units. The agent receives a compact assignment with pinned sources, prior evidence and relevant candidates; the full ledger remains available for targeted lookup. Batch limits never reduce the full coverage denominator. Delivery-only retries retain the full-scope challenge requirement and are not batched. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It may finish the current pass before moving to the next. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.+In an app's **Quality** tab, choose the categories, delivery policy, provider/model and **Audit depth → Deep**, then Run now. A launch performs one server-assigned batch of one pass, not the whole audit. Batches contain at most 12 units and 96 distinct source paths; an indivisible larger unit is assigned alone and remains blocked if it cannot be substantively reviewed. Untouched units precede blocked units, with feasible untouched units before indivisible oversized units. Blocked units rotate by attempt count regardless of size. The agent receives a compact assignment with pinned sources, prior evidence and relevant candidates; the full ledger remains available for targeted lookup. Batch limits never reduce the full coverage denominator. Delivery-only retries retain the full-scope challenge requirement and are not batched. A partial checkpoint stops the maintenance run. **Resume Deep audit** starts another invocation using the same coverage ledger. It may finish the current pass before moving to the next. Failed Deep tasks are parked rather than automatically retried. Completion keeps the task held until worktree cleanup finishes, then atomically parks it with any surviving branch/worktree pointer. Explicit resume waits for that handoff and reuses the persisted audit instructions. Recovery of an interrupted invocation also parks it for explicit resume instead of treating a commit or retry budget as permission to continue. Boot and reading status do not launch work.An app's **Automation** tab also exposes depth separately from delivery. An explicitly configured schedule can start a Deep audit; a partial task then parks and blocks further automatic dispatch for that app/category. Use Run Now to resume explicitly. Its app/category/delivery identity keeps the same ledger across those invocations. Custom agent jobs accept `taskMetadata.auditDepth: "deep"` and an optional `deepAuditId` for an explicitly selected checkpoint. A custom job without an audit category uses the code-quality coverage category. Different apps, categories and delivery modes cannot share a checkpoint.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 319c937ab4..cade412928 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -930,3 +930,22 @@ pointers, so edits replace staged work. Successful document publication removesthe checkpoint. It is regenerable runtime state rather than searchable projectmetadata, never federates, and the existing anchored `/cache/` backup exclusioncovers it. An absent checkpoint starts empty; no seed or migration is required.++### On-demand preparation handoffs++`data/cos/task-schedule.json` also holds `onDemandHandoffs`, keyed by request ID,+for asynchronous quota-burn and maintenance task preparation. Moving a request+out of `onDemandRequests` and recording its `preparing` owner/token happen in the+same schedule write queue. The exact owner records accepted task ID or refusal;+these receipts are durable control state, not disposable preflight UI telemetry.+Existing schedules need no migration; an absent map means no recorded handoffs.++An owner nonce fences settlement; a recorded owner PID must be proven absent+(`ESRCH`) before drain and maintenance/quota reconciliation settle a claim+against persisted request-stamped tasks; missing tasks become `interrupted`,+never automatically requeued. Unreadable task storage leaves the claim untouched.+Live/reused PIDs, missing identities and ambiguous probe errors remain held.+No age-based expiration is used. Refused/interrupted maintenance work stops until+explicit resume acknowledges the outcome. A legacy Deep queued request with no+queue, task, or receipt likewise stops for explicit resume. Repeating resume on+an already-running maintenance run does not dispatch or re-evaluate it.diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.jsindex c2d60ae735..6ec822dd21 100644--- a/server/lib/auditQuality.js+++ b/server/lib/auditQuality.js@@ -55,7 +55,7 @@ This contract overrides narrower slice-selection or ranking advice in the missio6. Score the worst finding's severity separately on 1–10: 1–3 minor localized impact, 4–6 material recurring cost, 7–8 major workflow/reliability impact, 9–10 critical data/security/availability failure. Use 0 only when no material finding was verified. List this severity for every finding in the narrative.7. Include exactly one single-line QUALITY_AUDIT_JSON: {...} in your completion sentinel summary AND final response, with no secrets or personal data. Replace the example values with observed evidence. The category is fixed to this task; do not rate other categories. Keep ordinary completion/PR instructions and summaries too.QUALITY_AUDIT_JSON: {"version":1,"category":"${category}","score":null,"worstSeverity":0,"coverage":"unavailable","confidence":"low","summary":"Explain the assessment and strongest evidence","scannedFiles":0,"totalFiles":0}-Allowed coverage: broad, partial, unavailable, not-applicable. Allowed confidence: low, medium, high. scannedFiles counts files actually included in the category signal scan; totalFiles is the eligible inventory. Broad requires the whole inventory to be scanned (deep review remains bounded). Partial scores are provisional and excluded from the overall score. If unavailable or not-applicable, score must be null and explain why. Even a zero-finding audit returns this assessment.`;+Allowed coverage: broad, partial, unavailable, not-applicable. Allowed confidence: low, medium, high. scannedFiles counts files actually included in the category signal scan; totalFiles is the eligible inventory. Broad requires the whole inventory to be scanned (deep review remains bounded). Partial assessments are excluded from the overall score. For partial coverage, use score:null when the inspected evidence cannot support a category score; explain why rather than inventing one. A numeric partial score is provisional. If unavailable or not-applicable, score must be null and explain why. Even a zero-finding audit returns this assessment.`;}export const appQualityQuerySchema = z.object({ includeQuality: z.enum(['true', 'false']).optional() });@@ -80,7 +80,7 @@ export const auditQualityReportSchema = z.object({scannedFiles: z.number().int().nonnegative(),totalFiles: z.number().int().nonnegative(),}).strict().refine(r => r.scannedFiles <= r.totalFiles)- .refine(r => ['unavailable', 'not-applicable'].includes(r.coverage) ? r.score === null : r.score !== null && r.scannedFiles > 0)+ .refine(r => ['unavailable', 'not-applicable'].includes(r.coverage) ? r.score === null : r.scannedFiles > 0 && (r.coverage === 'partial' || r.score !== null)).refine(r => r.coverage !== 'broad' || (r.totalFiles > 0 && r.scannedFiles === r.totalFiles));export function parseAuditQualityReport(summary, category) {diff --git a/server/lib/deepAudit.js b/server/lib/deepAudit.jsindex 084456957e..f1c46046a4 100644--- a/server/lib/deepAudit.js+++ b/server/lib/deepAudit.js@@ -95,6 +95,9 @@ export function assignDeepAuditAttempt(ledger, agentId) {const eligible = [...(deliveryOnly ? ledger.units : remaining)];// Untouched work first, then least-assigned retries: persistent blockers cannot starve peers.eligible.sort((a, b) => Number(Boolean(a.evidence[pass])) - Number(Boolean(b.evidence[pass]))+ // Review feasible untouched units before indivisible oversized ones. Once blocked,+ // all units rotate by attempt count rather than permanently preferring small blockers.+ || (!a.evidence[pass] && !b.evidence[pass] ? Number(a.files.length > 96) - Number(b.files.length > 96) : 0)|| (assignedCounts.get(a.id) || 0) - (assignedCounts.get(b.id) || 0));const unitIds = [];const files = new Set();diff --git a/server/services/appQuality.test.js b/server/services/appQuality.test.jsindex 88592caa0a..0c3c4a798d 100644--- a/server/services/appQuality.test.js+++ b/server/services/appQuality.test.js@@ -165,3 +165,20 @@ it('retains historical scores without hindsight, expires old evidence and exposeexpect(points.find(p => p.date === '2026-09-09')).toMatchObject({ score: 70, ratedCategories: 1 });expect(points.at(-1)).toMatchObject({ score: 80, ratedCategories: 2 });});+++it('records honest unscored partial Deep evidence without inventing a score or contributing to overall quality', async () => {+ const partial = report({ category: 'observability', score: null, worstSeverity: 0, coverage: 'partial', confidence: 'low',+ summary: '169 assigned files signal-scanned; substantive review incomplete and category score unavailable.', scannedFiles: 169, totalFiles: 10636 });+ const query = vi.fn().mockResolvedValue({ rows: [] });+ const run = { task: { ...task, metadata: { ...task.metadata, auditDepth: 'deep' } }, taskType: 'observability',+ agentId: 'agent-partial', workspacePath: '/repo', success: true, assessedAt };+ expect(await recordAuditQuality(run, { readFile: async () => sentinel(partial), query, ensureSchema: vi.fn() })).toBe(true);+ expect(JSON.parse(query.mock.calls[0][1][4])).toEqual(partial);+ const summary = summarizeAppQuality([{ category: 'observability', report: partial, assessedAt, agentId: 'agent-partial' }], Date.parse(assessedAt));+ expect(summary).toMatchObject({ score: null, ratedCategories: 0 });+ expect(summary.categories.find(category => category.id === 'observability')).toMatchObject({ score: null, coverage: 'partial' });+ expect(parseAuditQualityReport(sentinel({ ...partial, coverage: 'broad', scannedFiles: 10636 }), 'observability')).toBeNull();+ expect(parseAuditQualityReport(sentinel({ ...partial, scannedFiles: 0 }), 'observability')).toBeNull();+ expect(auditQualityInstructions('observability')).toContain('For partial coverage, use score:null');+});diff --git a/server/services/cosIdleReviewParity.test.js b/server/services/cosIdleReviewParity.test.jsindex 820245a5f6..1f8d13a90b 100644--- a/server/services/cosIdleReviewParity.test.js+++ b/server/services/cosIdleReviewParity.test.js@@ -61,6 +61,9 @@ vi.mock('./appActivity.js', async (importActual) => ({bindAppReviewAgent: async (appId, id) => { mocks.activity[appId] = { ...mocks.activity[appId], activeAgentId: id }; },updateAppActivity: async () => {},}));+// This suite exercises ordinary manual/idle admission; durable quota and+// maintenance handoffs are exercised by onDemandDrain.test.js.+vi.mock('./onDemandHandoff.js', () => ({ reconcileOnDemandHandoffs: async () => {} }));vi.mock('./taskSchedule.js', async (importActual) => ({...(await importActual()),loadSchedule: async () => ({ tasks: { 'code-quality': { enabled: true } } }),diff --git a/server/services/deepAudit.test.js b/server/services/deepAudit.test.jsindex 3ccf250dca..9265595aea 100644--- a/server/services/deepAudit.test.js+++ b/server/services/deepAudit.test.js@@ -128,12 +128,19 @@ describe('Deep coverage workflow across serialized restarts', () => {...Array.from({ length: 100 }, (_, i) => ({ path: `large/${i}.js`, blob, kind: 'blob' })),{ path: 'small/file.js', blob, kind: 'blob' },];+ await prepare('feasible');+ const initial = saved();+ expect(initial.attempts.feasible.unitIds).toHaveLength(3);+ expect(initial.units.filter(unit => initial.attempts.feasible.unitIds.includes(unit.id))+ .every(unit => unit.subsystem === 'small')).toBe(true);+ report = JSON.stringify(payload('feasible'));+ expect(await finish('feasible')).toMatchObject({ satisfiedPasses: 3, requiredPasses: 24, complete: false });await prepare('oversized');expect(saved().attempts.oversized.unitIds).toHaveLength(1);const first = saved().attempts.oversized.unitIds[0];report = JSON.stringify(payload('oversized', { units: payload('oversized').units.map(unit => ({ ...unit, status: 'blocked' })) }));await finish('oversized');- for (const id of ['second', 'third', 'small']) {+ for (const id of ['second', 'third']) {await prepare(id);expect(saved().attempts[id].unitIds).not.toContain(first);report = JSON.stringify(payload(id));diff --git a/server/services/htmlComposition/ownedBrowser.js b/server/services/htmlComposition/ownedBrowser.jsindex af6776752a..dd7c52f3b7 100644--- a/server/services/htmlComposition/ownedBrowser.js+++ b/server/services/htmlComposition/ownedBrowser.js@@ -34,6 +34,11 @@ export async function launchCompositionBrowser({ signal, startupMs = 20000, shutlet closed = false;let spawned = false;let closing;+ let profileCleanup;+ let terminationStarted;+ const termination = { term: 'not-attempted', kill: 'not-attempted', error: 'none' };+ const safeSignalError = error => ['EPERM', 'ESRCH', 'EINVAL', 'ENOSYS'].includes(error?.code) ? error.code : 'other';+ const cleanupProfile = () => profileCleanup ??= removeProfile(profile);let closeResolve;const childClosed = new Promise(resolve => { closeResolve = resolve; });const onExit = () => {@@ -42,21 +47,48 @@ export async function launchCompositionBrowser({ signal, startupMs = 20000, shut// Release our pipe without signaling unrelated or discovered processes.proc?.stderr?.destroy();};- const onClose = () => { closed = true; closeResolve(); };+ const onClose = () => {+ closed = true;+ // A deadline can reject close() before the OS reports exit. Retain ownership+ // until the eventual close event and remove only this child's profile then.+ cleanupProfile().catch(error => console.error(`❌ Composition browser profile cleanup failed (${safeSignalError(error)})`));+ closeResolve();+ };// Child 'error' may also be emitted by kill(). Keep a listener until close.- const onError = () => { if (!spawned && !proc?.pid) { onExit(); onClose(); } };+ const onError = error => {+ termination.error = safeSignalError(error);+ if (!spawned && !proc?.pid) { onExit(); onClose(); }+ };const close = () => closing ??= (async () => {signal?.removeEventListener('abort', abort);let escalation;let deadline;try {if (proc && !closed) {- if (!exited) escalation = killWithEscalation(proc, {+ terminationStarted = performance.now();+ const tracked = {+ get exitCode() { return proc.exitCode; },+ get signalCode() { return proc.signalCode; },+ kill(signal) {+ const key = signal === 'SIGTERM' ? 'term' : 'kill';+ termination[key] = 'attempted';+ try {+ const accepted = proc.kill(signal);+ termination[key] = accepted ? 'accepted' : 'refused';+ return accepted;+ } catch (error) {+ termination.error = safeSignalError(error);+ termination[key] = 'threw';+ throw error;+ }+ },+ };+ if (!exited) escalation = killWithEscalation(tracked, {label: 'Composition browser', delayMs: Math.min(1000, shutdownMs / 2),stillRunning: () => !exited,});await Promise.race([childClosed, new Promise((_, reject) => {- deadline = setTimeout(() => reject(new Error(`Composition browser cleanup exceeded its deadline (exit=${exited}, stdioClosed=${Boolean(proc.stderr?.destroyed)})`)), shutdownMs);+ deadline = setTimeout(() => reject(new Error(`Composition browser cleanup exceeded its deadline (exit=${exited}, stdioClosed=${Boolean(proc.stderr?.destroyed)}, term=${termination.term}, kill=${termination.kill}, signalError=${termination.error}, elapsedMs=${Math.round(performance.now() - terminationStarted)})`)), shutdownMs);})]);}} finally {@@ -65,7 +97,7 @@ export async function launchCompositionBrowser({ signal, startupMs = 20000, shut// Wait for the process and our pipe to close before removing its profile.if (!proc || closed) {proc?.removeListener('error', onError);- await removeProfile(profile);+ await cleanupProfile();}}})();diff --git a/server/services/htmlComposition/ownedBrowser.test.js b/server/services/htmlComposition/ownedBrowser.test.jsindex 0dd1d44db8..c6e66afbe5 100644--- a/server/services/htmlComposition/ownedBrowser.test.js+++ b/server/services/htmlComposition/ownedBrowser.test.js@@ -135,3 +135,19 @@ describe('owned composition capture browser lifecycle', () => {await expect(access(profile)).rejects.toThrow();});});+++it('retains the cleanup deadline failure but removes its owned profile after a late close', async () => {+ child.kill = vi.fn(() => true);+ const owner = await launchCompositionBrowser({ shutdownMs: 30 });+ await expect(owner.close()).rejects.toThrow(/cleanup exceeded its deadline.*term=accepted, kill=accepted, signalError=none/);+ expect(child.kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGTERM', 'SIGKILL']);+ await expect(access(profile)).resolves.toBeUndefined();+ child.signalCode = 'SIGKILL';+ child.emit('exit', null, 'SIGKILL');+ // Exit alone is insufficient: the child must release inherited stdio first.+ await expect(access(profile)).resolves.toBeUndefined();+ child.emit('close', null, 'SIGKILL');+ await vi.waitFor(async () => { await expect(access(profile)).rejects.toThrow(); });+ await expect(owner.close()).rejects.toThrow('cleanup exceeded its deadline');+});diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.jsindex a458b486bd..0b4684727e 100644--- a/server/services/maintenanceRun.js+++ b/server/services/maintenanceRun.js@@ -59,6 +59,7 @@ import { QUOTA_BURN_UNAVAILABLE } from '../lib/quotaBurnTaskRef.js';import { pluralize } from '../lib/textUtils.js';import { isQueuedContinuation } from '../lib/agentOutcome.js';import { cosEvents } from './cosEvents.js';+import { getOnDemandHandoffs } from './onDemandHandoff.js';import { getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';import { ACTIVE_TASK_STATUSES, probeSequenceDrain, sequenceStepShapeReason } from './quotaBurnSequence.js';@@ -273,15 +274,30 @@ export function updateMaintenanceStep(id, stepId, { providerId, model, effort =});}+// Prefer the exact request recorded by this run. Timestamp order is only a+// recovery fallback for a crash between enqueue and recording run.active.+function latestRunHandoff(run, handoffs) {+ if (run.active?.requestId) return handoffs[run.active.requestId] ?? null;+ return Object.values(handoffs).filter(claim => claim.request.burn?.maintenanceRunId === run.id)+ .sort((a, b) => b.claimedAt.localeCompare(a.claimedAt))[0] ?? null;+}+export async function resumeMaintenanceRun(id) {const resumed = await perRun(id, async () => {const run = await getMaintenanceRun(id);- if (!run || run.status === MAINTENANCE_RUN_STATUS.RUNNING) return run;+ if (!run || run.status === MAINTENANCE_RUN_STATUS.RUNNING) return { run, alreadyRunning: true };if (!run.taskTypes) await assertNoRunningRun(run.appId);console.log(`🧹 Maintenance run ${id} resumed`);- return patchRun(id, { status: MAINTENANCE_RUN_STATUS.RUNNING, finishedAt: null, reason: null });+ const prior = latestRunHandoff(run, await getOnDemandHandoffs());+ const acknowledgedRequestId = prior+ ? (['refused', 'interrupted'].includes(prior.status) ? prior.request.id : run.acknowledgedRequestId ?? null)+ : run.active?.requestId ?? run.acknowledgedRequestId ?? null;+ return { run: await patchRun(id, {+ status: MAINTENANCE_RUN_STATUS.RUNNING, finishedAt: null, reason: null, acknowledgedRequestId,+ }) };});- if (!resumed) return null;+ if (!resumed.run) return null;+ if (resumed.alreadyRunning) return { run: resumed.run, result: { dispatched: false, reason: 'Maintenance run is already running' } };const result = await evaluateOrHold(id);return { run: await getMaintenanceRun(id), result };}@@ -312,6 +328,10 @@ async function holdRun(id, run, reason, patch = null) {async function holdForOutstandingWork(id, run, ignoreTaskId) {const [{ getAllTasks }, { getOnDemandRequests }] = await Promise.all([import('./cosTaskStore.js'), import('./taskSchedule.js')]);+ // Observe queue -> handoff -> task in causal order: preparation may advance+ // between reads, but cannot disappear between two snapshots.+ const queued = (await getOnDemandRequests()).find((request) => request?.burn?.maintenanceRunId === id);+ const handoffs = await getOnDemandHandoffs();const { user, cos } = await getAllTasks();const ownTask = [...(user?.tasks || []), ...(cos?.tasks || [])].find((task) => task.id !== ignoreTaskId&& !(task.status === 'blocked' && run.deepCheckpointTaskIds?.includes(task.id))@@ -324,8 +344,20 @@ async function holdForOutstandingWork(id, run, ignoreTaskId) {active: { ...run.active, taskId: ownTask.id, agentId: agent?.id || run.active?.agentId || null, status: ownTask.status },});}- const queued = (await getOnDemandRequests()).find((request) => request?.burn?.maintenanceRunId === id);if (queued) return holdRun(id, run, `waiting for the CoS daemon to accept request ${queued.id} (${queued.taskType})`);+ const preparing = Object.values(handoffs).find(claim => claim.request.burn?.maintenanceRunId === id && claim.status === 'preparing');+ if (preparing) return holdRun(id, run, `waiting for request preparation ${preparing.request.id}`);+ const outcome = latestRunHandoff(run, handoffs);+ if (outcome && ['refused', 'interrupted'].includes(outcome.status) && run.acknowledgedRequestId !== outcome.request.id) {+ return holdRun(id, run, outcome.reason, { status: MAINTENANCE_RUN_STATUS.STOPPED, finishedAt: new Date().toISOString() });+ }+ // Pre-upgrade requests have no handoff receipt. Absence is uncertainty,+ // never proof that it is safe to automatically repeat a Deep invocation.+ if (run.auditDepth === 'deep' && run.active?.status === 'queued' && run.active.requestId && run.acknowledgedRequestId !== run.active.requestId && !outcome) {+ return holdRun(id, run, 'Request outcome is unavailable; resume explicitly.', {+ status: MAINTENANCE_RUN_STATUS.STOPPED, finishedAt: new Date().toISOString(),+ });+ }return null;}diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.jsindex 1a550e3dc7..49f1cf84e3 100644--- a/server/services/maintenanceRun.test.js+++ b/server/services/maintenanceRun.test.js@@ -13,6 +13,7 @@ const state = vi.hoisted(() => ({ tasks: [], requests: [], invoked: [], dispatch// verdict so these cases pin only the run's reaction to it.vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => ({ agents: {} })) }));vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ cos: { tasks: state.tasks }, user: { tasks: [] } })) }));+vi.mock('./onDemandHandoff.js', () => ({ getOnDemandHandoffs: vi.fn(async () => ({})) }));vi.mock('./taskSchedule.js', () => ({ getOnDemandRequests: vi.fn(async () => state.requests) }));vi.mock('./apps.js', () => ({ getAppById: vi.fn(async (id) => (id === 'app-1' ? { id, name: 'Example App' } : null)) }));// The registry a run's provider gate resolves against. `opencode-tui` belongs to@@ -493,3 +494,53 @@ it('Deep successful delivery alone never certifies discovery and deep proof alonawait __onMaintenanceAgentCompleted(agent);expect((await getMaintenanceRun(run.id)).completed).toEqual({});});+++it('makes concurrent and repeated resume calls idempotent while a request is preparing', async () => {+ const { run } = await start();+ await stopMaintenanceRun(run.id);+ const before = state.invoked.length;+ const results = await Promise.all([resumeMaintenanceRun(run.id), resumeMaintenanceRun(run.id)]);+ expect(results.filter(result => result.result.dispatched)).toHaveLength(1);+ expect(state.invoked).toHaveLength(before + 1);+ expect((await resumeMaintenanceRun(run.id)).result.dispatched).toBe(false);+ expect(state.invoked).toHaveLength(before + 1);+});++it('holds the scheduler during durable preparation, then stops on refusal until explicit resume', async () => {+ const { getOnDemandHandoffs } = await import('./onDemandHandoff.js');+ const { run } = await start();+ const claim = { request: { id: run.active.requestId, burn: { maintenanceRunId: run.id } }, claimedAt: new Date().toISOString(), status: 'preparing' };+ getOnDemandHandoffs.mockResolvedValue({ [claim.request.id]: claim });+ const before = state.invoked.length;+ expect((await evaluateMaintenanceRun(run.id)).dispatched).toBe(false);+ expect(state.invoked).toHaveLength(before);+ await stopMaintenanceRun(run.id);+ expect((await resumeMaintenanceRun(run.id)).result.dispatched).toBe(false);+ claim.status = 'interrupted'; claim.reason = 'Server restarted during preparation; resume explicitly.';+ await evaluateMaintenanceRun(run.id);+ expect((await getMaintenanceRun(run.id)).status).toBe('stopped');+ await __retryMaintenanceRuns();+ expect(state.invoked).toHaveLength(before);+ expect((await resumeMaintenanceRun(run.id)).result.dispatched).toBe(true);+ expect(state.invoked).toHaveLength(before + 1);+ getOnDemandHandoffs.mockResolvedValue({});+});+++it('acknowledges the exact active request when refusal timestamps tie', async () => {+ const { getOnDemandHandoffs } = await import('./onDemandHandoff.js');+ const { run } = await start();+ const claimedAt = new Date().toISOString();+ const makeReceipt = (id, reason) => ({ request: { id, burn: { maintenanceRunId: run.id } }, claimedAt, status: 'refused', reason });+ getOnDemandHandoffs.mockResolvedValue({+ 'older-request': makeReceipt('older-request', 'Older refusal'),+ [run.active.requestId]: makeReceipt(run.active.requestId, 'Active refusal'),+ });+ await evaluateMaintenanceRun(run.id);+ expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'stopped', reason: 'Active refusal' });+ const resumed = await resumeMaintenanceRun(run.id);+ expect(resumed.run.acknowledgedRequestId).toBe(run.active.requestId);+ expect(resumed.result.dispatched).toBe(true);+ getOnDemandHandoffs.mockResolvedValue({});+});diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.jsindex 3c43b44e39..62e211c6bb 100644--- a/server/services/onDemandDrain.js+++ b/server/services/onDemandDrain.js@@ -30,10 +30,11 @@*/import { emitLog } from './cosEvents.js';+import { claimOnDemandRequest, settleOnDemandRequest, reconcileOnDemandHandoffs } from './onDemandHandoff.js';import { getActiveApps } from './apps.js';import { loadState, saveState, withStateLock, isImprovementEnabled } from './cosState.js';import { markAppReviewCooldown, bindAppReviewAgent } from './appActivity.js';-import { isManualOnDemandRequest, onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';+import { isManualOnDemandRequest, onDemandRequestMetadata, quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';import { addTask, reviveBlockedTask } from './cosTaskStore.js';import { cardIdForRequest, finishPreflightCard, finishPreflightDispatch, reportPreflightStep, startPreflightCard } from './preflightTaskCard.js';@@ -76,6 +77,7 @@ export async function drainOnDemandRequests(ctx, adapter) {} = await import('./cosTaskGenerator.js');const taskScheduleMod = await import('./taskSchedule.js');+ await reconcileOnDemandHandoffs();const schedule = await taskScheduleMod.loadSchedule();const onDemandRequests = await taskScheduleMod.getOnDemandRequests();@@ -137,8 +139,10 @@ export async function drainOnDemandRequests(ctx, adapter) {// One helper so the log line and the card can never name different reasons —// the same hand-mirroring this module's header exists to eliminate.const dropRequest = async (level, reason, note) => {- const claimed = await taskScheduleMod.clearOnDemandRequest(queuedRequest.id);+ const handoff = queuedRequest.burn ? await claimOnDemandRequest(queuedRequest.id) : null;+ const claimed = queuedRequest.burn ? handoff?.request : await taskScheduleMod.clearOnDemandRequest(queuedRequest.id);if (!claimed) return;+ if (handoff) await settleOnDemandRequest(handoff, { reason: `${note} Resume explicitly.` });await openCard(claimed);emitLog(level, `On-demand request dropped — ${note}`, { requestId: queuedRequest.id, taskType: queuedRequest.taskType });await finishPreflightCard(cardIdForRequest(claimed), { outcome: 'failed', reason, note });@@ -199,135 +203,151 @@ export async function drainOnDemandRequests(ctx, adapter) {// Both engines can hold this snapshot. Only the atomic removal winner// owns preparation, accounting, and the shared card's terminal outcome.- const request = await taskScheduleMod.clearOnDemandRequest(queuedRequest.id);+ const claim = queuedRequest.burn ? await claimOnDemandRequest(queuedRequest.id) : null;+ const request = queuedRequest.burn ? claim?.request : await taskScheduleMod.clearOnDemandRequest(queuedRequest.id);if (!request) continue;- // Receipts are immutable while queued; resolve dispatch from the claimed- // record as well, rather than keeping snapshot objects across ownership.- targetApp = request.appId ? apps.find(app => app.id === request.appId) : null;- const cardId = cardIdForRequest(request);- await openCard(request);- // Off the queue and into preparation. A task type with its own preflight- // (pr-reviewer) has no `prepare` step and reports its real first step- // moments later, so this is a no-op there rather than a competing claim.- await reportPreflightStep(cardId, 'prepare');+ let acceptedTaskId = null;+ let preparationFailed = false;+ try {+ // Receipts are immutable while queued; resolve dispatch from the claimed+ // record as well, rather than keeping snapshot objects across ownership.+ targetApp = request.appId ? apps.find(app => app.id === request.appId) : null;+ const cardId = cardIdForRequest(request);+ await openCard(request);+ // Off the queue and into preparation. A task type with its own preflight+ // (pr-reviewer) has no `prepare` step and reports its real first step+ // moments later, so this is a no-op there rather than a competing claim.+ await reportPreflightStep(cardId, 'prepare');- const preparationStartedAt = performance.now();- const requestedAt = Date.parse(request.requestedAt);- const queueWaitMs = Number.isFinite(requestedAt) ? Math.max(0, Date.now() - requestedAt) : null;+ const preparationStartedAt = performance.now();+ const requestedAt = Date.parse(request.requestedAt);+ const queueWaitMs = Number.isFinite(requestedAt) ? Math.max(0, Date.now() - requestedAt) : null;- // A HUMAN "Run" re-checks live state (park + convergence signature + dispatch- // budget all cleared); an automated refill (origin: 'refill') inherits them,- // or the drain has no brakes left. The origin check lives inside- // applyOnDemandRunResets so this drain and the refill lane can't drift on it.- const userInitiated = await taskScheduleMod.applyOnDemandRunResets(request, targetApp?.id ?? null);- const lane = userInitiated ? '' : ' (drain refill)';+ // A HUMAN "Run" re-checks live state (park + convergence signature + dispatch+ // budget all cleared); an automated refill (origin: 'refill') inherits them,+ // or the drain has no brakes left. The origin check lives inside+ // applyOnDemandRunResets so this drain and the refill lane can't drift on it.+ const userInitiated = await taskScheduleMod.applyOnDemandRunResets(request, targetApp?.id ?? null);+ const lane = userInitiated ? '' : ' (drain refill)';- if (targetApp) {- emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: targetApp.id });- // Advance the cooldown eagerly (deduped per app per cycle), but defer- // binding the active agent until a task is produced — a null result- // here must not strand `activeAgentId` (issue #978).- if (!reviewStartedApps.has(targetApp.id)) {- await markAppReviewCooldown(targetApp.id);- reviewStartedApps.add(targetApp.id);+ if (targetApp) {+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: targetApp.id });+ // Advance the cooldown eagerly (deduped per app per cycle), but defer+ // binding the active agent until a task is produced — a null result+ // here must not strand `activeAgentId` (issue #978).+ if (!reviewStartedApps.has(targetApp.id)) {+ await markAppReviewCooldown(targetApp.id);+ reviewStartedApps.add(targetApp.id);+ }+ await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);+ const prepared = await prepareManagedAppImprovementTask(request.taskType, targetApp, state, {+ skipPreconditions: true,+ targetPullRequest: request.targetPullRequest ?? null,+ // The deterministic pre-agent work reports into the user's card as it+ // runs — this is the whole reason the card exists early.+ preflightCardId: cardId,+ providerOverride: request.providerOverride ?? null,+ // A quota-burn step's per-invocation run parameters. They must reach+ // the PROMPT, so unlike the provider/model/effort pins they cannot+ // ride the post-generation `onDemandRequestMetadata` stamp below —+ // the generator overlays them before it picks the mode banner.+ // `normalizeQuotaBurnProvenance` (lib/quotaBurnOrigin.js) has to keep+ // `overrides.params` for a step to reach this; it drops them today,+ // so a burn currently runs the task's SAVED mode, which is correct+ // for every step until the migration starts pinning one.+ runOverrides: request.burn?.overrides?.params ?? null+ });+ task = prepared.task;+ pendingPerpetualDispatch = prepared.pendingPerpetualDispatch;+ skip = prepared.skip;+ if (task) {+ await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);+ }+ } else {+ emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });+ await taskScheduleMod.recordExecution(`task:${request.taskType}`);+ await withStateLock(async () => {+ const s = await loadState();+ s.stats.lastSelfImprovement = new Date().toISOString();+ s.stats.lastSelfImprovementType = request.taskType;+ await saveState(s);+ });+ task = await generateSelfImprovementTaskForType(request.taskType, state);}- await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);- const prepared = await prepareManagedAppImprovementTask(request.taskType, targetApp, state, {- skipPreconditions: true,- targetPullRequest: request.targetPullRequest ?? null,- // The deterministic pre-agent work reports into the user's card as it- // runs — this is the whole reason the card exists early.- preflightCardId: cardId,- providerOverride: request.providerOverride ?? null,- // A quota-burn step's per-invocation run parameters. They must reach- // the PROMPT, so unlike the provider/model/effort pins they cannot- // ride the post-generation `onDemandRequestMetadata` stamp below —- // the generator overlays them before it picks the mode banner.- // `normalizeQuotaBurnProvenance` (lib/quotaBurnOrigin.js) has to keep- // `overrides.params` for a step to reach this; it drops them today,- // so a burn currently runs the task's SAVED mode, which is correct- // for every step until the migration starts pinning one.- runOverrides: request.burn?.overrides?.params ?? null- });- task = prepared.task;- pendingPerpetualDispatch = prepared.pendingPerpetualDispatch;- skip = prepared.skip;- if (task) {- await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);- }- } else {- emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });- await taskScheduleMod.recordExecution(`task:${request.taskType}`);- await withStateLock(async () => {- const s = await loadState();- s.stats.lastSelfImprovement = new Date().toISOString();- s.stats.lastSelfImprovementType = request.taskType;- await saveState(s);- });- task = await generateSelfImprovementTaskForType(request.taskType, state);- }- applyOnDemandConsent(task);- // Priority 0 is a COMMITTED tier: the request is already cleared and the- // marker bound, and this branch is the only thing that persists the task, so- // a denial would discard the user's "Run". See canSpawnCommitted (#4834).- if (task && canSpawn(task)) {- // Mark this a MANUAL (on-demand) run so its perpetual drain continues in- // the on-demand lane (see perpetualRefillPlan in cos.js). Stamped before- // addTask so the blocked-revive branch inherits it via `task.metadata`.- // `onDemandRequestMetadata` also carries the request's ORIGIN, which- // `perpetualRefillPlan` reads to decide whether the completed run may- // continue its drain — and a quota burn's provenance when it is one.- task.metadata = { ...(task.metadata || {}), ...onDemandRequestMetadata(request) };- // `addTaskOptions` carries the dequeue engine's `ignoreTaskId` so a- // completion-triggered re-issue is dedup-safe: the perpetual drain- // regenerates an identical first-line for the same app, and- // `agent:completed` fires before the completing task's updateTask settles- // it to `completed` — so without excluding it the re-issued claim is- // rejected as a duplicate of the run that just finished and the drain stalls.- const persisted = await addTask(task, 'internal', { raw: true, ...addTaskOptions, suppressDequeue: true });- await finishPreflightDispatch(cardId, persisted?.id || task.id);- if (!persisted?.duplicate) {- await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);- emitSpawn(task);- } else if (persisted.status === 'blocked') {- // Explicit user Run colliding with a failure-blocked twin (#2614):- // revive the existing task instead of silently dropping the Run and- // stranding the bound on-demand review marker.- const stored = await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });- if (stored?.error || stored?.statusChanged) continue;- await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);- // Deep resumes need the persisted branch pointer and original audit text,- // not a freshly rendered snapshot of volatile issue/PR preload data.- const revived = task.metadata.auditDepth === 'deep' ? stored : { ...task, id: persisted.id };- emitSpawn(revived);- emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });+ applyOnDemandConsent(task);+ // Priority 0 is a COMMITTED tier: the request is already cleared and the+ // marker bound, and this branch is the only thing that persists the task, so+ // a denial would discard the user's "Run". See canSpawnCommitted (#4834).+ if (task && canSpawn(task)) {+ // Mark this a MANUAL (on-demand) run so its perpetual drain continues in+ // the on-demand lane (see perpetualRefillPlan in cos.js). Stamped before+ // addTask so the blocked-revive branch inherits it via `task.metadata`.+ // `onDemandRequestMetadata` also carries the request's ORIGIN, which+ // `perpetualRefillPlan` reads to decide whether the completed run may+ // continue its drain — and a quota burn's provenance when it is one.+ task.metadata = { ...(task.metadata || {}), ...onDemandRequestMetadata(request) };+ // `addTaskOptions` carries the dequeue engine's `ignoreTaskId` so a+ // completion-triggered re-issue is dedup-safe: the perpetual drain+ // regenerates an identical first-line for the same app, and+ // `agent:completed` fires before the completing task's updateTask settles+ // it to `completed` — so without excluding it the re-issued claim is+ // rejected as a duplicate of the run that just finished and the drain stalls.+ const persisted = await addTask(task, 'internal', { raw: true, ...addTaskOptions, suppressDequeue: true });+ await finishPreflightDispatch(cardId, persisted?.id || task.id);+ if (persisted?.error) throw new Error(persisted.error);+ if (!persisted?.duplicate) {+ acceptedTaskId = persisted?.id || task.id;+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);+ emitSpawn(task);+ } else if (persisted.status === 'blocked') {+ // Explicit user Run colliding with a failure-blocked twin (#2614):+ // revive the existing task instead of silently dropping the Run and+ // stranding the bound on-demand review marker.+ const stored = await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });+ if (stored?.error || stored?.statusChanged) continue;+ acceptedTaskId = stored?.id || persisted.id;+ await recordDeferredPerpetualDispatch(pendingPerpetualDispatch, taskScheduleMod);+ // Deep resumes need the persisted branch pointer and original audit text,+ // not a freshly rendered snapshot of volatile issue/PR preload data.+ const revived = task.metadata.auditDepth === 'deep' ? stored : { ...task, id: persisted.id };+ emitSpawn(revived);+ emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });+ } else if (!claim || quotaBurnProvenance(persisted.metadata).requestId === request.id) {+ acceptedTaskId = persisted.id;+ }+ } else if (!task && userInitiated) {+ // Explicit user "Run" produced no task — surface WHY (parked / transient /+ // idle) so the trigger isn't a silent no-op. Because we reset the park+ // BEFORE the fresh detection above, the outcome classification reflects+ // THIS check.+ //+ // `userInitiated` only: a drain refill ends by converging (that's the point),+ // and nobody is waiting on it, so toasting "nothing to do" for every automated+ // hop would turn a healthy overnight drain into a pile of notifications.+ await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType], preflightCardId: cardId, skip });}- } else if (!task && userInitiated) {- // Explicit user "Run" produced no task — surface WHY (parked / transient /- // idle) so the trigger isn't a silent no-op. Because we reset the park- // BEFORE the fresh detection above, the outcome classification reflects- // THIS check.- //- // `userInitiated` only: a drain refill ends by converging (that's the point),- // and nobody is waiting on it, so toasting "nothing to do" for every automated- // hop would turn a healthy overnight drain into a pile of notifications.- await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType], preflightCardId: cardId, skip });- }- // Every other exit from this iteration (a task that capacity refused, or a- // refill with no task) still owes the card a close — a card left open would- // keep animating until the orphan sweep reaped it. Already-closed cards are- // a no-op, so the specific reason each path recorded above survives.- await finishPreflightDispatch(cardId);- if (userInitiated) {- const preparationMs = Math.round(performance.now() - preparationStartedAt);- emitLog('info', `On-demand preparation finished: ${request.taskType} (${request.id}) — queue wait ${queueWaitMs ?? 'unknown'}ms, preparation ${preparationMs}ms, ${task ? 'task generated' : 'no task generated'}`, {- requestId: request.id,- appId: targetApp?.id ?? null,- queueWaitMs,- preparationMs,- taskGenerated: !!task,- });+ // Every other exit from this iteration (a task that capacity refused, or a+ // refill with no task) still owes the card a close — a card left open would+ // keep animating until the orphan sweep reaped it. Already-closed cards are+ // a no-op, so the specific reason each path recorded above survives.+ await finishPreflightDispatch(cardId);+ if (userInitiated) {+ const preparationMs = Math.round(performance.now() - preparationStartedAt);+ emitLog('info', `On-demand preparation finished: ${request.taskType} (${request.id}) — queue wait ${queueWaitMs ?? 'unknown'}ms, preparation ${preparationMs}ms, ${task ? 'task generated' : 'no task generated'}`, {+ requestId: request.id,+ appId: targetApp?.id ?? null,+ queueWaitMs,+ preparationMs,+ taskGenerated: !!task,+ });+ }+ } catch (error) {+ preparationFailed = true;+ throw error;+ } finally {+ if (claim) await settleOnDemandRequest(claim, { taskId: acceptedTaskId,+ reason: acceptedTaskId ? null : preparationFailed ? 'Request preparation failed; resume explicitly.' : 'Request produced no task; resume explicitly.' });}}diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.jsindex 10a0002ea4..55714c3a50 100644--- a/server/services/onDemandDrain.test.js+++ b/server/services/onDemandDrain.test.js@@ -47,6 +47,12 @@ const mocks = vi.hoisted(() => ({finishPreflightDispatch: vi.fn(async () => null),}));+vi.mock('./onDemandHandoff.js', () => ({+ reconcileOnDemandHandoffs: vi.fn(async () => {}),+ claimOnDemandRequest: vi.fn(async (id) => { const request = await mocks.clearOnDemandRequest(id); return request ? { request, token: id } : null; }),+ settleOnDemandRequest: vi.fn(async () => true),+}));+vi.mock('./apps.js', () => ({ getActiveApps: (...a) => mocks.getActiveApps(...a) }));vi.mock('./cosState.js', () => ({isImprovementEnabled: (...a) => mocks.isImprovementEnabled(...a),@@ -724,3 +730,25 @@ describe('atomic on-demand preparation ownership', () => {}));});});++it('settles burn preparation failures and successful task persistence without leaving a live claim', async () => {+ const { settleOnDemandRequest } = await import('./onDemandHandoff.js');+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ origin: 'quota-burn', burn: { family: 'codex', stepId: 'step' } })]);+ mocks.prepareManagedAppImprovementTask.mockRejectedValueOnce(new Error('preparation failed'));+ const { adapter } = generatorAdapter({});+ await expect(drainOnDemandRequests({ state: STATE }, adapter)).rejects.toThrow('preparation failed');+ expect(settleOnDemandRequest).toHaveBeenLastCalledWith(expect.objectContaining({ request: expect.objectContaining({ id: 'req-1' }) }), { taskId: null, reason: 'Request preparation failed; resume explicitly.' });+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(settleOnDemandRequest).toHaveBeenLastCalledWith(expect.anything(), { taskId: 'persisted-1', reason: null });+});+++it('refuses an unrelated active duplicate instead of claiming its delivery', async () => {+ const { settleOnDemandRequest } = await import('./onDemandHandoff.js');+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ origin: 'quota-burn', burn: { family: 'codex', stepId: 'step' } })]);+ mocks.addTask.mockResolvedValue({ id: 'other-task', duplicate: true, status: 'in_progress', metadata: { quotaBurnRequestId: 'other-request' } });+ const { adapter, spawned } = generatorAdapter({});+ await drainOnDemandRequests({ state: STATE }, adapter);+ expect(spawned).toEqual([]);+ expect(settleOnDemandRequest).toHaveBeenLastCalledWith(expect.anything(), { taskId: null, reason: 'Request produced no task; resume explicitly.' });+});diff --git a/server/services/onDemandHandoff.js b/server/services/onDemandHandoff.jsnew file mode 100644index 0000000000..9bfb4c50d5--- /dev/null+++ b/server/services/onDemandHandoff.js@@ -0,0 +1,66 @@+/** Durable handoff for asynchronous quota/maintenance requests. A nonce fences+ * settlement, while only a proven missing owner PID permits crash reconciliation.+ * Live or ambiguous owners never expire. All transitions share the schedule queue. */+import { randomUUID } from 'node:crypto';+import { loadSchedule, updateSchedule } from './taskScheduleStore.js';+import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';++const owner = randomUUID();+const ownerPid = process.pid;++// ESRCH is proof of absence, unlike a different nonce or elapsed time. A reused+// PID conservatively remains held; permission/probe errors are not proof of death.+function ownerIsGone(claim) {+ if (claim.owner === owner || !Number.isSafeInteger(claim.ownerPid) || claim.ownerPid <= 0) return false;+ try { process.kill(claim.ownerPid, 0); return false; }+ catch (error) { return error.code === 'ESRCH'; }+}++export async function claimOnDemandRequest(requestId) {+ return updateSchedule(async (schedule) => {+ const index = (schedule.onDemandRequests || []).findIndex(request => request.id === requestId);+ if (index < 0 || schedule.onDemandHandoffs?.[requestId]) return { result: null, changed: false };+ const [request] = schedule.onDemandRequests.splice(index, 1);+ schedule.onDemandHandoffs ??= {};+ const claim = { request, owner, ownerPid, token: randomUUID(), status: 'preparing', claimedAt: new Date().toISOString() };+ schedule.onDemandHandoffs[requestId] = claim;+ return { result: claim, changed: true };+ });+}++export async function settleOnDemandRequest(claim, { taskId = null, reason = null } = {}) {+ return updateSchedule(async (schedule) => {+ const current = schedule.onDemandHandoffs?.[claim.request.id];+ if (current?.token !== claim.token || current.owner !== owner || current.ownerPid !== ownerPid || current.status !== 'preparing') {+ return { result: false, changed: false };+ }+ Object.assign(current, { status: taskId ? 'accepted' : 'refused', taskId, reason, settledAt: new Date().toISOString() });+ return { result: true, changed: true };+ });+}++/** Reconcile only proven dead owners. Reads of task storage must succeed, then+ * liveness is rechecked under the schedule queue before changing the claim. */+export async function reconcileOnDemandHandoffs() {+ const snapshot = await loadSchedule();+ if (!Object.values(snapshot.onDemandHandoffs || {}).some(claim => claim.status === 'preparing' && ownerIsGone(claim))) return;+ const { getAllTasks } = await import('./cosTaskStore.js');+ const { user, cos } = await getAllTasks();+ const tasks = [...(user?.tasks || []), ...(cos?.tasks || [])];+ await updateSchedule(async (schedule) => {+ let changed = false;+ for (const claim of Object.values(schedule.onDemandHandoffs || {})) {+ if (claim.status !== 'preparing' || !ownerIsGone(claim)) continue;+ const task = tasks.find(entry => quotaBurnProvenance(entry.metadata).requestId === claim.request.id);+ Object.assign(claim, { status: task ? 'accepted' : 'interrupted', taskId: task?.id ?? null,+ reason: task ? null : 'Server restarted during request preparation; resume explicitly.', settledAt: new Date().toISOString() });+ changed = true;+ }+ return { changed };+ });+}++export async function getOnDemandHandoffs() {+ await reconcileOnDemandHandoffs();+ return (await loadSchedule()).onDemandHandoffs || {};+}diff --git a/server/services/onDemandHandoff.test.js b/server/services/onDemandHandoff.test.jsnew file mode 100644index 0000000000..b395750794--- /dev/null+++ b/server/services/onDemandHandoff.test.js@@ -0,0 +1,82 @@+import { afterAll, afterEach, beforeEach, expect, it, vi } from 'vitest';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'on-demand-handoff-' });+vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));+const world = vi.hoisted(() => ({ tasks: [], fail: false }));+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: async () => {+ if (world.fail) throw new Error('unreadable tasks');+ return { cos: { tasks: world.tasks }, user: { tasks: [] } };+} }));+const { updateSchedule, loadSchedule } = await import('./taskScheduleStore.js');+const { claimOnDemandRequest, settleOnDemandRequest, getOnDemandHandoffs } = await import('./onDemandHandoff.js');+const request = { id: 'demand-one', taskType: 'security', burn: { maintenanceRunId: 'maint-one', stepId: 'step-one' } };+beforeEach(async () => {+ world.tasks = []; world.fail = false;+ await updateSchedule(async schedule => {+ schedule.onDemandRequests = [request]; schedule.onDemandHandoffs = {};+ return { changed: true };+ });+});+afterAll(cleanup);+afterEach(() => vi.restoreAllMocks());++it('durably claims once across competing engines and keeps a slow live claim pending until exact-owner settlement', async () => {+ const claims = await Promise.all([claimOnDemandRequest(request.id), claimOnDemandRequest(request.id)]);+ expect(claims.filter(Boolean)).toHaveLength(1);+ const claim = claims.find(Boolean);+ expect((await loadSchedule()).onDemandRequests).toEqual([]);+ await updateSchedule(async schedule => { schedule.onDemandHandoffs[request.id].claimedAt = '2000-01-01T00:00:00Z'; return { changed: true }; });+ expect((await getOnDemandHandoffs())[request.id].status).toBe('preparing');+ expect(await settleOnDemandRequest({ ...claim, token: 'stale' })).toBe(false);+ expect(await settleOnDemandRequest(claim, { taskId: 'task-one' })).toBe(true);+ expect(await settleOnDemandRequest(claim)).toBe(false);+ expect((await getOnDemandHandoffs())[request.id]).toMatchObject({ status: 'accepted', taskId: 'task-one' });+});++it('reconciles restart after task persistence and parks interrupted preparation without requeueing', async () => {+ await claimOnDemandRequest(request.id);+ await updateSchedule(async schedule => {+ schedule.onDemandHandoffs[request.id].owner = 'previous-process';+ schedule.onDemandHandoffs[request.id].ownerPid = 2147483647;+ schedule.onDemandHandoffs['demand-two'] = { ...schedule.onDemandHandoffs[request.id], request: { ...request, id: 'demand-two' } };+ return { changed: true };+ });+ vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('gone'), { code: 'ESRCH' }); });+ world.tasks = [{ id: 'task-one', metadata: { quotaBurnRequestId: request.id, quotaBurnMaintenanceRunId: 'maint-one', quotaBurnStepId: 'step-one' } }];+ world.fail = true;+ await expect(getOnDemandHandoffs()).rejects.toThrow('unreadable tasks');+ expect((await loadSchedule()).onDemandHandoffs[request.id].status).toBe('preparing');+ world.fail = false;+ const outcomes = await getOnDemandHandoffs();+ expect(outcomes[request.id]).toMatchObject({ status: 'accepted', taskId: 'task-one' });+ expect(outcomes['demand-two'].status).toBe('interrupted');+ expect((await loadSchedule()).onDemandRequests).toEqual([]);+ expect(await getOnDemandHandoffs()).toEqual(outcomes);+});+++it('preserves another live owner, ambiguous liveness and missing identity despite a different nonce', async () => {+ await claimOnDemandRequest(request.id);+ await updateSchedule(async schedule => {+ schedule.onDemandHandoffs[request.id].owner = 'another-live-process';+ return { changed: true };+ });+ const kill = vi.spyOn(process, 'kill').mockReturnValue(true);+ expect((await getOnDemandHandoffs())[request.id].status).toBe('preparing');+ expect(kill).toHaveBeenCalledWith(process.pid, 0);+ kill.mockImplementation(() => { throw Object.assign(new Error('denied'), { code: 'EPERM' }); });+ expect((await getOnDemandHandoffs())[request.id].status).toBe('preparing');+ await updateSchedule(async schedule => { delete schedule.onDemandHandoffs[request.id].ownerPid; return { changed: true }; });+ kill.mockImplementation(() => { throw Object.assign(new Error('gone'), { code: 'ESRCH' }); });+ expect((await getOnDemandHandoffs())[request.id].status).toBe('preparing');+});++it('never overwrites an existing receipt even if the same request is queued again', async () => {+ const claim = await claimOnDemandRequest(request.id);+ await settleOnDemandRequest(claim, { taskId: 'accepted-task' });+ const receipt = (await getOnDemandHandoffs())[request.id];+ await updateSchedule(async schedule => { schedule.onDemandRequests.push(request); return { changed: true }; });+ expect(await claimOnDemandRequest(request.id)).toBeNull();+ expect((await getOnDemandHandoffs())[request.id]).toEqual(receipt);+ expect((await loadSchedule()).onDemandRequests).toEqual([request]);+});diff --git a/server/services/quotaBurnAcceptance.js b/server/services/quotaBurnAcceptance.jsindex e268c60ad9..8e95b472a8 100644--- a/server/services/quotaBurnAcceptance.js+++ b/server/services/quotaBurnAcceptance.js@@ -44,6 +44,7 @@* are accepted the moment they return and the runner charges them directly.*/+import { getOnDemandHandoffs } from './onDemandHandoff.js';import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';import { recordQuotaBurnDispatch } from './quotaBurn.js';import { recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';@@ -177,7 +178,9 @@ export async function reconcileQuotaBurnReservations({ now = Date.now() } = {})const keys = Object.keys(reservations);if (!keys.length) return { accepted: 0, refused: 0 };- const [queued, tasksByRequest] = await Promise.all([queuedRequestIds(), burnTasksByRequestId()]);+ const queued = await queuedRequestIds();+ const handoffs = await getOnDemandHandoffs();+ const tasksByRequest = await burnTasksByRequestId();// Either read failing means we cannot tell "still waiting" from "accepted"// from "refused". Leave every reservation exactly where it is.if (!queued || !tasksByRequest) return { deferred: 'schedule or task queue unreadable', accepted: 0, refused: 0 };@@ -188,8 +191,9 @@ export async function reconcileQuotaBurnReservations({ now = Date.now() } = {})const record = reservations[key];// Still on the schedule: the engines have not drained it yet. The cap keeps// counting it, and the step stays blocked from a second dispatch.- if (queued.has(record.requestId)) continue;- const task = tasksByRequest.get(record.requestId);+ if (queued.has(record.requestId) || handoffs[record.requestId]?.status === 'preparing') continue;+ const receipt = handoffs[record.requestId];+ const task = tasksByRequest.get(record.requestId) || (receipt?.status === 'accepted' && receipt.taskId ? { id: receipt.taskId } : null);if (task) {if (await settleAccepted(key, record, task, now)) accepted += 1;continue;diff --git a/server/services/quotaBurnAcceptance.test.js b/server/services/quotaBurnAcceptance.test.jsindex af7d1b0cc9..32d3dea417 100644--- a/server/services/quotaBurnAcceptance.test.js+++ b/server/services/quotaBurnAcceptance.test.js@@ -30,6 +30,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) =>// what the on-demand engines actually produced.const world = { requests: [], tasks: [], requestsThrow: false, tasksThrow: false };+vi.mock('./onDemandHandoff.js', () => ({ getOnDemandHandoffs: vi.fn(async () => ({})) }));vi.mock('./taskSchedule.js', () => ({getOnDemandRequests: vi.fn(async () => {if (world.requestsThrow) throw new Error('schedule unreadable');@@ -220,3 +221,17 @@ describe('reads it cannot trust', () => {expect(await getQuotaBurnDispatches()).toEqual({});});});++it('retains a consumed request reservation while preparation is live and settles an accepted receipt once', async () => {+ const { getOnDemandHandoffs } = await import('./onDemandHandoff.js');+ await reserveQuotaBurnDispatch(reservation());+ getOnDemandHandoffs.mockResolvedValue({ [REQUEST_ID]: { status: 'preparing' } });+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ accepted: 0, refused: 0 });+ expect(Object.keys(await getQuotaBurnReservations())).toHaveLength(1);+ // Task archival may remove the join target after delivery. The exact-owner+ // persisted acceptance receipt still proves that this request was accepted.+ getOnDemandHandoffs.mockResolvedValue({ [REQUEST_ID]: { status: 'accepted', taskId: 'existing-task' } });+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ accepted: 1, refused: 0 });+ expect(await reconcileQuotaBurnReservations()).toMatchObject({ accepted: 0, refused: 0 });+ getOnDemandHandoffs.mockResolvedValue({});+});