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

feat: add ordered maintenance sequence to quota burn

[._.]/ Adam Eivy5c50b6b18844
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index f1aa36606b..634c0cd0e5 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -5,6 +5,7 @@ import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import { formatDateTime, formatTimeOfDaySeconds, timeAgo } from '../../../utils/formatters';
import Banner from '../../ui/Banner';
+import { MAINTENANCE_ORDER_GUIDANCE } from '../../../lib/quotaBurnTasks';
import { CodeReviewDefaultsProvider } from '../../../hooks/useCodeReviewDefaults';
import { useAppOverrideActions } from '../../../hooks/useAppOverrideActions';
import AppTaskTypeSection from './schedule/AppTaskTypeSection';
@@ -185,6 +186,11 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
</button>
</div>
+ <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>
+ </Banner>
+
{improvementDisabled && (
<Banner size="md" icon={AlertCircle} title="Improvement is disabled">
<div className="text-xs text-port-warning/80 mt-1">
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsx
index 50144c49ea..8d9495ac7a 100644
--- a/client/src/components/quotaBurn/FamilyCard.jsx
+++ b/client/src/components/quotaBurn/FamilyCard.jsx
@@ -15,13 +15,13 @@ import BrailleSpinner from '../BrailleSpinner';
import JobRow from './JobRow';
import TaskRefPicker from './TaskRefPicker';
import { dispatchCapInput, isUnlimitedDispatchCap, quotaBurnJobIsSpent, UNLIMITED_DISPATCHES } from '../../lib/quotaBurnPatch';
-import { CREATE_TASK_HREF, flattenTaskCatalog, quotaBurnStepPayload, stepFromTaskEntry, taskEntryNeedsApp } from '../../lib/quotaBurnTasks';
+import { CREATE_TASK_HREF, maintenanceSequence, MAINTENANCE_ORDER_GUIDANCE, flattenTaskCatalog, quotaBurnStepPayload, stepFromTaskEntry, taskEntryNeedsApp } from '../../lib/quotaBurnTasks';
import { formatDateTime } from '../../utils/formatters';
import { NumberField } from './fields';
export default function FamilyCard({
familyId, config, status, catalog, taskGroups, catalogError, catalogRetrying, expanded, actionsBusy,
- onToggleExpand, onPatch, onRunFamily, onRunJob, onRearm, onRetryCatalog,
+ onToggleExpand, onPatch, onStartSequence, onRunFamily, onRunJob, onRearm, onRetryCatalog,
}) {
const jobs = config.jobs || [];
const hasEnabledJobs = jobs.some((job) => job.enabled !== false);
@@ -70,10 +70,10 @@ export default function FamilyCard({
const addStep = (entry) => {
const targeted = [...new Set(jobs.map((job) => job.taskRef?.appId).filter(Boolean))];
const id = nextJobId();
- patchJobs([...jobs, stepFromTaskEntry(entry, {
+ patchJobs([...jobs, { ...stepFromTaskEntry(entry, {
id,
appId: taskEntryNeedsApp(entry) && targeted.length === 1 ? targeted[0] : null,
- })]);
+ }), ...(config.sequence ? { runOnce: true } : {}) }]);
setExpandedJobIds((prev) => new Set(prev).add(id));
};
@@ -94,6 +94,9 @@ export default function FamilyCard({
});
};
+ const [sequenceAppId, setSequenceAppId] = useState('');
+ const sequenceApps = catalog?.apps || [];
+ const sequenceJobs = maintenanceSequence(taskGroups, sequenceAppId, `maintenance-${Date.now().toString(36)}`);
const hasTasks = flattenTaskCatalog(taskGroups).length > 0;
return (
@@ -156,7 +159,7 @@ export default function FamilyCard({
dispatch again. */}
<span className="text-[11px] text-gray-500">
{jobs.length
- ? `${jobs.length} job${jobs.length === 1 ? '' : 's'} · ${jobs.filter((job) => job.enabled !== false).length} enabled${spentCount ? ` · ${spentCount} ran once` : ''}`
+ ? `${jobs.length} job${jobs.length === 1 ? '' : 's'} · ${jobs.filter((job) => job.enabled !== false).length} enabled${spentCount ? ` · ${spentCount} ${config.sequence ? 'completed' : 'ran once'}` : ''}`
: 'no jobs'}
</span>
@@ -226,6 +229,27 @@ export default function FamilyCard({
<NumberField id={`burn-${familyId}-priority`} label="Priority" value={config.priority} onChange={(v) => onPatch({ priority: v })} min={0} max={100} hint="Lower wins when two windows reset together." />
</div>
+ <div className="space-y-2 text-xs">
+ <p>{MAINTENANCE_ORDER_GUIDANCE}</p>
+ <p>Audit once, drain eligible issues between audits, then improve documentation. Requires enabled tasks for the app and perpetual claim-issue. Quota limits still apply.</p>
+ <label htmlFor={`maintenance-app-${familyId}`}>Maintenance sequence app</label>
+ <select id={`maintenance-app-${familyId}`} value={sequenceAppId} onChange={event => setSequenceAppId(event.target.value)} className="block w-full bg-port-bg border border-port-border rounded p-2">
+ <option value="">Select app</option>
+ {sequenceApps.map(app => <option key={app.id} value={app.id}>{app.name || app.id}</option>)}
+ </select>
+ {sequenceAppId && !sequenceJobs && <p>Enable the listed tasks for this app in <Link to="/cos/schedule" className="text-port-accent underline">Scheduled Tasks</Link>, including perpetual mode on claim-issue.</p>}
+ <button type="button" disabled={actionsBusy || !sequenceJobs || jobs.length > 0} className="text-port-accent disabled:opacity-40"
+ onClick={() => onPatch({ sequence: true, jobs: sequenceJobs.map(quotaBurnStepPayload) })}>
+ Populate maintenance sequence
+ </button>
+ <button type="button" disabled={actionsBusy || !sequenceJobs || jobs.length > 0} className="ml-3 text-port-accent disabled:opacity-40"
+ onClick={() => onStartSequence(familyId, sequenceJobs.map(quotaBurnStepPayload))}>
+ Populate and start sequence
+ </button>
+ <p>Start enables Quota Burn and this family, saves the plan, and evaluates it under the configured quota limits.</p>
+ {jobs.length > 0 && <p>Clear the existing plan to populate a new sequence.</p>}
+ {config.sequence && <p>Strict sequence: waits for each step; claim steps repeat until eligible work is drained. Enable Quota Burn and this family, then use Burn now to start.</p>}
+ </div>
<div className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<h3 className="text-xs uppercase tracking-wide text-gray-400">Burn plan — runs in order</h3>
@@ -287,6 +311,7 @@ export default function FamilyCard({
key={job.id}
job={job}
familyId={familyId}
+ sequence={config.sequence === true}
index={index}
total={jobs.length}
catalog={catalog}
diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsx
index 856d22698a..2c1433ded8 100644
--- a/client/src/components/quotaBurn/JobRow.jsx
+++ b/client/src/components/quotaBurn/JobRow.jsx
@@ -42,7 +42,7 @@ function providersForFamily(providers, familyId) {
export default function JobRow({
job, index, total, catalog, taskGroups, pending, ranAt, actionsBusy,
- familyId,
+ familyId, sequence = false,
expanded = false, onToggleExpand,
onChange, onMove, onRemove, onRun, onRearm,
}) {
@@ -242,12 +242,13 @@ export default function JobRow({
id={`${idPrefix}-run-once`}
type="checkbox"
checked={job.runOnce === true}
+ disabled={sequence}
onChange={(event) => onChange({ ...job, runOnce: event.target.checked })}
/>
<label htmlFor={`${idPrefix}-run-once`}>Run once</label>
</div>
<p className="text-[11px] text-gray-500 mt-1">
- {job.runOnce
+ {sequence ? (job.drain ? 'Repeats claim-issue until eligible work is drained, then advances.' : 'Advances after successful completion; re-arm to repeat.') : job.runOnce
? 'Dispatches once, then drops out of the rotation until you re-arm it.'
: 'Repeats every lap of the plan while the window still has quota.'}
</p>
@@ -273,7 +274,7 @@ export default function JobRow({
{spent ? (
<p className="flex flex-wrap items-center gap-2 text-[11px] text-gray-400">
<span className="inline-flex items-center gap-1 text-sky-300">
- <CheckCircle2 size={12} /> Ran once {timeAgo(ranAt)}
+ <CheckCircle2 size={12} /> {sequence ? 'Completed' : 'Ran once'} {timeAgo(ranAt)}
</span>
<button
type="button"
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 044a6f5622..af8b6f6c6c 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -130,7 +130,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |
-| `quotaBurnTasks.js` | The Quota Burn page's view of the SHARED scheduled-task catalog. `buildQuotaBurnTaskCatalog({ schedule, jobs, apps })` groups PortOS built-in task types and app custom jobs into the picker's two groups (dropping what a burn may never invoke, and stamping a `blockedReason` on what is merely disabled or untargetable); `searchTaskCatalog` / `flattenTaskCatalog` / `findTaskEntry` query it. `taskRefKey` / `stepFromTaskEntry` / `taskEntryNeedsApp` build and address a step's `taskRef`. `effectiveQuotaBurnSettings(step, saved)` mirrors the server's `effectiveSettings` (overrides layered over the task's saved settings, params merged key-by-key). `quotaBurnStepPayload(job)` reduces a step to what the strict PUT schema accepts, dropping the top-level override mirrors that would otherwise outrank the `overrides` bag. `taskSourceHref(entry)` / `CREATE_TASK_HREF` link out to the source task. |
+| `quotaBurnTasks.js` | `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE` document the default ladder; `maintenanceSequence` populates audit and claim-drain references. The Quota Burn page's view of the SHARED scheduled-task catalog. `buildQuotaBurnTaskCatalog({ schedule, jobs, apps })` groups PortOS built-in task types and app custom jobs into the picker's two groups (dropping what a burn may never invoke, and stamping a `blockedReason` on what is merely disabled or untargetable); `searchTaskCatalog` / `flattenTaskCatalog` / `findTaskEntry` query it. `taskRefKey` / `stepFromTaskEntry` / `taskEntryNeedsApp` build and address a step's `taskRef`. `effectiveQuotaBurnSettings(step, saved)` mirrors the server's `effectiveSettings` (overrides layered over the task's saved settings, params merged key-by-key). `quotaBurnStepPayload(job)` reduces a step to what the strict PUT schema accepts, dropping the top-level override mirrors that would otherwise outrank the `overrides` bag. `taskSourceHref(entry)` / `CREATE_TASK_HREF` link out to the source task. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `effortCostEstimate.js` | `withEstimatedCosts(observations)` / `deriveEffortCostRatios(observations)` — fill the reasoning-effort rows Artificial Analysis publishes a quality score but no cost per task for, by scaling each model's own published cost anchor along the effort-cost curve measured across the models that do publish a full set. Estimated rows are flagged `costEstimated`; nothing is written back to the catalog. |
| `falVideoHandoff.js` | `buildFalH3MaxPrompt(prompt, negativePrompt)` composes the provider-neutral shot prompt fal's free MiniMax H3 Max tool is driven with; `FAL_H3_MAX_FREE_URL` and `FAL_H3_MAX_FREE_ALLOWANCE_NOTE` carry the tool URL and current vendor allowance copy. The free web allowance is deliberately a handoff, not the separately metered fal API. |
diff --git a/client/src/lib/quotaBurnTasks.js b/client/src/lib/quotaBurnTasks.js
index da768bfa8e..eac92ef664 100644
--- a/client/src/lib/quotaBurnTasks.js
+++ b/client/src/lib/quotaBurnTasks.js
@@ -218,6 +218,7 @@ export function quotaBurnStepPayload(job) {
params: job.overrides?.params || {},
},
runOnce: job.runOnce === true,
+ ...(job.drain === true ? { drain: true } : {}),
};
}
@@ -250,3 +251,27 @@ 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';
+
+/** 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));
+ if (!appId || picked.some(entry => !entry || entry.blockedReason || !entry.appIds.includes(appId))) return null;
+ if (picked.find(entry => entry.taskType === 'claim-issue').config.perpetual !== true) 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' } },
+ }));
+}
diff --git a/client/src/lib/quotaBurnTasks.test.js b/client/src/lib/quotaBurnTasks.test.js
index f952ee728b..220cbe3739 100644
--- a/client/src/lib/quotaBurnTasks.test.js
+++ b/client/src/lib/quotaBurnTasks.test.js
@@ -1,6 +1,8 @@
import { describe, it, expect } from 'vitest';
import {
buildQuotaBurnTaskCatalog,
+ MAINTENANCE_TASK_ORDER,
+ maintenanceSequence,
effectiveQuotaBurnSettings,
findTaskEntry,
quotaBurnStepPayload,
@@ -217,3 +219,20 @@ describe('taskSourceHref', () => {
});
// @vitest-environment node
+
+it('populates the canonical audit ladder with perpetual drains and refuses incomplete app scope', () => {
+ const tasks = Object.fromEntries([...MAINTENANCE_TASK_ORDER, 'claim-issue'].map(type => [type, {
+ enabled: true, perpetual: type === 'claim-issue', appOverrides: { app1: { enabled: true } },
+ }]));
+ const groups = buildQuotaBurnTaskCatalog({ schedule: { tasks } });
+ const jobs = maintenanceSequence(groups, 'app1', 'sequence');
+ expect(jobs).toHaveLength(13);
+ expect(jobs.filter(job => !job.drain).map(job => job.taskRef.taskType)).toEqual(MAINTENANCE_TASK_ORDER);
+ expect(jobs.filter(job => job.drain)).toHaveLength(6);
+ expect(jobs.every(job => job.runOnce && job.taskRef.appId === 'app1')).toBe(true);
+ expect(jobs[0].overrides.params).toEqual({ fileIssues: true });
+ expect(jobs.at(-1).overrides.params).toEqual({ fileIssues: false });
+ expect(maintenanceSequence(groups, 'app2', 'sequence')).toBeNull();
+ tasks['claim-issue'].perpetual = false;
+ expect(maintenanceSequence(buildQuotaBurnTaskCatalog({ schedule: { tasks } }), 'app1', 'sequence')).toBeNull();
+});
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index cddb4e05fc..279f0770cb 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -355,6 +355,18 @@ export default function QuotaBurn() {
const patchFamily = (familyId, patch) => save({ families: { [familyId]: patch } });
+ const startSequence = async (familyId, jobs) => {
+ setRunning(true);
+ const patch = { enabled: true, families: { [familyId]: { enabled: true, sequence: true, jobs } } };
+ const saved = await api.saveQuotaBurn(patch, { silent: true })
+ .catch(err => { toast.error(`Could not save sequence: ${err.message}`); return null; });
+ if (saved) {
+ setConfig(prev => mergeQuotaBurnPatch(prev, patch));
+ await run({ familyId }, 'Maintenance sequence');
+ }
+ setRunning(false);
+ };
+
// Re-arm spends nothing — it only makes a spent `run once` step eligible again
// — so it needs no confirm, and the response carries the fresh status so the
// badges clear without a second round trip. `config` is deliberately NOT
@@ -552,6 +564,7 @@ export default function QuotaBurn() {
actionsBusy={unsaved || running}
onToggleExpand={(id) => navigate(expanded === id ? '/devtools/quota-burn' : `/devtools/quota-burn/${id}`)}
onPatch={(patch) => patchFamily(familyId, patch)}
+ onStartSequence={startSequence}
onRunFamily={(id) => run({ familyId: id, force: true }, 'Burn')}
onRunJob={(id, job) => run({ familyId: id, jobId: job.id, force: true }, 'Job run')}
onRearm={rearm}
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index fd49ddb75e..4bc93ee3b6 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -32,6 +32,7 @@ vi.mock('../components/ui/Toast', () => {
});
import * as api from '../services/api';
+import { MAINTENANCE_TASK_ORDER } from '../lib/quotaBurnTasks';
const NO_OVERRIDES = { providerId: null, model: null, effort: null, params: {} };
@@ -1107,3 +1108,27 @@ describe('QuotaBurn per-invocation overrides', () => {
expect(await screen.findByText(/ux · App One · claude-sonnet-4 · high/)).toBeInTheDocument();
});
});
+
+it('saves and enables the maintenance sequence before starting, and never runs after a failed save', async () => {
+ const tasks = Object.fromEntries([...MAINTENANCE_TASK_ORDER, 'claim-issue'].map(type => [type, {
+ enabled: true, perpetual: type === 'claim-issue', appOverrides: { a1: { enabled: true } },
+ }]));
+ api.getCosSchedule.mockResolvedValue({ tasks });
+ const empty = { ...config, families: { ...config.families, grok: { ...config.families.grok, jobs: [] } } };
+ api.getQuotaBurn.mockResolvedValue({ config: empty, status });
+ renderPage('/devtools/quota-burn/grok');
+ const user = userEvent.setup();
+ await screen.findByLabelText('Maintenance sequence app');
+ await user.selectOptions(screen.getByLabelText('Maintenance sequence app'), 'a1');
+ api.saveQuotaBurn.mockRejectedValueOnce(new Error('save unavailable'));
+ await user.click(screen.getByRole('button', { name: 'Populate and start sequence' }));
+ await waitFor(() => expect(toastError).toHaveBeenCalledWith('Could not save sequence: save unavailable'));
+ expect(api.runQuotaBurn).not.toHaveBeenCalled();
+ api.saveQuotaBurn.mockResolvedValueOnce({ config: empty });
+ await user.click(screen.getByRole('button', { name: 'Populate and start sequence' }));
+ await waitFor(() => expect(api.runQuotaBurn).toHaveBeenCalledWith({ familyId: 'grok' }, { silent: true }));
+ const patch = api.saveQuotaBurn.mock.calls.at(-1)[0];
+ expect(patch.enabled).toBe(true);
+ expect(patch.families.grok).toMatchObject({ enabled: true, sequence: true });
+ expect(patch.families.grok.jobs).toHaveLength(13);
+});
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 52a72c55e8..e46c5547f8 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -598,3 +598,28 @@ reaches disk instead of being persisted as a step the runner can only refuse.
| `client/src/pages/QuotaBurn.jsx` | The config page |
| `client/src/components/quotaBurn/TaskRefPicker.jsx` | The searchable, grouped scheduled-task picker |
| `client/src/components/quotaBurn/StepSettings.jsx` | Per-invocation overrides + the effective settings and audit mode |
+
+## 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
+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
+remaining actionable or in-flight issues. Transient detection errors hold the
+step. Claim filters, the canonical perpetual convergence guard, and the CoS
+Improve gate still apply. The completion ledger survives restarts; re-arm the
+plan to run it again. Existing plans retain rotation behavior.
diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.js
index 097906d312..982ee32c14 100644
--- a/server/lib/auditCatalog.js
+++ b/server/lib/auditCatalog.js
@@ -648,7 +648,7 @@ export const AUDIT_SUGGESTED_AFTER = Object.freeze({
'better-cognitive-load': Object.freeze(['better-complexity']),
// Measure and describe the shape that survived the ladder.
performance: Object.freeze(['better-complexity']),
- documentation: Object.freeze(['better-cognitive-load']),
+ documentation: Object.freeze(['performance', 'better-cognitive-load']),
});
// WHY each audit sits where it does in the order above — rationale only. The
diff --git a/server/lib/auditCatalog.test.js b/server/lib/auditCatalog.test.js
index 61a4d2b86a..3b56d3a8b9 100644
--- a/server/lib/auditCatalog.test.js
+++ b/server/lib/auditCatalog.test.js
@@ -309,3 +309,14 @@ describe('AUDIT_SUGGESTED_AFTER', () => {
}
});
});
+
+it('keeps the quota-burn maintenance preset on registered tasks in the advisory order', async () => {
+ const { MAINTENANCE_TASK_ORDER } = await import('../../client/src/lib/quotaBurnTasks.js');
+ const { DEFAULT_TASK_INTERVALS } = await import('../services/taskScheduleRegistry.js');
+ for (const [index, taskType] of MAINTENANCE_TASK_ORDER.entries()) {
+ expect(DEFAULT_TASK_INTERVALS[taskType], taskType).toBeDefined();
+ for (const predecessor of AUDIT_SUGGESTED_AFTER[taskType] || []) {
+ expect(MAINTENANCE_TASK_ORDER.indexOf(predecessor), predecessor).toBeLessThan(index);
+ }
+ }
+});
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
index 04edce1678..9ac0e9b54d 100644
--- a/server/lib/quotaBurnConfig.js
+++ b/server/lib/quotaBurnConfig.js
@@ -322,6 +322,7 @@ export function normalizeQuotaBurnJob(raw, index = 0) {
// Opt-IN, and absent reads as `false`, so every plan written before this
// field existed keeps repeating exactly as it did. See `jobIsSpent`.
runOnce: raw.runOnce === true,
+ ...(raw.drain === true ? { drain: true } : {}),
// Compat mirrors of `overrides` for the shipped editor and the legacy
// executor. Derived on every read (normalization is total), so they cannot
// drift from the canonical bag the way two independently-written fields
@@ -366,6 +367,7 @@ export function normalizeQuotaBurnFamily(raw) {
.filter(Boolean);
return {
enabled: value.enabled === true,
+ ...(value.sequence === true ? { sequence: true } : {}),
resetWithinHours: clamp(BOUNDS.resetWithinHours, value.resetWithinHours),
reservePercent: clamp(BOUNDS.reservePercent, value.reservePercent),
maxDispatchesPerWindow: clampDispatchCap(value.maxDispatchesPerWindow),
diff --git a/server/lib/quotaBurnValidation.js b/server/lib/quotaBurnValidation.js
index c2fb87aed0..0a21f634c0 100644
--- a/server/lib/quotaBurnValidation.js
+++ b/server/lib/quotaBurnValidation.js
@@ -101,8 +101,12 @@ const quotaBurnJobSchema = z.object({
// rotation until the user re-arms it. Absent reads as `false`, so plans
// written before this field keep repeating.
runOnce: z.boolean().optional(),
+ drain: z.boolean().optional(),
params: z.record(paramValueSchema).optional(),
}).strict().superRefine((job, ctx) => {
+ if (job.drain && (job.taskRef?.kind !== 'builtin' || job.taskRef.taskType !== 'claim-issue' || job.runOnce !== true)) {
+ ctx.addIssue({ code: 'custom', path: ['drain'], message: 'A drain must reference claim-issue and run once until drained' });
+ }
// Exactly one identity. Both would leave the normalizer choosing between a
// reference and a copied prompt; neither is a step with no work at all.
if (job.taskRef && job.jobType) {
@@ -129,6 +133,7 @@ const pinnedOutOfFamily = (familyId, pin) => {
};
const quotaBurnFamilySchema = z.object({
+ sequence: z.boolean().optional(),
enabled: z.boolean().optional(),
resetWithinHours: z.number().min(B.resetWithinHours.min).max(B.resetWithinHours.max).optional(),
reservePercent: z.number().min(B.reservePercent.min).max(B.reservePercent.max).optional(),
@@ -152,6 +157,9 @@ const quotaBurnFamilySchema = z.object({
*/
const familySchemaFor = (familyId) => quotaBurnFamilySchema.superRefine((family, ctx) => {
(family.jobs || []).forEach((job, index) => {
+ if (family.sequence && (!job.runOnce || job.taskRef?.kind !== 'builtin' || (!job.taskRef.appId || requiresInstallWideTarget(job.taskRef.taskType)))) {
+ ctx.addIssue({ code: 'custom', path: ['jobs', index], message: 'Sequence steps must be run-once app scheduled tasks' });
+ }
for (const [path, pin] of [
[['jobs', index, 'providerId'], job.providerId],
[['jobs', index, 'overrides', 'providerId'], job.overrides?.providerId],
diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.js
index 7da5dec699..6686b4d708 100644
--- a/server/routes/quotaBurn.test.js
+++ b/server/routes/quotaBurn.test.js
@@ -232,3 +232,16 @@ describe('POST /api/quota-burn/rearm', () => {
expect(runQuotaBurnCycle).not.toHaveBeenCalled();
});
});
+
+it('accepts a strict claim-drain sequence and rejects non-drainable or repeating steps', async () => {
+ saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
+ const job = { id: 'claim', runOnce: true, drain: true, taskRef: { kind: 'builtin', taskType: 'claim-issue', appId: 'example-app' } };
+ const body = { families: { codex: { sequence: true, jobs: [job] } } };
+ expect((await request(buildApp()).put('/api/quota-burn').send(body)).status).toBe(200);
+ expect(saveQuotaBurnConfig).toHaveBeenCalledWith(body);
+ job.runOnce = false;
+ expect((await request(buildApp()).put('/api/quota-burn').send(body)).status).toBe(400);
+ job.runOnce = true;
+ job.taskRef.taskType = 'documentation';
+ expect((await request(buildApp()).put('/api/quota-burn').send(body)).status).toBe(400);
+});
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index ca3a5f18da..9bb77fa56c 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -462,7 +462,9 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
// is what carries a migrated issues-only burn's explicit
// `fileIssues: true` (#6381); without it the burn would run the
// referenced task's SAVED mode and start writing code.
- params: resolved.effective.params,
+ // The canonical generator merges saved global and app metadata itself.
+ // Re-sending the global defaults here would overwrite app-specific claim filters.
+ params: step.overrides?.params || {},
},
},
});
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index 90e62a573b..d5452bd45f 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -355,7 +355,7 @@ describe('refusal paths', () => {
describe('built-in agent task invocation', () => {
const uxStep = () => step({
taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' },
- overrides: { effort: 'high' },
+ overrides: { effort: 'high', params: { fileIssues: false } },
});
it('routes through the schedule\'s on-demand lane with quota-burn provenance', async () => {
@@ -372,10 +372,11 @@ describe('built-in agent task invocation', () => {
limitingResetAt: candidate.limitingResetAt,
// The RESOLVED provider, and the family's TUI at that — an unpinned
// step must not fall through to whatever the daemon is running.
- // The step's effective run params ride along too: they have to reach
+ // Only explicit run params ride along; saved global defaults must not
+ // overwrite the app's own metadata. Explicit false must reach
// the PROMPT, so the engines hand them to the generator as
// `runOverrides` before the mode banner is chosen (#6381).
- overrides: { providerId: 'grok-tui', model: 'saved-model', effort: 'high', params: { fileIssues: true, depth: 'full' } },
+ overrides: { providerId: 'grok-tui', model: 'saved-model', effort: 'high', params: { fileIssues: false } },
},
},
}]);
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 65a8cf44d5..739879f131 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -57,15 +57,16 @@ import { applyQuotaBurnAvailability } from '../lib/quotaBurnTaskRef.js';
import { windowLabelOf } from '../lib/quotaWindows.js';
import { WAIT } from '../lib/staleWhileRevalidate.js';
import { cosEvents } from './cosEvents.js';
+import { nextQuotaBurnSequenceJob, completeQuotaBurnSequenceStep } from './quotaBurnSequence.js';
const TICK_MS = 60_000;
let tickTimer = null;
let running = false;
let lastRunAt = null;
-// Family ids whose completion continuation arrived while a cycle was running —
-// drained by `drainDeferredContinuations` when that cycle releases the guard.
-const deferredContinuations = new Set();
+// Completion continuations deferred while a cycle runs. Retain the completed
+// task id: its task record can still say in_progress when the event arrives.
+const deferredContinuations = new Map();
/**
* The jobs a cycle will consider, in plan order.
@@ -232,7 +233,7 @@ export async function runQuotaBurnCycle(options = {}) {
// this feature exists to spend. Keyed by family, so several completions from
// one family while it is mid-cycle collapse to the single re-evaluation they
// amount to.
- if (options.trigger === 'continuation' && options.familyId) deferredContinuations.add(options.familyId);
+ if (options.trigger === 'continuation' && options.familyId) deferredContinuations.set(options.familyId, options.ignoreTaskId || null);
return { skipped: 'already-running' };
}
running = true;
@@ -261,14 +262,14 @@ export async function runQuotaBurnCycle(options = {}) {
*/
async function drainDeferredContinuations() {
while (deferredContinuations.size) {
- const [familyId] = deferredContinuations;
+ const [[familyId, ignoreTaskId]] = deferredContinuations;
deferredContinuations.delete(familyId);
- await runQuotaBurnCycle({ trigger: 'continuation', familyId })
+ await runQuotaBurnCycle({ trigger: 'continuation', familyId, ignoreTaskId })
.catch((err) => console.error(`❌ Quota-burn deferred continuation for ${familyId} failed: ${err.message}`));
}
}
-async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null, force = false }) {
+async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null, force = false, ignoreTaskId = null }) {
const finish = async (entry) => {
// Only a SCHEDULED cycle advances the interval clock. A manual "Evaluate
// now" that reports "no burnable window" would otherwise push the next
@@ -414,8 +415,17 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
// that passed the full gate ladder, and each entry spends a different
// provider's window.
for (const candidate of candidates) {
+ let selectedJobId = jobId;
+ if (candidate.family.sequence) {
+ const next = await nextQuotaBurnSequenceJob(candidate.family, { completions, reservations, catalog, ignoreTaskId });
+ if (!next.job || (jobId && jobId !== next.job.id)) {
+ attempts.push({ familyId: candidate.family.id, jobId: jobId || 'sequence', skipped: next.reason || 'an earlier sequence step must finish first' });
+ continue;
+ }
+ selectedJobId = next.job.id;
+ }
const outcome = await dispatchFromCandidate(candidate, {
- jobId, force, completions, catalog, reserved, afterJobId: cursors.get(candidate.family.id) || null,
+ jobId: selectedJobId, force, completions, catalog, reserved, afterJobId: cursors.get(candidate.family.id) || null,
});
attempts.push(...outcome.attempts.map((entry) => ({ familyId: candidate.family.id, ...entry })));
if (!outcome.dispatched) continue;
@@ -434,7 +444,9 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
stepId: outcome.job.id,
dispatchKey: candidate.dispatchKey,
charge: candidate.charge,
- runOnce: outcome.job.runOnce === true,
+ // A strict sequence finishes on successful agent completion (or a drained
+ // claim backlog), not merely on the request being accepted.
+ runOnce: outcome.job.runOnce === true && !candidate.family.sequence,
requestId,
});
// The request is already on the schedule and cannot be recalled, so this
@@ -450,7 +462,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
// statement about the WORK ("this only needs doing once") — and the work
// just happened, however it was triggered. The ▶ on the row stays the way
// back, since a forced run bypasses this gate too.
- if (outcome.job.runOnce) {
+ if (outcome.job.runOnce && !candidate.family.sequence) {
await recordQuotaBurnJobCompletion(candidate.family.id, outcome.job.id)
// A ledger failure must not fail a dispatch that already happened —
// the worst case is the job running one extra time next cycle, which
@@ -679,7 +691,8 @@ function onBurnAgentCompleted(agent) {
// continuation, so it degrades to a logged warning.
return recordBurnAgentCompletion(agent)
.catch((err) => console.error(`⚠️ Quota-burn denial ledger for ${familyId}: ${err.message}`))
- .then(() => runQuotaBurnCycle({ trigger: 'continuation', familyId }))
+ .then(() => completeQuotaBurnSequenceStep(agent))
+ .then(() => runQuotaBurnCycle({ trigger: 'continuation', familyId, ignoreTaskId: agent?.result?.success ? agent?.taskId : null }))
.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 72b8094745..978b70d37f 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -38,6 +38,8 @@ const state = {
settlement: { accepted: 0, refused: 0 },
};
+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ cos: { tasks: state.sequenceTasks || [] } })) }));
+
vi.mock('./providerUsage.js', () => ({
getProviderQuotas: vi.fn(async () => state.quotas),
}));
@@ -141,6 +143,7 @@ const plan = (overrides = {}) => normalizeQuotaBurnConfig({
});
beforeEach(() => {
+ state.sequenceTasks = [];
state.config = plan();
state.quotas = [card('grok')];
state.runs = [];
@@ -614,15 +617,19 @@ describe('completion continuation', () => {
enabled: true,
families: {
claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'c1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
- agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ agy: { enabled: true, sequence: true, resetWithinHours: 24, jobs: [
+ { id: 'a0', runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ { id: 'a1', runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ ] },
},
});
state.quotas = [card('claude'), card('agy')];
state.invokePending = { c1: { count: 1 }, a1: { count: 1 } };
+ state.sequenceTasks = [{ id: 'agy-finishing', status: 'in_progress', metadata: { quotaBurnFamily: 'agy' } }];
// agy's agent finishes while claude's cycle is still mid-dispatch.
invokeQuotaBurnStep.mockImplementationOnce(async ({ step, family, candidate }) => {
state.invoked.push({ stepId: step.id, familyId: family.id, charge: candidate.charge });
- await expect(__onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'agy' } }))
+ await expect(__onBurnAgentCompleted({ taskId: 'agy-finishing', result: { success: true }, metadata: { taskQuotaBurnFamily: 'agy', taskQuotaBurnStepId: 'a0' } }))
.resolves.toEqual({ skipped: 'already-running' });
return { dispatched: true, summary: `ran ${step.id}` };
});
@@ -1016,3 +1023,23 @@ describe('charging the cap and the run-once ledger exactly once', () => {
expect(status.families.find((family) => family.id === 'grok').dispatchesUsed).toBe(1);
});
});
+
+it('holds a strict sequence until acceptance and successful completion, then advances despite the rotation cursor', async () => {
+ state.config = plan({ families: { grok: { enabled: true, sequence: true, jobs: [
+ { id: 'audit', runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ { id: 'docs', runOnce: true, taskRef: { kind: 'builtin', taskType: 'docs', appId: 'app-1' } },
+ ] } } });
+ state.invokePending = { audit: { count: 1 }, docs: { count: 1 } };
+ state.invokeResult = { dispatched: true, awaiting: { requestId: 'demand-sequence' }, summary: 'Requested audit' };
+ expect((await runQuotaBurnCycle()).jobId).toBe('audit');
+ expect(state.reserved[0].runOnce).toBe(false);
+ expect(state.completed).toHaveLength(0);
+ state.reservations = { 'grok::audit': { familyId: 'grok', stepId: 'audit' } };
+ expect((await runQuotaBurnCycle()).dispatched).toBe(false);
+ state.reservations = {};
+ state.sequenceTasks = [{ id: 'task-audit', status: 'in_progress', metadata: { quotaBurnFamily: 'grok' } }];
+ expect((await runQuotaBurnCycle()).dispatched).toBe(false);
+ const outcome = await __onBurnAgentCompleted({ taskId: 'task-audit', result: { success: true }, metadata: { taskQuotaBurnFamily: 'grok', taskQuotaBurnStepId: 'audit' } });
+ expect(state.completions['grok:audit']).toBeTruthy();
+ expect(outcome.jobId).toBe('docs');
+});
diff --git a/server/services/quotaBurnSequence.js b/server/services/quotaBurnSequence.js
new file mode 100644
index 0000000000..8a262a6ab8
--- /dev/null
+++ b/server/services/quotaBurnSequence.js
@@ -0,0 +1,67 @@
+/** Strict sequence barriers; ordinary burn rotations keep their existing semantics. */
+import { requiresInstallWideTarget } from '../lib/taskTargetScope.js';
+import { quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
+import { jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';
+import { recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
+
+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));
+ 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' };
+ }
+ for (const job of family.jobs) {
+ 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' };
+ }
+ 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 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)];
+ }
+ return { reason: 'maintenance sequence complete' };
+}
+
+export async function completeQuotaBurnSequenceStep(agent) {
+ const familyId = agent?.metadata?.taskQuotaBurnFamily;
+ const jobId = agent?.metadata?.taskQuotaBurnStepId;
+ if (!familyId || !jobId) return;
+ const { getQuotaBurnConfig } = await import('./quotaBurnStore.js');
+ const family = (await getQuotaBurnConfig()).families[familyId];
+ if (!family?.sequence || !agent?.result?.success) return;
+ const job = family.jobs.find(entry => entry.id === jobId);
+ if (job && !job.drain && job.runOnce) {
+ if (!await recordQuotaBurnJobCompletion(familyId, jobId)) throw new Error('could not record completed sequence step');
+ }
+}
diff --git a/server/services/quotaBurnSequence.test.js b/server/services/quotaBurnSequence.test.js
new file mode 100644
index 0000000000..f9c1a200fc
--- /dev/null
+++ b/server/services/quotaBurnSequence.test.js
@@ -0,0 +1,62 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn() }));
+vi.mock('./apps.js', () => ({ getAppById: vi.fn() }));
+vi.mock('./perpetualWork.js', () => ({ detectActionableWork: vi.fn() }));
+vi.mock('./quotaBurnInvoke.js', () => ({ resolveQuotaBurnStep: vi.fn() }));
+vi.mock('./quotaBurnStore.js', () => ({ getQuotaBurnConfig: vi.fn() }));
+vi.mock('./quotaBurnCompletions.js', () => ({ recordQuotaBurnJobCompletion: vi.fn() }));
+import { getAllTasks } from './cosTaskStore.js';
+import { getAppById } from './apps.js';
+import { detectActionableWork } from './perpetualWork.js';
+import { resolveQuotaBurnStep } from './quotaBurnInvoke.js';
+import { getQuotaBurnConfig } from './quotaBurnStore.js';
+import { recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
+import { nextQuotaBurnSequenceJob, completeQuotaBurnSequenceStep } from './quotaBurnSequence.js';
+const audit = { id: 'audit', runOnce: true, taskRef: { kind: 'builtin', taskType: 'simplify', appId: 'app-1' } };
+const drain = { id: 'drain', runOnce: true, taskRef: { kind: 'builtin', taskType: 'claim-issue', appId: 'app-1' }, drain: true, overrides: { params: {} } };
+const docs = { id: 'docs', runOnce: true, taskRef: { kind: 'builtin', taskType: 'documentation', appId: 'app-1' } };
+const family = { id: 'codex', sequence: true, jobs: [audit, drain, docs] };
+const context = () => ({ completions: { 'codex:audit': 'done' }, reservations: {}, catalog: {} });
+beforeEach(() => {
+ vi.clearAllMocks();
+ getAllTasks.mockResolvedValue({ cos: { tasks: [] }, user: { tasks: [] } });
+ getQuotaBurnConfig.mockResolvedValue({ families: { codex: family } });
+ getAppById.mockResolvedValue({ id: 'app-1', taskTypeOverrides: { 'claim-issue': { taskMetadata: { issueAuthorFilter: 'collaborators', issueExcludeLabels: ['hold'] } } } });
+ resolveQuotaBurnStep.mockResolvedValue({ ref: { taskType: 'claim-issue', appId: 'app-1' }, interval: { perpetual: true, taskMetadata: { issueAuthorFilter: 'self' } } });
+ detectActionableWork.mockResolvedValue({ hasDetector: true, actionable: true, count: 2 });
+ recordQuotaBurnJobCompletion.mockImplementation(async (f, j) => ({ [`${f}:${j}`]: 'done' }));
+});
+describe('maintenance sequence workflow', () => {
+ it('repeats claims with saved app filters, then advances only after the backlog drains', async () => {
+ const ctx = context();
+ expect(await nextQuotaBurnSequenceJob(family, ctx)).toEqual({ job: drain });
+ expect(detectActionableWork).toHaveBeenCalledWith('claim-issue', expect.anything(), { issueAuthorFilter: 'collaborators', issueExcludeLabels: ['hold'], ignoreTaskId: null });
+ expect(recordQuotaBurnJobCompletion).not.toHaveBeenCalled();
+ detectActionableWork.mockResolvedValue({ hasDetector: true, actionable: false, count: 0 });
+ expect(await nextQuotaBurnSequenceJob(family, ctx)).toEqual({ job: docs });
+ expect(ctx.completions['codex:drain']).toBe('done');
+ });
+ it('holds for reservations, blocked tasks, failed probes, and claims still in flight', async () => {
+ expect(await nextQuotaBurnSequenceJob(family, { ...context(), reservations: { x: { familyId: 'codex' } } })).toHaveProperty('reason');
+ getAllTasks.mockResolvedValue({ cos: { tasks: [{ id: 'task-1', status: 'blocked', metadata: { quotaBurnFamily: 'codex' } }] } });
+ expect(await nextQuotaBurnSequenceJob(family, context())).toHaveProperty('reason');
+ getAllTasks.mockResolvedValue({});
+ detectActionableWork.mockResolvedValue({ hasDetector: true, transient: true, actionable: false });
+ expect(await nextQuotaBurnSequenceJob(family, context())).toHaveProperty('reason');
+ detectActionableWork.mockResolvedValue({ hasDetector: true, actionable: false, inFlightCount: 1 });
+ expect(await nextQuotaBurnSequenceJob(family, context())).toHaveProperty('reason');
+ expect(recordQuotaBurnJobCompletion).not.toHaveBeenCalled();
+ });
+ it('records only successful audit completions, leaving claim drains to the detector', async () => {
+ const agent = { metadata: { taskQuotaBurnFamily: 'codex', taskQuotaBurnStepId: 'audit' }, result: { success: false } };
+ await completeQuotaBurnSequenceStep(agent);
+ expect(recordQuotaBurnJobCompletion).not.toHaveBeenCalled();
+ agent.result.success = true;
+ await completeQuotaBurnSequenceStep(agent);
+ expect(recordQuotaBurnJobCompletion).toHaveBeenCalledWith('codex', 'audit');
+ recordQuotaBurnJobCompletion.mockClear();
+ agent.metadata.taskQuotaBurnStepId = 'drain';
+ await completeQuotaBurnSequenceStep(agent);
+ expect(recordQuotaBurnJobCompletion).not.toHaveBeenCalled();
+ });
+});