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

run the maintenance sequence from the Schedule tab independently of Quota Burn

[._.]/ Adam Eivyccda3d95678e
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index 3de78b3fb1..ef9e07e2fc 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -190,7 +190,7 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
<Banner size="md" title="Recommended maintenance order">
<p className="text-sm break-words">{MAINTENANCE_ORDER_GUIDANCE}</p>
- <p className="text-xs mt-1">Resolve findings between audits, then document the resulting code. Quota Burn offers this sequence with perpetual claim-issue drains between steps.</p>
+ <p className="text-xs mt-1">Resolve findings between audits, then document the resulting code. Run the whole sequence now from here, or schedule it under quota gates in Quota Burn; both drain claim-issue between steps.</p>
<details className="mt-2">
<summary className="cursor-pointer text-sm font-medium">Run maintenance now</summary>
<MaintenanceRunForm schedule={{ ...schedule, tasks }} apps={apps} providers={providers} providersLoaded={providersLoaded} improvementDisabled={improvementDisabled} daemonRunning={daemonRunning} onRefresh={fetchSchedule} />
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
index 7d02e0b8d2..36ff06783e 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.jsx
@@ -1,12 +1,25 @@
-import { useState } from 'react';
-import { uuidv4 } from '../../../../lib/uuid';
+import { useCallback, useState } from 'react';
import { Link } from 'react-router';
import ProviderModelSelector from '../../../ProviderModelSelector';
import * as api from '../../../../services/api';
-import { buildQuotaBurnTaskCatalog, maintenancePrerequisites, maintenanceSequence, taskSourceHref } from '../../../../lib/quotaBurnTasks';
+import { useAutoRefetch } from '../../../../hooks/useAutoRefetch';
+import { buildQuotaBurnTaskCatalog, maintenancePrerequisites, taskSourceHref } from '../../../../lib/quotaBurnTasks';
+import { getAppName } from '../../../../utils/formatters';
import { effortAwareModelOptions, isProcessProvider } from '../../../../utils/providers';
import { familyForProvider } from '../../../../../../server/lib/providerFamilies';
+const RUNS_POLL_MS = 15_000;
+const FINISHED_RUNS_SHOWN = 3;
+
+/** Step progress as the user reads it: audits and drains done, out of the ladder. */
+const progressOf = run => ({ done: Object.keys(run.completed || {}).length, total: run.steps?.length || 0 });
+
+const currentStepOf = run => {
+ if (run.active?.taskType) return run.active.taskType;
+ const next = (run.steps || []).find(step => !run.completed?.[step.id]);
+ return next?.taskRef?.taskType || null;
+};
+
export default function MaintenanceRunForm({ schedule, apps = [], providers = [], providersLoaded, improvementDisabled, daemonRunning, onRefresh }) {
const [appId, setAppId] = useState('');
const [providerId, setProviderId] = useState('');
@@ -16,14 +29,25 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
const [busy, setBusy] = useState(false);
const [preparing, setPreparing] = useState(false);
const [message, setMessage] = useState('');
+ // `null` = not read yet, `[]` = read and empty — the first read must happen
+ // even when there is nothing to show.
+ const [runs, setRuns] = useState(null);
const availableProviders = providers.filter(provider => provider.enabled && isProcessProvider(provider) && familyForProvider(provider));
const provider = availableProviders.find(entry => entry.id === providerId);
- const familyId = familyForProvider(provider);
const groups = buildQuotaBurnTaskCatalog({ schedule, apps });
- const jobs = maintenanceSequence(groups, appId, 'preview');
const prerequisites = maintenancePrerequisites(groups, appId);
+ const ready = Boolean(appId) && prerequisites.length === 0;
const blocked = improvementDisabled || daemonRunning === false;
+ const fetchRuns = useCallback(async () => {
+ const response = await api.getMaintenanceRuns({ silent: true }).catch(() => null);
+ setRuns(response?.runs || (current => current || []));
+ }, []);
+ const anyRunning = (runs || []).some(run => run.status === 'running');
+ // One read on mount, then polling only while a run is in flight — an idle
+ // form costs nothing, and a start/resume already holds the fresh record.
+ const { refetch: refreshRuns } = useAutoRefetch(fetchRuns, RUNS_POLL_MS, { pollOnly: true, enabled: runs === null || anyRunning, immediate: runs === null });
+
const prepare = async () => {
if (busy || !onRefresh || !prerequisites.length || prerequisites.some(item => item.unavailable)) return;
setBusy(true);
@@ -56,49 +80,51 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
setBusy(false);
};
+ const describe = result => (result?.dispatched
+ ? `Maintenance started with ${result.taskType}. Later steps follow as each one finishes; progress is shown below and in Tasks.`
+ : `Maintenance run saved; holding: ${result?.reason || 'nothing dispatched'}. It retries on its own.`);
+
const run = async () => {
- if (busy || blocked || !jobs || !provider || !model || !consent) return;
+ if (busy || blocked || !ready || !provider || !model || !consent) return;
setBusy(true);
- setMessage('Checking existing plan…');
- const current = await api.getQuotaBurn(false, { silent: true }).catch(error => {
- setMessage(`Could not check existing plan: ${error.message}`);
+ setMessage('Starting maintenance…');
+ const response = await api.startMaintenanceRun({ appId, providerId, model, effort: effort || null }, { silent: true }).catch(error => {
+ setMessage(`Could not start maintenance: ${error.message}`);
return null;
});
- if (!current?.config || current.config.families?.[familyId]?.jobs?.length) {
- if (current?.config) setMessage('This family already has a plan. Manage or clear it in Quota Burn before starting another sequence.');
- setBusy(false);
- return;
- }
- setMessage('Saving maintenance sequence…');
- // Each invocation gets fresh completion keys. Pins apply to the audits AND
- // their claim drains; the scheduled tasks' saved settings remain intact.
- const steps = maintenanceSequence(groups, appId, `maintenance-${uuidv4()}`).map(job => ({
- ...job,
- overrides: { ...job.overrides, providerId, model, effort: effort || null },
- }));
- const saved = await api.saveQuotaBurn({
- enabled: true,
- families: { [familyId]: { enabled: true, sequence: true, jobs: steps } },
- }, { silent: true }).catch(error => {
- setMessage(`Could not save maintenance sequence: ${error.message}`);
- return null;
- });
- if (saved) {
- const response = await api.runQuotaBurn({ familyId, force: true }, { silent: true }).catch(error => {
- setMessage(`Sequence saved, but could not start: ${error.message}. Manage it in Quota Burn.`);
- return null;
- });
- if (response) {
- const result = response.result;
- setMessage(result?.dispatched
- ? 'Maintenance started. Follow progress in Tasks and Quota Burn.'
- : `Sequence saved; waiting: ${result?.reason || 'no task dispatched'}. See Quota Burn for details.`);
- }
+ if (response?.run) {
+ setRuns(current => [response.run, ...(current || []).filter(entry => entry.id !== response.run.id)]);
+ setMessage(describe(response.result));
setConsent(false);
}
setBusy(false);
};
+ const applyRun = (updated, result) => {
+ if (!updated) return;
+ setRuns(current => (current || []).map(entry => (entry.id === updated.id ? updated : entry)));
+ if (result) setMessage(describe(result));
+ };
+ const stop = async id => {
+ const response = await api.stopMaintenanceRun(id, { silent: true }).catch(error => {
+ setMessage(`Could not stop the run: ${error.message}`);
+ return null;
+ });
+ applyRun(response?.run);
+ };
+ const resume = async id => {
+ const response = await api.resumeMaintenanceRun(id, { silent: true }).catch(error => {
+ setMessage(`Could not resume the run: ${error.message}`);
+ return null;
+ });
+ applyRun(response?.run, response?.result);
+ };
+
+ const visibleRuns = [
+ ...(runs || []).filter(entry => entry.status === 'running'),
+ ...(runs || []).filter(entry => entry.status !== 'running').slice(0, FINISHED_RUNS_SHOWN),
+ ];
+
return (
<div className="mt-3 space-y-3 text-sm">
<label htmlFor="maintenance-run-app" className="block">
@@ -123,7 +149,7 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
loading={!providersLoaded}
disabled={busy}
/>
- {appId && !jobs && <div className="space-y-2">
+ {appId && !ready && <div className="space-y-2">
<p role="status">Run now needs these saved task settings:</p>
<ul className="list-disc pl-5 space-y-1">
{prerequisites.map(item => <li key={item.taskType}>
@@ -138,18 +164,34 @@ export default function MaintenanceRunForm({ schedule, apps = [], providers = []
</>}
</div>}
{blocked && <p role="status">Enable Improvement and start the CoS daemon before running maintenance.</p>}
- <p className="text-xs">Runs the first step now, bypassing its reset window, reserve, and dispatch cap; later steps continue in order through Quota Burn, subject to its quota gates. Supports subscription CLI/TUI providers. Blank effort inherits each scheduled task’s saved effort.</p>
+ <p className="text-xs">Runs every step now, in order: each audit starts when the previous step finishes, and each claim-issue drain repeats until the app’s issue backlog is empty. Independent of Quota Burn — no master switch, no quota gates, nothing to re-arm. Supports subscription CLI/TUI providers. Blank effort inherits each scheduled task’s saved effort.</p>
<label className="flex items-start gap-2" htmlFor="maintenance-run-consent">
<input id="maintenance-run-consent" type="checkbox" checked={consent} disabled={busy} onChange={event => setConsent(event.target.checked)} />
- <span>Enable Quota Burn and add this maintenance sequence to an empty provider family plan. Other enabled family plans may also resume.</span>
+ <span>Run the whole maintenance sequence for this app on the selected provider now, spending its quota as needed.</span>
</label>
<div className="flex items-center gap-3 flex-wrap">
- <button type="button" onClick={run} disabled={busy || blocked || !jobs || !provider || !model || !consent || !providersLoaded} className="px-3 py-1.5 bg-port-accent text-white rounded disabled:opacity-50">
+ <button type="button" onClick={run} disabled={busy || blocked || !ready || !provider || !model || !consent || !providersLoaded} className="px-3 py-1.5 bg-port-accent text-white rounded disabled:opacity-50">
{busy && !preparing ? 'Starting…' : 'Run now'}
</button>
- <Link className="underline" to={familyId ? `/devtools/quota-burn/${familyId}` : '/devtools/quota-burn'}>Manage sequence in Quota Burn</Link>
+ <Link className="underline" to="/devtools/quota-burn">Schedule this sequence in Quota Burn instead</Link>
</div>
{message && <p role="status">{message}</p>}
+ {visibleRuns.length > 0 && <ul aria-label="Maintenance runs" className="space-y-2">
+ {visibleRuns.map(entry => {
+ const { done, total } = progressOf(entry);
+ const step = currentStepOf(entry);
+ return <li key={entry.id} className="border border-port-border rounded p-2 flex flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="font-medium">{getAppName(entry.appId, apps, entry.appId)}</span>
+ <span className="text-xs">{entry.providerId}{entry.model ? ` · ${entry.model}` : ''}</span>
+ <span className="text-xs">{entry.status} · {done}/{total} steps{entry.status === 'running' && step ? ` · ${step}` : ''}</span>
+ {entry.reason && <span className="text-xs basis-full">{entry.reason}</span>}
+ {entry.status === 'running'
+ ? <button type="button" onClick={() => stop(entry.id)} className="px-2 py-1 text-xs bg-port-border rounded">Stop</button>
+ : entry.status === 'stopped' && <button type="button" onClick={() => resume(entry.id)} className="px-2 py-1 text-xs bg-port-border rounded">Resume</button>}
+ </li>;
+ })}
+ </ul>}
+ {visibleRuns.length > 0 && <button type="button" onClick={refreshRuns} className="text-xs underline">Refresh runs</button>}
</div>
);
}
diff --git a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
index 7c2300ea82..feb7a6fb19 100644
--- a/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
+++ b/client/src/components/cos/tabs/schedule/MaintenanceRunForm.test.jsx
@@ -4,9 +4,13 @@ import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router';
import { MAINTENANCE_TASK_ORDER } from '../../../../lib/quotaBurnTasks';
+import { MAINTENANCE_SEQUENCE_TYPES } from '../../../../../../server/lib/maintenanceSequence';
import MaintenanceRunForm from './MaintenanceRunForm';
-const api = vi.hoisted(() => ({ getQuotaBurn: vi.fn(), saveQuotaBurn: vi.fn(), runQuotaBurn: vi.fn(), updateCosTaskInterval: vi.fn(), updateAppTaskTypeOverride: vi.fn() }));
+const api = vi.hoisted(() => ({
+ getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), resumeMaintenanceRun: vi.fn(),
+ updateCosTaskInterval: vi.fn(), updateAppTaskTypeOverride: vi.fn(),
+}));
vi.mock('../../../../services/api', () => api);
const tasks = Object.fromEntries([...MAINTENANCE_TASK_ORDER, 'claim-issue'].map(taskType => [taskType, {
enabled: true, perpetual: taskType === 'claim-issue', appOverrides: { example: { enabled: true } },
@@ -16,6 +20,11 @@ const props = {
providers: [{ id: 'claude', name: 'Claude', type: 'cli', command: 'claude', enabled: true, models: ['sonnet'] }],
providersLoaded: true, daemonRunning: true,
};
+const steps = MAINTENANCE_SEQUENCE_TYPES.map((taskType, index) => ({ id: `maint-1-${index}`, taskRef: { taskType } }));
+const runRecord = (overrides = {}) => ({
+ id: 'maint-1', appId: 'example', providerId: 'claude', model: 'sonnet', status: 'running', steps,
+ completed: { 'maint-1-0': 'done' }, active: { stepId: 'maint-1-1', taskType: 'claim-issue' }, reason: null, ...overrides,
+});
const show = (overrides = {}) => render(<MemoryRouter><MaintenanceRunForm {...props} {...overrides} /></MemoryRouter>);
const select = async user => {
await user.selectOptions(screen.getByLabelText('App'), 'example');
@@ -28,70 +37,53 @@ beforeEach(() => {
vi.clearAllMocks();
api.updateCosTaskInterval.mockResolvedValue({ success: true });
api.updateAppTaskTypeOverride.mockResolvedValue({ success: true });
- api.getQuotaBurn.mockResolvedValue({ config: { families: {} } });
- api.saveQuotaBurn.mockResolvedValue({ config: {} });
- api.runQuotaBurn.mockResolvedValue({ result: { dispatched: true } });
+ api.getMaintenanceRuns.mockResolvedValue({ runs: [] });
+ api.startMaintenanceRun.mockResolvedValue({ run: runRecord({ completed: {}, active: { stepId: 'maint-1-0', taskType: 'better-structural-drift' } }), result: { dispatched: true, taskType: 'better-structural-drift' } });
});
describe('maintenance launch', () => {
- it('saves ordered steps with app and pins before dispatch and gates duplicate launches', async () => {
+ it('starts a standalone run with the app and pins, and shows its progress', async () => {
const user = userEvent.setup();
- let finishSave;
- api.saveQuotaBurn.mockReturnValue(new Promise(resolve => { finishSave = resolve; }));
+ let finishStart;
+ api.startMaintenanceRun.mockReturnValue(new Promise(resolve => { finishStart = resolve; }));
show();
- expect(api.saveQuotaBurn).not.toHaveBeenCalled();
await select(user);
await user.click(screen.getByRole('button', { name: 'Run now' }));
- expect(api.runQuotaBurn).not.toHaveBeenCalled();
expect(screen.getByRole('button', { name: 'Starting…' })).toBeDisabled();
- const patch = api.saveQuotaBurn.mock.calls[0][0];
- expect(patch.enabled).toBe(true);
- const family = patch.families.claude;
- expect(family.sequence).toBe(true);
- expect(family.jobs.map(job => job.taskRef.taskType)).toEqual(MAINTENANCE_TASK_ORDER.flatMap((type, index) => index ? ['claim-issue', type] : [type]));
- for (const job of family.jobs) {
- expect(job.taskRef.appId).toBe('example');
- expect(job.overrides).toMatchObject({ providerId: 'claude', model: 'sonnet', effort: 'high' });
- expect(job.runOnce).toBe(true);
- }
- finishSave({ config: patch });
- await waitFor(() => expect(api.runQuotaBurn).toHaveBeenCalledWith({ familyId: 'claude', force: true }, { silent: true }));
- expect(await screen.findByText(/Maintenance started/)).toBeInTheDocument();
+ 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' });
+ expect(row).toHaveTextContent('Example App');
+ expect(row).toHaveTextContent('running · 1/13 steps · claim-issue');
expect(screen.getByRole('button', { name: 'Run now' })).toBeDisabled();
+ expect(screen.getByRole('link', { name: /Quota Burn/ })).toHaveAttribute('href', '/devtools/quota-burn');
});
- it('does not dispatch after a failed save and reports a saved but blocked run honestly', async () => {
+ it('reports a saved-but-holding run and a failed start honestly', async () => {
const user = userEvent.setup();
- api.saveQuotaBurn.mockRejectedValueOnce(new Error('save unavailable'));
+ api.startMaintenanceRun.mockResolvedValueOnce({ run: runRecord({ completed: {}, active: null, reason: 'provider unavailable' }), result: { dispatched: false, reason: 'provider unavailable' } });
show();
await select(user);
await user.click(screen.getByRole('button', { name: 'Run now' }));
- expect(await screen.findByText(/Could not save maintenance sequence: save unavailable/)).toBeInTheDocument();
- expect(api.runQuotaBurn).not.toHaveBeenCalled();
- api.runQuotaBurn.mockResolvedValueOnce({ result: { dispatched: false, reason: 'provider unavailable' } });
+ expect(await screen.findByText(/holding: provider unavailable/)).toBeInTheDocument();
+ api.startMaintenanceRun.mockRejectedValueOnce(new Error('a maintenance run is already in progress'));
+ await user.click(screen.getByRole('checkbox'));
await user.click(screen.getByRole('button', { name: 'Run now' }));
- expect(await screen.findByText(/Sequence saved; waiting: provider unavailable/)).toBeInTheDocument();
+ expect(await screen.findByText(/Could not start maintenance: a maintenance run is already in progress/)).toBeInTheDocument();
});
- it('preserves existing family plans and refuses to save when the plan cannot be read', async () => {
+ it('stops and resumes an existing run from the list', async () => {
const user = userEvent.setup();
+ api.getMaintenanceRuns.mockResolvedValue({ runs: [runRecord()] });
+ api.stopMaintenanceRun.mockResolvedValue({ run: runRecord({ status: 'stopped', reason: 'stopped by the user' }) });
+ api.resumeMaintenanceRun.mockResolvedValue({ run: runRecord(), result: { dispatched: true, taskType: 'claim-issue' } });
show();
- await select(user);
- api.getQuotaBurn.mockResolvedValueOnce({ config: { families: { claude: { jobs: [{ id: 'existing' }] } } } });
- await user.click(screen.getByRole('button', { name: 'Run now' }));
- expect(await screen.findByText(/This family already has a plan/)).toBeInTheDocument();
- expect(api.saveQuotaBurn).not.toHaveBeenCalled();
- api.getQuotaBurn.mockRejectedValueOnce(new Error('offline'));
- await user.click(screen.getByRole('button', { name: 'Run now' }));
- expect(await screen.findByText(/Could not check existing plan: offline/)).toBeInTheDocument();
- expect(api.saveQuotaBurn).not.toHaveBeenCalled();
- expect(api.runQuotaBurn).not.toHaveBeenCalled();
- });
- it('links to the saved plan after dispatch transport failure', async () => {
- const user = userEvent.setup();
- show();
- await select(user);
- api.runQuotaBurn.mockRejectedValueOnce(new Error('runner offline'));
- await user.click(screen.getByRole('button', { name: 'Run now' }));
- expect(await screen.findByText(/Sequence saved, but could not start: runner offline/)).toBeInTheDocument();
- expect(screen.getByRole('link', { name: /Manage sequence/ })).toHaveAttribute('href', '/devtools/quota-burn/claude');
+ await user.click(await screen.findByRole('button', { name: 'Stop' }));
+ expect(await screen.findByText(/stopped · 1\/13 steps/)).toBeInTheDocument();
+ expect(api.stopMaintenanceRun).toHaveBeenCalledWith('maint-1', { silent: true });
+ await user.click(screen.getByRole('button', { name: 'Resume' }));
+ expect(await screen.findByText(/running · 1\/13 steps/)).toBeInTheDocument();
+ expect(screen.getByText(/Maintenance started with claim-issue/)).toBeInTheDocument();
});
it('blocks missing task eligibility and a stopped daemon', async () => {
const user = userEvent.setup();
@@ -101,7 +93,7 @@ describe('maintenance launch', () => {
expect(screen.getByText(/Run now needs these saved task settings/)).toBeInTheDocument();
expect(screen.getByText(/start the CoS daemon/)).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Enable required tasks' })).not.toBeInTheDocument();
- expect(api.saveQuotaBurn).not.toHaveBeenCalled();
+ expect(api.startMaintenanceRun).not.toHaveBeenCalled();
});
});
@@ -135,14 +127,14 @@ it('enables only missing prerequisites and waits for refreshed saved settings be
expect(api.updateAppTaskTypeOverride).toHaveBeenCalledExactlyOnceWith('example', 'simplify', { enabled: true }, { silent: true });
expect(screen.getByRole('button', { name: 'Run now' })).toBeDisabled();
expect(screen.getByRole('combobox', { name: 'App' })).toBeDisabled();
- expect(api.runQuotaBurn).not.toHaveBeenCalled();
+ expect(api.startMaintenanceRun).not.toHaveBeenCalled();
finishRefresh();
await waitFor(() => expect(screen.getByRole('button', { name: 'Run now' })).toBeEnabled());
await user.click(screen.getByRole('button', { name: 'Run now' }));
expect(await screen.findByText(/Maintenance started/)).toBeInTheDocument();
});
-it('refreshes partial setup after failure without saving a plan or starting work', async () => {
+it('refreshes partial setup after failure without starting work', async () => {
const user = userEvent.setup();
const onRefresh = vi.fn().mockRejectedValue(new Error('refresh unavailable'));
api.updateAppTaskTypeOverride.mockRejectedValueOnce(new Error('save unavailable'));
@@ -153,6 +145,5 @@ it('refreshes partial setup after failure without saving a plan or starting work
expect(onRefresh).toHaveBeenCalledOnce();
expect(screen.getByText(/Refreshing the schedule also failed/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Run now' })).toBeDisabled();
- expect(api.saveQuotaBurn).not.toHaveBeenCalled();
- expect(api.runQuotaBurn).not.toHaveBeenCalled();
+ expect(api.startMaintenanceRun).not.toHaveBeenCalled();
});
diff --git a/client/src/lib/quotaBurnTasks.js b/client/src/lib/quotaBurnTasks.js
index 98718a368a..ecbd3b92e3 100644
--- a/client/src/lib/quotaBurnTasks.js
+++ b/client/src/lib/quotaBurnTasks.js
@@ -12,6 +12,8 @@
* inheritance display and the PUT payload without a server.
*/
+import { MAINTENANCE_DRAIN_TASK, MAINTENANCE_SEQUENCE_TYPES, MAINTENANCE_TASK_ORDER, maintenanceStepParams } from '../../../server/lib/maintenanceSequence.js';
+
/** Mirrors `QUOTA_BURN_TASK_REF_KIND` in `server/lib/quotaBurnTaskRef.js`. */
export const QUOTA_BURN_TASK_REF_KIND = Object.freeze({ BUILTIN: 'builtin', CUSTOM: 'custom' });
@@ -252,23 +254,24 @@ export const taskSourceHref = (entry) => (entry?.kind === QUOTA_BURN_TASK_REF_KI
/** Where a user goes to CREATE the on-demand scheduled task a new step would reference. */
export const CREATE_TASK_HREF = '/cos/jobs';
-/** Default maintenance ladder, using the canonical scheduled-task identifiers. */
-export const MAINTENANCE_TASK_ORDER = Object.freeze([
- 'better-structural-drift', 'simplify', 'module-hygiene', 'better-complexity',
- 'performance', 'better-cognitive-load', 'documentation',
-]);
-export const MAINTENANCE_ORDER_GUIDANCE = 'better-structural-drift → simplify → module-hygiene → better-complexity → performance + better-cognitive-load → documentation';
+/**
+ * The maintenance ladder is declared ONCE, server-side (`server/lib/maintenanceSequence.js`),
+ * because two runners walk it — the Schedule tab's manual run builds its steps
+ * there, and this page saves the same steps into a family plan. Re-exported so
+ * the guidance banner and the prerequisite check read the same list.
+ */
+export { MAINTENANCE_TASK_ORDER, MAINTENANCE_ORDER_GUIDANCE } from '../../../server/lib/maintenanceSequence.js';
/** Saved settings required by the maintenance ladder, including actionable patches. */
export function maintenancePrerequisites(groups, appId) {
if (!appId) return [];
const entries = flattenTaskCatalog(groups);
- return [...MAINTENANCE_TASK_ORDER, 'claim-issue'].flatMap(taskType => {
+ return [...MAINTENANCE_TASK_ORDER, MAINTENANCE_DRAIN_TASK].flatMap(taskType => {
const entry = entries.find(candidate => candidate.taskType === taskType);
if (!entry) return [{ taskType, reason: 'unavailable in Scheduled Tasks', unavailable: true }];
const settings = {
...(!entry.enabled ? { enabled: true } : {}),
- ...(taskType === 'claim-issue' && entry.config.perpetual !== true ? { perpetual: true } : {}),
+ ...(taskType === MAINTENANCE_DRAIN_TASK && entry.config.perpetual !== true ? { perpetual: true } : {}),
};
const enableApp = !entry.appIds.includes(appId);
const reasons = [
@@ -283,15 +286,12 @@ export function maintenancePrerequisites(groups, appId) {
/** Populate references only; preserve the source tasks and their configured filters. */
export function maintenanceSequence(groups, appId, idPrefix) {
const entries = flattenTaskCatalog(groups);
- const types = MAINTENANCE_TASK_ORDER.flatMap((type, index) =>
- index ? ['claim-issue', type] : [type]);
- const picked = types.map(type => entries.find(entry => entry.taskType === type));
+ const picked = MAINTENANCE_SEQUENCE_TYPES.map(type => entries.find(entry => entry.taskType === type));
if (!appId || maintenancePrerequisites(groups, appId).length) return null;
return picked.map((entry, index) => ({
...stepFromTaskEntry(entry, { id: `${idPrefix}-${index}`, appId }),
runOnce: true,
- drain: entry.taskType === 'claim-issue',
- overrides: { providerId: null, model: null, effort: null,
- params: entry.taskType === 'claim-issue' ? {} : { fileIssues: entry.taskType !== 'documentation' } },
+ drain: entry.taskType === MAINTENANCE_DRAIN_TASK,
+ overrides: { providerId: null, model: null, effort: null, params: maintenanceStepParams(entry.taskType) },
}));
}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index a33a6da4d5..bccaa045b3 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -41,7 +41,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiApps.js` | App CRUD + PM2 ops (start/stop/restart) + local open actions (editor, folder, Xcode) + `getAppIssues` (open GitHub/GitLab issues for the Issues tab). |
| `apiWorkspaceContexts.js` | Per-project working-context save/restore (branch, shells, tasks). |
| `apiAccounts.js` | Platform accounts. |
-| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, and persistent-mind conversation, lifecycle, context, and runtime-telemetry calls. |
+| `apiAgents.js` | Running-agent process management, CoS run-event diagnostics, the CoS task schedule (intervals, on-demand triggers, manual maintenance runs via `getMaintenanceRuns`/`startMaintenanceRun`/`stopMaintenanceRun`/`resumeMaintenanceRun`), and persistent-mind conversation, lifecycle, context, and runtime-telemetry calls. |
| `apiCommands.js` | CLI command dispatch. |
| `apiDashboard.js` | Dashboard state. |
| `apiDatabase.js` | Database introspection. |
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index aca979c868..0d07a70392 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -305,6 +305,17 @@ export const updateCosTaskInterval = (taskType, settings, options = {}) => reque
...options
});
+// Manual maintenance runs — the Schedule tab's "Run maintenance now" (server:
+// services/maintenanceRun.js).
+export const getMaintenanceRuns = (options) => request('/cos/schedule/maintenance-runs', options);
+export const startMaintenanceRun = ({ appId, providerId, model, effort = null }, options = {}) => request('/cos/schedule/maintenance-runs', {
+ method: 'POST',
+ body: JSON.stringify({ appId, providerId, model, effort }),
+ ...options
+});
+export const stopMaintenanceRun = (id, options = {}) => request(`/cos/schedule/maintenance-runs/${id}/stop`, { method: 'POST', ...options });
+export const resumeMaintenanceRun = (id, options = {}) => request(`/cos/schedule/maintenance-runs/${id}/resume`, { method: 'POST', ...options });
+
export const triggerCosOnDemandTask = (taskType, appId = null, options = {}) => request('/cos/schedule/trigger', {
method: 'POST',
body: JSON.stringify({ taskType, appId }),
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index e46c5547f8..24d3916804 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -601,21 +601,45 @@ reaches disk instead of being persisted as a step the runner can only refuse.
## Maintenance sequence
-An empty family plan offers **Populate maintenance sequence** and **Populate and
-start sequence** after choosing an app. The latter saves first, enables Quota
-Burn and the family, then evaluates the plan under its quota gates. No tasks
-run merely by opening the page or populating the plan.
-
-The default order is structural drift → simplify → module hygiene → complexity
-→ performance + cognitive load → documentation. Performance and cognitive load
-share a stage in the guidance; the preset serializes performance first. A
-perpetual `claim-issue` drain separates every pair of audits (13 steps total).
-The first six audits explicitly file issues; documentation explicitly does the
-work. All steps reference the existing scheduled tasks and inherit their pins
-and configuration. Each task must be enabled for the selected app, and
-`claim-issue` must have perpetual mode enabled in Scheduled Tasks.
-
-This opts the family into `sequence: true`. Unlike the existing rotation, an
+The maintenance ladder — structural drift → simplify → module hygiene →
+complexity → performance → cognitive load → documentation, with a perpetual
+`claim-issue` drain between every pair of audits (13 steps) — is declared once
+in `server/lib/maintenanceSequence.js` and can be run two ways:
+
+- **Now, from the CoS Schedule tab** ("Run maintenance now"). This is a
+ standalone run (`server/services/maintenanceRun.js`, `data/cos/maintenance-runs.json`),
+ NOT a burn: it needs no Quota Burn master switch, faces no reset-window /
+ reserve / dispatch-cap gates, writes nothing into any family plan, and has
+ nothing to re-arm — every "Run now" is a fresh run with its own completion
+ ledger. Pick the app, a subscription CLI/TUI provider, a model and an optional
+ effort; every step is pinned to them. Each audit is dispatched when the
+ previous step finishes and each drain repeats until the app's issue backlog
+ is empty, so the run walks to the end on its own. A step that cannot go out
+ (a task disabled since, a blocked task, a transient claim probe) HOLDS the run
+ with its reason and is retried on each completion and on a slow sweep; Stop
+ ends dispatching (a task already queued or running is not recalled) and Resume
+ picks the ladder up from its ledger. One running run per app.
+- **Later, under quota gates, from this page.** An empty family plan offers
+ **Populate maintenance sequence** and **Populate and start sequence** after
+ choosing an app. The latter saves first, enables Quota Burn and the family,
+ then evaluates the plan under its quota gates. No tasks run merely by opening
+ the page or populating the plan.
+
+Both share the invocation path (`quotaBurnInvoke.js`), so the schedule's own
+gate ladder applies either way: each task must be enabled globally and for the
+selected app, `claim-issue` must have perpetual mode enabled in Scheduled
+Tasks, the master Improve switch must be on, and the CoS daemon must be running
+to accept the requests. The first six audits explicitly file issues; documentation
+explicitly does the work. All steps reference the existing scheduled tasks and
+inherit their pins and configuration.
+
+A manual run's tasks carry the family provenance (so they are cooldown-exempt
+and an observed refusal is credited to the window they spent) plus a
+`maintenanceRunId`, which is what tells the burn loop to leave them alone: a
+manual run's completion never dispatches a plan step, and a plan's sequence
+never waits on a manual run's task.
+
+A saved plan opts the family into `sequence: true`. Unlike the existing rotation, an
unavailable, disabled, queued, running, or blocked predecessor holds the sequence.
Audits finish after successful completion; a `drain: true` claim step repeats
under the same quota gates until the configured eligibility detector reports no
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 50a116f81e..06a650e282 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -68,6 +68,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, explicit display aliases keyed by opaque resource identity (never backfilled from records), user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. Guest travel sessions and live chat cursors are ephemeral transport state held only in memory; they are not a new record store or sync category. Explicit guest conversation follows the [guest-chat ADR](decisions/2026-09-05-eidoverse-guest-chat.md). PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + an ordered list of steps, each a REFERENCE to a scheduled task (`data/cos/task-schedule.json` or the app job store) plus its per-invocation overrides. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and a step's scheduled-task reference names task types and managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
+- Manual maintenance runs — `data/cos/maintenance-runs.json`. A capped list of the Schedule tab's "Run maintenance now" records: the app, the pinned provider/model/effort, the ladder's steps, the per-step completion ledger and the current hold reason. `ephemeral-file` and machine-local like the burn plan (its steps name task types and managed apps that only exist here); deleting it only forgets progress — a run in flight would have to be started again. See [Quota Burn → Maintenance sequence](./QUOTA-BURN.md#maintenance-sequence).
- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.
- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.
- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).
diff --git a/server/lib/README.md b/server/lib/README.md
index 25613abc0c..e0826f972b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -71,7 +71,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `autonomousJobTask.js` | `generatedJobTaskFields` — flattens a `generateTaskFromJob` result into the top-level keys the non-raw `cos.addTask` path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the retired executor's task-description parser (`QUOTA_BURN_TASK_PREFIX` / `quotaBurnFamilyOfDescription`), kept for migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |
| `quotaBurnLegacyConversion.js` | The ONE rule turning a LEGACY quota-burn step (copied prompt + quota-only `jobType`) into a scheduled-task reference, shared by migration 359 and the live compat path so the two cannot drift. `planQuotaBurnStepConversion` decides between three outcomes — a recognized unmodified shipped preset onto its scheduled audit counterpart with issues-only pinned explicitly (`AUDIT_TASK_TYPE_BY_PRESET_ID`, inverted from `auditCatalog.js`), the two programmatic types onto their scheduled handlers, and anything customized or targetless onto a `buildQuotaBurnCustomJob` on-demand custom task addressed by the deterministic `quotaBurnCustomJobId` (which is what makes a repeated or resumed conversion create no duplicate). `legacyAgentTaskMetadata` reproduces the retired executor's dispatch posture; `applyQuotaBurnStepConversion` rewrites the step, preserving id, label, enabled and run-once state. Recognition is `matchStoredAuditPreset`, never a label or a partial match. |
-| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block. `onDemandRequestMetadata` is the single spread both on-demand engines apply. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |
+| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (family + burn-step id required, plus the limiting-window reset, the provider/model/effort overrides and the optional manual `maintenanceRunId`); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block; `burnPlanOwnsTask` / `burnPlanOwnsAgent` are the ONE rule for whether the family plan (not a manual maintenance run) owns a burn-provenanced task. `onDemandRequestMetadata` is the single spread both on-demand engines apply. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |
| `quotaBurnPresets.js` | FROZEN compatibility-and-migration input (#6381). `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`; `matchStoredAuditPreset` is migration 305's recognition rule (match the MISSION half, gated on the shipped contract anchors + headings) and `upgradeStoredAuditPrompt` is the refresh built on it. |
| `auditCatalog.js` | `getAuditScheduleMetadata` derives upgrade-safe display names and cluster labels; `AUDIT_RUN_GUIDANCE` supplies advisory sequencing. Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, `quotaBurnStepIsDispatchable`, and `evaluateOnDemandEligibility` — the ONE on-demand gate ladder (`enabled` / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with `taskSchedule.triggerOnDemandTask`, with `enabledAppIdsByTaskType` deriving its per-app input. |
@@ -181,6 +181,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. |
| `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |
| `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |
+| `maintenanceSequence.js` | The maintenance ladder shared by both runners: `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE`, the interleaved `MAINTENANCE_SEQUENCE_TYPES` (a perpetual `claim-issue` drain between every pair of audits), `maintenanceStepParams` (audits file issues, documentation does the work), and `buildMaintenanceSteps` which emits quota-burn-shaped run-once steps so `quotaBurnInvoke.js` can run a step from the Schedule tab's manual run or a Quota Burn family plan alike. Pure. |
| `meetingUrl.js` | Selects the one cacheable join URL (`selectMeetingUrl`) out of a raw Google Calendar event — first http(s) `video` entry point, else `hangoutLink` — and owns the shared `MEETING_URL_MAX` bound. Three-state: `undefined` = the producer never described conferencing, `null` = described with none usable. |
| `minimaxH3Memory.js` | The declared weight-placement table for the three MiniMax H3 entries (#5420) — H3 is the one video model family whose components fit nowhere unassisted, so "does this box have enough" is a render gate, not a UI fact. `MINIMAX_H3_MEMORY_PROFILES` maps entry id → `{ shippedRepo, shippedRevision, profiles }`, each profile carrying an honest `minMemoryGb` host floor and (CUDA only) a `minVramGb` device floor, ordered best-first. Every capacity number is HOISTED from what already existed — the CUDA tiers are `resolve_offload_profile()`'s own thresholds in `scripts/generate_minimax_h3_cuda.py`, the host floors are the entries' `memoryGb` — the sole new number being `MINIMAX_H3_HOST_RESERVE_GB`, a policy reserve held back for the OS. `applyMiniMaxH3MemoryProfiles(list)` is the load-time backfill (twin of migration 317) and guards BOTH `repo` and `revision`, like the speed-profile decorator. `selectMiniMaxH3MemoryProfile({ model, totalMemoryGb })` picks the best profile the HOST can hold (VRAM is the runner's call — the server has no synchronous device view); `miniMaxH3MemoryDeclineReason()` RETURNS the fail-closed reason so the render path can 400 it and a status surface can show it, and returns `null` on an UNMEASURED host — "not measured" is a deferral to the runner, never the same as zero. `validateMiniMaxH3MemoryProfileTable` / `sanitizeMiniMaxH3MemoryProfiles` warn + strip a hand-edited table (NaN floor, duplicate/reserved id, mis-ordered tiers) at load. |
| `videoContinuity.js` | How chunk N+1 of a chained video render is conditioned on chunk N. `resolveContextFrames(requested)` normalizes the tail-window size (absent → `DEFAULT_CONTEXT_FRAMES` = 22 ≈ 1s @ 24fps; an explicit `0` is preserved as "last frame only", NOT collapsed into the default) and clamps to `MIN_CONTEXT_FRAMES`..`MAX_CONTEXT_FRAMES`. `resolveContinuityStrategy({model, contextFrames})` picks `'window'` (LTX-2 `extend_from_video` conditioned on the prior chunk's last N frames — motion, not just a pose) or `'frame'` (extract the last frame, run i2v), degrading to `'frame'` on any runtime outside `CONTEXT_WINDOW_RUNTIMES` rather than rejecting. `extendLatentFrames` / `extendedPixelFrames` convert across the VAE's `LATENT_FRAME_STRIDE` (8 pixel frames per latent), `contextPrefixFrames({totalFrames, extendLatents})` measures how much of an extend render is echoed context to trim back off before stitching (0 = leave it alone), and `tailWindowStartFrame` gives the cut index for the window itself. Pure — importable from `prepareParams.js` without dragging in `local.js`. Mirrored for the picker in `client/src/lib/videoGenParams.js`, pinned by `videoContinuity.parity.test.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index ca736a8e56..865ba707b9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -228,6 +228,7 @@ export * from './mtplxModels.js';
export * from './mtplxRuntime.js';
export * from './slotstreamCatalog.js';
export * from './slotstreamModels.js';
+export * from './maintenanceSequence.js';
export * from './managedDaemon.js';
export * from './recordedProjectDir.js';
export * from './vllmQwenProject.js';
diff --git a/server/lib/maintenanceSequence.js b/server/lib/maintenanceSequence.js
new file mode 100644
index 0000000000..f96704fda6
--- /dev/null
+++ b/server/lib/maintenanceSequence.js
@@ -0,0 +1,60 @@
+/**
+ * The maintenance ladder: the ordered audits PortOS recommends running against a
+ * managed app, with a perpetual `claim-issue` drain between every pair so each
+ * audit's findings are resolved before the next audit reads the code.
+ *
+ * ONE definition, shared by both runners. `services/maintenanceRun.js` walks
+ * these steps directly for the Schedule tab's "Run now" — no quota gates, no
+ * burn plan — and the Quota Burn page's "Populate maintenance sequence" saves the
+ * same steps into a family plan to be walked later under that family's window
+ * gates. The client (`client/src/lib/quotaBurnTasks.js`) imports the order from
+ * here so the guidance banner, the prerequisite check and the server's own
+ * builder cannot disagree about what the ladder is.
+ *
+ * Pure: no I/O, no imports out of `lib/`. The step shape is the quota-burn job
+ * shape (`quotaBurnTaskRef.js`) so `quotaBurnInvoke.js` can run a step from
+ * either runner without knowing which one asked.
+ */
+
+/** The audits, in the order they should run. */
+export const MAINTENANCE_TASK_ORDER = Object.freeze([
+ 'better-structural-drift', 'simplify', 'module-hygiene', 'better-complexity',
+ 'performance', 'better-cognitive-load', 'documentation',
+]);
+
+export const MAINTENANCE_ORDER_GUIDANCE = 'better-structural-drift → simplify → module-hygiene → better-complexity → performance + better-cognitive-load → documentation';
+
+/** The drain that separates every pair of audits. */
+export const MAINTENANCE_DRAIN_TASK = 'claim-issue';
+
+/** Every scheduled task the ladder references, drain included, in ladder order. */
+export const MAINTENANCE_SEQUENCE_TYPES = Object.freeze(MAINTENANCE_TASK_ORDER.flatMap((type, index) =>
+ (index ? [MAINTENANCE_DRAIN_TASK, type] : [type])));
+
+/**
+ * The run params an audit step pins. The first six audits explicitly FILE
+ * issues (which the drain then claims); documentation explicitly does the work.
+ * A drain pins nothing — it inherits the app's saved claim filters.
+ */
+export const maintenanceStepParams = (taskType) => (taskType === MAINTENANCE_DRAIN_TASK
+ ? {}
+ : { fileIssues: taskType !== 'documentation' });
+
+/**
+ * Build the ladder as run-once steps targeting `appId`, every one pinned to the
+ * provider/model/effort the user chose. `effort: null` inherits each scheduled
+ * task's saved effort. Ids are `${idPrefix}-${index}`, so a fresh prefix per
+ * invocation yields fresh step identities.
+ */
+export function buildMaintenanceSteps({ appId, idPrefix, providerId = null, model = null, effort = null }) {
+ return MAINTENANCE_SEQUENCE_TYPES.map((taskType, index) => ({
+ id: `${idPrefix}-${index}`,
+ enabled: true,
+ label: '',
+ taskRef: { kind: 'builtin', taskType, appId },
+ jobType: null,
+ runOnce: true,
+ drain: taskType === MAINTENANCE_DRAIN_TASK,
+ overrides: { providerId, model, effort, params: maintenanceStepParams(taskType) },
+ }));
+}
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.js
index 2a16586c62..2446e0b12d 100644
--- a/server/lib/quotaBurnOrigin.js
+++ b/server/lib/quotaBurnOrigin.js
@@ -84,6 +84,12 @@ export const QUOTA_BURN_PROVENANCE_FIELDS = Object.freeze([
// synthesized — on the synchronous custom-job lane, which queues the task itself
// and has no request to name; a fake id would make a join over it silently wrong.
{ field: 'requestId', taskKey: 'quotaBurnRequestId', agentKey: 'taskQuotaBurnRequestId', read: asId },
+ // The MANUAL maintenance run that asked (`services/maintenanceRun.js`), absent
+ // on an automatic burn. It is what lets the quota-burn runner leave a manual
+ // run's agents alone — the run walks its own ladder, outside the family's
+ // plan, its completion ledger and its window gates — while the family
+ // attribution above still credits a refusal to the window it actually spent.
+ { field: 'maintenanceRunId', taskKey: 'quotaBurnMaintenanceRunId', agentKey: 'taskQuotaBurnMaintenanceRunId', read: asId },
].map(Object.freeze));
/**
@@ -132,6 +138,20 @@ export function quotaBurnAgentMetadata(taskMetadata) {
/** Whether a task carries attributable burn provenance at all. */
export const hasQuotaBurnProvenance = (taskMetadata) => Boolean(quotaBurnProvenance(taskMetadata).family);
+/**
+ * Whether the family's burn PLAN owns this task: burn-provenanced, and not a
+ * manual maintenance run's. The one rule the plan's sequence walk and its
+ * completion continuation both apply — a manual run spends the family's
+ * window (so the denial ledger still hears about it) but walks its own ladder,
+ * so the plan neither advances on it nor waits for it. `burnPlanOwnsAgent` is
+ * the same rule over the agent projection (`quotaBurnAgentMetadata`).
+ */
+export function burnPlanOwnsTask(taskMetadata) {
+ const block = quotaBurnProvenance(taskMetadata);
+ return Boolean(block.family) && !block.maintenanceRunId;
+}
+export const burnPlanOwnsAgent = (agent) => Boolean(agent?.metadata?.taskQuotaBurnFamily) && !agent.metadata.taskQuotaBurnMaintenanceRunId;
+
const trimmed = (value, max = MAX_FIELD) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
const nullable = (value, max = MAX_FIELD) => trimmed(value, max) || null;
@@ -186,6 +206,7 @@ export function normalizeQuotaBurnProvenance(raw) {
family,
stepId,
limitingResetAt: Number.isFinite(limitingResetAt) ? limitingResetAt : null,
+ ...(nullable(raw.maintenanceRunId) ? { maintenanceRunId: nullable(raw.maintenanceRunId) } : {}),
overrides: {
providerId: nullable(overrides.providerId),
model: nullable(overrides.model),
diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.js
index aff79e7cc6..5b5a004001 100644
--- a/server/lib/quotaBurnOrigin.test.js
+++ b/server/lib/quotaBurnOrigin.test.js
@@ -136,7 +136,7 @@ describe('the quota-burn provenance block', () => {
// ledger being able to read it. Driving both sides off the one table means a
// new row cannot be half-applied, and this asserts the table IS both sides.
const persisted = quotaBurnTaskMetadata({
- family: 'grok', limitingResetAt: 1700000000000, stepId: 'step-1', requestId: 'demand-7',
+ family: 'grok', limitingResetAt: 1700000000000, stepId: 'step-1', requestId: 'demand-7', maintenanceRunId: 'maint-1',
});
const projected = quotaBurnAgentMetadata(persisted);
for (const { taskKey, agentKey } of QUOTA_BURN_PROVENANCE_FIELDS) {
@@ -155,6 +155,7 @@ describe('the quota-burn provenance block', () => {
taskQuotaBurnLimitingResetAt: 1700000000000,
taskQuotaBurnStepId: null,
taskQuotaBurnRequestId: null,
+ taskQuotaBurnMaintenanceRunId: null,
});
expect(quotaBurnAgentMetadata(undefined).taskQuotaBurnFamily).toBeNull();
});
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index 47650ad9cb..07890cf54c 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -13,6 +13,7 @@ import { EFFORT_LEVELS } from '../lib/providerModels.js';
import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../services/taskScheduleConstants.js';
import { normalizeSuggestedAfter, SUGGESTED_AFTER_MAX } from '../lib/scheduleRunOrder.js';
import { findCronExpressionError } from '../lib/cronValidation.js';
+import { listMaintenanceRuns, resumeMaintenanceRun, startMaintenanceRun, stopMaintenanceRun } from '../services/maintenanceRun.js';
const templateTaskSchema = z.object({
name: z.string().min(1),
@@ -30,6 +31,16 @@ const scheduleLabelsSchema = z.array(z.string().trim().min(1).max(40)).max(20)
// so the storage rules live with the field's own helper, not in the route.
const suggestedAfterSchema = z.array(z.string()).max(SUGGESTED_AFTER_MAX);
+// A manual maintenance run names the app, the subscription provider and the
+// model up front (AGENTS.md AI-policy: the click IS the consent). Blank effort
+// inherits each scheduled task's saved effort.
+const maintenanceRunStartSchema = z.object({
+ appId: z.string().trim().min(1),
+ providerId: z.string().trim().min(1),
+ model: z.string().trim().min(1),
+ effort: z.enum(EFFORT_LEVELS).nullable().optional(),
+}).strict();
+
const router = Router();
const SCHEDULE_FIELDS = ['type', 'perpetual', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'description', 'labels', 'dataInputs', 'taskMetadata', 'runAfter',
@@ -246,6 +257,29 @@ router.post('/schedule/trigger', asyncHandler(async (req, res) => {
res.json({ success: true, request });
}));
+// Manual maintenance runs — the Schedule tab's "Run maintenance now"; see
+// services/maintenanceRun.js for why this is not a quota burn.
+router.get('/schedule/maintenance-runs', asyncHandler(async (_req, res) => {
+ res.json({ runs: await listMaintenanceRuns() });
+}));
+
+router.post('/schedule/maintenance-runs', asyncHandler(async (req, res) => {
+ const body = validateRequest(maintenanceRunStartSchema, req.body || {});
+ res.status(201).json(await startMaintenanceRun(body));
+}));
+
+router.post('/schedule/maintenance-runs/:id/stop', asyncHandler(async (req, res) => {
+ const run = await stopMaintenanceRun(req.params.id);
+ if (!run) throw new ServerError('Maintenance run not found', { status: 404, code: 'NOT_FOUND' });
+ res.json({ run });
+}));
+
+router.post('/schedule/maintenance-runs/:id/resume', asyncHandler(async (req, res) => {
+ const resumed = await resumeMaintenanceRun(req.params.id);
+ if (!resumed) throw new ServerError('Maintenance run not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(resumed);
+}));
+
// GET /api/cos/schedule/on-demand - Get pending on-demand requests
router.get('/schedule/on-demand', asyncHandler(async (req, res) => {
const requests = await taskSchedule.getOnDemandRequests();
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index 2ffd927ccf..7cb47fe778 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -5,6 +5,8 @@ import scheduleRoutes from './cosScheduleRoutes.js';
const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
vi.mock('../services/userActions.js', () => ({ recordUserAction }));
+const maintenance = vi.hoisted(() => ({ listMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), resumeMaintenanceRun: vi.fn() }));
+vi.mock('../services/maintenanceRun.js', () => maintenance);
vi.mock('../services/taskSchedule.js', () => ({
getScheduleStatus: vi.fn(),
@@ -72,6 +74,28 @@ describe('CoS Schedule Routes', () => {
});
});
+ describe('manual maintenance runs', () => {
+ it('starts a run from a validated body and reports the first dispatch', async () => {
+ maintenance.startMaintenanceRun.mockResolvedValue({ run: { id: 'maint-1', status: 'running' }, result: { dispatched: true, taskType: 'better-structural-drift' } });
+ const response = await request(app).post('/api/cos/schedule/maintenance-runs').send({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: null });
+ expect(response.status).toBe(201);
+ expect(response.body.result.taskType).toBe('better-structural-drift');
+ expect(maintenance.startMaintenanceRun).toHaveBeenCalledWith({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: null });
+ // The model is not optional: a run must name what it spends.
+ expect((await request(app).post('/api/cos/schedule/maintenance-runs').send({ appId: 'app-1', providerId: 'codex' })).status).toBe(400);
+ expect(maintenance.startMaintenanceRun).toHaveBeenCalledTimes(1);
+ });
+
+ it('lists, stops and resumes runs, and 404s an unknown id', async () => {
+ maintenance.listMaintenanceRuns.mockResolvedValue([{ id: 'maint-1' }]);
+ expect((await request(app).get('/api/cos/schedule/maintenance-runs')).body).toEqual({ runs: [{ id: 'maint-1' }] });
+ maintenance.stopMaintenanceRun.mockResolvedValue({ id: 'maint-1', status: 'stopped' });
+ expect((await request(app).post('/api/cos/schedule/maintenance-runs/maint-1/stop')).body.run.status).toBe('stopped');
+ maintenance.resumeMaintenanceRun.mockResolvedValue(null);
+ expect((await request(app).post('/api/cos/schedule/maintenance-runs/maint-1/resume')).status).toBe(404);
+ });
+ });
+
describe('GET /api/cos/upcoming', () => {
it('should return upcoming tasks with default limit', async () => {
taskSchedule.getUpcomingTasks.mockResolvedValue([{ taskType: 'review', dueIn: 300 }]);
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index fdbb0f7830..00e10e5d33 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -83,6 +83,7 @@ import { initVoiceTimers } from './voice/timers.js';
import { startBackupScheduler } from './backupScheduler.js';
import { startPrivacyRecheckScheduler } from './privacyRecheckScheduler.js';
import { startQuotaBurnScheduler } from './quotaBurnRunner.js';
+import { startMaintenanceRunScheduler } from './maintenanceRun.js';
import { startSeriesAutopilotScheduler } from './seriesAutopilotScheduler.js';
import { startCommissionScheduler } from './creativeCommissions/scheduler.js';
import { startImessageScheduler } from './imessageScheduler.js';
@@ -425,6 +426,9 @@ const startBackgroundServices = ({ spawnerReady, io }) => {
// family, provider, model, and work are all named first (sanctioned
// scheduled-automation exception).
startQuotaBurnScheduler();
+ // Manual maintenance runs (Schedule tab → "Run maintenance now"): arms a
+ // listener and a slow sweep; dispatches only for a run the user started.
+ startMaintenanceRunScheduler();
// Initialize Series Autopilot scheduler — OFF by default; registers a cron per
// series only when the user configured + enabled one via Settings → Series
// Autopilot. Each scheduled run still passes through the cos autonomy gate +
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
new file mode 100644
index 0000000000..63da1b6267
--- /dev/null
+++ b/server/services/maintenanceRun.js
@@ -0,0 +1,281 @@
+/**
+ * Manual maintenance runs — the Schedule tab's "Run maintenance now".
+ *
+ * A run walks the maintenance ladder (`lib/maintenanceSequence.js`) against ONE
+ * managed app, pinned to the provider/model/effort the user chose, and it walks
+ * it to the END: each audit is dispatched when the previous step finishes, and
+ * every `claim-issue` drain repeats until the app's issue backlog is empty.
+ *
+ * It is deliberately NOT a quota burn. The Quota Burn page offers the same
+ * ladder as a family plan to be walked later, under that family's window gates
+ * — and a run started here used to be written INTO that plan and force-started,
+ * which coupled "run it now" to everything the plan is for: the master switch
+ * had to be on, the family plan had to be empty, only the first step bypassed
+ * the reset-window / reserve / cap gates (every later step waited on them), and
+ * running again meant re-arming the plan. A manual run keeps its own record,
+ * its own completion ledger and its own continuation, so none of that applies:
+ * it runs whether or not Quota Burn is enabled, beside whatever plan the family
+ * holds, and a second run is just a second record.
+ *
+ * What it shares with a burn is the INVOCATION: every step is dispatched through
+ * `quotaBurnInvoke.invokeQuotaBurnStep`, so the schedule's own gate ladder (task
+ * enabled, per-app switch, master Improve, target scope, duplicate requests)
+ * still applies, the provider is pinned to the family the user named, and the
+ * task carries the family provenance that makes it cooldown-exempt and lets an
+ * observed refusal be credited to the right window. The `maintenanceRunId`
+ * provenance field is what tells the quota-burn loop to leave these agents
+ * alone (`quotaBurnRunner.js#onBurnAgentCompleted`).
+ *
+ * Pacing is by completion: `agent:completed` for one of the run's tasks
+ * re-evaluates the run, and a slow interval re-evaluates every running run as
+ * the safety net for holds that no agent completion will lift — a transient
+ * claim probe, a queued request an engine refused, a task setting the user
+ * fixes after the fact. A hold never ends a run: it is re-tried until it
+ * clears, or the user stops the run.
+ *
+ * AI-policy posture (AGENTS.md): every dispatch traces to the user's click on
+ * "Run now", which names the app, provider and model. Boot arms the listener
+ * and the interval; neither dispatches anything on an install with no running
+ * run, and a fresh install has none.
+ *
+ * Storage: `data/cos/maintenance-runs.json`, machine-local and `ephemeral-file`
+ * — a capped list of run records, newest first. No `data.reference/` seed: an
+ * absent file is "no runs yet".
+ */
+
+import { join } from 'path';
+import { ServerError } from '../lib/errorHandler.js';
+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
+import { buildMaintenanceSteps } from '../lib/maintenanceSequence.js';
+import { familyForProvider } from '../lib/providerFamilies.js';
+import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
+import { cosEvents } from './cosEvents.js';
+import { getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';
+import { ACTIVE_TASK_STATUSES, probeSequenceDrain, sequenceStepShapeReason } from './quotaBurnSequence.js';
+
+const runsFile = () => join(PATHS.cos, 'maintenance-runs.json');
+
+/** Finished runs kept for the page's history; running ones are never pruned. */
+const RUN_HISTORY_LIMIT = 20;
+/** The safety-net re-evaluation cadence for holds no agent completion will lift. */
+const RETRY_MS = 2 * 60_000;
+
+export const MAINTENANCE_RUN_STATUS = Object.freeze({ RUNNING: 'running', COMPLETED: 'completed', STOPPED: 'stopped' });
+
+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();
+let retryTimer = null;
+
+export async function listMaintenanceRuns() {
+ const loaded = await readJSONFile(runsFile(), null);
+ return Array.isArray(loaded?.runs) ? loaded.runs : [];
+}
+
+/**
+ * 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.
+ */
+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;
+ });
+}
+
+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);
+ if (active) throw activeRunError(appId, active.id);
+}
+
+/**
+ * Start a run. Refused (with a thrown, coded error the route maps to a 4xx)
+ * when the app is unknown or archived, the provider is not an enabled
+ * subscription CLI/TUI provider in a known family — the SAME gate every dispatch
+ * re-applies (`resolveBurnProvider`), so a run can never start on a provider
+ * its steps would then refuse — or the app already has a running run.
+ *
+ * The first evaluation runs before this returns, so the caller learns whether
+ * step one actually went out (or why it is holding) in the same response.
+ */
+export async function startMaintenanceRun({ appId, providerId, model = null, effort = null }) {
+ const [{ getAppById }, { getProviderById }, { resolveBurnProvider }] = await Promise.all([
+ import('./apps.js'), import('./providers.js'), import('./scheduledHandlers/providerPick.js'),
+ ]);
+ const [app, provider] = await Promise.all([getAppById(appId), getProviderById(providerId)]);
+ if (!app || app.archived === true) throw new ServerError(`managed app "${appId}" is not available`, { status: 400, code: 'MAINTENANCE_RUN_APP_UNAVAILABLE' });
+ const familyId = familyForProvider(provider);
+ const pinned = familyId ? await resolveBurnProvider({ job: { providerId }, family: { id: familyId } }) : null;
+ if (!pinned) throw new ServerError(`provider "${providerId}" is not an enabled subscription CLI/TUI provider`, { status: 400, code: 'MAINTENANCE_RUN_PROVIDER_UNAVAILABLE' });
+ await assertNoRunningRun(appId);
+
+ 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({
+ id, appId, familyId, ...pins,
+ status: MAINTENANCE_RUN_STATUS.RUNNING,
+ steps: buildMaintenanceSteps({ appId, idPrefix: id, ...pins }),
+ completed: {},
+ active: null,
+ reason: null,
+ startedAt: now, updatedAt: now, finishedAt: null,
+ });
+ console.log(`🧹 Maintenance run ${id} started for ${appId} via ${providerId}`);
+ const result = await evaluateMaintenanceRun(id);
+ return { run: await getMaintenanceRun(id) || run, result };
+}
+
+/**
+ * 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 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);
+ 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.
+ */
+export const evaluateMaintenanceRun = (id, { ignoreTaskId = null } = {}) => evaluations(id, () => evaluate(id, { ignoreTaskId }));
+
+async function evaluate(id, { ignoreTaskId }) {
+ const run = await getMaintenanceRun(id);
+ if (!run) return { skipped: 'unknown run' };
+ 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 }));
+ return { dispatched: false, reason };
+ };
+
+ const [{ getAllTasks }, { getOnDemandRequests }] = await Promise.all([import('./cosTaskStore.js'), import('./taskSchedule.js')]);
+ const { user, cos } = await getAllTasks();
+ const ownTask = [...(user?.tasks || []), ...(cos?.tasks || [])].find((task) => task.id !== ignoreTaskId
+ && quotaBurnProvenance(task.metadata).maintenanceRunId === id && ACTIVE_TASK_STATUSES.has(task.status));
+ if (ownTask) return hold(`waiting for ${ownTask.status.replace('_', ' ')} task ${ownTask.id}`);
+ const queued = (await getOnDemandRequests()).find((request) => request?.burn?.maintenanceRunId === id);
+ if (queued) return hold(`waiting for the CoS daemon to accept request ${queued.id} (${queued.taskType})`);
+
+ const catalog = await getQuotaBurnTaskCatalog();
+ const completed = { ...run.completed };
+ for (const step of run.steps) {
+ if (completed[step.id]) continue;
+ const shape = sequenceStepShapeReason(step);
+ if (shape) return hold(shape);
+ if (step.drain) {
+ const probe = await probeSequenceDrain(step, { catalog, ignoreTaskId });
+ if (probe.drained) {
+ completed[step.id] = new Date().toISOString();
+ continue;
+ }
+ if (!probe.job) return hold(probe.reason);
+ }
+ 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, {
+ 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, {
+ 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' };
+}
+
+/**
+ * Continuation. An audit step is done when its agent SUCCEEDS; a failed agent
+ * leaves its task blocked, which the next evaluation reports as a hold until
+ * the user retries or dismisses it. A drain step is never completed here — the
+ * claim probe decides that on the evaluation this triggers.
+ */
+function onMaintenanceAgentCompleted(agent) {
+ const id = agent?.metadata?.taskQuotaBurnMaintenanceRunId;
+ if (!id) return null;
+ const stepId = agent.metadata?.taskQuotaBurnStepId;
+ const success = agent.result?.success === true;
+ return getMaintenanceRun(id)
+ .then(async (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 });
+ })
+ .catch((err) => console.error(`❌ Maintenance run ${id} continuation failed: ${err.message}`));
+}
+
+async function retryRunningRuns() {
+ const running = (await listMaintenanceRuns()).filter((run) => run.status === MAINTENANCE_RUN_STATUS.RUNNING);
+ for (const run of running) {
+ await evaluateMaintenanceRun(run.id).catch((err) => console.error(`❌ Maintenance run ${run.id} retry failed: ${err.message}`));
+ }
+}
+
+/** Arm the continuation listener and the safety-net interval. Called once at boot. */
+export function startMaintenanceRunScheduler() {
+ if (retryTimer) return;
+ // Both run outside the request lifecycle: the listener never rethrows and the
+ // timer's callback owns its rejections, so neither can take the process down.
+ cosEvents.on('agent:completed', onMaintenanceAgentCompleted);
+ retryTimer = setInterval(() => {
+ retryRunningRuns().catch((err) => console.error(`❌ Maintenance run retry sweep failed: ${err.message}`));
+ }, RETRY_MS);
+ retryTimer.unref?.();
+ console.log('🧹 Maintenance run loop armed (idle until a run is started from the Schedule tab)');
+}
+
+/** Test seams. */
+export const __onMaintenanceAgentCompleted = onMaintenanceAgentCompleted;
+export const __retryMaintenanceRuns = retryRunningRuns;
+export function __resetMaintenanceRunScheduler() {
+ if (retryTimer) clearInterval(retryTimer);
+ retryTimer = null;
+ cosEvents.off('agent:completed', onMaintenanceAgentCompleted);
+ evaluations.clear();
+}
diff --git a/server/services/maintenanceRun.test.js b/server/services/maintenanceRun.test.js
new file mode 100644
index 0000000000..698c56c0c0
--- /dev/null
+++ b/server/services/maintenanceRun.test.js
@@ -0,0 +1,132 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { rm } from 'fs/promises';
+import { join } from 'path';
+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';
+import { MAINTENANCE_SEQUENCE_TYPES } from '../lib/maintenanceSequence.js';
+
+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-maintenance-run-' });
+vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));
+
+const state = vi.hoisted(() => ({ tasks: [], requests: [], invoked: [], dispatch: null, probe: null }));
+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ cos: { tasks: state.tasks }, user: { tasks: [] } })) }));
+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)) }));
+vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async (id) => (id === 'codex' ? { id, type: 'cli', command: 'codex', enabled: true } : null)) }));
+vi.mock('./scheduledHandlers/providerPick.js', () => ({ resolveBurnProvider: vi.fn(async ({ job, family }) => (job.providerId === 'codex' && family.id === 'codex' ? { id: 'codex' } : null)) }));
+vi.mock('./quotaBurnInvoke.js', () => ({
+ getQuotaBurnTaskCatalog: vi.fn(async () => ({ builtin: {}, custom: {} })),
+ invokeQuotaBurnStep: vi.fn(async (call) => {
+ state.invoked.push(call);
+ return state.dispatch || { dispatched: true, summary: `ran ${call.step.taskRef.taskType}`, awaiting: { requestId: `demand-${state.invoked.length}` } };
+ }),
+}));
+vi.mock('./quotaBurnSequence.js', async (importActual) => ({
+ ...(await importActual()),
+ probeSequenceDrain: vi.fn(async (job) => state.probe || { job }),
+}));
+// The independence claim, made checkable: the plan store is never consulted.
+vi.mock('./quotaBurnStore.js', () => ({ getQuotaBurnConfig: vi.fn(async () => { throw new Error('quota burn config must not be read'); }) }));
+
+const { getQuotaBurnConfig } = await import('./quotaBurnStore.js');
+const { invokeQuotaBurnStep } = await import('./quotaBurnInvoke.js');
+const {
+ startMaintenanceRun, stopMaintenanceRun, resumeMaintenanceRun, evaluateMaintenanceRun, getMaintenanceRun, listMaintenanceRuns,
+ __onMaintenanceAgentCompleted, __retryMaintenanceRuns, __resetMaintenanceRunScheduler,
+} = await import('./maintenanceRun.js');
+
+const start = () => startMaintenanceRun({ appId: 'app-1', providerId: 'codex', model: 'gpt-5', effort: 'high' });
+const agentFor = (run, index, success = true) => ({
+ taskId: `task-${index}`,
+ result: { success },
+ metadata: { taskQuotaBurnFamily: run.familyId, taskQuotaBurnStepId: run.steps[index].id, taskQuotaBurnMaintenanceRunId: run.id },
+});
+const dispatchedTypes = () => state.invoked.map((call) => call.step.taskRef.taskType);
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ __resetMaintenanceRunScheduler();
+ await rm(join(tempRoot, 'cos', 'maintenance-runs.json'), { force: true });
+ Object.assign(state, { tasks: [], requests: [], invoked: [], dispatch: null, probe: null });
+});
+afterAll(cleanup);
+
+describe('manual maintenance run', () => {
+ it('walks the whole ladder to completion on agent completions and drain probes, never touching the burn plan', async () => {
+ const { run, result } = await start();
+ expect(result).toMatchObject({ dispatched: true, taskType: 'better-structural-drift' });
+ expect(run).toMatchObject({ status: 'running', familyId: 'codex', active: { stepId: run.steps[0].id, requestId: 'demand-1' } });
+ expect(run.steps.map((step) => step.taskRef.taskType)).toEqual(MAINTENANCE_SEQUENCE_TYPES);
+ expect(invokeQuotaBurnStep).toHaveBeenCalledWith(expect.objectContaining({
+ maintenanceRunId: run.id, family: { id: 'codex' },
+ step: expect.objectContaining({ runOnce: true, taskRef: { kind: 'builtin', taskType: 'better-structural-drift', appId: 'app-1' }, overrides: { providerId: 'codex', model: 'gpt-5', effort: 'high', params: { fileIssues: true } } }),
+ }));
+
+ // The audit finishes → the drain is probed → the backlog is actionable → a claim goes out.
+ await __onMaintenanceAgentCompleted(agentFor(run, 0));
+ expect(dispatchedTypes()).toEqual(['better-structural-drift', 'claim-issue']);
+ expect((await getMaintenanceRun(run.id)).completed).toHaveProperty(run.steps[0].id);
+ // The claim finishes with issues left → the drain repeats, ignoring the task that just finished.
+ await __onMaintenanceAgentCompleted(agentFor(run, 1));
+ expect(dispatchedTypes()).toEqual(['better-structural-drift', 'claim-issue', 'claim-issue']);
+ // Backlog empty → the drain is done and the next audit goes out in the same evaluation.
+ state.probe = { drained: true };
+ await __onMaintenanceAgentCompleted(agentFor(run, 1));
+ expect(dispatchedTypes().at(-1)).toBe('simplify');
+ expect((await getMaintenanceRun(run.id)).completed).toHaveProperty(run.steps[1].id);
+
+ // Finish every remaining audit; every drain reports empty.
+ for (let index = 2; index < run.steps.length; index += 2) await __onMaintenanceAgentCompleted(agentFor(run, index));
+ const finished = await getMaintenanceRun(run.id);
+ expect(finished).toMatchObject({ status: 'completed', reason: 'maintenance sequence complete', active: null });
+ expect(Object.keys(finished.completed)).toHaveLength(run.steps.length);
+ expect(dispatchedTypes().filter((type) => type !== 'claim-issue')).toEqual(MAINTENANCE_SEQUENCE_TYPES.filter((type) => type !== 'claim-issue'));
+ expect(getQuotaBurnConfig).not.toHaveBeenCalled();
+ });
+
+ it('holds on its own queued, running or blocked work and on a failed audit, then retries once the hold clears', async () => {
+ const { run } = await start();
+ state.requests = [{ id: 'demand-1', taskType: 'better-structural-drift', burn: { maintenanceRunId: run.id } }];
+ expect(await evaluateMaintenanceRun(run.id)).toMatchObject({ dispatched: false, reason: expect.stringContaining('demand-1') });
+ state.requests = [];
+ state.tasks = [{ id: 'task-0', status: 'in_progress', metadata: { quotaBurnFamily: 'codex', quotaBurnMaintenanceRunId: run.id } }];
+ expect(await evaluateMaintenanceRun(run.id)).toMatchObject({ dispatched: false, reason: 'waiting for in progress task task-0' });
+ // A failed audit completes nothing; its blocked task is the hold the user sees.
+ state.tasks[0].status = 'blocked';
+ await __onMaintenanceAgentCompleted(agentFor(run, 0, false));
+ expect((await getMaintenanceRun(run.id)).completed).toEqual({});
+ expect((await getMaintenanceRun(run.id)).reason).toBe('waiting for blocked task task-0');
+ expect(state.invoked).toHaveLength(1);
+ // Another run's task on the same family is not this run's business.
+ state.tasks = [{ id: 'other', status: 'in_progress', metadata: { quotaBurnFamily: 'codex' } }];
+ state.dispatch = { dispatched: false, reason: 'an on-demand run of "better-structural-drift" is already queued' };
+ await __retryMaintenanceRuns();
+ expect((await getMaintenanceRun(run.id)).reason).toMatch(/already queued/);
+ state.dispatch = null;
+ await __retryMaintenanceRuns();
+ expect(state.invoked).toHaveLength(3);
+ expect((await getMaintenanceRun(run.id)).active.stepId).toBe(run.steps[0].id);
+ });
+
+ it('stops without recalling work, resumes from its ledger, and refuses a second run for the same app', async () => {
+ const { run } = await start();
+ await expect(start()).rejects.toMatchObject({ status: 409, code: 'MAINTENANCE_RUN_ACTIVE' });
+ await __onMaintenanceAgentCompleted(agentFor(run, 0));
+ const stopped = await stopMaintenanceRun(run.id);
+ expect(stopped).toMatchObject({ status: 'stopped', reason: 'stopped by the user' });
+ expect(await __onMaintenanceAgentCompleted(agentFor(run, 1))).toEqual({ skipped: 'stopped' });
+ expect(await __retryMaintenanceRuns()).toBeUndefined();
+ expect(state.invoked).toHaveLength(2);
+ const { run: resumed, result } = await resumeMaintenanceRun(run.id);
+ expect(resumed.status).toBe('running');
+ expect(resumed.completed).toHaveProperty(run.steps[0].id);
+ expect(result).toMatchObject({ dispatched: true, taskType: 'claim-issue' });
+ expect((await listMaintenanceRuns()).map((entry) => entry.id)).toEqual([run.id]);
+ });
+
+ 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' });
+ expect(await listMaintenanceRuns()).toEqual([]);
+ expect(state.invoked).toEqual([]);
+ });
+});
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index 9bb77fa56c..695c1067ca 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -391,13 +391,13 @@ async function queuedOnDemandReason(queued, taskType, appId) {
* same step the dispatch would refuse — and a burn cannot be the one path that
* spends a subscription while the user has CoS improvement switched off.
*/
-export async function invokeQuotaBurnStep({ step, family, candidate, context, force = false, catalog = null } = {}) {
+export async function invokeQuotaBurnStep({ step, family, candidate, context, force = false, catalog = null, maintenanceRunId = null } = {}) {
const resolved = await resolveQuotaBurnStep(step, catalog);
if (resolved.unavailable) return declined(resolved.unavailable.reason);
if (resolved.kind === 'programmatic') return runProgrammaticStep({ resolved, family, context, force });
- if (resolved.kind === 'custom') return runCustomJobStep({ resolved, step, family, candidate });
- return runBuiltinTaskStep({ resolved, step, family, candidate });
+ if (resolved.kind === 'custom') return runCustomJobStep({ resolved, step, family, candidate, maintenanceRunId });
+ return runBuiltinTaskStep({ resolved, step, family, candidate, maintenanceRunId });
}
/**
@@ -429,7 +429,7 @@ async function runProgrammaticStep({ resolved, family, context, force }) {
* `force` is NOT passed through: it means "past the quota gates", and the
* schedule's gates are not quota gates.
*/
-async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
+async function runBuiltinTaskStep({ resolved, step, family, candidate, maintenanceRunId }) {
// Re-checked HERE, not left to the probe: a forced run of a named step skips
// the probe entirely (the click IS the selection), and `triggerOnDemandTask`
// appends unconditionally — so without this, two forced clicks queue the same
@@ -449,6 +449,10 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
family: family.id,
stepId: step.id,
limitingResetAt: candidate?.limitingResetAt ?? null,
+ // Set only by a MANUAL maintenance run (`maintenanceRun.js`): the mark
+ // that keeps the quota-burn loop from walking its plan on this agent's
+ // completion. Omitted, not null, on an automatic burn.
+ ...(maintenanceRunId ? { maintenanceRunId } : {}),
overrides: {
// The RESOLVED provider, not the step's pin: an unpinned step must still
// land on this family's provider rather than the daemon's active one, or
@@ -502,7 +506,7 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
* `forceSpawnTask`, and a blocked twin is reported as a decline instead of
* revived. See this module's header for why each of those matters.
*/
-async function runCustomJobStep({ resolved, step, family, candidate }) {
+async function runCustomJobStep({ resolved, step, family, candidate, maintenanceRunId }) {
const approval = unattendedApprovalRefusal(resolved.job);
if (approval) return declined(approval);
// `addTask`'s duplicate detection catches an identical QUEUED twin below, but
@@ -539,6 +543,7 @@ async function runCustomJobStep({ resolved, step, family, candidate }) {
quotaBurnFamily: family.id,
quotaBurnLimitingResetAt: candidate?.limitingResetAt ?? null,
quotaBurnStepId: step.id,
+ ...(maintenanceRunId ? { quotaBurnMaintenanceRunId: maintenanceRunId } : {}),
}, 'internal', { suppressDequeue: true });
if (!persisted?.id) return declined(`"${resolved.job.name}" was not queued`);
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 739879f131..1553833d9b 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -58,6 +58,7 @@ import { windowLabelOf } from '../lib/quotaWindows.js';
import { WAIT } from '../lib/staleWhileRevalidate.js';
import { cosEvents } from './cosEvents.js';
import { nextQuotaBurnSequenceJob, completeQuotaBurnSequenceStep } from './quotaBurnSequence.js';
+import { burnPlanOwnsAgent } from '../lib/quotaBurnOrigin.js';
const TICK_MS = 60_000;
@@ -689,10 +690,15 @@ function onBurnAgentCompleted(agent) {
// subscriber, whose ordering against this one is not guaranteed) is one wasted
// agent too late, every single time. A ledger failure must not stop the
// continuation, so it degrades to a logged warning.
+ // The plan is walked only for an agent the plan OWNS (`burnPlanOwnsAgent`):
+ // a manual maintenance run's agent spends this family's window — so the
+ // denial ledger still hears about it — but its completion advances that run,
+ // never this plan.
+ const walkPlan = () => completeQuotaBurnSequenceStep(agent)
+ .then(() => runQuotaBurnCycle({ trigger: 'continuation', familyId, ignoreTaskId: agent?.result?.success ? agent?.taskId : null }));
return recordBurnAgentCompletion(agent)
.catch((err) => console.error(`⚠️ Quota-burn denial ledger for ${familyId}: ${err.message}`))
- .then(() => completeQuotaBurnSequenceStep(agent))
- .then(() => runQuotaBurnCycle({ trigger: 'continuation', familyId, ignoreTaskId: agent?.result?.success ? agent?.taskId : null }))
+ .then(() => (burnPlanOwnsAgent(agent) ? walkPlan() : { skipped: 'maintenance-run' }))
.catch((err) => console.error(`❌ Quota-burn continuation for ${familyId} failed: ${err.message}`));
}
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
index 978b70d37f..bc69f7c4aa 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -645,6 +645,20 @@ describe('completion continuation', () => {
expect(state.invoked).toEqual([]);
});
+ it('credits the agent of a manual maintenance run to the denial ledger but never walks the plan on it', async () => {
+ // The Schedule tab's "Run maintenance now" spends this family's window
+ // (so a refusal is still the family's), but its ladder is its own — the
+ // plan must not dispatch, and no plan step may be marked spent, because a
+ // manual run finished a task.
+ state.invokePending = { first: { count: 1 } };
+ const agent = { taskId: 'manual-1', result: { success: true }, metadata: { taskQuotaBurnFamily: 'grok', taskQuotaBurnStepId: 'first', taskQuotaBurnMaintenanceRunId: 'maint-1' } };
+ await expect(__onBurnAgentCompleted(agent)).resolves.toEqual({ skipped: 'maintenance-run' });
+ expect(state.settled).toEqual(['grok']);
+ expect(state.invoked).toEqual([]);
+ expect(state.completed).toEqual([]);
+ expect(state.runs).toEqual([]);
+ });
+
it('stops when the master switch is off', async () => {
// A continuation is unattended spending — switching the feature off must end
// the chain, not leave it running until the window cap happens to close it.
diff --git a/server/services/quotaBurnSequence.js b/server/services/quotaBurnSequence.js
index 8a262a6ab8..e07f99bf0a 100644
--- a/server/services/quotaBurnSequence.js
+++ b/server/services/quotaBurnSequence.js
@@ -1,15 +1,69 @@
/** Strict sequence barriers; ordinary burn rotations keep their existing semantics. */
import { requiresInstallWideTarget } from '../lib/taskTargetScope.js';
-import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
+import { burnPlanOwnsAgent, burnPlanOwnsTask, quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
+import { MAINTENANCE_DRAIN_TASK } from '../lib/maintenanceSequence.js';
import { jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';
import { recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
+/** A task the sequence still has to wait on. */
+export const ACTIVE_TASK_STATUSES = new Set(['pending', 'in_progress', 'blocked']);
+
+/**
+ * Whether a sequence step may be walked at all: a run-once reference to an
+ * app-scoped built-in task. Shared with the manual maintenance run, which
+ * builds exactly these steps and must be refused the same way if it ever
+ * stops doing so.
+ */
+export const sequenceStepShapeReason = (job) => (
+ !job.runOnce || job.taskRef?.kind !== 'builtin' || !job.taskRef.appId || requiresInstallWideTarget(job.taskRef.taskType)
+ ? 'sequence steps must be run-once app scheduled tasks'
+ : null);
+
+/**
+ * Probe a `drain: true` claim step. Returns `{ job }` when the referenced app
+ * still has claimable issues, `{ reason }` when the step must hold (the
+ * detector is transient, claims are still in flight, or the reference does not
+ * resolve to a perpetual `claim-issue`), or `{ drained: true }` when the backlog
+ * is empty and the step counts as done.
+ *
+ * Shared by the quota-burn sequence and the manual maintenance run: the drain is
+ * the one step whose completion is decided by a probe rather than by an agent
+ * finishing, and two probes would drift on which filters they honor.
+ */
+export async function probeSequenceDrain(job, { catalog, ignoreTaskId = null }) {
+ const { resolveQuotaBurnStep } = await import('./quotaBurnInvoke.js');
+ const resolved = await resolveQuotaBurnStep(job, catalog);
+ if (resolved.unavailable) return { reason: resolved.unavailable.reason };
+ if (resolved.ref?.taskType !== MAINTENANCE_DRAIN_TASK || resolved.interval?.perpetual !== true) {
+ return { reason: 'sequence drain requires perpetual claim-issue in Scheduled Tasks' };
+ }
+ const [{ getAppById }, { detectActionableWork }, { sanitizeTaskMetadata }] = await Promise.all([
+ import('./apps.js'), import('./perpetualWork.js'), import('../lib/cosValidation.js'),
+ ]);
+ const app = await getAppById(resolved.ref.appId);
+ if (!app) return { reason: 'sequence target app is unavailable' };
+ const metadata = {
+ ...sanitizeTaskMetadata(resolved.interval.taskMetadata),
+ ...sanitizeTaskMetadata(app.taskTypeOverrides?.[MAINTENANCE_DRAIN_TASK]?.taskMetadata),
+ ...sanitizeTaskMetadata(job.overrides?.params),
+ };
+ const detection = await detectActionableWork(MAINTENANCE_DRAIN_TASK, app, {
+ issueAuthorFilter: metadata.issueAuthorFilter || 'self',
+ issueExcludeLabels: metadata.issueExcludeLabels || [],
+ ignoreTaskId,
+ });
+ if (detection.transient || !detection.hasDetector) return { reason: detection.reason || 'claim probe unavailable' };
+ if (detection.actionable) return { job };
+ if (detection.inFlightCount > 0) return { reason: 'sequence waiting for in-flight issue claims' };
+ return { drained: true };
+}
+
export async function nextQuotaBurnSequenceJob(family, { completions, reservations, catalog, ignoreTaskId = null }) {
const { getAllTasks } = await import('./cosTaskStore.js');
const { user, cos } = await getAllTasks();
- const active = [...(user?.tasks || []), ...(cos?.tasks || [])].find(task =>
- task.id !== ignoreTaskId && quotaBurnProvenance(task.metadata).family === family.id
- && ['pending', 'in_progress', 'blocked'].includes(task.status));
+ const active = [...(user?.tasks || []), ...(cos?.tasks || [])].find(task => task.id !== ignoreTaskId
+ && burnPlanOwnsTask(task.metadata) && quotaBurnProvenance(task.metadata).family === family.id
+ && ACTIVE_TASK_STATUSES.has(task.status));
if (active) return { reason: 'sequence waiting for its queued, running, or blocked task' };
if (Object.values(reservations).some(record => record.familyId === family.id)) {
return { reason: 'sequence waiting for acceptance' };
@@ -18,34 +72,11 @@ export async function nextQuotaBurnSequenceJob(family, { completions, reservatio
if (jobIsSpent(job, family.id, completions)) continue;
// Disabled or unavailable predecessors are barriers, never permission to skip ahead.
if (job.enabled === false) return { reason: 'sequence step is disabled' };
- if (!job.runOnce || job.taskRef?.kind !== 'builtin' || !job.taskRef.appId || requiresInstallWideTarget(job.taskRef.taskType)) {
- return { reason: 'sequence steps must be run-once app scheduled tasks' };
- }
+ const shape = sequenceStepShapeReason(job);
+ if (shape) return { reason: shape };
if (!job.drain) return { job };
- const { resolveQuotaBurnStep } = await import('./quotaBurnInvoke.js');
- const resolved = await resolveQuotaBurnStep(job, catalog);
- if (resolved.unavailable) return { reason: resolved.unavailable.reason };
- if (resolved.ref?.taskType !== 'claim-issue' || resolved.interval?.perpetual !== true) {
- return { reason: 'sequence drain requires perpetual claim-issue in Scheduled Tasks' };
- }
- const [{ getAppById }, { detectActionableWork }, { sanitizeTaskMetadata }] = await Promise.all([
- import('./apps.js'), import('./perpetualWork.js'), import('../lib/cosValidation.js'),
- ]);
- const app = await getAppById(resolved.ref.appId);
- if (!app) return { reason: 'sequence target app is unavailable' };
- const metadata = {
- ...sanitizeTaskMetadata(resolved.interval.taskMetadata),
- ...sanitizeTaskMetadata(app.taskTypeOverrides?.['claim-issue']?.taskMetadata),
- ...sanitizeTaskMetadata(job.overrides?.params),
- };
- const detection = await detectActionableWork('claim-issue', app, {
- issueAuthorFilter: metadata.issueAuthorFilter || 'self',
- issueExcludeLabels: metadata.issueExcludeLabels || [],
- ignoreTaskId,
- });
- if (detection.transient || !detection.hasDetector) return { reason: detection.reason || 'claim probe unavailable' };
- if (detection.actionable) return { job };
- if (detection.inFlightCount > 0) return { reason: 'sequence waiting for in-flight issue claims' };
+ const probe = await probeSequenceDrain(job, { catalog, ignoreTaskId });
+ if (!probe.drained) return probe;
const written = await recordQuotaBurnJobCompletion(family.id, job.id);
if (!written) return { reason: 'could not record drained sequence step' };
completions[quotaBurnJobKey(family.id, job.id)] = written[quotaBurnJobKey(family.id, job.id)];
@@ -54,9 +85,10 @@ export async function nextQuotaBurnSequenceJob(family, { completions, reservatio
}
export async function completeQuotaBurnSequenceStep(agent) {
- const familyId = agent?.metadata?.taskQuotaBurnFamily;
- const jobId = agent?.metadata?.taskQuotaBurnStepId;
- if (!familyId || !jobId) return;
+ if (!burnPlanOwnsAgent(agent)) return;
+ const familyId = agent.metadata.taskQuotaBurnFamily;
+ const jobId = agent.metadata.taskQuotaBurnStepId;
+ if (!jobId) return;
const { getQuotaBurnConfig } = await import('./quotaBurnStore.js');
const family = (await getQuotaBurnConfig()).families[familyId];
if (!family?.sequence || !agent?.result?.success) return;