Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add a per-step Run once mode to quota burn so a plan can be a one-shot series
[._.]/ Adam Eivyf7b9ef880f43
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ec78203c1a..d3eb44d39b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@- CoS now notices when a scheduled task (the overnight branch-reconcile loop) finishes the same work over and over in short-lived agent runs. It parks a looping coordinator so it stops burning quota, files one GitHub issue to fix the drain, and records per-run duration so the burst is visible as a metric.- Git submodules are now managed per app instead of on one global Dev Tools page. Any managed app whose repo has a `.gitmodules` gets a Submodules tab showing each submodule against its remote, so PortOS's own bundled slashdo is maintained from the PortOS app page alongside its git, processes and update controls. Updating a submodule can now also commit the pointer bump for you: leave "Commit the pointer bump" on and the update stages just that submodule and commits it on the repo's default branch. It refuses to commit — and says why — when the repo is checked out on some other branch, so the bump can't land in the middle of unrelated work. The old `/devtools/submodules` link redirects to PortOS's own tab.+- Quota Burn steps can now be marked **Run once**, so a burn plan can be a one-shot series instead of a rotation that repeats forever. A plan is walked lap after lap until a quota gate closes, which is right for a standing audit and wrong for work that only needs doing once — that work was simply re-done every lap for as long as the window had quota left. A step marked Run once records its dispatch, drops out of the rotation, and shows when it ran, with a ↺ Re-arm on the row (and Re-arm all on the plan) to put it back. Re-arming spends nothing; the next cycle still faces every gate. Existing plans are unaffected: steps repeat by default, exactly as before. A plan whose steps have all run also stops paying for the multi-second provider quota scrape every interval, and reports "every enabled job has already run once" rather than looking misconfigured.- The Usage page can now record what you pay each month for your AI subscriptions (Claude, Codex, Antigravity, Grok) and shows what those plans saved against the estimated API cost. Each plan's price is prorated across whatever report window is selected, so both sides of the comparison cover the same days, and every plan gets its own row: monthly price, cost for this window, the API-rate cost its usage ran up, and the difference. Usage no subscription covers — pay-as-you-go API providers and pre-breakdown legacy rows — is reported separately instead of being credited to a plan.## Fixeddiff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsxindex 2c2bded228..b52a7ba6cb 100644--- a/client/src/components/quotaBurn/FamilyCard.jsx+++ b/client/src/components/quotaBurn/FamilyCard.jsx@@ -7,7 +7,7 @@* runner evaluates, so the card can't disagree with what actually happens.*/-import { Ban, ChevronDown, ChevronRight, Flame, Plus } from 'lucide-react';+import { Ban, ChevronDown, ChevronRight, Flame, Plus, RotateCcw } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';import JobRow from './JobRow';import PresetPicker from './PresetPicker';@@ -17,15 +17,19 @@ import { NumberField } from './fields';export default function FamilyCard({familyId, config, status, catalog, expanded, actionsBusy,- onToggleExpand, onPatch, onRunFamily, onRunJob,+ onToggleExpand, onPatch, onRunFamily, onRunJob, onRearm,}) {const jobs = config.jobs || [];- // Pending counts stay on the STATUS side and are passed to JobRow as their own- // prop — merging them into the job objects would mean stripping them back off- // before every save (the PUT schema is strict). Matched by id so a reorder- // mid-save can't mis-pair them.+ // Pending counts and `run once` completions stay on the STATUS side and are+ // passed to JobRow as their own props — merging them into the job objects+ // would mean stripping them back off before every save (the PUT schema is+ // strict). Matched by id so a reorder mid-save can't mis-pair them.const statusJobs = status?.jobs || [];- const pendingFor = (id) => statusJobs.find((row) => row.id === id)?.pending ?? null;+ const statusFor = (id) => statusJobs.find((row) => row.id === id) || null;+ // Gated on the CONFIG's `runOnce` (as JobRow's badge is), so the count matches+ // the number of "Ran once" rows on screen rather than counting a stale+ // completion on a step the user has since switched back to repeating.+ const spentCount = jobs.filter((job) => job.runOnce && statusFor(job.id)?.ranAt).length;const patchJobs = (next) => onPatch({ jobs: next });const changeJob = (index, next) => patchJobs(jobs.map((job, i) => (i === index ? next : job)));@@ -61,6 +65,9 @@ export default function FamilyCard({jobType: catalog.jobTypes[0].id,model: null,providerId: null,+ // Standing work by default — the pre-`runOnce` behavior, so adding a step+ // does the same thing it always did.+ runOnce: false,params: {},}]);// A preset job inherits the app the plan is already pointed at, when the plan@@ -122,10 +129,13 @@ export default function FamilyCard({{/* A collapsed card otherwise says nothing about whether this family hasa plan at all — and a family with zero enabled jobs can never burn,- no matter how healthy its window looks. */}+ no matter how healthy its window looks. A spent `run once` step is+ counted here for the same reason: it is enabled but unrunnable, so+ without it "3 jobs · 3 enabled" sits above a family that will never+ 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`+ ? `${jobs.length} job${jobs.length === 1 ? '' : 's'} · ${jobs.filter((job) => job.enabled !== false).length} enabled${spentCount ? ` · ${spentCount} ran once` : ''}`: 'no jobs'}</span>@@ -160,17 +170,35 @@ export default function FamilyCard({</div><div className="space-y-3">- <div className="flex items-center justify-between">+ <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>- <button- type="button"- className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-40"- disabled={!canAddJob}- title={canAddJob ? 'Add a job to this plan' : 'Job catalog unavailable — reload the page'}- onClick={addJob}- >- <Plus size={13} /> Add job- </button>+ <div className="flex items-center gap-3">+ {/* Re-arming step by step is the wrong shape for the case this+ exists to serve: a plan configured as a one-shot SERIES,+ which the user wants to run again as a series. Not confirmed+ — it dispatches nothing on its own, it just makes the steps+ eligible for a future cycle's gates. */}+ {spentCount > 0 && (+ <button+ type="button"+ className="inline-flex items-center gap-1 text-xs text-gray-300 hover:text-white disabled:opacity-40"+ disabled={actionsBusy}+ onClick={() => onRearm(familyId)}+ title="Put every step that has already run back into the rotation"+ >+ <RotateCcw size={13} /> Re-arm all ({spentCount})+ </button>+ )}+ <button+ type="button"+ className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-40"+ disabled={!canAddJob}+ title={canAddJob ? 'Add a job to this plan' : 'Job catalog unavailable — reload the page'}+ onClick={addJob}+ >+ <Plus size={13} /> Add job+ </button>+ </div></div><div className="sm:max-w-md"><PresetPicker@@ -191,12 +219,14 @@ export default function FamilyCard({index={index}total={jobs.length}catalog={catalog}- pending={pendingFor(job.id)}+ pending={statusFor(job.id)?.pending ?? null}+ ranAt={statusFor(job.id)?.ranAt ?? null}actionsBusy={actionsBusy}onChange={(next) => changeJob(index, next)}onMove={moveJob}onRemove={(i) => patchJobs(jobs.filter((_, x) => x !== i))}onRun={(target) => onRunJob(familyId, target)}+ onRearm={(target) => onRearm(familyId, target.id)}/>))}</div>diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsxindex 716da2044e..c18d23ff2c 100644--- a/client/src/components/quotaBurn/JobRow.jsx+++ b/client/src/components/quotaBurn/JobRow.jsx@@ -7,17 +7,18 @@*/import { useEffect, useState } from 'react';-import { ArrowDown, ArrowUp, Play, Trash2 } from 'lucide-react';+import { ArrowDown, ArrowUp, CheckCircle2, Play, RotateCcw, Trash2 } from 'lucide-react';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import InlineConfirmRow from '../ui/InlineConfirmRow';import JobParamField from './JobParamField';import PresetPicker from './PresetPicker';import { applyQuotaBurnPreset } from '../../lib/quotaBurnPatch';+import { timeAgo } from '../../utils/formatters';import { inputClass } from './fields';export default function JobRow({- job, index, total, catalog, pending, actionsBusy,- onChange, onMove, onRemove, onRun,+ job, index, total, catalog, pending, ranAt, actionsBusy,+ onChange, onMove, onRemove, onRun, onRearm,}) {// Two-click arm on delete (the repo's inline-confirm convention). A job holds// the family's whole free-text work prompt and nothing else stores it — a@@ -41,6 +42,12 @@ export default function JobRow({useEffect(() => { if (actionsBusy) setRunArmed(false); }, [actionsBusy]);const spec = catalog.jobTypes.find((type) => type.id === job.jobType);const idPrefix = `burn-job-${job.id}`;+ // A completion is recorded whenever a `run once` step dispatches, and is kept+ // even if the checkbox is later cleared — so the badge is gated on the+ // checkbox rather than on `ranAt` alone. That way ticking "run once" on a step+ // that already ran immediately SHOWS that it is spent (with Re-arm right+ // there), instead of silently dropping it out of the rotation.+ const spent = Boolean(job.runOnce && ranAt);const setParam = (key, value) => onChange({ ...job, params: { ...job.params, [key]: value } });const promptText = String(job.params?.prompt || '').trim();const hasPromptText = Boolean(promptText);@@ -140,6 +147,26 @@ export default function JobRow({onChange={(event) => onChange({ ...job, model: event.target.value || null })}/></label>+ {/* The repeat/one-shot choice. The plan is a rotation the runner walks+ lap after lap while the window still has quota, which is right for a+ standing audit and wrong for work that only needs doing once — that+ was simply re-done every lap. */}+ <div className="text-xs text-gray-400">+ <div className="flex items-center gap-2 mt-1">+ <input+ id={`${idPrefix}-run-once`}+ type="checkbox"+ checked={job.runOnce === true}+ 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+ ? '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>+ </div><PresetPickerid={`${idPrefix}-preset`}label="Start from a preset (optional)"@@ -181,7 +208,26 @@ export default function JobRow({)}{spec?.description && <p className="text-[11px] text-gray-500">{spec.description}</p>}- {pending && (+ {/* A spent step is not probed server-side (its count would never be acted+ on), so this REPLACES the pending line rather than sitting beside it —+ "Idle — no pending work" would otherwise be the only thing a finished+ step said about itself. */}+ {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)}+ </span>+ <button+ type="button"+ className="inline-flex items-center gap-1 text-port-accent hover:underline disabled:opacity-40"+ disabled={actionsBusy}+ onClick={() => onRearm(job)}+ title="Put this step back into the rotation — it burns again on a future cycle"+ >+ <RotateCcw size={12} /> Re-arm+ </button>+ </p>+ ) : pending && (<p className={`text-[11px] ${pending.count > 0 ? 'text-emerald-400' : 'text-gray-500'}`}>{pending.count > 0 ? `Ready — ${pending.detail}` : `Idle — ${pending.detail}`}</p>diff --git a/client/src/lib/quotaBurnPatch.js b/client/src/lib/quotaBurnPatch.jsindex fc7a8eb246..7993aee9ca 100644--- a/client/src/lib/quotaBurnPatch.js+++ b/client/src/lib/quotaBurnPatch.js@@ -38,6 +38,10 @@ export function mergeQuotaBurnPatch(base, patch) {* - `params.appId` — which managed app the work targets. Wiping it would turn* "make this step a UX audit" into a silently unrunnable job whose only* symptom is a status line at the bottom of the row.+ * - `runOnce` — whether this is one-shot or standing work. The presets are+ * standing audits, but the user may have marked a step "run once" for their+ * own reasons, and re-picking a preset must not quietly put it back into the+ * rotation to spend quota on every lap.*/export function applyQuotaBurnPreset(job, preset) {if (!preset) return job;@@ -58,6 +62,9 @@ export function applyQuotaBurnPreset(job, preset) {export function jobFromPreset(preset, { id, appId = null } = {}) {return applyQuotaBurnPreset({id, enabled: true, label: '', jobType: preset.jobType, model: null, providerId: null,+ // Standing work by default, matching a hand-added step — an audit dimension+ // is worth re-running as the code changes.+ runOnce: false,params: appId ? { appId } : {},}, preset);}diff --git a/client/src/lib/quotaBurnPatch.test.js b/client/src/lib/quotaBurnPatch.test.jsindex bf5e3d8119..c863737f93 100644--- a/client/src/lib/quotaBurnPatch.test.js+++ b/client/src/lib/quotaBurnPatch.test.js@@ -80,12 +80,21 @@ describe('applyQuotaBurnPreset', () => {it('returns the job untouched when there is no preset', () => {expect(applyQuotaBurnPreset(job, null)).toBe(job);});++ it('preserves the step\'s run-once choice', () => {+ // The presets are standing audits, but the user may have marked this step+ // one-shot for their own reasons — re-picking a preset must not quietly put+ // it back into a rotation that spends quota on every lap.+ expect(applyQuotaBurnPreset({ ...job, runOnce: true }, preset).runOnce).toBe(true);+ });});describe('jobFromPreset', () => {it('mints a runnable job with the caller\'s id and app', () => {expect(jobFromPreset(preset, { id: 'job-x', appId: 'a1' })).toEqual({id: 'job-x', enabled: true, label: 'UX issues', jobType: 'agent-prompt', model: null, providerId: null,+ // Standing work: an audit dimension is worth re-running as the code moves.+ runOnce: false,params: { ...preset.params, appId: 'a1' },});});diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex fb67e1c108..aa65b7c637 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -181,6 +181,19 @@ export default function QuotaBurn() {const patchFamily = (familyId, patch) => save({ families: { [familyId]: patch } });+ // 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+ // touched: completions live in their own ledger, and adopting a config here+ // would fight the debounced save.+ const rearm = async (familyId, jobId = null) => {+ setRunning(true);+ const next = await api.rearmQuotaBurn(familyId, jobId, { silent: true })+ .catch((err) => { toast.error(`Could not re-arm: ${err.message}`); return null; });+ if (next?.status) setStatus(next.status);+ setRunning(false);+ };+const run = async (body, label) => {setRunning(true);const response = await api.runQuotaBurn(body, { silent: true })@@ -260,7 +273,9 @@ export default function QuotaBurn() {<p className="text-xs text-gray-400">One loop for this install, but each provider family burns independently: every family whose window is inside its resethorizon, above its reserve, and under its dispatch cap (unlimited by default) runs the first job in its plan that has work waiting — one job- per family per cycle. Turning this on is explicit consent to spend those subscriptions on a schedule.+ per family per cycle. A plan is a rotation: steps repeat lap after lap until a gate closes, unless you mark one+ “Run once” — one-shot work then drops out after its dispatch until you re-arm it. Turning this on is explicit+ consent to spend those subscriptions on a schedule.</p>{lastRun && (<p className="text-[11px] text-gray-500">@@ -283,6 +298,7 @@ export default function QuotaBurn() {onPatch={(patch) => patchFamily(familyId, patch)}onRunFamily={(id) => run({ familyId: id }, 'Burn')}onRunJob={(id, job) => run({ familyId: id, jobId: job.id, force: true }, 'Job run')}+ onRearm={rearm}/>))}</section>diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex 4c28214507..d1e5bfe7f1 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -10,6 +10,7 @@ vi.mock('../services/api', () => ({getQuotaBurnCatalog: vi.fn(),saveQuotaBurn: vi.fn(),runQuotaBurn: vi.fn(),+ rearmQuotaBurn: vi.fn(),}));import * as api from '../services/api';@@ -80,6 +81,7 @@ beforeEach(() => {api.getQuotaBurnCatalog.mockResolvedValue(catalog);api.saveQuotaBurn.mockResolvedValue({ config });api.runQuotaBurn.mockResolvedValue({ result: { dispatched: false, reason: 'nothing to burn' } });+ api.rearmQuotaBurn.mockResolvedValue({ config, status });});describe('QuotaBurn page', () => {@@ -276,6 +278,69 @@ describe('QuotaBurn page', () => {await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalled());const [patch] = api.saveQuotaBurn.mock.calls.at(-1);expect(patch.families.grok.jobs[0]).not.toHaveProperty('pending');+ expect(patch.families.grok.jobs[0]).not.toHaveProperty('ranAt');+ });+});++/**+ * `run once` — a plan is a rotation the runner walks lap after lap, which is+ * wrong for work that only needs doing once.+ */+describe('QuotaBurn run-once steps', () => {+ const ranAt = new Date(Date.now() - 3_600_000).toISOString();+ // A spent step: `runOnce` on the config side, `ranAt` on the status side.+ const spent = {+ config: {+ ...config,+ families: { ...config.families, grok: { ...config.families.grok, jobs: [{ ...config.families.grok.jobs[0], runOnce: true }] } },+ },+ status: {+ ...status,+ families: [{ ...status.families[0], jobs: [{ id: 'j1', ranAt, spent: true, pending: null }] }, status.families[1]],+ },+ };++ it('saves the run-once choice as part of the job', async () => {+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ await user.click(await screen.findByLabelText('Run once'));+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalled());+ expect(api.saveQuotaBurn.mock.calls.at(-1)[0].families.grok.jobs[0].runOnce).toBe(true);+ });++ it('reports a spent step as ran rather than idle', async () => {+ // The server stops probing a spent step, so without this the row's only+ // self-description would be the absence of a pending line.+ api.getQuotaBurn.mockResolvedValue(spent);+ renderPage('/devtools/quota-burn/grok');+ expect(await screen.findByText(/Ran once/)).toBeInTheDocument();+ expect(screen.getByText(/1 ran once/)).toBeInTheDocument();+ });++ it('re-arms one step without dispatching anything', async () => {+ api.getQuotaBurn.mockResolvedValue(spent);+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ await user.click(await screen.findByRole('button', { name: /Re-arm$/ }));+ await waitFor(() => expect(api.rearmQuotaBurn).toHaveBeenCalledWith('grok', 'j1', { silent: true }));+ // Re-arming makes a step ELIGIBLE; the next cycle's gates still decide.+ expect(api.runQuotaBurn).not.toHaveBeenCalled();+ });++ it('re-arms a whole one-shot series in one click', async () => {+ // The case this exists for: a plan configured as a series the user wants to+ // run again as a series.+ api.getQuotaBurn.mockResolvedValue(spent);+ const user = userEvent.setup();+ renderPage('/devtools/quota-burn/grok');+ await user.click(await screen.findByRole('button', { name: /Re-arm all/ }));+ await waitFor(() => expect(api.rearmQuotaBurn).toHaveBeenCalledWith('grok', null, { silent: true }));+ });++ it('offers no re-arm control while nothing has run', async () => {+ renderPage('/devtools/quota-burn/grok');+ await screen.findByText(/Ready — 4 bible entries/);+ expect(screen.queryByRole('button', { name: /Re-arm/ })).not.toBeInTheDocument();});});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex caf8276dfb..6c6d043331 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -58,7 +58,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiRuns.js` | Agent run history. || `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. |-| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`). |+| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison). || `apiAuth.js` | Optional login password — status, login/logout, set/clear password. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiQuotaBurn.js b/client/src/services/apiQuotaBurn.jsindex 2a0ecf6bfe..e6ba8b70e8 100644--- a/client/src/services/apiQuotaBurn.js+++ b/client/src/services/apiQuotaBurn.js@@ -26,3 +26,12 @@ export const runQuotaBurn = (body = {}, options) => request('/quota-burn/run', {body: JSON.stringify(body),...options,});++// Put spent `run once` steps back into the rotation and return the fresh status.+// `jobId` scopes it to one step; omitting it re-arms the family's whole plan.+// Nothing is dispatched — the next cycle decides that.+export const rearmQuotaBurn = (familyId, jobId = null, options) => request('/quota-burn/rearm', {+ method: 'POST',+ body: JSON.stringify(jobId ? { familyId, jobId } : { familyId }),+ ...options,+});diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex ce31606b93..d8f7145cfa 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -19,8 +19,8 @@ Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:have headroom above `reservePercent` in *every* window on the card, and that havenot spent `maxDispatchesPerWindow` for that window (`-1`, the default, meansno cap — see below). Ties break on `priority` (lower wins).-4. Runs the **first enabled job in that family's ordered plan that reports- pending work** — at most one dispatch per cycle.+4. Runs the **first enabled, unspent job in that family's ordered plan that+ reports pending work** — at most one dispatch per cycle.5. Charges the window in `data/cos/quota-burn-dispatches.json` and appends theoutcome (including skips, with reasons) to `data/cos/quota-burn-runs.json`.@@ -118,6 +118,52 @@ its own type, optional model/provider pin, and type-specific params.| `agent-prompt` | Queues a CoS agent in a named managed app with a custom prompt. Visible in the CoS queue and Active Agents like any other task. || `universe-bible-images` | **Programmatic** — no agent. Enqueues renders for universe bible entries whose `imageRefs[]` is empty. Render backend defaults to the burning family's own image mode, so a codex burn spends codex's image quota. |+### Repeating vs one-shot work (`runOnce`)++A plan is a **rotation**: the walk resumes after the family's last dispatch+(`rotatePlanAfter`), so an N-job plan cycles through all N and then starts the+next lap, spending the window until a gate closes. That is right for standing+work — an audit dimension is worth re-running as the code moves — and wrong for+work that only needs doing once, which was simply re-done every lap.++Each job therefore carries a **`runOnce`** flag (default `false`, so every plan+written before it keeps repeating):++| `runOnce` | Behavior |+| --- | --- |+| `false` | Standing work. Repeats every lap while the window still has quota. |+| `true` | One-shot. Records its dispatch and drops out of the rotation until re-armed. |++A whole plan of `runOnce` steps is how "run this series once" is expressed: the+completion continuation walks it one agent at a time and it stops of its own+accord instead of looping.++- **The ledger is `data/cos/quota-burn-completions.json`**, `<familyId>:<jobId>`+ → the ISO instant it ran, capped at 200 entries (newest kept). It is a+ separate file rather than a flag on the job because a config PUT **replaces**+ a family's `jobs` array — that is how every reorder and edit saves — so a flag+ on the job would be reset by an unrelated edit, and by the client's optimistic+ copy of the plan, which never sees the runner's write. The run log can't answer+ it either: it is a capped UI feed, so a job that ran last month has aged out.+- **Recorded only on a real dispatch.** A job that declines (`dispatched: false`)+ is not spent — a misconfigured step must stay retryable.+- **A forced ▶ run bypasses the gate AND still records.** `charge: false` is about+ the *window's automatic budget*; `runOnce` is a statement about the *work*, and+ the work just happened however it was triggered.+- **An unreadable ledger fails CLOSED** — the cycle reports `run-once ledger+ unreadable` rather than treating "nothing has run" as fact and re-dispatching+ every one-shot job on the plan.+- **A finished plan stops costing a quota scrape.** `familyIsActionable(family,+ completions)` returns false once every enabled job is a spent one-shot, so the+ cycle returns before the multi-second per-family TUI scrape. The page reports+ it as `every enabled job has already run once`, kept distinct from `no enabled+ jobs configured` — a finished plan wants Re-arm, an unset one wants a job added.+- **Re-arm** puts steps back in the rotation: the ↺ on a job row for one step,+ **Re-arm all** on the plan header for the family. `POST /api/quota-burn/rearm`+ with `{ familyId, jobId? }`; a `familyId` is required, since a bare "clear+ everything" would silently re-queue every one-shot job on the install. It+ dispatches nothing — the next cycle still faces every gate.+Adding a job type is three edits: a `QUOTA_BURN_JOB_TYPE` entry + catalog row in`server/lib/quotaBurnConfig.js`, a module in `server/services/quotaBurnJobs/`, andone line in that directory's `JOB_MODULES`. The config page builds its form from@@ -210,7 +256,7 @@ request), and the catalog descriptors the client renders as `min`/`max`.## Storage-Five files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json`), the per-window dispatch ledger (`quota-burn-dispatches.json`), the run log (`quota-burn-runs.json`), the in-flight set (`quota-burn-inflight.json` — entries a job enqueued whose renders have not landed yet, so the next cycle does not re-queue them; 6-hour TTL), and the denial ledger (`quota-burn-denials.json` — per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL). They are not federated: quota belongs to a+Six files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json`), the per-window dispatch ledger (`quota-burn-dispatches.json`), the run log (`quota-burn-runs.json`), the in-flight set (`quota-burn-inflight.json` — entries a job enqueued whose renders have not landed yet, so the next cycle does not re-queue them; 6-hour TTL), the denial ledger (`quota-burn-denials.json` — per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL), and the `run once` completion ledger (`quota-burn-completions.json` — which one-shot steps have had their dispatch, cleared by Re-arm). They are not federated: quota belongs to aparticular machine and provider account, and the "which managed app" targetsdiffer per machine.@@ -232,6 +278,7 @@ folds those overrides into the single plan (each app's family prompt becomes an| `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) || `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log || `server/services/quotaBurn.js` | `evaluateFamily` — the one gate ladder both selection and the page's skip reasons read — plus the dispatch ledger |+| `server/services/quotaBurnCompletions.js` | The `run once` completion ledger and its re-arm || `server/services/quotaBurnDenials.js` | The observed-refusal ledger and its `agent:completed` subscriber || `server/services/quotaBurnJobs/` | The job registry and its modules || `server/services/quotaBurnRunner.js` | The loop, the cycle, and the status feed |diff --git a/server/lib/README.md b/server/lib/README.mdindex bf80bac9bd..f6ba92e731 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -28,9 +28,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |-| `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 queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. |+| `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 queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the completion-aware form of `familyIsActionable`). Pure — no storage, no provider I/O. || `quotaBurnPresets.js` | `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)`. |-| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |+| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). || `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. || `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. || `appleHealthValidation.js` | Apple Health import payloads. |diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.jsindex 5c9f5bc7b3..7ecf09835f 100644--- a/server/lib/quotaBurnConfig.js+++ b/server/lib/quotaBurnConfig.js@@ -53,6 +53,15 @@ export function quotaBurnFamilyOfDescription(description) {return QUOTA_BURN_FAMILIES.includes(family) ? family : null;}+/**+ * The completion-ledger key for one job: `<familyId>:<jobId>`.+ *+ * Job ids are only unique within a family (they are minted from a clock), so the+ * family has to be part of the key or a `run once` job in one plan would mark+ * its namesake in another as already spent.+ */+export const quotaBurnJobKey = (familyId, jobId) => `${familyId}:${jobId}`;+/*** `maxDispatchesPerWindow` sentinel for "no cap on how many burns this window* may spend" — and the default. Why the cap is opt-in rather than a safety@@ -225,10 +234,32 @@ export function normalizeQuotaBurnJob(raw, index = 0) {jobType,model: nullableString(raw.model, BOUNDS.labelLength.max),providerId: nullableString(raw.providerId, BOUNDS.labelLength.max),+ // 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,params: normalizeParams(raw.params),};}+/**+ * Whether a `run once` job has already had its one dispatch.+ *+ * A plan is an ordered ROTATION the runner walks until a quota gate closes+ * (`quotaBurnRunner.js#rotatePlanAfter`), which is right for standing work+ * ("audit performance") and wrong for one-shot work ("write the missing README")+ * — the latter was simply re-done every lap. `runOnce` marks the second kind:+ * once `quotaBurnCompletions.js` has recorded a dispatch for it, it drops out of+ * the rotation until the user re-arms it from the page.+ *+ * Held in a separate machine-local ledger rather than as a flag on the job so+ * the plan the user edits stays a statement of intent, and so a config PUT that+ * replaces the `jobs` array (which is how every reorder and edit saves) can't+ * silently resurrect a job that already ran.+ */+export function jobIsSpent(job, familyId, completions = {}) {+ return job?.runOnce === true && Boolean(completions?.[quotaBurnJobKey(familyId, job.id)]);+}+/*** Normalize one provider family's burn plan. Bounds mirror the pre-#3179* per-app sanitizer so a migrated config keeps its meaning: reset window up to@@ -279,7 +310,16 @@ export function normalizeQuotaBurnConfig(raw) {* is a half-finished setup, not a burn plan — treating it as actionable would* spawn a candidate the runner then has to discard, which shows up as a* confusing "selected, then skipped" cycle in the run log.+ *+ * `completions` additionally excludes spent `run once` jobs, so a plan made+ * entirely of one-shot work stops being actionable the moment its last job has+ * run. Defaulted to `{}` because the two questions have different answers and+ * the callers want different ones: the config-only form distinguishes "you+ * configured nothing" from "your plan is finished", and the runner needs the+ * completion-aware form so an exhausted plan stops paying for a multi-second+ * quota scrape every interval, forever.*/-export function familyIsActionable(family) {- return family?.enabled === true && (family.jobs || []).some((job) => job?.enabled !== false);+export function familyIsActionable(family, completions = {}) {+ return family?.enabled === true+ && (family.jobs || []).some((job) => job?.enabled !== false && !jobIsSpent(job, family.id, completions));}diff --git a/server/lib/quotaBurnConfig.test.js b/server/lib/quotaBurnConfig.test.jsindex 56b70860cc..d178e9a28e 100644--- a/server/lib/quotaBurnConfig.test.js+++ b/server/lib/quotaBurnConfig.test.js@@ -6,8 +6,10 @@ import {QUOTA_BURN_UNLIMITED_DISPATCHES,familyIsActionable,isUnlimitedDispatchCap,+ jobIsSpent,normalizeQuotaBurnConfig,normalizeQuotaBurnJob,+ quotaBurnJobKey,} from './quotaBurnConfig.js';describe('normalizeQuotaBurnConfig', () => {@@ -83,6 +85,35 @@ describe('normalizeQuotaBurnJob', () => {expect(normalizeQuotaBurnJob({ jobType: 'agent-prompt' }, 2).id).toBe('job-3');});+ it('treats an absent runOnce as repeating so an older plan keeps its meaning', () => {+ // Opt-IN. Every plan written before this field existed is standing work, and+ // coercing those to one-shot would silently retire someone's whole rotation.+ expect(normalizeQuotaBurnJob({ jobType: 'agent-prompt' }).runOnce).toBe(false);+ expect(normalizeQuotaBurnJob({ jobType: 'agent-prompt', runOnce: 'yes' }).runOnce).toBe(false);+ expect(normalizeQuotaBurnJob({ jobType: 'agent-prompt', runOnce: true }).runOnce).toBe(true);+ });+});++describe('jobIsSpent', () => {+ const ran = { 'grok:j1': '2026-08-01T00:00:00.000Z' };++ it('only retires a job that opted into running once', () => {+ // A completion is kept even after the checkbox is cleared, so the flag — not+ // the ledger entry — is what decides whether the job still runs.+ expect(jobIsSpent({ id: 'j1', runOnce: true }, 'grok', ran)).toBe(true);+ expect(jobIsSpent({ id: 'j1', runOnce: false }, 'grok', ran)).toBe(false);+ });++ it('scopes the completion to the family, so two plans cannot retire each other', () => {+ expect(jobIsSpent({ id: 'j1', runOnce: true }, 'claude', ran)).toBe(false);+ expect(quotaBurnJobKey('grok', 'j1')).toBe('grok:j1');+ });++ it('reads an unrecorded job as unspent, including with no ledger at all', () => {+ expect(jobIsSpent({ id: 'j2', runOnce: true }, 'grok', ran)).toBe(false);+ expect(jobIsSpent({ id: 'j1', runOnce: true }, 'grok')).toBe(false);+ });+it('keeps scalar params and strips nested blobs and prototype keys', () => {// `JSON.parse`, not an object literal: `{ __proto__: … }` in a literal sets// [[Prototype]] rather than creating an own property, so Object.entries@@ -102,6 +133,22 @@ describe('familyIsActionable', () => {expect(familyIsActionable({ enabled: true, jobs: [{ enabled: false }] })).toBe(false);expect(familyIsActionable({ enabled: true, jobs: [{ enabled: true }] })).toBe(true);});++ it('stops being actionable once every enabled job is a spent one-shot', () => {+ const family = {+ id: 'grok',+ enabled: true,+ jobs: [{ id: 'j1', enabled: true, runOnce: true }, { id: 'j2', enabled: false }],+ };+ const ran = { 'grok:j1': '2026-08-01T00:00:00.000Z' };+ // The completion-blind form still answers "you configured something" — the+ // runner and the page report those as two different verdicts, because a+ // finished plan wants Re-arm and an unset one wants a job added.+ expect(familyIsActionable(family)).toBe(true);+ expect(familyIsActionable(family, ran)).toBe(false);+ // One repeating job is enough to keep the plan alive.+ expect(familyIsActionable({ ...family, jobs: [...family.jobs, { id: 'j3', enabled: true }] }, ran)).toBe(true);+ });});describe('isUnlimitedDispatchCap', () => {diff --git a/server/lib/quotaBurnValidation.js b/server/lib/quotaBurnValidation.jsindex c853c437c2..a20c09c197 100644--- a/server/lib/quotaBurnValidation.js+++ b/server/lib/quotaBurnValidation.js@@ -36,6 +36,10 @@ const quotaBurnJobSchema = z.object({jobType: z.enum(QUOTA_BURN_JOB_TYPES),model: z.string().max(B.labelLength.max).nullable().optional(),providerId: z.string().max(B.labelLength.max).nullable().optional(),+ // One-shot work: dispatch this step at most once, then drop it out of the+ // rotation until the user re-arms it. Absent reads as `false`, so plans+ // written before this field keep repeating.+ runOnce: z.boolean().optional(),params: z.record(paramValueSchema).optional(),}).strict();@@ -73,3 +77,14 @@ export const quotaBurnRunSchema = z.object({// meaningful with `familyId` — the route rejects it otherwise.force: z.boolean().optional(),}).strict();++/**+ * Re-arm a spent `run once` step. `familyId` is required — a bare "clear+ * everything" would silently re-queue every one-shot job on the install, which+ * is real spend nobody asked for. Omitting `jobId` re-arms that family's whole+ * plan, which is how "run that series again" is expressed.+ */+export const quotaBurnRearmSchema = z.object({+ familyId: z.enum(QUOTA_BURN_FAMILIES),+ jobId: z.string().max(B.idLength.max).optional(),+}).strict();diff --git a/server/routes/quotaBurn.js b/server/routes/quotaBurn.jsindex 15f34359e7..87e0298da1 100644--- a/server/routes/quotaBurn.js+++ b/server/routes/quotaBurn.js@@ -6,10 +6,11 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest, quotaBurnConfigUpdateSchema, quotaBurnRunSchema } from '../lib/validation.js';+import { validateRequest, quotaBurnConfigUpdateSchema, quotaBurnRearmSchema, quotaBurnRunSchema } from '../lib/validation.js';import { QUOTA_BURN_JOB_CATALOG } from '../lib/quotaBurnConfig.js';import { QUOTA_BURN_PROMPT_PRESETS } from '../lib/quotaBurnPresets.js';import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';+import { clearQuotaBurnJobCompletion } from '../services/quotaBurnCompletions.js';import { saveQuotaBurnConfig } from '../services/quotaBurnStore.js';import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';import { getActiveApps } from '../services/apps.js';@@ -74,4 +75,17 @@ router.post('/run', asyncHandler(async (req, res) => {res.json({ result });}));+// POST /api/quota-burn/rearm — put spent `run once` steps back into the+// rotation. `{ familyId }` re-arms that family's whole plan; adding `jobId`+// scopes it to one step. Does NOT dispatch anything: the next cycle decides+// that, against the same quota gates as always.+router.post('/rearm', asyncHandler(async (req, res) => {+ const { familyId, jobId = null } = validateRequest(quotaBurnRearmSchema, req.body || {});+ await clearQuotaBurnJobCompletion(familyId, jobId);+ // The fresh status, so the page's job rows drop their "ran once" badges+ // without a second round trip. Cached quota (no `refresh`) — re-arming says+ // nothing about the provider's numbers.+ res.json(await getQuotaBurnStatus());+}));+export default router;diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.jsindex 4865da97fa..ebb7658cf8 100644--- a/server/routes/quotaBurn.test.js+++ b/server/routes/quotaBurn.test.js@@ -11,9 +11,11 @@ vi.mock('../services/quotaBurnRunner.js', () => ({getQuotaBurnStatus: vi.fn(),runQuotaBurnCycle: vi.fn(),}));+vi.mock('../services/quotaBurnCompletions.js', () => ({ clearQuotaBurnJobCompletion: vi.fn() }));vi.mock('../services/apps.js', () => ({ getActiveApps: vi.fn() }));vi.mock('../services/universeBuilder.js', () => ({ listUniverseNames: vi.fn() }));+import { clearQuotaBurnJobCompletion } from '../services/quotaBurnCompletions.js';import { getQuotaBurnConfig, saveQuotaBurnConfig } from '../services/quotaBurnStore.js';import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';import { getActiveApps } from '../services/apps.js';@@ -127,3 +129,34 @@ describe('POST /api/quota-burn/run', () => {expect(runQuotaBurnCycle).not.toHaveBeenCalled();});});++describe('POST /api/quota-burn/rearm', () => {+ it('re-arms one named step and returns the fresh status', async () => {+ const res = await request(buildApp()).post('/api/quota-burn/rearm').send({ familyId: 'grok', jobId: 'job-1' });+ expect(res.status).toBe(200);+ expect(clearQuotaBurnJobCompletion).toHaveBeenCalledWith('grok', 'job-1');+ // The page swaps its badges from this response rather than re-fetching, and+ // re-arming says nothing about the provider's numbers — so no scrape.+ expect(getQuotaBurnStatus).toHaveBeenCalledWith();+ expect(res.body.status).toEqual({ running: false, families: [], runs: [] });+ });++ it('re-arms the whole family when no step is named', async () => {+ await request(buildApp()).post('/api/quota-burn/rearm').send({ familyId: 'grok' });+ expect(clearQuotaBurnJobCompletion).toHaveBeenCalledWith('grok', null);+ });++ it('refuses an unscoped or unknown-family re-arm', async () => {+ // A bare "clear everything" would silently re-queue every one-shot job on+ // the install — real spend nobody asked for.+ const app = buildApp();+ expect((await request(app).post('/api/quota-burn/rearm').send({})).status).toBe(400);+ expect((await request(app).post('/api/quota-burn/rearm').send({ familyId: 'nope' })).status).toBe(400);+ expect(clearQuotaBurnJobCompletion).not.toHaveBeenCalled();+ });++ it('never dispatches anything', async () => {+ await request(buildApp()).post('/api/quota-burn/rearm').send({ familyId: 'grok' });+ expect(runQuotaBurnCycle).not.toHaveBeenCalled();+ });+});diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex 0d8702b09d..a417ac9c60 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -131,15 +131,20 @@ export function windowKey(familyId, limit, { now = Date.now() } = {}) {* percentage and reset time instead of a fabricated one. It comes back* `charge: false` so it never eats the automatic budget.*/-export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}, blocks = {}, bypassGates = false } = {}) {- // The two "switched off" gates. A forced run passes both: `enabled` on the- // family and on a job governs the UNATTENDED loop, and the user clicking ▶ on- // a specific row is a more specific instruction than a checkbox they set- // earlier. Everything below — no provider, unreadable quota, unburnable card- // — is a fact about the world and holds even under force.+export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}, blocks = {}, completions = {}, bypassGates = false } = {}) {+ // The three "switched off" gates. A forced run passes all of them: `enabled`+ // on the family, `enabled` on a job, and a spent `run once` job all govern the+ // UNATTENDED loop, and the user clicking ▶ on a specific row is a more+ // specific instruction than a checkbox they set earlier. Everything below — no+ // provider, unreadable quota, unburnable card — is a fact about the world and+ // holds even under force.if (!bypassGates) {if (!family.enabled) return { skipReason: 'disabled' };+ // Reported as two distinct verdicts, because they call for opposite actions:+ // "you configured nothing" wants a job added, while a finished one-shot plan+ // wants Re-arm (or nothing at all — it did what it was asked).if (!familyIsActionable(family)) return { skipReason: 'no enabled jobs configured' };+ if (!familyIsActionable(family, completions)) return { skipReason: 'every enabled job has already run once' };}if (!card) return { skipReason: 'no enabled provider in this family' };if (card.supported === false) return { skipReason: 'provider has no queryable quota surface' };@@ -244,15 +249,16 @@ const familiesOf = (config) => Object.entries(config?.families || {})** `config` is a normalized quota-burn config; `quotas` the provider cards from* `providerUsage.getProviderQuotas()`; `blocks` the active denial ledger from- * `quotaBurnDenials.getActiveQuotaBurnBlocks()`. `bypassGatesFor` names one- * family whose window/reserve/cap/denial gates are skipped (see- * `evaluateFamily`).+ * `quotaBurnDenials.getActiveQuotaBurnBlocks()`; `completions` the `run once`+ * ledger from `quotaBurnCompletions.getQuotaBurnCompletions()`.+ * `bypassGatesFor` names one family whose window/reserve/cap/denial gates are+ * skipped (see `evaluateFamily`).*/-export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {}, blocks = {}, bypassGatesFor = null } = {}) {+export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {}, blocks = {}, completions = {}, bypassGatesFor = null } = {}) {const cards = new Map((quotas || []).map((card) => [card.family, card]));return familiesOf(config).map((family) => evaluateFamily(family, cards.get(family.id), {- now, dispatches, blocks, bypassGates: bypassGatesFor === family.id,+ now, dispatches, blocks, completions, bypassGates: bypassGatesFor === family.id,}).candidate).filter(Boolean).sort((a, b) => a.hoursUntilReset - b.hoursUntilReset || a.family.priority - b.family.priority);@@ -263,11 +269,11 @@ export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatc* burn on the next tick, otherwise the exact gate that closed. One pass over the* SAME ladder the runner uses, so the two can't disagree.*/-export function evaluateFamilies(quotas, config, { now = Date.now(), dispatches = {}, blocks = {} } = {}) {+export function evaluateFamilies(quotas, config, { now = Date.now(), dispatches = {}, blocks = {}, completions = {} } = {}) {const cards = new Map((quotas || []).map((card) => [card.family, card]));return familiesOf(config).map((family) => ({family,block: blocks[family.id] || null,- ...evaluateFamily(family, cards.get(family.id), { now, dispatches, blocks }),+ ...evaluateFamily(family, cards.get(family.id), { now, dispatches, blocks, completions }),}));}diff --git a/server/services/quotaBurnCompletions.js b/server/services/quotaBurnCompletions.jsnew file mode 100644index 0000000000..c374f115b8--- /dev/null+++ b/server/services/quotaBurnCompletions.js@@ -0,0 +1,98 @@+/**+ * The `run once` completion ledger — which burn jobs have already had their one+ * dispatch.+ *+ * A burn plan is an ordered ROTATION the runner walks lap after lap until a+ * quota gate closes. That is right for standing work ("audit accessibility",+ * "render the bible entries that still have no image") and wrong for one-shot+ * work ("write the missing setup doc"), which was simply re-done every lap for+ * as long as the window had quota left. A job marked `runOnce` in the plan+ * records itself here when it dispatches and drops out of the rotation until the+ * user re-arms it.+ *+ * One file, `data/cos/quota-burn-completions.json`: `<familyId>:<jobId>` → the+ * ISO instant it ran. Machine-local and deliberately NOT federated, like every+ * other quota-burn ledger — quota belongs to a particular machine and provider+ * account, and each machine's plan names its own managed apps.+ *+ * Why a ledger rather than a flag on the job: a config PUT replaces a family's+ * whole `jobs` array (that is how every reorder and edit saves), so a "已 ran"+ * "already ran" flag living on the job would be silently reset by an unrelated edit — and by+ * the client's optimistic copy of the plan, which never sees the runner's write+ * at all. The run log can't answer it either: it is a capped UI feed (50+ * entries), so a job that ran last month has already aged out of it.+ */++import { join } from 'path';+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { isPlainObject } from '../lib/objects.js';+import { quotaBurnJobKey } from '../lib/quotaBurnConfig.js';++const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-completions.json');++/**+ * Entries kept, newest first. Deliberately larger than the most keys a live plan+ * can hold (4 families × the 25-job cap = 100), so pruning can only ever evict+ * the record of a job that has since been deleted from the plan — never a live+ * one, which would put a spent job back into the rotation behind the user's+ * back. Without any bound the file would grow by one dead key for every job the+ * user ever adds and removes.+ */+const LEDGER_LIMIT = 200;++// Single tail for the read-modify-write. The scheduler tick and a manual "Run+// now" can both finish a dispatch at once; unserialized, the second read would+// miss the first's write and lose a completion — putting a one-shot job back in+// the rotation. The "serialize two write paths that mutate the same record"+// case, not a defense against competing users.+const writeQueue = createFileWriteQueue();++/** `<familyId>:<jobId>` → ISO instant of the dispatch that spent the job. */+export async function getQuotaBurnCompletions() {+ const loaded = await readJSONFile(LEDGER_FILE(), null);+ if (!isPlainObject(loaded)) return {};+ return Object.fromEntries(Object.entries(loaded).filter(([, at]) => typeof at === 'string' && at));+}++// Newest first, then capped — `Date.parse` on an unparseable value yields NaN,+// which sorts last and is dropped first, which is the right end for a value we+// can't date.+const prune = (ledger) => Object.fromEntries(+ Object.entries(ledger)+ .sort(([, a], [, b]) => (Date.parse(b) || 0) - (Date.parse(a) || 0))+ .slice(0, LEDGER_LIMIT),+);++/**+ * Mark one job as having had its run. Idempotent on the key and re-stamps the+ * instant, so a forced re-run of an already-spent job reports the latest time.+ */+export async function recordQuotaBurnJobCompletion(familyId, jobId, { now = Date.now() } = {}) {+ if (!familyId || !jobId) return null;+ return writeQueue(async () => {+ const ledger = await getQuotaBurnCompletions();+ const next = prune({ ...ledger, [quotaBurnJobKey(familyId, jobId)]: new Date(now).toISOString() });+ await atomicWrite(LEDGER_FILE(), next);+ return next;+ });+}++/**+ * Re-arm: put a spent `run once` job back into the rotation. Omitting `jobId`+ * re-arms the family's whole plan, which is how "run that series again" is+ * expressed — the alternative is clicking through every step of a plan the user+ * configured as a series in the first place.+ */+export async function clearQuotaBurnJobCompletion(familyId, jobId = null) {+ if (!familyId) return null;+ return writeQueue(async () => {+ const ledger = await getQuotaBurnCompletions();+ const prefix = `${familyId}:`;+ const next = Object.fromEntries(Object.entries(ledger).filter(([key]) => (jobId+ ? key !== quotaBurnJobKey(familyId, jobId)+ : !key.startsWith(prefix))));+ await atomicWrite(LEDGER_FILE(), next);+ return next;+ });+}diff --git a/server/services/quotaBurnCompletions.test.js b/server/services/quotaBurnCompletions.test.jsnew file mode 100644index 0000000000..95ebbd2fe1--- /dev/null+++ b/server/services/quotaBurnCompletions.test.js@@ -0,0 +1,107 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { readFileSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-burn-completions-', extraOverrides: (root) => ({ cos: root }) });+vi.mock('../lib/fileUtils.js', async (importActual) => makeProxy(await importActual()));++const {+ clearQuotaBurnJobCompletion, getQuotaBurnCompletions, recordQuotaBurnJobCompletion,+} = await import('./quotaBurnCompletions.js');++const LEDGER = () => join(tempRoot, 'quota-burn-completions.json');+const NOW = Date.parse('2026-08-13T12:00:00.000Z');+const seed = (entries) => writeFileSync(LEDGER(), JSON.stringify(entries));+const onDisk = () => JSON.parse(readFileSync(LEDGER(), 'utf8'));++beforeEach(() => rmSync(LEDGER(), { force: true }));+afterAll(cleanup);++describe('getQuotaBurnCompletions', () => {+ it('reads an empty ledger as no completions rather than failing', async () => {+ await expect(getQuotaBurnCompletions()).resolves.toEqual({});+ });++ it('drops entries that are not a usable instant', async () => {+ // A hand-edited or half-written file must not put a truthy non-string in+ // front of `jobIsSpent`, which would silently retire a job forever.+ seed({ 'grok:a': '2026-08-01T00:00:00.000Z', 'grok:b': null, 'grok:c': 42, 'grok:d': '' });+ await expect(getQuotaBurnCompletions()).resolves.toEqual({ 'grok:a': '2026-08-01T00:00:00.000Z' });+ });++ it('reads a non-object file as no completions', async () => {+ seed(['grok:a']);+ await expect(getQuotaBurnCompletions()).resolves.toEqual({});+ });+});++describe('recordQuotaBurnJobCompletion', () => {+ it('keys the family into the entry so two plans cannot share a completion', async () => {+ // Job ids are minted from a clock and are only unique WITHIN a family, so a+ // bare job id would let one plan's one-shot step retire another's.+ await recordQuotaBurnJobCompletion('grok', 'job-1', { now: NOW });+ await recordQuotaBurnJobCompletion('claude', 'job-1', { now: NOW });+ expect(Object.keys(onDisk()).sort()).toEqual(['claude:job-1', 'grok:job-1']);+ });++ it('re-stamps an existing entry instead of duplicating it', async () => {+ await recordQuotaBurnJobCompletion('grok', 'job-1', { now: NOW - 86_400_000 });+ await recordQuotaBurnJobCompletion('grok', 'job-1', { now: NOW });+ expect(onDisk()).toEqual({ 'grok:job-1': new Date(NOW).toISOString() });+ });++ it('ignores a call with no family or job rather than writing a junk key', async () => {+ await expect(recordQuotaBurnJobCompletion('grok', null)).resolves.toBeNull();+ await expect(recordQuotaBurnJobCompletion(null, 'job-1')).resolves.toBeNull();+ await expect(getQuotaBurnCompletions()).resolves.toEqual({});+ });++ it('prunes the oldest entries only, keeping far more than a live plan can hold', async () => {+ // The cap exists so the file cannot grow by one dead key per deleted job+ // forever. It must never evict a LIVE key — that would put a spent job back+ // into the rotation behind the user's back — so it is set well above the 100+ // keys a maxed-out plan (4 families x 25 jobs) can produce.+ seed(Object.fromEntries(Array.from({ length: 240 }, (_, index) => [+ `grok:old-${index}`, new Date(NOW - (240 - index) * 60_000).toISOString(),+ ])));+ await recordQuotaBurnJobCompletion('grok', 'fresh', { now: NOW });+ const kept = onDisk();+ expect(Object.keys(kept)).toHaveLength(200);+ expect(kept['grok:fresh']).toBe(new Date(NOW).toISOString());+ // Oldest first out: `old-0` is the furthest back, `old-239` the most recent.+ expect(kept['grok:old-0']).toBeUndefined();+ expect(kept['grok:old-239']).toBeDefined();+ });+});++describe('clearQuotaBurnJobCompletion', () => {+ beforeEach(() => seed({+ 'grok:a': '2026-08-01T00:00:00.000Z',+ 'grok:b': '2026-08-02T00:00:00.000Z',+ 'claude:a': '2026-08-03T00:00:00.000Z',+ }));++ it('re-arms one named step', async () => {+ await clearQuotaBurnJobCompletion('grok', 'a');+ expect(Object.keys(onDisk()).sort()).toEqual(['claude:a', 'grok:b']);+ });++ it('re-arms the whole family when no step is named', async () => {+ // "Run that series again" — the shape the one-shot plan was configured in.+ await clearQuotaBurnJobCompletion('grok');+ expect(Object.keys(onDisk())).toEqual(['claude:a']);+ });++ it('refuses to clear anything without a family', async () => {+ await expect(clearQuotaBurnJobCompletion(null)).resolves.toBeNull();+ expect(Object.keys(onDisk())).toHaveLength(3);+ });++ it('matches the family on the full key segment, not a bare prefix', async () => {+ // `grok` must not clear a hypothetical `grok-two` family's entries.+ seed({ 'grok:a': '2026-08-01T00:00:00.000Z', 'grokish:a': '2026-08-01T00:00:00.000Z' });+ await clearQuotaBurnJobCompletion('grok');+ expect(Object.keys(onDisk())).toEqual(['grokish:a']);+ });+});diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex ed6bbbf11b..f733ff3588 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -38,10 +38,11 @@import { getProviderQuotas } from './providerUsage.js';import { getQuotaBurnDispatches, evaluateFamilies, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';+import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';-import { familyIsActionable } from '../lib/quotaBurnConfig.js';+import { familyIsActionable, jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';import { windowLabelOf } from '../lib/quotaWindows.js';import { WAIT } from '../lib/staleWhileRevalidate.js';import { cosEvents } from './cosEvents.js';@@ -59,14 +60,18 @@ const deferredContinuations = new Set();* The jobs a cycle will consider, in plan order.** `jobId` scopes to one named job. When it is named AND the run was forced, the- * job's own `enabled` checkbox is ignored: the user just clicked ▶ on that- * exact row, which is a more specific instruction than the checkbox they set- * earlier. Without this, clicking ▶ on a paused job is a silent no-op reported- * as "no pending work".+ * job's own `enabled` checkbox — and a spent `run once` marker — are ignored:+ * the user just clicked ▶ on that exact row, which is a more specific+ * instruction than the checkbox they set earlier, and re-running a finished+ * one-shot job on demand is exactly what that button is for. Without this,+ * clicking ▶ on a paused (or already-run) job is a silent no-op reported as "no+ * pending work".*/-const selectJobs = (family, { jobId = null, force = false } = {}) =>- (family.jobs || []).filter((job) =>- (!jobId || job.id === jobId) && (job?.enabled !== false || (jobId && force)));+const selectJobs = (family, { jobId = null, force = false, completions = {} } = {}) => {+ const targeted = Boolean(jobId) && force;+ return (family.jobs || []).filter((job) => (!jobId || job.id === jobId)+ && (targeted || (job?.enabled !== false && !jobIsSpent(job, family.id, completions))));+};/*** The plan, re-anchored to start just AFTER the job this family last dispatched.@@ -114,7 +119,7 @@ async function lastDispatchedJobByFamily() {* and `run` needs the very same scan to know what to render. Without the* passthrough that multi-megabyte read happened twice per dispatch.*/-async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null } = {}) {+async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null, completions = {} } = {}) {const attempts = [];// A forced run of a NAMED job skips the pending probe entirely and calls the// job directly. The probe exists to pick which job in the plan to run; when@@ -125,7 +130,7 @@ async function dispatchFromCandidate(candidate, { jobId = null, force = false, a// override it from the page. `force` is threaded into the job so it can relax// its own cooldown too.const targeted = force && jobId;- for (const job of rotatePlanAfter(selectJobs(candidate.family, { jobId, force }), afterJobId)) {+ for (const job of rotatePlanAfter(selectJobs(candidate.family, { jobId, force, completions }), afterJobId)) {const pending = targeted ? null : await countJobPending({ job, family: candidate.family });if (pending && !(pending.count > 0)) {attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });@@ -223,18 +228,41 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// allowlist of automatic triggers so a trigger added later fails CLOSED.if (!config.enabled && trigger !== 'manual') return { skipped: 'disabled' };+ // Read once per cycle and threaded through selection, the gate ladder, and the+ // dispatch record, so a job spent mid-cycle can't be re-picked by a later+ // family's walk.+ const completions = await getQuotaBurnCompletions().catch((err) => {+ // Fail CLOSED for the ONE-SHOT jobs: an unreadable ledger reads as "nothing+ // has run", which would re-dispatch every `run once` job on the plan. Better+ // to skip the cycle and say so than to redo work the user asked for once.+ console.error(`❌ Quota-burn could not read its run-once ledger: ${err.message}`);+ return null;+ });+ if (!completions) return finish({ dispatched: false, reason: 'run-once ledger unreadable' });+// Check the plan BEFORE the quota read. `getProviderQuotas({ wait: WAIT.FRESH })`// spawns a multi-second TUI scrape per enabled family; with no actionable// family configured that scrape could never produce a dispatch, and it would- // otherwise run every `checkIntervalMinutes` forever.+ // otherwise run every `checkIntervalMinutes` forever. A plan made entirely of+ // spent `run once` jobs is the same case, which is why `completions` is passed+ // — without it a finished one-shot plan keeps paying for the scrape forever.//// A forced run of a NAMED job is exempt: `familyIsActionable` requires an- // enabled family with an enabled job, but ▶ on a paused job (or a paused- // family) is exactly the case the force path exists to serve — gating it here- // would make the click a silent no-op before selection ever ran.+ // enabled family with an enabled, unspent job, but ▶ on a paused job (or a+ // paused family, or one that already ran) is exactly the case the force path+ // exists to serve — gating it here would make the click a silent no-op before+ // selection ever ran.+ //+ // Spelled as arrows, NOT `.some(familyIsActionable)`: `.some` passes the INDEX+ // as the second argument, which would land in `completions`.const targeted = force && familyId;- if (!targeted && !Object.values(config.families).some(familyIsActionable)) {- return finish({ dispatched: false, reason: 'no families enabled' });+ const configured = Object.values(config.families).filter((family) => familyIsActionable(family));+ if (!targeted && !configured.length) return finish({ dispatched: false, reason: 'no families enabled' });+ // Kept distinct from "no families enabled": a finished one-shot plan did what+ // it was asked, and the action it wants (Re-arm) is not the action an unset+ // plan wants (add a job).+ if (!targeted && !configured.some((family) => familyIsActionable(family, completions))) {+ return finish({ dispatched: false, reason: 'every enabled job has already run once — re-arm a step to run the plan again' });}// Scoped to the one family when the caller named it — a per-family "Run now",@@ -255,7 +283,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// goes through the same selection, so the candidate still carries the family's// real card and limit; it only comes back `charge: false`.const candidates = selectBurnCandidates(quotas, config, {- dispatches, blocks, bypassGatesFor: force ? familyId : null,+ dispatches, blocks, completions, bypassGatesFor: force ? familyId : null,}).filter((candidate) => !familyId || candidate.family.id === familyId);if (!candidates.length) {@@ -264,7 +292,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// off, "disabled" IS the answer — reporting a different family's verdict// instead (or claiming it is "ready" when it did not run) leaves them with// no path to the control they need.- const reasons = evaluateFamilies(quotas, config, { dispatches, blocks })+ const reasons = evaluateFamilies(quotas, config, { dispatches, blocks, completions }).filter(({ family }) => (familyId ? family.id === familyId : family.enabled)).map(({ family, skipReason }) => `${family.id}: ${skipReason || 'ready'}`);return finish({@@ -285,7 +313,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// provider's window.for (const candidate of candidates) {const outcome = await dispatchFromCandidate(candidate, {- jobId, force, afterJobId: cursors.get(candidate.family.id) || null,+ jobId, force, completions, afterJobId: cursors.get(candidate.family.id) || null,});attempts.push(...outcome.attempts.map((entry) => ({ familyId: candidate.family.id, ...entry })));if (!outcome.dispatched) continue;@@ -294,6 +322,19 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// the cap bounds real burns, not attempts. `charge` is false for a forced// run, which the user asked for outside the automatic budget.if (candidate.charge) await recordQuotaBurnDispatch(candidate.dispatchKey);+ // A `run once` job records its one dispatch even when the run was FORCED+ // and therefore uncharged. The two ledgers answer different questions:+ // `charge` is about this window's automatic budget, while `runOnce` is a+ // 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) {+ 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+ // is the pre-`runOnce` behavior.+ .catch((err) => console.error(`⚠️ Quota-burn run-once ledger for ${candidate.family.id}/${outcome.job.id}: ${err.message}`));+ }// One run-log entry PER dispatch, recorded as it happens: the page's// "Recent runs" list is how the user audits what their subscriptions were// spent on, and folding three families into one row would hide two of them.@@ -360,7 +401,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,export async function getQuotaBurnStatus({ refresh = false } = {}) {// Independent reads: only `quotas` is slow (a PTY scrape on the Refresh path),// and nothing else waits on it.- const [config, quotas, dispatches, blocks, runs] = await Promise.all([+ const [config, quotas, dispatches, blocks, completions, runs] = await Promise.all([getQuotaBurnConfig(),getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER }).catch((err) => {console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);@@ -368,13 +409,14 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {}),getQuotaBurnDispatches(),getActiveQuotaBurnBlocks(),+ getQuotaBurnCompletions().catch(() => ({})),getQuotaBurnRuns(),]);const cards = new Map(quotas.map((card) => [card.family, card]));// ONE pass over the gate ladder the runner uses — the page's "will burn" and// its reason come from the same verdict, so they can't contradict each other.- const families = await Promise.all(evaluateFamilies(quotas, config, { dispatches, blocks })+ const families = await Promise.all(evaluateFamilies(quotas, config, { dispatches, blocks, completions }).map(async ({ family, candidate, skipReason, block }) => {const card = cards.get(family.id);return {@@ -397,12 +439,22 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {// The reading for this family is being taken right now — the page polls// again instead of leaving a card that looks like it has no quota.pending: Boolean(card?.pending),- // Probe pending work only for families the user actually enabled — a probe- // is not free (the universe job reads every bible), and a disabled- // family's counts are never acted on.- jobs: family.enabled- ? await Promise.all(family.jobs.map(async (job) => ({ id: job.id, pending: await countJobPending({ job, family }) })))- : family.jobs.map((job) => ({ id: job.id, pending: null })),+ // Probe pending work only for families the user actually enabled, and+ // only for jobs a cycle could still pick — a probe is not free (the+ // universe job reads every bible), and neither a disabled family's+ // counts nor a spent `run once` job's are ever acted on. `ranAt` is what+ // the row renders instead, and it is the only signal the page has that a+ // step is finished rather than merely idle.+ jobs: await Promise.all(family.jobs.map(async (job) => {+ const ranAt = completions[quotaBurnJobKey(family.id, job.id)] || null;+ const spent = jobIsSpent(job, family.id, completions);+ return {+ id: job.id,+ ranAt,+ spent,+ pending: family.enabled && !spent ? await countJobPending({ job, family }) : null,+ };+ })),};}));diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.jsindex 90474ecace..d3ca7474ea 100644--- a/server/services/quotaBurnRunner.test.js+++ b/server/services/quotaBurnRunner.test.js@@ -13,6 +13,9 @@ const state = {ran: [],contexts: [],blocks: {},+ completions: {},+ completed: [],+ completionsError: null,settled: [],settleError: null,};@@ -60,6 +63,21 @@ vi.mock('./quotaBurnDenials.js', async (importActual) => ({}),}));+// The `run once` ledger, stubbed off the install's `data/cos/` like the other+// two. `state.completed` records the writes so "a one-shot job marks itself+// spent" is assertable without a filesystem round trip.+vi.mock('./quotaBurnCompletions.js', () => ({+ getQuotaBurnCompletions: vi.fn(async () => {+ if (state.completionsError) throw new Error(state.completionsError);+ return state.completions;+ }),+ recordQuotaBurnJobCompletion: vi.fn(async (familyId, jobId) => {+ state.completed.push(`${familyId}:${jobId}`);+ state.completions = { ...state.completions, [`${familyId}:${jobId}`]: new Date(now).toISOString() };+ return state.completions;+ }),+}));+const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');const { getQuotaBurnStatus, runQuotaBurnCycle, rotatePlanAfter, __tickQuotaBurn, __onBurnAgentCompleted, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');@@ -93,6 +111,9 @@ beforeEach(() => {state.dispatches = {};state.recorded = [];state.blocks = {};+ state.completions = {};+ state.completed = [];+ state.completionsError = null;state.settled = [];state.settleError = null;state.jobResult = undefined;@@ -607,3 +628,123 @@ describe('forced run bypasses the pending probe', () => {expect(countJobPending).toHaveBeenCalled();});});++/**+ * `run once` — the per-step choice between one-shot and standing work.+ *+ * A plan is a rotation the runner walks lap after lap while the window still has+ * quota. That is right for a standing audit and wrong for work that only needs+ * doing once, which was simply re-done every lap.+ */+describe('run-once jobs', () => {+ const oneShotPlan = (jobs) => plan({+ families: { grok: { enabled: true, resetWithinHours: 24, jobs } },+ });++ it('marks a run-once job spent when it dispatches, and skips it next cycle', async () => {+ state.config = oneShotPlan([+ { id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} },+ { id: 'standing', enabled: true, jobType: 'agent-prompt', params: {} },+ ]);+ state.pending = { once: { count: 1 }, standing: { count: 1 } };++ await runQuotaBurnCycle();+ expect(state.ran.map((entry) => entry.jobId)).toEqual(['once']);+ expect(state.completed).toEqual(['grok:once']);++ // The plan's next lap must reach `standing` and never return to `once`.+ await runQuotaBurnCycle();+ await runQuotaBurnCycle();+ expect(state.ran.map((entry) => entry.jobId)).toEqual(['once', 'standing', 'standing']);+ });++ it('leaves a repeating job in the rotation and records nothing', async () => {+ state.pending = { first: { count: 1 }, second: { count: 1 } };+ await runQuotaBurnCycle();+ await runQuotaBurnCycle();+ await runQuotaBurnCycle();+ // Regression guard for the default: absent `runOnce` must keep repeating.+ expect(state.ran.map((entry) => entry.jobId)).toEqual(['first', 'second', 'first']);+ expect(state.completed).toEqual([]);+ });++ it('stops scraping provider quota once every step of a one-shot plan has run', async () => {+ // The whole point of threading completions into `familyIsActionable`: a+ // finished plan would otherwise pay for a multi-second TUI scrape every+ // interval, forever, to be told there is nothing to dispatch.+ const { getProviderQuotas } = await import('./providerUsage.js');+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);+ state.pending = { once: { count: 1 } };+ await runQuotaBurnCycle();+ getProviderQuotas.mockClear();++ const result = await runQuotaBurnCycle();+ expect(getProviderQuotas).not.toHaveBeenCalled();+ expect(result).toMatchObject({ dispatched: false });+ // Distinct from "no families enabled": a finished plan wants Re-arm, an+ // unset one wants a job added.+ expect(result.reason).toMatch(/already run once/);+ });++ it('lets a forced run re-run a spent job, and re-stamps it', async () => {+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);+ state.completions = { 'grok:once': new Date(now - 86_400_000).toISOString() };++ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'once', force: true });+ expect(result.dispatched).toBe(true);+ // Uncharged against the window's automatic budget, but still recorded — the+ // two ledgers answer different questions, and the work just happened.+ expect(state.ran).toEqual([{ jobId: 'once', familyId: 'grok', charge: false }]);+ expect(state.recorded).toEqual([]);+ expect(state.completed).toEqual(['grok:once']);+ });++ it('does not record a completion for a job that declined to dispatch', async () => {+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);+ state.pending = { once: { count: 1 } };+ state.jobResult = { dispatched: false, reason: 'no managed app selected' };+ await runQuotaBurnCycle();+ // A misconfigured step must stay retryable — burning its one run on a+ // decline would strand it behind a Re-arm click for work that never ran.+ expect(state.completed).toEqual([]);+ });++ it('skips the cycle rather than re-running one-shot work when the ledger is unreadable', async () => {+ // Fails CLOSED: an unreadable ledger reads as "nothing has run", which would+ // re-dispatch every run-once job on the plan.+ state.completionsError = 'EIO';+ const result = await runQuotaBurnCycle();+ expect(result).toMatchObject({ dispatched: false, reason: 'run-once ledger unreadable' });+ expect(state.ran).toEqual([]);+ });++ it('walks a whole one-shot series through the completion continuation', async () => {+ // The "run the series once" case: each finished burn agent advances the+ // plan, and the series stops of its own accord instead of looping.+ state.config = oneShotPlan([+ { id: 's1', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} },+ { id: 's2', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} },+ ]);+ state.pending = { s1: { count: 1 }, s2: { count: 1 } };++ await runQuotaBurnCycle();+ await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });+ await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });++ expect(state.ran.map((entry) => entry.jobId)).toEqual(['s1', 's2']);+ expect(state.completed).toEqual(['grok:s1', 'grok:s2']);+ });++ it('reports a spent step as ran rather than probing it', async () => {+ const { countJobPending } = await import('./quotaBurnJobs/index.js');+ const ranAt = new Date(now - 3_600_000).toISOString();+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);+ state.completions = { 'grok:once': ranAt };++ const { status } = await getQuotaBurnStatus();+ const grok = status.families.find((family) => family.id === 'grok');+ expect(grok.jobs).toEqual([{ id: 'once', ranAt, spent: true, pending: null }]);+ expect(countJobPending).not.toHaveBeenCalled();+ expect(grok.skipReason).toBe('every enabled job has already run once');+ });+});