Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

merge maintenance-run writes so a Stop or completion cannot be overwritten by an in-flight walk

[._.]/ Adam Eivy07ca954758ad
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
index 36ff06783e..fb428a2991 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
@@ -41,7 +41,9 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
const fetchRuns = useCallback(async () => {
const response = await api.getMaintenanceRuns({ silent: true }).catch(() => null);
- setRuns(response?.runs || (current => current || []));
+ // A failed read stays `null` so the poll keeps trying; only a real answer
+ // settles the list.
+ if (response) setRuns(response.runs || []);
}, []);
const anyRunning = (runs || []).some(run => run.status === 'running');
// One read on mount, then polling only while a run is in flight — an idle
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
index feb7a6fb19..7b2b142c01 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
@@ -50,8 +50,6 @@ describe('maintenance launch', () => {
await user.click(screen.getByRole('button', { name: 'Run now' }));
expect(screen.getByRole('button', { name: 'Starting…' })).toBeDisabled();
expect(api.startMaintenanceRun).toHaveBeenCalledWith({ appId: 'example', providerId: 'claude', model: 'sonnet', effort: 'high' }, { silent: true });
- // The poll re-fires once a run is in flight and reads the persisted record back.
- api.getMaintenanceRuns.mockResolvedValue({ runs: [runRecord()] });
finishStart({ run: runRecord(), result: { dispatched: true, taskType: 'better-structural-drift' } });
expect(await screen.findByText(/Maintenance started with better-structural-drift/)).toBeInTheDocument();
const row = screen.getByRole('list', { name: 'Maintenance runs' });
diff --git a/docs/API.md b/docs/API.md
index 2930e0163a..e22a5d911e 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -268,6 +268,10 @@ Context tools remain read-only. Semantic reads and writes are independent, defau
| GET | `/cos/schedule/task/:taskType` | Get interval and schedule settings for a task type |
| PUT | `/cos/schedule/task/:taskType` | Update schedule settings for a task type (`type`: `on-demand` \| `cron`; `cronExpression`: 5-field or null; `perpetual`: boolean drain flag, orthogonal to `type`) |
| POST | `/cos/schedule/trigger` | Trigger an on-demand task run |
+| GET | `/cos/schedule/maintenance-runs` | List manual maintenance runs (the Schedule tab's "Run maintenance now"; running first, then recent history) |
+| POST | `/cos/schedule/maintenance-runs` | Start a manual maintenance run for one app (`appId`, `providerId`, `model`, optional `effort`); returns the run and its first dispatch or hold reason. Independent of Quota Burn |
+| POST | `/cos/schedule/maintenance-runs/:id/stop` | Stop a run from dispatching further steps (a task already queued or running is not recalled) |
+| POST | `/cos/schedule/maintenance-runs/:id/resume` | Resume a stopped run from its completion ledger |
| GET | `/cos/schedule/on-demand` | List pending on-demand task requests |
| DELETE | `/cos/schedule/on-demand/:requestId` | Clear a pending on-demand request |
| POST | `/cos/schedule/reset` | Reset execution history for a task type |
diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.js
index 5b5a004001..02a81ab014 100644
--- a/server/lib/quotaBurnOrigin.test.js
+++ b/server/lib/quotaBurnOrigin.test.js
@@ -27,6 +27,16 @@ describe('normalizeQuotaBurnProvenance', () => {
});
});
+ it('carries a manual maintenance run id through, and omits it on an automatic burn', () => {
+ // The only hop where the request's run id survives into task metadata — the
+ // engines spread the normalized block. Dropping it would put the burn plan
+ // back to walking on a manual run's completions with the suite still green.
+ expect(normalizeQuotaBurnProvenance(provenance({ maintenanceRunId: 'maint-1' })).maintenanceRunId).toBe('maint-1');
+ expect(normalizeQuotaBurnProvenance(provenance())).not.toHaveProperty('maintenanceRunId');
+ expect(onDemandRequestMetadata({ id: 'demand-9', origin: 'quota-burn', burn: provenance({ maintenanceRunId: 'maint-1' }) }))
+ .toMatchObject({ quotaBurnFamily: 'grok', quotaBurnMaintenanceRunId: 'maint-1' });
+ });
+
it('drops a non-scalar run param rather than carrying a blob into task metadata', () => {
const block = normalizeQuotaBurnProvenance(provenance({ overrides: { params: { fileIssues: true, nested: { a: 1 } } } }));
expect(block.overrides.params).toEqual({ fileIssues: true });
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index 63da1b6267..f3a98c4d30 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -67,10 +67,11 @@ export const MAINTENANCE_RUN_STATUS = Object.freeze({ RUNNING: 'running', COMPLE
const activeRunError = (appId, runId) => new ServerError(`a maintenance run is already in progress for "${appId}" (${runId})`, { status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });
const writeQueue = createFileWriteQueue();
-// One evaluation at a time PER RUN: a completion and the interval can land
-// together, and two concurrent walks of one ladder would dispatch its next
-// step twice.
-const evaluations = createKeyCachedQueue();
+// One operation at a time PER RUN — evaluations, the completion ledger, stop
+// and resume all queue here. A completion and the interval can land together,
+// and two concurrent walks of one ladder would dispatch its next step twice; a
+// Stop landing mid-walk must take effect before the walk's next dispatch.
+const perRun = createKeyCachedQueue();
let retryTimer = null;
export async function listMaintenanceRuns() {
@@ -79,27 +80,46 @@ export async function listMaintenanceRuns() {
}
/**
- * Persist a run: replace it in place, or prepend a new one, then prune finished
- * history past the cap. Running records are never pruned — a run the user can
- * still see progressing must not vanish because twenty others finished.
+ * Persist the list, pruning finished history past the cap. Running records are
+ * never pruned — a run the user can still see progressing must not vanish
+ * because twenty others finished.
*/
-function writeRun(run) {
- return writeQueue(async () => {
- const runs = await listMaintenanceRuns();
- const next = runs.some((entry) => entry.id === run.id) ? runs.map((entry) => (entry.id === run.id ? run : entry)) : [run, ...runs];
- let finished = 0;
- const kept = next.filter((entry) => entry.status === MAINTENANCE_RUN_STATUS.RUNNING || ++finished <= RUN_HISTORY_LIMIT);
- await atomicWrite(runsFile(), { runs: kept });
- return run;
- });
+async function writeRuns(runs) {
+ let finished = 0;
+ await atomicWrite(runsFile(), { runs: runs.filter((entry) => entry.status === MAINTENANCE_RUN_STATUS.RUNNING || ++finished <= RUN_HISTORY_LIMIT) });
}
+const insertRun = (run) => writeQueue(async () => {
+ await writeRuns([run, ...(await listMaintenanceRuns())]);
+ return run;
+});
+
+/**
+ * Apply a PATCH to the stored record — re-read inside the write queue and
+ * merged, never a whole-record replace from a caller's snapshot. An evaluation
+ * holds its snapshot across several awaits (task read, catalog, claim probe,
+ * dispatch), and a replace from that snapshot would carry a stale `status` or
+ * `completed` back over a Stop or a completion that landed meanwhile. The
+ * completion ledger merges key-wise for the same reason: it only ever grows.
+ */
+const patchRun = (id, patch) => writeQueue(async () => {
+ const runs = await listMaintenanceRuns();
+ const current = runs.find((entry) => entry.id === id);
+ if (!current) return null;
+ const updated = {
+ ...current,
+ ...patch,
+ completed: { ...current.completed, ...(patch.completed || {}) },
+ updatedAt: new Date().toISOString(),
+ };
+ await writeRuns(runs.map((entry) => (entry.id === id ? updated : entry)));
+ return updated;
+});
+
export async function getMaintenanceRun(id) {
return (await listMaintenanceRuns()).find((run) => run.id === id) || null;
}
-const stamp = (run, patch) => ({ ...run, ...patch, updatedAt: new Date().toISOString() });
-
/** Two ladders against one app would file and claim each other's findings. */
async function assertNoRunningRun(appId) {
const active = (await listMaintenanceRuns()).find((run) => run.appId === appId && run.status === MAINTENANCE_RUN_STATUS.RUNNING);
@@ -130,7 +150,7 @@ export async function startMaintenanceRun({ appId, providerId, model = null, eff
const id = `maint-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const now = new Date().toISOString();
const pins = { providerId, model: model || null, effort: effort || null };
- const run = await writeRun({
+ const run = await insertRun({
id, appId, familyId, ...pins,
status: MAINTENANCE_RUN_STATUS.RUNNING,
steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins }),
@@ -140,41 +160,62 @@ export async function startMaintenanceRun({ appId, providerId, model = null, eff
startedAt: now, updatedAt: now, finishedAt: null,
});
console.log(`🧹 Maintenance run ${id} started for ${appId} via ${providerId}`);
- const result = await evaluateMaintenanceRun(id);
+ const result = await evaluateOrHold(id);
return { run: await getMaintenanceRun(id) || run, result };
}
+/**
+ * The evaluation a route awaits. A throw inside the walk (an unreadable
+ * schedule, a failed request write) is recorded as the run's hold instead of
+ * escaping: the record is already on disk as `running`, so a 500 here would
+ * leave a run the page never showed, that the sweep then dispatches.
+ */
+const evaluateOrHold = (id) => evaluateMaintenanceRun(id).catch(async (err) => {
+ console.error(`❌ Maintenance run ${id} evaluation failed: ${err.message}`);
+ await patchRun(id, { reason: err.message });
+ return { dispatched: false, reason: err.message };
+});
+
/**
* Stop dispatching. A task already queued or running is NOT recalled — the
* daemon owns it — so the run's last step may still finish; it just advances
* nothing afterwards. `resume` picks the ladder up from its completion ledger.
*/
-export async function stopMaintenanceRun(id) {
- const run = await getMaintenanceRun(id);
- if (!run) return null;
- if (run.status !== MAINTENANCE_RUN_STATUS.RUNNING) return run;
- console.log(`🧹 Maintenance run ${id} stopped by the user`);
- return writeRun(stamp(run, { status: MAINTENANCE_RUN_STATUS.STOPPED, finishedAt: new Date().toISOString(), reason: 'stopped by the user' }));
+export function stopMaintenanceRun(id) {
+ return perRun(id, async () => {
+ const run = await getMaintenanceRun(id);
+ if (!run) return null;
+ if (run.status !== MAINTENANCE_RUN_STATUS.RUNNING) return run;
+ console.log(`🧹 Maintenance run ${id} stopped by the user`);
+ return patchRun(id, { status: MAINTENANCE_RUN_STATUS.STOPPED, finishedAt: new Date().toISOString(), reason: 'stopped by the user' });
+ });
}
export async function resumeMaintenanceRun(id) {
- const run = await getMaintenanceRun(id);
- if (!run) return null;
- if (run.status === MAINTENANCE_RUN_STATUS.RUNNING) return { run, result: await evaluateMaintenanceRun(id) };
- await assertNoRunningRun(run.appId);
- await writeRun(stamp(run, { status: MAINTENANCE_RUN_STATUS.RUNNING, finishedAt: null, reason: null }));
- console.log(`🧹 Maintenance run ${id} resumed`);
- const result = await evaluateMaintenanceRun(id);
+ const resumed = await perRun(id, async () => {
+ const run = await getMaintenanceRun(id);
+ if (!run || run.status === MAINTENANCE_RUN_STATUS.RUNNING) return run;
+ await assertNoRunningRun(run.appId);
+ console.log(`🧹 Maintenance run ${id} resumed`);
+ return patchRun(id, { status: MAINTENANCE_RUN_STATUS.RUNNING, finishedAt: null, reason: null });
+ });
+ if (!resumed) return null;
+ const result = await evaluateOrHold(id);
return { run: await getMaintenanceRun(id), result };
}
/**
* Evaluate one run: dispatch its next step if nothing of its own is still
* queued, running or blocked, mark a drained claim step done, or record why it
- * is holding. Serialized per run; the returned promise is the outcome of THIS
- * caller's evaluation.
+ * is holding. Serialized per run with every other transition; the returned
+ * promise is the outcome of THIS caller's evaluation. `completeStepId` records
+ * an audit step's successful agent in the same queued turn, so no walk can read
+ * the ledger between the completion and the evaluation it triggers.
*/
-export const evaluateMaintenanceRun = (id, { ignoreTaskId = null } = {}) => evaluations(id, () => evaluate(id, { ignoreTaskId }));
+export const evaluateMaintenanceRun = (id, { ignoreTaskId = null, completeStepId = null } = {}) => perRun(id, async () => {
+ if (completeStepId) await patchRun(id, { completed: { [completeStepId]: new Date().toISOString() }, active: null });
+ return evaluate(id, { ignoreTaskId });
+});
async function evaluate(id, { ignoreTaskId }) {
const run = await getMaintenanceRun(id);
@@ -182,7 +223,7 @@ async function evaluate(id, { ignoreTaskId }) {
if (run.status !== MAINTENANCE_RUN_STATUS.RUNNING) return { skipped: run.status };
const hold = async (reason, patch = null) => {
- if (patch || run.reason !== reason) await writeRun(stamp(run, { ...patch, reason }));
+ if (patch || run.reason !== reason) await patchRun(id, { ...patch, reason });
return { dispatched: false, reason };
};
@@ -211,18 +252,18 @@ async function evaluate(id, { ignoreTaskId }) {
const result = await invokeQuotaBurnStep({ step, family: { id: run.familyId }, catalog, maintenanceRunId: id });
if (!result.dispatched) return hold(result.reason, { completed });
const taskType = step.taskRef.taskType;
- await writeRun(stamp(run, {
+ await patchRun(id, {
completed,
reason: null,
active: { stepId: step.id, taskType, requestId: result.awaiting?.requestId ?? null, at: new Date().toISOString() },
- }));
+ });
console.log(`🧹 Maintenance run ${id}: dispatched ${taskType} (${step.id})`);
return { dispatched: true, stepId: step.id, taskType, summary: result.summary };
}
- await writeRun(stamp(run, {
+ await patchRun(id, {
completed, active: null, reason: 'maintenance sequence complete',
status: MAINTENANCE_RUN_STATUS.COMPLETED, finishedAt: new Date().toISOString(),
- }));
+ });
console.log(`🧹 Maintenance run ${id} complete for ${run.appId}`);
return { dispatched: false, completed: true, reason: 'maintenance sequence complete' };
}
@@ -239,13 +280,11 @@ function onMaintenanceAgentCompleted(agent) {
const stepId = agent.metadata?.taskQuotaBurnStepId;
const success = agent.result?.success === true;
return getMaintenanceRun(id)
- .then(async (run) => {
+ .then((run) => {
if (!run) return { skipped: 'unknown run' };
const step = run.steps.find((entry) => entry.id === stepId);
- if (success && step && !step.drain && !run.completed[step.id]) {
- await writeRun(stamp(run, { completed: { ...run.completed, [step.id]: new Date().toISOString() }, active: null }));
- }
- return evaluateMaintenanceRun(id, { ignoreTaskId: success ? agent.taskId || null : null });
+ const completeStepId = success && step && !step.drain ? step.id : null;
+ return evaluateMaintenanceRun(id, { ignoreTaskId: success ? agent.taskId || null : null, completeStepId });
})
.catch((err) => console.error(`❌ Maintenance run ${id} continuation failed: ${err.message}`));
}
@@ -277,5 +316,5 @@ export function __resetMaintenanceRunScheduler() {
if (retryTimer) clearInterval(retryTimer);
retryTimer = null;
cosEvents.off('agent:completed', onMaintenanceAgentCompleted);
- evaluations.clear();
+ perRun.clear();
}
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
index 698c56c0c0..467c4eb0ca 100644
--- a/server/services/maintenanceRun.test.js
+++ b/server/services/maintenanceRun.test.js
@@ -123,6 +123,37 @@ describe('manual maintenance run', () => {
expect((await listMaintenanceRuns()).map((entry) => entry.id)).toEqual([run.id]);
});
+ it('lets a Stop or a completion that lands mid-evaluation win over the stale walk snapshot', async () => {
+ const { run } = await start();
+ // A completion arrives while a sweep is mid-walk holding on the in-flight task.
+ state.tasks = [{ id: 'task-0', status: 'in_progress', metadata: { quotaBurnFamily: 'codex', quotaBurnMaintenanceRunId: run.id } }];
+ const sweep = evaluateMaintenanceRun(run.id);
+ const completion = __onMaintenanceAgentCompleted(agentFor(run, 0));
+ await Promise.all([sweep, completion]);
+ const afterCompletion = await getMaintenanceRun(run.id);
+ expect(afterCompletion.completed).toHaveProperty(run.steps[0].id);
+ expect(dispatchedTypes()).toEqual(['better-structural-drift', 'claim-issue']);
+ // A Stop clicked while a dispatch is in flight sticks: the walk cannot write
+ // the snapshot status back over it.
+ state.tasks = [];
+ let finishDispatch;
+ invokeQuotaBurnStep.mockImplementationOnce(() => new Promise((resolve) => { finishDispatch = resolve; }));
+ const walk = evaluateMaintenanceRun(run.id);
+ const stop = stopMaintenanceRun(run.id);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ finishDispatch({ dispatched: true, summary: 'ran', awaiting: { requestId: 'demand-late' } });
+ await Promise.all([walk, stop]);
+ expect(await getMaintenanceRun(run.id)).toMatchObject({ status: 'stopped', active: { requestId: 'demand-late' } });
+ expect(await evaluateMaintenanceRun(run.id)).toEqual({ skipped: 'stopped' });
+ });
+
+ it('records a walk that throws as the hold reason instead of leaving a phantom running record', async () => {
+ invokeQuotaBurnStep.mockRejectedValueOnce(new Error('schedule unreadable'));
+ const { run, result } = await start();
+ expect(result).toEqual({ dispatched: false, reason: 'schedule unreadable' });
+ expect(run).toMatchObject({ status: 'running', reason: 'schedule unreadable' });
+ });
+
it('refuses an unknown app or a provider outside every subscription family before writing anything', async () => {
await expect(startMaintenanceRun({ appId: 'nope', providerId: 'codex', model: 'gpt-5' })).rejects.toMatchObject({ status: 400, code: 'MAINTENANCE_RUN_APP_UNAVAILABLE' });
await expect(startMaintenanceRun({ appId: 'app-1', providerId: 'ollama', model: 'llama' })).rejects.toMatchObject({ status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index d5452bd45f..e0906af9a2 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -358,6 +358,13 @@ describe('built-in agent task invocation', () => {
overrides: { effort: 'high', params: { fileIssues: false } },
});
+ it('stamps a manual maintenance run id on the request only when one is given', async () => {
+ await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate, maintenanceRunId: 'maint-1' });
+ expect(state.triggered[0].options.burn).toMatchObject({ family: 'grok', stepId: 'step-1', maintenanceRunId: 'maint-1' });
+ await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
+ expect(state.triggered[1].options.burn).not.toHaveProperty('maintenanceRunId');
+ });
+
it('routes through the schedule\'s on-demand lane with quota-burn provenance', async () => {
const result = await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
expect(result.dispatched).toBe(true);