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

replace the Quota Burn prompt editor with a scheduled-task picker (#6382)

[._.]/ Adam Eivy88538ac2c19e
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsx
index 277322e463..50144c49ea 100644
--- a/client/src/components/quotaBurn/FamilyCard.jsx
+++ b/client/src/components/quotaBurn/FamilyCard.jsx
@@ -8,17 +8,19 @@
*/
import { useState } from 'react';
-import { AlertTriangle, Ban, ChevronDown, ChevronRight, Flame, Plus, RotateCcw } from 'lucide-react';
+import { Link } from 'react-router';
+import { AlertTriangle, Ban, ChevronDown, ChevronRight, Flame, RotateCcw } from 'lucide-react';
import Banner from '../ui/Banner';
import BrailleSpinner from '../BrailleSpinner';
import JobRow from './JobRow';
-import PresetPicker from './PresetPicker';
-import { dispatchCapInput, getAvailablePresetsForJobs, isUnlimitedDispatchCap, jobFromPreset, quotaBurnJobIsSpent, UNLIMITED_DISPATCHES } from '../../lib/quotaBurnPatch';
+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 { formatDateTime } from '../../utils/formatters';
import { NumberField } from './fields';
export default function FamilyCard({
- familyId, config, status, catalog, catalogError, catalogRetrying, expanded, actionsBusy,
+ familyId, config, status, catalog, taskGroups, catalogError, catalogRetrying, expanded, actionsBusy,
onToggleExpand, onPatch, onRunFamily, onRunJob, onRearm, onRetryCatalog,
}) {
const jobs = config.jobs || [];
@@ -35,7 +37,12 @@ export default function FamilyCard({
const statusById = new Map((status?.jobs || []).map((row) => [row.id, row]));
const spentCount = jobs.filter((job) => quotaBurnJobIsSpent(job, statusById.get(job.id)?.ranAt)).length;
- const patchJobs = (next) => onPatch({ jobs: next });
+ // Serialized on the way OUT, in one place, because the PUT's job schema is
+ // strict and the GET hands back more than it accepts as input — including the
+ // top-level override mirrors, which outrank the `overrides` bag by presence.
+ // Doing it here rather than per call site is what keeps a reorder, an edit and
+ // a removal all sending the same shape.
+ const patchJobs = (next) => onPatch({ jobs: next.map(quotaBurnStepPayload) });
const changeJob = (index, next) => patchJobs(jobs.map((job, i) => (i === index ? next : job)));
const moveJob = (index, delta) => {
const next = [...jobs];
@@ -43,17 +50,11 @@ export default function FamilyCard({
next.splice(index + delta, 0, moved);
patchJobs(next);
};
- // Without a catalog there is no job type to mint, and a job with
- // `jobType: undefined` is dropped by JSON.stringify and rejected by the
- // strict PUT schema — poisoning every later save for this family until the
- // page is reloaded. The catalog fetch is best-effort (the page still renders
- // without it), so gate on it rather than minting an unsavable row.
- const canAddJob = catalog.jobTypes.length > 0;
// Ids key the React list AND pair each job with its server-side pending count,
// so a duplicate is a real defect, not a cosmetic one. `Date.now()` alone can
- // repeat within the same millisecond (two adds from one handler, a preset add
- // immediately following a blank add), so disambiguate against the ids already
- // in the plan rather than trusting the clock to have ticked.
+ // repeat within the same millisecond (two picks in quick succession from the
+ // Add a step control), so disambiguate against the ids already in the plan
+ // rather than trusting the clock to have ticked.
const nextJobId = () => {
const taken = new Set(jobs.map((job) => job.id));
const base = `job-${Date.now().toString(36)}`;
@@ -62,31 +63,16 @@ export default function FamilyCard({
while (taken.has(`${base}-${suffix}`)) suffix += 1;
return `${base}-${suffix}`;
};
- const addJob = () => {
+ // A new step inherits the app the plan is already pointed at, when the plan is
+ // unambiguous about it — otherwise a one-click "add the UX audit" lands as a
+ // step that cannot run until the user notices the unset target picker. Derived
+ // at click time, not per render: the page polls while any family is pending.
+ const addStep = (entry) => {
+ const targeted = [...new Set(jobs.map((job) => job.taskRef?.appId).filter(Boolean))];
const id = nextJobId();
- patchJobs([...jobs, {
+ patchJobs([...jobs, stepFromTaskEntry(entry, {
id,
- enabled: true,
- label: '',
- jobType: catalog.jobTypes[0].id,
- model: null,
- providerId: null,
- effort: null,
- runOnce: false,
- params: {},
- }]);
- setExpandedJobIds((prev) => new Set(prev).add(id));
- };
- // A preset job inherits the app the plan is already pointed at, when the plan
- // is unambiguous about it — otherwise a one-click "add a UX audit" lands as a
- // step that cannot run until the user notices the unset app picker. Derived at
- // click time, not per render: the page polls while any family is pending.
- const addPresetJob = (preset) => {
- const targetedAppIds = [...new Set(jobs.map((job) => job.params?.appId).filter(Boolean))];
- const id = nextJobId();
- patchJobs([...jobs, jobFromPreset(preset, {
- id,
- appId: targetedAppIds.length === 1 ? targetedAppIds[0] : null,
+ appId: taskEntryNeedsApp(entry) && targeted.length === 1 ? targeted[0] : null,
})]);
setExpandedJobIds((prev) => new Set(prev).add(id));
};
@@ -108,7 +94,7 @@ export default function FamilyCard({
});
};
- const availablePresets = getAvailablePresetsForJobs(catalog.presets, jobs);
+ const hasTasks = flattenTaskCatalog(taskGroups).length > 0;
return (
<div className="rounded border border-port-border bg-port-card/40">
@@ -197,11 +183,11 @@ export default function FamilyCard({
{expanded && (
<div className="border-t border-port-border/60 p-3 space-y-4">
- {/* Every choice this section offers — job type, app, universe, image
- mode, and the preset picker — comes from the catalog, so a failed
- catalog read empties them all and hides the picker outright. Say
- so where the empty controls are, and offer the re-read here rather
- than making a browser reload the only way back. */}
+ {/* Every choice this section offers — which scheduled task, which app,
+ which provider/model — comes from the catalog reads, so a failure
+ empties them all. Say so where the empty controls are, and offer
+ the re-read here rather than making a browser reload the only way
+ back. */}
{catalogError && (
<Banner
tone="warning"
@@ -229,8 +215,7 @@ export default function FamilyCard({
reads as one mangled sentence half the time. */}
<p className="mt-0.5 break-words">{catalogError}</p>
<p className="mt-1">
- Job types, apps, universes, and presets are unavailable — editing a step now would save an empty job type
- and be rejected.
+ Scheduled tasks, apps, and providers are unavailable — a step added now would have no task to reference.
</p>
</Banner>
)}
@@ -271,28 +256,31 @@ export default function FamilyCard({
<RotateCcw size={13} /> Re-arm all ({spentCount})
</button>
)}
- <button
- type="button"
- className="inline-flex items-center gap-1 text-port-accent hover:underline disabled:opacity-40"
- disabled={!canAddJob}
- title={canAddJob ? 'Add a job to this plan' : 'Job catalog unavailable — retry the catalog load above'}
- onClick={addJob}
- >
- <Plus size={13} /> Add job
- </button>
</div>
</div>
<div className="sm:max-w-md">
- <PresetPicker
- id={`burn-${familyId}-preset`}
- label="Add a preset job"
- presets={availablePresets}
- onPick={addPresetJob}
- hint="Single-focus audits that read the code, file GitHub issues, and change nothing — safe work for an unattended window."
+ <TaskRefPicker
+ id={`burn-${familyId}-add-step`}
+ label="Add a step"
+ groups={taskGroups}
+ onPick={addStep}
+ placeholder={hasTasks ? 'Add a scheduled task to this plan…' : 'No scheduled tasks available'}
+ hint="Every step runs an existing scheduled task with this family's quota. Overrides apply to the burn only."
/>
+ {/* Creating work happens in Scheduled Tasks, not here — that is
+ what keeps one automation catalog instead of two. A plan with
+ nothing to reference needs this link more than anything else on
+ the card, so it is stated rather than implied. */}
+ <p className="mt-1 text-[11px] text-gray-500">
+ Need work that does not exist yet?{' '}
+ <Link to={CREATE_TASK_HREF} className="text-port-accent hover:underline">
+ Create an on-demand scheduled task
+ </Link>
+ , then add it here.
+ </p>
</div>
{!jobs.length && (
- <p className="text-xs text-gray-500">No jobs yet — this family will never burn until one is added.</p>
+ <p className="text-xs text-gray-500">No steps yet — this family will never burn until one is added.</p>
)}
{jobs.map((job, index) => (
<JobRow
@@ -302,6 +290,7 @@ export default function FamilyCard({
index={index}
total={jobs.length}
catalog={catalog}
+ taskGroups={taskGroups}
pending={statusById.get(job.id)?.pending ?? null}
ranAt={statusById.get(job.id)?.ranAt ?? null}
actionsBusy={actionsBusy}
diff --git a/client/src/components/quotaBurn/JobParamField.jsx b/client/src/components/quotaBurn/JobParamField.jsx
deleted file mode 100644
index dc4712c828..0000000000
--- a/client/src/components/quotaBurn/JobParamField.jsx
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * One burn-job parameter input, rendered from the server's param descriptor
- * (`QUOTA_BURN_JOB_CATALOG[].params[]`). Keeping the descriptor server-side is
- * what lets a new job type ship without a client change — this component only
- * needs to know the param KINDS, not any particular job's fields.
- */
-
-import { NumberField, inputClass } from './fields';
-
-export default function JobParamField({ descriptor, value, onChange, options, idPrefix }) {
- const id = `${idPrefix}-${descriptor.key}`;
- const current = value ?? descriptor.default ?? '';
-
- if (descriptor.kind === 'boolean') {
- return (
- <label htmlFor={id} className="flex items-center gap-2 text-xs text-gray-300">
- <input
- id={id}
- type="checkbox"
- checked={value ?? descriptor.default ?? false}
- onChange={(event) => onChange(descriptor.key, event.target.checked)}
- />
- {descriptor.label}
- </label>
- );
- }
-
- if (descriptor.kind === 'text') {
- return (
- <label htmlFor={id} className="block sm:col-span-2 text-xs text-gray-400">
- {descriptor.label}
- <textarea
- id={id}
- className={`${inputClass} min-h-24 font-mono`}
- value={current}
- placeholder="What should this provider spend its remaining quota on?"
- onChange={(event) => onChange(descriptor.key, event.target.value)}
- />
- </label>
- );
- }
-
- if (descriptor.kind === 'number') {
- // NumberField, not a bare input: an emptied box must not commit `0` (below
- // several server minimums) and 400 the whole coalesced save.
- return (
- <NumberField
- id={id}
- label={descriptor.label}
- value={current}
- min={descriptor.min}
- max={descriptor.max}
- onChange={(next) => onChange(descriptor.key, next)}
- />
- );
- }
-
- // Everything else is a select over a list the page supplied (apps, universes,
- // image modes) or the descriptor's own enum. The "no pin" row, when a kind has
- // one, is DESCRIBED BY THE SERVER (`emptyLabel`/`emptyValue`) rather than
- // switched on `kind` here — otherwise every new job type with an optional
- // param would need a client change, which is the thing the catalog exists to
- // avoid.
- const rows = descriptor.kind === 'enum'
- ? (descriptor.options || []).map((option) => ({ value: option, label: option }))
- : (options || []).map((option) => ({ value: option.id ?? option, label: option.name ?? option }));
- const sentinel = descriptor.emptyLabel
- ? { value: descriptor.emptyValue ?? '', label: descriptor.emptyLabel }
- : null;
-
- return (
- <label htmlFor={id} className="block text-xs text-gray-400">
- {descriptor.label}
- <select
- id={id}
- className={inputClass}
- value={current ?? ''}
- onChange={(event) => onChange(descriptor.key, event.target.value || null)}
- >
- {sentinel && <option value={sentinel.value}>{sentinel.label}</option>}
- {descriptor.required && !sentinel && <option value="">Select…</option>}
- {rows.map((row) => <option key={row.value} value={row.value}>{row.label}</option>)}
- </select>
- </label>
- );
-}
diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsx
index 0aef8e4721..856d22698a 100644
--- a/client/src/components/quotaBurn/JobRow.jsx
+++ b/client/src/components/quotaBurn/JobRow.jsx
@@ -1,25 +1,47 @@
/**
- * One burn job inside a family's ordered plan: its type, its per-job model, its
- * type-specific params, and the controls that move/remove/run it.
+ * One burn step inside a family's ordered plan: the scheduled task it points at,
+ * the app it targets, its per-invocation overrides, and the controls that
+ * move/remove/run it.
*
- * Order is meaningful — the runner takes the FIRST enabled job with pending
- * work — so the move controls are part of the configuration, not a convenience.
+ * A step is a REFERENCE, never a copy — removing it here deletes nothing in
+ * Scheduled Tasks, and editing the work itself happens there. Order is
+ * meaningful (the runner takes the first enabled step with pending work), so the
+ * move controls are part of the configuration rather than a convenience.
*/
import { useEffect, useState } from 'react';
-import { ArrowDown, ArrowUp, CheckCircle2, ChevronDown, ChevronRight, Play, RotateCcw, Trash2 } from 'lucide-react';
+import { AlertTriangle, ArrowDown, ArrowUp, CheckCircle2, ChevronDown, ChevronRight, 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 EffortSelect from '../cos/EffortSelect';
-import { applyQuotaBurnPreset, quotaBurnJobIsSpent } from '../../lib/quotaBurnPatch';
+import StepSettings from './StepSettings';
+import TaskRefPicker from './TaskRefPicker';
+import { quotaBurnJobIsSpent } from '../../lib/quotaBurnPatch';
+import { findTaskEntry, stepFromTaskEntry, taskEntryNeedsApp, taskRefKey } from '../../lib/quotaBurnTasks';
import { timeAgo } from '../../utils/formatters';
-import { commandBasename, effortAwareModelOptions, effortLevelsForProvider, effortSurvivingModel } from '../../utils/providers';
+import { commandBasename } from '../../utils/providers';
import { inputClass } from './fields';
+/**
+ * The CLI/TUI providers that spend THIS family's subscription.
+ *
+ * A burn draws down one family's window, so a pin naming another family's binary
+ * is never what the user meant — and the server rejects it. Local-model backends
+ * are excluded outright: they have no subscription quota to burn.
+ */
+function providersForFamily(providers, familyId) {
+ return (providers || []).filter((provider) =>
+ provider?.enabled !== false
+ && provider?.ollamaBacked !== true && provider?.lmstudioBacked !== true
+ && provider?.mtplxBacked !== true
+ && provider?.llamaBacked !== true && provider?.vllmBacked !== true
+ && provider?.sglangBacked !== true
+ && (provider?.type === 'cli' || provider?.type === 'tui')
+ && (commandBasename(provider?.command) === familyId
+ || String(provider?.id || '').toLowerCase().includes(familyId || '')
+ || (familyId === 'agy' && String(provider?.id || '').toLowerCase().includes('antigravity'))));
+}
+
export default function JobRow({
- job, index, total, catalog, pending, ranAt, actionsBusy,
+ job, index, total, catalog, taskGroups, pending, ranAt, actionsBusy,
familyId,
expanded = false, onToggleExpand,
onChange, onMove, onRemove, onRun, onRearm,
@@ -28,79 +50,51 @@ export default function JobRow({
const isExpanded = onToggleExpand !== undefined ? expanded : localExpanded;
const toggleExpand = onToggleExpand || (() => setLocalExpanded((prev) => !prev));
- // 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
- // stray click on the trash icon would drop it from the persisted plan with no
- // undo.
+ // Two-click arm on delete (the repo's inline-confirm convention). It removes
+ // the step from the plan — its order, name, overrides and run-once state — and
+ // there is no undo. The referenced scheduled task is untouched either way.
const [armed, setArmed] = useState(false);
// Run is armed for the same reason: it force-dispatches past the window,
// reserve, and cap gates and spends real subscription quota. The icon sits in
// a row of small controls on a page whose edits save on change, so a stray
// click reads as "save" — it must not be a one-click spend.
const [runArmed, setRunArmed] = useState(false);
- // A preset overwrites the work prompt. Held rather than applied immediately
- // when there is already prompt text, so picking one never silently discards a
- // prompt the user wrote by hand.
- const [pendingPreset, setPendingPreset] = useState(null);
// Disarm the run confirm the moment the page has unsaved (or stalled) edits.
// The confirm asks "spend now?" about the SAVED plan, so an edit invalidates
// the question — and the alternative (leaving the pair on screen with both
// buttons disabled, since `busy` disables Cancel too) strands an armed
// confirm the user cannot dismiss when a save has stopped retrying.
useEffect(() => { if (actionsBusy) setRunArmed(false); }, [actionsBusy]);
- const spec = catalog.jobTypes.find((type) => type.id === job.jobType);
+
+ const entry = findTaskEntry(taskGroups, job.taskRef);
const idPrefix = `burn-job-${job.id}`;
const spent = quotaBurnJobIsSpent(job, ranAt);
+ // Derived server-side from the live catalog on every read: a reference whose
+ // task was deleted, disabled, or pointed at an app it may not target keeps its
+ // place in the plan and states WHY it cannot run, rather than disappearing.
+ const unavailable = job.unavailable || null;
const actionButtonClass = 'inline-flex min-h-[44px] min-w-[44px] items-center justify-center';
- const setParam = (key, value) => onChange({ ...job, params: { ...job.params, [key]: value } });
- const promptText = String(job.params?.prompt || '').trim();
- const hasPromptText = Boolean(promptText);
- // Which preset this row currently IS, derived rather than stored: a preset is
- // copied into `params.prompt` and nothing on disk points back at its id, so
- // matching the text is the only claim that stays true after an edit. The
- // picker shows the preset while the prompt is verbatim and reverts to its
- // placeholder as soon as the user changes a word.
- const matchedPreset = (catalog.presets || [])
- .find((preset) => promptText && String(preset.params?.prompt || '').trim() === promptText);
- const applyPreset = (preset) => { setPendingPreset(null); onChange(applyQuotaBurnPreset(job, preset)); };
- const optionsFor = (descriptor) => ({
- app: catalog.apps,
- universe: catalog.universes,
- imageMode: catalog.imageModes,
- })[descriptor.kind];
+ const providers = providersForFamily(catalog.providers, familyId);
+ const summary = entry?.label || job.taskRef?.taskType || job.taskRef?.jobId || job.jobType || 'unreferenced step';
+ const targetApps = (catalog.apps || []).filter((app) => (entry?.appIds || []).includes(app.id));
+ // The app's NAME in the collapsed summary, falling back to its id: a plan is
+ // read at a glance, and a raw id is the one thing on that line the user never
+ // chose.
+ const targetName = job.taskRef?.appId
+ ? (catalog.apps || []).find((app) => app.id === job.taskRef.appId)?.name || job.taskRef.appId
+ : null;
- // Resolve the provider for this family/job to provide model options and effort support
- const familyProviders = (catalog.providers || []).filter((provider) =>
- provider?.enabled !== false &&
- provider?.ollamaBacked !== true && provider?.lmstudioBacked !== true &&
- provider?.mtplxBacked !== true &&
- provider?.llamaBacked !== true && provider?.vllmBacked !== true &&
- provider?.sglangBacked !== true &&
- (provider?.type === 'cli' || provider?.type === 'tui') &&
- (commandBasename(provider?.command) === familyId ||
- String(provider?.id || '').toLowerCase().includes(familyId || '') ||
- (familyId === 'agy' && String(provider?.id || '').toLowerCase().includes('antigravity')))
- );
-
- const selectedProvider = (job.providerId && familyProviders.find((p) => p.id === job.providerId))
- || (job.providerId && (catalog.providers || []).find((p) => p.id === job.providerId))
- || familyProviders.find((p) => p.type === (job.jobType === 'agent-prompt' ? 'tui' : 'cli'))
- || familyProviders[0]
- || null;
-
- const availableModels = selectedProvider ? effortAwareModelOptions(selectedProvider, job.model) : [];
- const effortLevels = selectedProvider ? effortLevelsForProvider(selectedProvider, job.model) : null;
- const showEffort = Boolean(effortLevels && effortLevels.length > 0);
-
- const handleModelChange = (modelVal) => {
- const nextModel = modelVal || null;
- let nextEffort = job.effort || null;
- if (job.effort && selectedProvider) {
- const surviving = effortSurvivingModel(selectedProvider, nextModel, job.effort);
- nextEffort = surviving || null;
- }
- onChange({ ...job, model: nextModel, effort: nextEffort });
- };
+ // Switching the referenced task rebuilds the reference (and re-targets it),
+ // but KEEPS the step's own choices — its name, order, run-once flag and
+ // overrides are the user's, not the task's.
+ const pickTask = (picked) => onChange({
+ ...job,
+ ...stepFromTaskEntry(picked, { id: job.id }),
+ enabled: job.enabled !== false,
+ label: job.label || '',
+ runOnce: job.runOnce === true,
+ overrides: job.overrides || {},
+ });
return (
// `bg-port-bg`, not `bg-port-bg/40`: a step sits INSIDE the family card, so
@@ -128,15 +122,16 @@ export default function JobRow({
<input
className={`${inputClass} flex-1 min-w-40 mt-0`}
value={job.label || ''}
- placeholder={spec ? `Step name (defaults to “${spec.label}”)` : 'Step name'}
+ placeholder={`Step name (defaults to “${summary}”)`}
aria-label={`Name for step ${index + 1}`}
onChange={(event) => onChange({ ...job, label: event.target.value })}
/>
{!isExpanded && (
<span className="text-xs text-gray-400 truncate max-w-xs">
- {spec?.label || job.jobType}
- {job.model ? ` · ${job.model}` : ''}
- {job.effort ? ` · ${job.effort}` : ''}
+ {summary}
+ {targetName ? ` · ${targetName}` : ''}
+ {job.overrides?.model ? ` · ${job.overrides.model}` : ''}
+ {job.overrides?.effort ? ` · ${job.overrides.effort}` : ''}
{job.runOnce ? ' · run once' : ''}
</span>
)}
@@ -144,7 +139,11 @@ export default function JobRow({
<div className="flex items-center gap-1">
<button type="button" className={`${actionButtonClass} text-gray-400 hover:text-white disabled:opacity-30`} disabled={index === 0} onClick={() => onMove(index, -1)} aria-label={`Move step ${index + 1} earlier`}><ArrowUp size={14} /></button>
<button type="button" className={`${actionButtonClass} text-gray-400 hover:text-white disabled:opacity-30`} disabled={index === total - 1} onClick={() => onMove(index, 1)} aria-label={`Move step ${index + 1} later`}><ArrowDown size={14} /></button>
- {runArmed ? (
+ {/* An unavailable step has NO run affordance at all — not a disabled
+ one. The server would decline the dispatch, so offering the
+ button (even greyed) invites a click whose only outcome is a
+ toast; the reason below is the actionable thing. */}
+ {unavailable ? null : runArmed ? (
// `warning`, not `error`: forcing a run is expensive-but-safe, and
// it must not look identical to the delete confirm beside it.
<ConfirmButtonPair
@@ -159,14 +158,14 @@ export default function JobRow({
onCancel={() => setRunArmed(false)}
/>
) : (
- <button type="button" className={`${actionButtonClass} text-port-accent hover:text-white disabled:opacity-30`} disabled={actionsBusy} onClick={() => { setArmed(false); setRunArmed(true); }} aria-label={`Run step ${index + 1} now`} title="Run this job now, ignoring the reset window (asks to confirm)"><Play size={14} /></button>
+ <button type="button" className={`${actionButtonClass} text-port-accent hover:text-white disabled:opacity-30`} disabled={actionsBusy} onClick={() => { setArmed(false); setRunArmed(true); }} aria-label={`Run step ${index + 1} now`} title={actionsBusy ? 'Saving your changes…' : 'Run this job now, ignoring the reset window (asks to confirm)'}><Play size={14} /></button>
)}
</div>
<div className="ml-2 border-l border-port-border/50 pl-2">
{armed ? (
<ConfirmButtonPair
- prompt="Discards its prompt."
- confirmText="Delete"
+ prompt="Removes the step, not the task."
+ confirmText="Remove"
confirmIcon={Trash2}
cancelText="Cancel"
ariaLabel={`Confirm removing step ${index + 1}`}
@@ -181,61 +180,63 @@ export default function JobRow({
</div>
</div>
+ {/* Stated whether or not the row is expanded: an unrunnable step is the
+ reason a whole family stops burning, and it must not be hidden behind a
+ chevron. */}
+ {unavailable && (
+ <p role="status" className="flex flex-wrap items-start gap-1 text-[11px] text-amber-300">
+ <AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span className="break-words">
+ Cannot run — {unavailable.reason || unavailable.code}. Pick another scheduled task below, or fix it in Scheduled Tasks.
+ </span>
+ </p>
+ )}
+
{isExpanded && (
<>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <label htmlFor={`${idPrefix}-type`} className="block text-xs text-gray-400">
- Job type
- <select
- id={`${idPrefix}-type`}
- className={inputClass}
- value={job.jobType}
- // Params are CARRIED, not cleared. Each job type reads only its own
- // keys (the server's normalizer keeps any scalar), so a stray click
- // through the type picker no longer silently destroys a long work
- // prompt — switching back restores it.
- onChange={(event) => onChange({ ...job, jobType: event.target.value })}
- >
- {catalog.jobTypes.map((type) => <option key={type.id} value={type.id}>{type.label}</option>)}
- </select>
- </label>
- <label htmlFor={`${idPrefix}-model`} className="block text-xs text-gray-400">
- Model (optional)
- <select
- id={`${idPrefix}-model`}
- className={inputClass}
- value={job.model || ''}
- onChange={(event) => handleModelChange(event.target.value)}
- >
- <option value="">Default model</option>
- {availableModels.map((m) => {
- const val = typeof m === 'string' ? m : m.id;
- const lbl = typeof m === 'string' ? m : (m.name || m.id);
- return <option key={val} value={val}>{lbl}</option>;
- })}
- {job.model && !availableModels.some((m) => (typeof m === 'string' ? m : m.id) === job.model) && (
- <option value={job.model}>{job.model}</option>
- )}
- </select>
- </label>
- {showEffort && (
- <label htmlFor={`${idPrefix}-effort`} className="block text-xs text-gray-400">
- Thinking effort (optional)
- <EffortSelect
- id={`${idPrefix}-effort`}
- provider={selectedProvider}
- model={job.model}
- value={job.effort || ''}
- onChange={(effort) => onChange({ ...job, effort: effort || null })}
+ <TaskRefPicker
+ id={`${idPrefix}-task`}
+ label="Scheduled task"
+ groups={taskGroups}
+ value={taskRefKey(job.taskRef)}
+ onPick={pickTask}
+ hint="Burn steps run work you already defined in Scheduled Tasks or System Tasks — they never edit it."
+ />
+ {/* Only a type that acts on ONE managed app gets a target: an
+ install-wide type sweeps every app in one dispatch, and a
+ programmatic type acts on PortOS's own records — the server
+ rejects a request from either that names an app. */}
+ {entry && taskEntryNeedsApp(entry) && (
+ <label htmlFor={`${idPrefix}-app`} className="block text-xs text-gray-400">
+ Target app
+ <select
+ id={`${idPrefix}-app`}
className={inputClass}
- />
+ value={job.taskRef?.appId || ''}
+ onChange={(event) => onChange({
+ ...job,
+ taskRef: { ...job.taskRef, appId: event.target.value || null },
+ })}
+ >
+ <option value="">Select an app…</option>
+ {targetApps.map((app) => <option key={app.id} value={app.id}>{app.name}</option>)}
+ </select>
+ {targetApps.length === 0 && (
+ <span className="mt-1 block text-[11px] text-amber-300">
+ No managed app has this task enabled — turn it on in the app’s Automation tab first.
+ </span>
+ )}
</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">
+ {entry && !taskEntryNeedsApp(entry) && (
+ <p className="self-end text-[11px] text-gray-500">
+ {entry.programmatic
+ ? 'PortOS runs this task itself, against its own records — there is no app to target.'
+ : 'Runs install-wide: one dispatch sweeps every managed app.'}
+ </p>
+ )}
+ <div className="text-xs text-gray-400 sm:col-span-2">
<div className="flex items-center gap-2 mt-1">
<input
id={`${idPrefix}-run-once`}
@@ -251,47 +252,17 @@ export default function JobRow({
: 'Repeats every lap of the plan while the window still has quota.'}
</p>
</div>
- <PresetPicker
- id={`${idPrefix}-preset`}
- label="Start from a preset (optional)"
- presets={catalog.presets}
- // Deliberately NOT filtered to this row's current job type. Filtering
- // hid the control entirely on a non-agent row, so converting an
- // existing step into an audit meant deleting and re-adding it — and
- // the conversion is safe: params carry across the type switch and
- // existing prompt text is confirmed before it is replaced.
- hint="Fills the work prompt below with a ready-made single-focus audit that files issues and changes no code."
- value={matchedPreset?.id || ''}
- // Re-picking the preset the row already matches is a no-op, so it
- // needs no "replace your text?" confirm — the text IS the preset's.
- onPick={(preset) => (hasPromptText && preset.id !== matchedPreset?.id
- ? setPendingPreset(preset)
- : applyPreset(preset))}
- />
- {(spec?.params || []).map((descriptor) => (
- <JobParamField
- key={descriptor.key}
- descriptor={descriptor}
- value={job.params?.[descriptor.key]}
- options={optionsFor(descriptor)}
- idPrefix={idPrefix}
- onChange={setParam}
- />
- ))}
</div>
- {pendingPreset && (
- <InlineConfirmRow
- tone="warning"
- question={`Replace this step's work prompt with the “${pendingPreset.label}” preset? Your current text is discarded.`}
- confirmText="Replace"
- cancelText="Keep mine"
- onConfirm={() => applyPreset(pendingPreset)}
- onCancel={() => setPendingPreset(null)}
- />
- )}
+ <StepSettings
+ job={job}
+ entry={entry}
+ providers={providers}
+ idPrefix={idPrefix}
+ onChange={onChange}
+ />
- {spec?.description && <p className="text-[11px] text-gray-500">{spec.description}</p>}
+ {entry?.description && <p className="text-[11px] text-gray-500">{entry.description}</p>}
</>
)}
diff --git a/client/src/components/quotaBurn/PresetPicker.jsx b/client/src/components/quotaBurn/PresetPicker.jsx
deleted file mode 100644
index 81a1eee37e..0000000000
--- a/client/src/components/quotaBurn/PresetPicker.jsx
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Prompt-preset picker for `agent-prompt` burn jobs.
- *
- * A burn window is spent unattended, so the quality of the work prompt IS the
- * quality of the feature — and a blank textarea labeled "what should this
- * provider spend its remaining quota on?" is a hard question to answer well at
- * configuration time. The server ships worked answers
- * (`server/lib/quotaBurnPresets.js`); this is how they get picked.
- *
- * Two modes, chosen by whether the caller passes `value`:
- *
- * - **Bound** (a job row): `value` is the id of the preset whose prompt the row
- * STILL matches verbatim, derived by the caller — nothing on disk records a
- * preset id. So the control reports a fact rather than a memory: it shows the
- * preset while the text is that preset's, and falls back to the placeholder
- * the moment the user edits the prompt into something else. Leaving it blank
- * at all times (the original behavior) made picking a preset look like a
- * no-op, because the only visible effect was 60 lines below the fold.
- * - **One-shot action** (the family's "add a preset job"): no `value`, so the
- * select snaps back to its placeholder after firing — it adds a NEW step
- * rather than describing an existing one.
- */
-
-import { inputClass } from './fields';
-
-export default function PresetPicker({ id, label, presets, onPick, hint, value = '' }) {
- // Deliberately unfiltered by the row's current job type: a preset carries the
- // job type it needs, so picking one CONVERTS the step rather than being
- // inapplicable to it. Filtering hid the control entirely on a non-agent row,
- // leaving delete-and-re-add as the only way to turn a step into an audit.
- const rows = presets || [];
- if (!rows.length) return null;
-
- return (
- <label htmlFor={id} className="block text-xs text-gray-400">
- {label}
- <select
- id={id}
- className={inputClass}
- // Guarded against a stale id: a `value` no match exists for would leave
- // React's <select> on whatever option the browser picked instead.
- value={rows.some((preset) => preset.id === value) ? value : ''}
- onChange={(event) => {
- const picked = rows.find((preset) => preset.id === event.target.value);
- if (picked) onPick(picked);
- }}
- >
- <option value="">Choose a preset…</option>
- {rows.map((preset) => (
- <option key={preset.id} value={preset.id} title={preset.summary}>
- {preset.label} — {preset.summary}
- </option>
- ))}
- </select>
- {hint && <span className="block mt-1 text-[11px] text-gray-500">{hint}</span>}
- </label>
- );
-}
diff --git a/client/src/components/quotaBurn/StepSettings.jsx b/client/src/components/quotaBurn/StepSettings.jsx
new file mode 100644
index 0000000000..d5ec65cae3
--- /dev/null
+++ b/client/src/components/quotaBurn/StepSettings.jsx
@@ -0,0 +1,200 @@
+/**
+ * A burn step's PER-INVOCATION overrides, and the effective settings they add up
+ * to.
+ *
+ * The step references a scheduled task the user already configured, so every
+ * control here is a three-state one: INHERIT the task's saved setting, or pin
+ * something else for this burn only. Nothing written here ever edits the task —
+ * that is what the "view / edit" link beside the picker is for.
+ *
+ * Effective values (and the audit mode) are stated ABOVE the controls rather
+ * than left to be inferred: a burn spends real subscription quota unattended,
+ * and "what will actually run" must be readable before Run Now or the next
+ * cycle, not reconstructed from two pages.
+ *
+ * The audit-mode and agent-option vocabulary is imported from the Schedule tab's
+ * own constants, not restated — one catalog, rendered twice.
+ */
+
+import { ExternalLink } from 'lucide-react';
+import { Link } from 'react-router';
+import EffortSelect from '../cos/EffortSelect';
+import { AGENT_OPTIONS } from '../cos/constants';
+import { fileIssuesEffective, managedAgentOptionsFor } from '../cos/tabs/schedule/scheduleConstants';
+import { effectiveQuotaBurnSettings, QUOTA_BURN_TASK_REF_KIND, taskSourceHref } from '../../lib/quotaBurnTasks';
+import { effortAwareModelOptions, effortLevelsForProvider, effortSurvivingModel } from '../../utils/providers';
+import { inputClass } from './fields';
+
+const INHERIT = '';
+
+/** A tri-state boolean as a `<select>` value: inherit, on, off. */
+const booleanValue = (value) => (value === undefined || value === null ? INHERIT : String(value === true));
+const parseBooleanValue = (raw) => (raw === INHERIT ? undefined : raw === 'true');
+
+export default function StepSettings({ job, entry, providers, idPrefix, onChange }) {
+ const overrides = job.overrides || {};
+ const params = overrides.params || {};
+ const saved = entry?.config || null;
+ const effective = effectiveQuotaBurnSettings(job, saved);
+
+ const setOverride = (key, value) => onChange({ ...job, overrides: { ...overrides, [key]: value || null } });
+ // A param set back to "Inherit" is DELETED rather than written as null: the
+ // server merges the bag over the task's saved metadata, so a null would pin
+ // the key to null instead of letting the task's own value through.
+ const setParam = (key, value) => {
+ const next = { ...params };
+ if (value === undefined) delete next[key];
+ else next[key] = value;
+ onChange({ ...job, overrides: { ...overrides, params: next } });
+ };
+
+ // Falls back to the family's first eligible binary rather than to nothing: an
+ // unpinned step runs on whatever the family resolves, so that provider's model
+ // ladder and effort tiers are the ones to offer. Without the fallback the
+ // model and effort controls simply vanished for every step that inherits.
+ const selectedProvider = providers.find((provider) => provider.id === effective.providerId) || providers[0] || null;
+ const availableModels = selectedProvider ? effortAwareModelOptions(selectedProvider, effective.model) : [];
+ const effortLevels = selectedProvider ? effortLevelsForProvider(selectedProvider, effective.model) : null;
+
+ const handleModelChange = (raw) => {
+ const nextModel = raw || null;
+ // A pinned effort the new model does not offer is dropped rather than saved
+ // onto a model that cannot honor it.
+ const surviving = overrides.effort && selectedProvider
+ ? effortSurvivingModel(selectedProvider, nextModel, overrides.effort)
+ : overrides.effort;
+ onChange({ ...job, overrides: { ...overrides, model: nextModel, effort: surviving || null } });
+ };
+
+ const auditCapable = saved?.fileIssuesCapable === true;
+ const filesIssues = fileIssuesEffective(saved, params);
+ const managed = auditCapable ? managedAgentOptionsFor(saved, params) : (saved?.managedAgentOptions || []);
+ const agentOptionsShown = entry && !entry.programmatic;
+
+ return (
+ <div className="space-y-3">
+ <p className="text-[11px] text-gray-400">
+ <span className="text-gray-500">Effective: </span>
+ {effective.providerId || 'family default provider'}
+ {' · '}{effective.model || 'task default model'}
+ {effective.effort ? ` · ${effective.effort} effort` : ''}
+ {auditCapable ? ` · ${filesIssues ? 'files issues, changes no code' : 'does the work'}` : ''}
+ {entry && (
+ <>
+ {' · '}
+ <Link to={taskSourceHref(entry)} className="inline-flex items-center gap-0.5 text-port-accent hover:underline">
+ {entry.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM ? 'View / edit the job' : 'View / edit the task'}
+ <ExternalLink size={10} aria-hidden="true" />
+ </Link>
+ </>
+ )}
+ </p>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <label htmlFor={`${idPrefix}-provider`} className="block text-xs text-gray-400">
+ Provider
+ <select
+ id={`${idPrefix}-provider`}
+ className={inputClass}
+ value={overrides.providerId || INHERIT}
+ onChange={(event) => setOverride('providerId', event.target.value)}
+ >
+ <option value={INHERIT}>Inherit ({saved?.providerId || 'family default'})</option>
+ {providers.map((provider) => (
+ <option key={provider.id} value={provider.id}>{provider.name || provider.id}</option>
+ ))}
+ </select>
+ </label>
+
+ <label htmlFor={`${idPrefix}-model`} className="block text-xs text-gray-400">
+ Model
+ <select
+ id={`${idPrefix}-model`}
+ className={inputClass}
+ value={overrides.model || INHERIT}
+ onChange={(event) => handleModelChange(event.target.value)}
+ >
+ <option value={INHERIT}>Inherit ({saved?.model || 'task default'})</option>
+ {availableModels.map((option) => {
+ const value = typeof option === 'string' ? option : option.id;
+ return <option key={value} value={value}>{typeof option === 'string' ? option : (option.name || option.id)}</option>;
+ })}
+ {/* A pin the current provider no longer lists still has to render as
+ itself, or the select silently reports a different model than the
+ one that will run. */}
+ {overrides.model && !availableModels.some((option) => (typeof option === 'string' ? option : option.id) === overrides.model) && (
+ <option value={overrides.model}>{overrides.model}</option>
+ )}
+ </select>
+ </label>
+
+ {effortLevels?.length > 0 && (
+ <label htmlFor={`${idPrefix}-effort`} className="block text-xs text-gray-400">
+ Thinking effort
+ <EffortSelect
+ id={`${idPrefix}-effort`}
+ provider={selectedProvider}
+ model={effective.model}
+ value={overrides.effort || INHERIT}
+ onChange={(effort) => setOverride('effort', effort)}
+ className={inputClass}
+ />
+ </label>
+ )}
+
+ {auditCapable && (
+ <label htmlFor={`${idPrefix}-file-issues`} className="block text-xs text-gray-400">
+ Audit mode
+ <select
+ id={`${idPrefix}-file-issues`}
+ className={inputClass}
+ value={booleanValue(params.fileIssues)}
+ onChange={(event) => setParam('fileIssues', parseBooleanValue(event.target.value))}
+ >
+ <option value={INHERIT}>
+ Inherit ({fileIssuesEffective(saved) ? 'file issues only' : 'do the work'})
+ </option>
+ <option value="true">File issues only</option>
+ <option value="false">Do the work</option>
+ </select>
+ </label>
+ )}
+
+ {agentOptionsShown && AGENT_OPTIONS.map(({ field, label, description }) => (
+ <label key={field} htmlFor={`${idPrefix}-${field}`} className="block text-xs text-gray-400">
+ {label}
+ <select
+ id={`${idPrefix}-${field}`}
+ className={inputClass}
+ disabled={managed.includes(field)}
+ value={managed.includes(field) ? INHERIT : booleanValue(params[field])}
+ title={managed.includes(field) ? `${label} is managed by this task in its current mode` : description}
+ onChange={(event) => setParam(field, parseBooleanValue(event.target.value))}
+ >
+ <option value={INHERIT}>
+ {managed.includes(field)
+ ? 'Managed by the task'
+ : `Inherit (${saved?.taskMetadata?.[field] === true ? 'on' : 'off'})`}
+ </option>
+ <option value="true">On</option>
+ <option value="false">Off</option>
+ </select>
+ </label>
+ ))}
+ </div>
+
+ {/* A programmatic task's run parameters live on the task itself (they are
+ per-type, and PortOS executes them directly). Showing them read-only
+ keeps the burn honest about what it will do without growing a second
+ editor for a shape only Scheduled Tasks knows. */}
+ {entry?.programmatic && (
+ <p className="text-[11px] text-gray-500">
+ Run parameters come from the scheduled task:{' '}
+ {Object.keys(effective.params).length
+ ? Object.entries(effective.params).map(([key, value]) => `${key}=${value}`).join(' · ')
+ : 'none set'}.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/quotaBurn/TaskRefPicker.jsx b/client/src/components/quotaBurn/TaskRefPicker.jsx
new file mode 100644
index 0000000000..f61edac77f
--- /dev/null
+++ b/client/src/components/quotaBurn/TaskRefPicker.jsx
@@ -0,0 +1,87 @@
+/**
+ * The searchable, grouped scheduled-task picker a burn step is built from.
+ *
+ * A burn window is spent unattended, so what it spends on has to be work the
+ * user already defined and can inspect — not a prompt typed into this page and
+ * duplicated away from the automation catalog. This control therefore offers the
+ * SAME two catalogs the rest of PortOS schedules from: built-in scheduled task
+ * types and app custom jobs. Creating new work happens in Scheduled Tasks, and
+ * the picker links there rather than growing an editor of its own.
+ *
+ * The filter box is separate from the `<select>` on purpose: an install ships
+ * ~30 built-in types plus however many custom jobs, which is past the point a
+ * flat dropdown is usable, and a native grouped select keeps the whole thing
+ * keyboard- and touch-usable without a popover to clamp to the viewport.
+ */
+
+import { useId, useState } from 'react';
+import { Search } from 'lucide-react';
+import { searchTaskCatalog } from '../../lib/quotaBurnTasks';
+import { inputClass } from './fields';
+
+export default function TaskRefPicker({
+ id, label, groups, value = '', onPick, hint, disabled = false, placeholder = 'Choose a scheduled task…',
+}) {
+ const [query, setQuery] = useState('');
+ const searchId = useId();
+ const filtered = searchTaskCatalog(groups, query);
+ const hasAny = (groups || []).some((group) => group.entries?.length);
+ const total = filtered.reduce((sum, group) => sum + group.entries.length, 0);
+ // A stale `value` (the referenced task was deleted, or the catalog read
+ // failed) must not leave React's <select> sitting on whatever option the
+ // browser picked instead — the row's own unavailable banner is what explains
+ // it, and the picker reverts to its placeholder.
+ const selectable = filtered.some((group) => group.entries.some((entry) => entry.key === value));
+
+ return (
+ <div className="space-y-1">
+ <label htmlFor={searchId} className="block text-xs text-gray-400">
+ Search tasks
+ <span className="relative mt-1 block">
+ <Search size={12} className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />
+ <input
+ id={searchId}
+ type="search"
+ className={`${inputClass} mt-0 pl-6`}
+ value={query}
+ disabled={disabled || !hasAny}
+ placeholder="Filter by task, app, or description"
+ onChange={(event) => setQuery(event.target.value)}
+ />
+ </span>
+ </label>
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {label}
+ <select
+ id={id}
+ className={inputClass}
+ value={selectable ? value : ''}
+ disabled={disabled || !hasAny}
+ onChange={(event) => {
+ const entry = filtered.flatMap((group) => group.entries).find((row) => row.key === event.target.value);
+ if (entry) onPick(entry);
+ }}
+ >
+ <option value="">{placeholder}</option>
+ {filtered.map((group) => (
+ <optgroup key={group.id} label={group.label}>
+ {group.entries.map((entry) => (
+ <option key={entry.key} value={entry.key} title={entry.description || undefined}>
+ {entry.label}
+ {entry.blockedReason ? ` — ${entry.blockedReason}` : ''}
+ </option>
+ ))}
+ </optgroup>
+ ))}
+ </select>
+ </label>
+ {/* A filter that matched nothing is its own state: without it the select
+ silently collapses to just the placeholder and reads as "this install
+ has no scheduled tasks". */}
+ {hasAny && total === 0 && (
+ <p role="status" className="text-[11px] text-amber-300">No scheduled task matches “{query}”.</p>
+ )}
+ {hint && <p className="text-[11px] text-gray-500">{hint}</p>}
+ </div>
+ );
+}
diff --git a/client/src/components/quotaBurn/fields.jsx b/client/src/components/quotaBurn/fields.jsx
index abd9ef0572..38235d8c70 100644
--- a/client/src/components/quotaBurn/fields.jsx
+++ b/client/src/components/quotaBurn/fields.jsx
@@ -1,7 +1,7 @@
/**
* Shared field primitives for the Quota Burn config surface.
*
- * `FamilyCard`, `JobRow`, `JobParamField` and `PresetPicker` all render the same
+ * `FamilyCard`, `JobRow`, `StepSettings` and `TaskRefPicker` all render the same
* dark label+control pair. Keeping the class string and the number field in one
* place means a styling change is one edit rather than four — before this, the
* identical Tailwind string was declared or inlined at four sites and had
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 28f9e534dd..3a0842dd73 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -123,7 +123,8 @@ grep -i "what you want to do" client/src/lib/README.md
| `chipContrast.js` | Contrast-safe chip colors for data-supplied colors the app did not pick — forge issue-label hexes (`apps/tabs/IssuesTab.jsx`), Google Calendar subcalendar colors (`calendar/calendarUtils.js`), and fixed category palettes rendered on theme-following surfaces (`brain/tabs/BrainGraph.jsx`, `cos/TerminalCoSPanel.jsx`). `chipColors(color, mode)` → `{ color, borderColor, backgroundColor }` for an inline `style` (null when the color is missing/unparseable, so the caller falls back to a neutral chip): the wash keeps the label's own color, while the text/border keep its HUE and move only its LIGHTNESS, by the smallest step that clears WCAG AA against the chip's own tint on the ACTIVE theme mode. Memoized per (color, mode). Graded against `SURFACES` — the worst-case surface per mode (darkest `day`, lightest `night`), which the test re-derives from `THEMES` so a new theme can't silently escape the grading. Plus the primitives: `parseColor` (`#rgb`/`#rrggbb`/bare hex/`rgb()`), `relativeLuminance`, `contrastRatio`, `blend`, `chipBackdrop`, `rgbToHsl`/`hslToRgb`, `ensureReadable`. Pure — the caller passes `theme.mode`, nothing here reads the DOM. |
| `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. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. `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. |
+| `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. |
| `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/index.js b/client/src/lib/index.js
index 2e3cf69dce..d0d8836820 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -191,6 +191,7 @@ export * from './threejsRig.js';
export * from './threejsSculpt.js';
export * from './tribe.js';
export * from './quotaBurnPatch.js';
+export * from './quotaBurnTasks.js';
export * from './tribeCadence.js';
export * from './universeBuilderExpand.js';
export * from './videoTimelineModel.js';
diff --git a/client/src/lib/quotaBurnPatch.js b/client/src/lib/quotaBurnPatch.js
index c145495fa1..e6dd5f7ef7 100644
--- a/client/src/lib/quotaBurnPatch.js
+++ b/client/src/lib/quotaBurnPatch.js
@@ -27,48 +27,6 @@ export function mergeQuotaBurnPatch(base, patch) {
return merged;
}
-/**
- * Apply a catalog preset to a burn job, returning the next job.
- *
- * A preset is a TEMPLATE: its prompt and recommended flags are copied in, and
- * from then on the job owns them. Two things are deliberately preserved rather
- * than overwritten, because they are choices the preset cannot make:
- * - `label` — only filled when blank, so applying a preset to a step the user
- * named does not rename it.
- * - `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;
- const { appId } = job?.params || {};
- return {
- ...job,
- label: job?.label?.trim() ? job.label : preset.label,
- jobType: preset.jobType || job?.jobType,
- params: { ...(job?.params || {}), ...(preset.params || {}), ...(appId ? { appId } : {}) },
- };
-}
-
-/**
- * A brand-new job seeded from a preset. `id` is passed in rather than minted
- * here so this stays pure (and so the caller keeps using whatever id scheme the
- * rest of its list uses).
- */
-export function jobFromPreset(preset, { id, appId = null } = {}) {
- return applyQuotaBurnPreset({
- id, enabled: true, label: '', jobType: preset.jobType, model: null, providerId: null, effort: null,
- // Standing work, matching a hand-added step: an audit dimension is worth
- // re-running as the code changes.
- runOnce: false,
- params: appId ? { appId } : {},
- }, preset);
-}
-
/**
* Whether a step has already had its one dispatch — the client's mirror of the
* server's `jobIsSpent`, taking the row's `ranAt` from the status feed instead
@@ -86,30 +44,6 @@ export function jobFromPreset(preset, { id, appId = null } = {}) {
*/
export const quotaBurnJobIsSpent = (job, ranAt) => Boolean(job?.runOnce && ranAt);
-/**
- * Whether a preset is already represented in a family's jobs list.
- * Matched by comparing the trimmed prompt text (or jobType + label for non-prompt presets).
- */
-export function isPresetInJobs(preset, jobs = []) {
- if (!preset) return false;
- const presetPrompt = String(preset.params?.prompt || '').trim();
- if (presetPrompt) {
- return (jobs || []).some(
- (job) => String(job?.params?.prompt || '').trim() === presetPrompt,
- );
- }
- return (jobs || []).some(
- (job) => job?.jobType === preset.jobType && job?.label === preset.label,
- );
-}
-
-/**
- * Filter catalog presets to only those not currently in the given jobs list.
- */
-export function getAvailablePresetsForJobs(presets = [], jobs = []) {
- return (presets || []).filter((preset) => !isPresetInJobs(preset, jobs));
-}
-
/**
* `QUOTA_BURN_UNLIMITED_DISPATCHES` in `server/lib/quotaBurnConfig.js`: the
* `maxDispatchesPerWindow` value that means the window is not counted at all,
diff --git a/client/src/lib/quotaBurnPatch.test.js b/client/src/lib/quotaBurnPatch.test.js
index b89fdb4ed8..fbcfed7ce0 100644
--- a/client/src/lib/quotaBurnPatch.test.js
+++ b/client/src/lib/quotaBurnPatch.test.js
@@ -1,11 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
- applyQuotaBurnPreset,
dispatchCapInput,
- getAvailablePresetsForJobs,
- isPresetInJobs,
isUnlimitedDispatchCap,
- jobFromPreset,
mergeQuotaBurnPatch,
quotaBurnJobIsSpent,
UNLIMITED_DISPATCHES,
@@ -66,66 +62,6 @@ describe('mergeQuotaBurnPatch', () => {
});
});
-const preset = {
- id: 'ux-audit',
- label: 'UX issues',
- summary: 'Audit the UI.',
- jobType: 'agent-prompt',
- params: { prompt: 'Audit the UI and file issues.', useWorktree: true, openPR: false, simplify: false },
-};
-
-describe('applyQuotaBurnPreset', () => {
- const job = { id: 'j1', enabled: true, label: '', jobType: 'agent-prompt', model: null, providerId: null, params: {} };
-
- it('copies the preset prompt and its recommended flags in', () => {
- expect(applyQuotaBurnPreset(job, preset).params).toEqual(preset.params);
- });
-
- it('keeps the app the step already targets', () => {
- // The preset cannot know which managed app this plan points at; wiping it
- // would leave a step that silently cannot run.
- const targeted = { ...job, params: { appId: 'a1', prompt: '' } };
- expect(applyQuotaBurnPreset(targeted, preset).params.appId).toBe('a1');
- });
-
- it('names an unnamed step but never renames one the user named', () => {
- expect(applyQuotaBurnPreset(job, preset).label).toBe('UX issues');
- expect(applyQuotaBurnPreset({ ...job, label: 'Nightly sweep' }, preset).label).toBe('Nightly sweep');
- });
-
- it('switches the step to the job type the preset needs', () => {
- expect(applyQuotaBurnPreset({ ...job, jobType: 'universe-bible-images' }, preset).jobType).toBe('agent-prompt');
- });
-
- 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, effort: null,
- // Standing work: an audit dimension is worth re-running as the code moves.
- runOnce: false,
- params: { ...preset.params, appId: 'a1' },
- });
- });
-
- it('omits appId entirely when none is known, rather than storing an empty one', () => {
- // `appId: ''` would read as a configured-but-blank app; absent is the honest
- // shape, and the row's own status line then says the app is unset.
- expect(jobFromPreset(preset, { id: 'job-x' }).params).not.toHaveProperty('appId');
- });
-});
-
describe('dispatch cap helpers', () => {
it('reads any negative cap as unlimited and a real cap as bounded', () => {
expect(isUnlimitedDispatchCap(UNLIMITED_DISPATCHES)).toBe(true);
@@ -143,41 +79,6 @@ describe('dispatch cap helpers', () => {
});
});
-describe('isPresetInJobs and getAvailablePresetsForJobs', () => {
- const p1 = { id: 'ux-audit', label: 'UX issues', jobType: 'agent-prompt', params: { prompt: 'Audit UX.' } };
- const p2 = { id: 'a11y-audit', label: 'A11y issues', jobType: 'agent-prompt', params: { prompt: 'Audit A11y.' } };
- const p3 = { id: 'perf-audit', label: 'Perf issues', jobType: 'agent-prompt', params: { prompt: 'Audit Perf.' } };
-
- it('matches a preset in jobs by prompt text', () => {
- const jobs = [{ id: 'j1', params: { prompt: 'Audit UX.' } }];
- expect(isPresetInJobs(p1, jobs)).toBe(true);
- expect(isPresetInJobs(p2, jobs)).toBe(false);
- });
-
- it('filters presets to only those not already in jobs', () => {
- const jobs = [{ id: 'j1', params: { prompt: 'Audit UX.' } }];
- const available = getAvailablePresetsForJobs([p1, p2, p3], jobs);
- expect(available).toEqual([p2, p3]);
- });
-
- it('returns all presets when jobs list is empty', () => {
- expect(getAvailablePresetsForJobs([p1, p2], [])).toEqual([p1, p2]);
- });
-
- it('returns empty list when all presets are in jobs', () => {
- const jobs = [
- { id: 'j1', params: { prompt: 'Audit UX.' } },
- { id: 'j2', params: { prompt: 'Audit A11y.' } },
- ];
- expect(getAvailablePresetsForJobs([p1, p2], jobs)).toEqual([]);
- });
-
- it('handles null/undefined gracefully', () => {
- expect(isPresetInJobs(null, [])).toBe(false);
- expect(getAvailablePresetsForJobs(null, null)).toEqual([]);
- });
-});
-
// @vitest-environment node
diff --git a/client/src/lib/quotaBurnTasks.js b/client/src/lib/quotaBurnTasks.js
new file mode 100644
index 0000000000..da768bfa8e
--- /dev/null
+++ b/client/src/lib/quotaBurnTasks.js
@@ -0,0 +1,252 @@
+/**
+ * The Quota Burn page's view of the SHARED scheduled-task catalog.
+ *
+ * A burn step no longer carries its own copied prompt: it REFERENCES a scheduled
+ * task the user already owns (`server/lib/quotaBurnTaskRef.js`) and layers
+ * per-invocation overrides on top. So the page's picker is a view over the same
+ * two catalogs the CoS Schedule and System Tasks pages render — PortOS built-in
+ * task types (`GET /api/cos/schedule`) and app custom jobs (`GET /api/cos/jobs`)
+ * — rather than a second automation catalog of its own.
+ *
+ * Everything here is pure, so the page can test the grouping, the search, the
+ * inheritance display and the PUT payload without a server.
+ */
+
+/** Mirrors `QUOTA_BURN_TASK_REF_KIND` in `server/lib/quotaBurnTaskRef.js`. */
+export const QUOTA_BURN_TASK_REF_KIND = Object.freeze({ BUILTIN: 'builtin', CUSTOM: 'custom' });
+
+export const BUILTIN_TASK_GROUP = 'PortOS scheduled tasks';
+export const CUSTOM_TASK_GROUP = 'App custom tasks';
+
+/**
+ * A reference rendered as one `<select>` value.
+ *
+ * Deliberately WITHOUT the app: which task to run and which app to run it against
+ * are two separate controls, so folding the target into this key would multiply
+ * the picker by the app list and make "same audit, different app" read as two
+ * unrelated entries.
+ */
+export const taskRefKey = (ref) => (ref?.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM
+ ? `custom:${ref.jobId}`
+ : ref?.taskType
+ ? `builtin:${ref.taskType}`
+ : '');
+
+/**
+ * Which managed apps a built-in type may be pointed at.
+ *
+ * The server's own catalog builder (`getQuotaBurnTaskCatalog`) reads exactly this
+ * — an app whose `taskTypeOverrides[type].enabled === true` — and its availability
+ * resolver reports `wrong-scope` for any other app, so offering the full app list
+ * here would offer targets the step can never run against.
+ */
+const enabledAppIds = (task) => Object.entries(task?.appOverrides || {})
+ .filter(([, override]) => override?.enabled === true)
+ .map(([appId]) => appId);
+
+/**
+ * Whether a step targeting this entry needs to name a managed app.
+ *
+ * Mirrors the affordance `RunTaskButton` already applies on the Schedule page:
+ * an install-wide type's real run is the app-less one, and a programmatic type
+ * acts on PortOS's own records and is REJECTED when it names an app. Everything
+ * else acts on one app.
+ *
+ * Deliberately derived from the two flags the schedule status already publishes
+ * rather than from a client copy of `taskTargetScope.js`'s sets — a mirrored
+ * constant is a constant that drifts, and these two already cover every type the
+ * server's schema would 400 for naming (or omitting) an app.
+ */
+export const taskEntryNeedsApp = (entry) => entry?.kind === QUOTA_BURN_TASK_REF_KIND.BUILTIN
+ && !entry.installWide && !entry.programmatic;
+
+/**
+ * Whether a burn may invoke a custom job at all — the client mirror of
+ * `isBurnEligibleCustomJob`. A `shell` job runs an allowlisted command and a
+ * `script` job runs a built-in handler; neither spends provider quota, which is
+ * the only thing a burn is for. A job written before `type` existed is an agent.
+ */
+const isBurnEligibleCustomJob = (job) => Boolean(job) && (!job.type || job.type === 'agent');
+
+/**
+ * Build the picker's catalog from the two reads the page makes.
+ *
+ * Entries a burn can NEVER invoke are dropped outright rather than offered and
+ * then refused; entries that are merely switched off, or that no app has enabled
+ * yet, are kept with a `blockedReason` so the picker can say what to go and fix.
+ * `config` is the raw task/job record, carried through so the settings panel can
+ * read the saved provider/model/effort/metadata it inherits from.
+ */
+export function buildQuotaBurnTaskCatalog({ schedule, jobs, apps } = {}) {
+ const appName = new Map((apps || []).map((app) => [app.id, app.name || app.id]));
+ const builtin = Object.entries(schedule?.tasks || {})
+ .filter(([, task]) => task?.invocation?.userInvokable !== false)
+ .map(([taskType, task]) => {
+ const appIds = enabledAppIds(task);
+ const entry = {
+ key: `builtin:${taskType}`,
+ kind: QUOTA_BURN_TASK_REF_KIND.BUILTIN,
+ taskType,
+ jobId: null,
+ label: taskType,
+ group: BUILTIN_TASK_GROUP,
+ description: task?.description || '',
+ enabled: task?.enabled === true,
+ installWide: task?.installWide === true,
+ programmatic: task?.programmatic === true,
+ appIds,
+ appNames: appIds.map((id) => appName.get(id) || id),
+ config: task || {},
+ };
+ return { ...entry, blockedReason: builtinBlockedReason(entry) };
+ });
+
+ const custom = (jobs || [])
+ .filter(isBurnEligibleCustomJob)
+ .map((job) => ({
+ key: `custom:${job.id}`,
+ kind: QUOTA_BURN_TASK_REF_KIND.CUSTOM,
+ taskType: null,
+ jobId: job.id,
+ label: job.name || job.id,
+ group: CUSTOM_TASK_GROUP,
+ description: job.description || '',
+ enabled: job.enabled === true,
+ installWide: false,
+ programmatic: false,
+ appIds: job.appId ? [job.appId] : [],
+ appNames: job.appId ? [appName.get(job.appId) || job.appId] : [],
+ config: job,
+ blockedReason: job.enabled === true ? null : 'disabled in System Tasks',
+ }));
+
+ const byLabel = (a, b) => a.label.localeCompare(b.label);
+ return [
+ { id: BUILTIN_TASK_GROUP, label: BUILTIN_TASK_GROUP, entries: builtin.sort(byLabel) },
+ { id: CUSTOM_TASK_GROUP, label: CUSTOM_TASK_GROUP, entries: custom.sort(byLabel) },
+ ].filter((group) => group.entries.length > 0);
+}
+
+/**
+ * Why picking this built-in entry would not immediately produce a runnable step.
+ *
+ * It does NOT hide the entry: "no app has this task enabled" and "it is switched
+ * off" are both one click away from fixed on a page this row links to, and a
+ * user assembling a plan for work they are about to enable is a real case. The
+ * step then renders the SERVER's own unavailability reason until it is fixed.
+ */
+function builtinBlockedReason(entry) {
+ if (!entry.enabled) return 'disabled in Scheduled Tasks';
+ if (taskEntryNeedsApp(entry) && entry.appIds.length === 0) return 'no managed app has this task enabled';
+ return null;
+}
+
+/** Every entry across every group, flattened — for lookups and for search. */
+export const flattenTaskCatalog = (groups) => (groups || []).flatMap((group) => group.entries || []);
+
+/** The catalog entry a step points at, or `null` when the reference is stale. */
+export function findTaskEntry(groups, ref) {
+ const key = taskRefKey(ref);
+ return key ? flattenTaskCatalog(groups).find((entry) => entry.key === key) || null : null;
+}
+
+/**
+ * Filter the grouped catalog by a free-text query, keeping the grouping.
+ *
+ * Matched against the label, the task type, the description and the names of the
+ * apps the entry can target — searching "portos" for the app rather than the
+ * task name is the obvious thing to type on an install with a dozen apps.
+ */
+export function searchTaskCatalog(groups, query) {
+ const needle = String(query || '').trim().toLowerCase();
+ if (!needle) return groups || [];
+ const matches = (entry) => [entry.label, entry.taskType, entry.description, ...(entry.appNames || [])]
+ .some((field) => String(field || '').toLowerCase().includes(needle));
+ return (groups || [])
+ .map((group) => ({ ...group, entries: (group.entries || []).filter(matches) }))
+ .filter((group) => group.entries.length > 0);
+}
+
+/**
+ * The settings an invocation will actually run with — the client mirror of
+ * `effectiveSettings` in `server/services/quotaBurnInvoke.js`.
+ *
+ * Presence, not truthiness: an override the user cleared normalizes to `null`
+ * and INHERITS, while a pinned value wins. `params` merge key-by-key rather than
+ * replacing the bag, so overriding one run parameter does not blank the rest of
+ * the task's saved metadata.
+ */
+export function effectiveQuotaBurnSettings(step, saved) {
+ const overrides = step?.overrides || {};
+ return {
+ providerId: overrides.providerId ?? saved?.providerId ?? null,
+ model: overrides.model ?? saved?.model ?? null,
+ effort: overrides.effort ?? saved?.effort ?? null,
+ params: { ...(saved?.taskMetadata || {}), ...(overrides.params || {}) },
+ };
+}
+
+/**
+ * One step, reduced to the fields the PUT schema accepts as INPUT.
+ *
+ * The point is the DROP: `normalizeQuotaBurnJob` resolves the top-level
+ * `model` / `providerId` / `effort` / `params` compat mirrors by PRESENCE, so a
+ * body that still carried them (the GET hands them back on every read) would let
+ * a stale mirror outrank the `overrides` bag this editor writes — clearing a
+ * pinned model would silently restore it. Everything else the GET grows is
+ * dropped for a blunter reason: the job schema is `.strict()`, and one unknown
+ * key 400s the whole coalesced save.
+ *
+ * `unavailable` is deliberately KEPT even though the server ignores it and
+ * re-derives it from the live catalog: the page applies this same object to its
+ * optimistic config, so stripping it would make a stale step's reason vanish the
+ * moment any other field on the row was touched.
+ */
+export function quotaBurnStepPayload(job) {
+ return {
+ id: job.id,
+ enabled: job.enabled !== false,
+ label: job.label || '',
+ // A legacy step carries a `jobType` and no reference; the schema rejects a
+ // payload with both, and one with neither.
+ ...(job.taskRef ? { taskRef: job.taskRef } : { jobType: job.jobType }),
+ ...(job.unavailable ? { unavailable: job.unavailable } : {}),
+ overrides: {
+ providerId: job.overrides?.providerId ?? null,
+ model: job.overrides?.model ?? null,
+ effort: job.overrides?.effort ?? null,
+ params: job.overrides?.params || {},
+ },
+ runOnce: job.runOnce === true,
+ };
+}
+
+/** A brand-new burn step referencing `entry`. `id` is minted by the caller. */
+export function stepFromTaskEntry(entry, { id, appId = null } = {}) {
+ const taskRef = entry.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM
+ ? { kind: QUOTA_BURN_TASK_REF_KIND.CUSTOM, jobId: entry.jobId }
+ : {
+ kind: QUOTA_BURN_TASK_REF_KIND.BUILTIN,
+ taskType: entry.taskType,
+ // Only a type that targets one app may carry an appId at all — the schema
+ // rejects one on an install-wide or programmatic type.
+ appId: taskEntryNeedsApp(entry) ? (appId ?? entry.appIds[0] ?? null) : null,
+ };
+ return { id, enabled: true, label: '', taskRef, jobType: null, runOnce: false, overrides: { providerId: null, model: null, effort: null, params: {} } };
+}
+
+/**
+ * Where the source task is viewed, edited, or created.
+ *
+ * A burn step never edits the task it points at — that is the whole point of the
+ * reference — so every row carries the link out instead. `?task=` is the deep
+ * link the Schedule tab already reads for its config drawer.
+ */
+export const taskSourceHref = (entry) => (entry?.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM
+ ? '/cos/jobs'
+ : entry?.taskType
+ ? `/cos/schedule?task=${encodeURIComponent(entry.taskType)}`
+ : '/cos/schedule');
+
+/** Where a user goes to CREATE the on-demand scheduled task a new step would reference. */
+export const CREATE_TASK_HREF = '/cos/jobs';
diff --git a/client/src/lib/quotaBurnTasks.test.js b/client/src/lib/quotaBurnTasks.test.js
new file mode 100644
index 0000000000..f952ee728b
--- /dev/null
+++ b/client/src/lib/quotaBurnTasks.test.js
@@ -0,0 +1,219 @@
+import { describe, it, expect } from 'vitest';
+import {
+ buildQuotaBurnTaskCatalog,
+ effectiveQuotaBurnSettings,
+ findTaskEntry,
+ quotaBurnStepPayload,
+ searchTaskCatalog,
+ stepFromTaskEntry,
+ taskEntryNeedsApp,
+ taskRefKey,
+ taskSourceHref,
+} from './quotaBurnTasks';
+
+const schedule = {
+ tasks: {
+ ux: {
+ enabled: true,
+ description: 'Audit the interface and file issues.',
+ appOverrides: { app1: { enabled: true }, app2: { enabled: false } },
+ providerId: 'claude-cli',
+ model: 'sonnet',
+ taskMetadata: { useWorktree: true },
+ fileIssuesCapable: true,
+ defaultFileIssues: true,
+ },
+ 'repo-sync': { enabled: true, installWide: true, appOverrides: {} },
+ 'universe-bible-images': { enabled: true, programmatic: true, appOverrides: {}, taskMetadata: { scope: 'all' } },
+ 'model-comparison-refresh': { enabled: false, installWide: true, appOverrides: {} },
+ 'internal-only': { enabled: true, appOverrides: {}, invocation: { userInvokable: false } },
+ },
+};
+
+const jobs = [
+ { id: 'job-a', name: 'Nightly changelog', appId: 'app1', enabled: true, type: 'agent', providerId: 'codex-cli' },
+ { id: 'job-shell', name: 'Disk sweep', appId: 'app1', enabled: true, type: 'shell' },
+ { id: 'job-legacy', name: 'Legacy job', appId: null, enabled: false },
+];
+
+const apps = [{ id: 'app1', name: 'Example App' }, { id: 'app2', name: 'Second App' }];
+
+const catalog = () => buildQuotaBurnTaskCatalog({ schedule, jobs, apps });
+
+describe('buildQuotaBurnTaskCatalog', () => {
+ it('groups PortOS scheduled tasks and app custom jobs from the SHARED catalogs', () => {
+ const groups = catalog();
+ expect(groups.map((group) => group.id)).toEqual(['PortOS scheduled tasks', 'App custom tasks']);
+ expect(groups[0].entries.map((entry) => entry.taskType))
+ .toEqual(['model-comparison-refresh', 'repo-sync', 'universe-bible-images', 'ux']);
+ // A job written before `type` existed is an agent job, so it stays.
+ expect(groups[1].entries.map((entry) => entry.jobId)).toEqual(['job-legacy', 'job-a']);
+ });
+
+ it('drops what a burn may NEVER invoke rather than offering it and refusing', () => {
+ const keys = catalog().flatMap((group) => group.entries.map((entry) => entry.key));
+ // Not user-invokable, and a shell job spends no provider quota at all —
+ // mirrors `isBurnEligibleCustomJob` / the registry's `userInvokable`.
+ expect(keys).not.toContain('builtin:internal-only');
+ expect(keys).not.toContain('custom:job-shell');
+ });
+
+ it('keeps a merely-blocked entry, with the reason that says what to go and fix', () => {
+ const byKey = Object.fromEntries(catalog().flatMap((group) => group.entries).map((entry) => [entry.key, entry]));
+ expect(byKey['builtin:model-comparison-refresh'].blockedReason).toBe('disabled in Scheduled Tasks');
+ expect(byKey['custom:job-legacy'].blockedReason).toBe('disabled in System Tasks');
+ // `ux` targets one app, and only app1 has it enabled — app2's override is off.
+ expect(byKey['builtin:ux'].appIds).toEqual(['app1']);
+ expect(byKey['builtin:ux'].appNames).toEqual(['Example App']);
+ expect(byKey['builtin:ux'].blockedReason).toBeNull();
+ });
+
+ it('offers a target only for a type that acts on ONE app', () => {
+ const byKey = Object.fromEntries(catalog().flatMap((group) => group.entries).map((entry) => [entry.key, entry]));
+ expect(taskEntryNeedsApp(byKey['builtin:ux'])).toBe(true);
+ // The server's schema rejects an appId on either of these.
+ expect(taskEntryNeedsApp(byKey['builtin:repo-sync'])).toBe(false);
+ expect(taskEntryNeedsApp(byKey['builtin:universe-bible-images'])).toBe(false);
+ });
+});
+
+describe('searchTaskCatalog', () => {
+ it('matches the task, its description, and the apps it can target', () => {
+ const byQuery = (query) => searchTaskCatalog(catalog(), query)
+ .flatMap((group) => group.entries.map((entry) => entry.key));
+ expect(byQuery('ux')).toEqual(['builtin:ux']);
+ expect(byQuery('file issues')).toEqual(['builtin:ux']);
+ // The app name is the obvious thing to type on an install with many apps.
+ expect(byQuery('Example App')).toEqual(['builtin:ux', 'custom:job-a']);
+ });
+
+ it('drops a group that matched nothing rather than rendering an empty heading', () => {
+ expect(searchTaskCatalog(catalog(), 'nightly').map((group) => group.id)).toEqual(['App custom tasks']);
+ expect(searchTaskCatalog(catalog(), 'zzzz')).toEqual([]);
+ expect(searchTaskCatalog(catalog(), ' ')).toHaveLength(2);
+ });
+});
+
+describe('task reference keys', () => {
+ it('renders a reference as the picker\'s select value, without the target', () => {
+ expect(taskRefKey({ kind: 'builtin', taskType: 'ux', appId: 'app1' })).toBe('builtin:ux');
+ expect(taskRefKey({ kind: 'custom', jobId: 'job-a' })).toBe('custom:job-a');
+ // No reference at all is the empty value, so a legacy step's picker shows
+ // its placeholder rather than latching onto whatever option came first.
+ expect(taskRefKey(null)).toBe('');
+ expect(taskRefKey({ kind: 'builtin' })).toBe('');
+ });
+
+ it('finds the entry a step points at, and reports a stale reference as missing', () => {
+ expect(findTaskEntry(catalog(), { kind: 'builtin', taskType: 'ux' })?.label).toBe('ux');
+ expect(findTaskEntry(catalog(), { kind: 'builtin', taskType: 'deleted-task' })).toBeNull();
+ });
+});
+
+describe('stepFromTaskEntry', () => {
+ const entryFor = (key) => catalog().flatMap((group) => group.entries).find((entry) => entry.key === key);
+
+ it('targets an app-scoped type, defaulting to the first app that has it enabled', () => {
+ expect(stepFromTaskEntry(entryFor('builtin:ux'), { id: 'step-1' })).toEqual({
+ id: 'step-1',
+ enabled: true,
+ label: '',
+ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app1' },
+ jobType: null,
+ runOnce: false,
+ overrides: { providerId: null, model: null, effort: null, params: {} },
+ });
+ });
+
+ it('never puts an appId on a type the server would reject one for', () => {
+ expect(stepFromTaskEntry(entryFor('builtin:repo-sync'), { id: 's', appId: 'app1' }).taskRef.appId).toBeNull();
+ expect(stepFromTaskEntry(entryFor('builtin:universe-bible-images'), { id: 's', appId: 'app1' }).taskRef.appId).toBeNull();
+ });
+
+ it('stores no appId on a custom job — the job record owns its own scope', () => {
+ expect(stepFromTaskEntry(entryFor('custom:job-a'), { id: 's' }).taskRef)
+ .toEqual({ kind: 'custom', jobId: 'job-a' });
+ });
+});
+
+describe('effectiveQuotaBurnSettings', () => {
+ const saved = { providerId: 'claude-cli', model: 'sonnet', effort: 'medium', taskMetadata: { useWorktree: true, openPR: true } };
+
+ it('inherits an unset override and lets a pin win', () => {
+ const step = { overrides: { providerId: null, model: 'opus', effort: null, params: {} } };
+ expect(effectiveQuotaBurnSettings(step, saved)).toEqual({
+ providerId: 'claude-cli',
+ model: 'opus',
+ effort: 'medium',
+ params: { useWorktree: true, openPR: true },
+ });
+ });
+
+ it('merges run params key-by-key instead of replacing the saved bag', () => {
+ // Overriding one parameter must not blank every other one the task saved.
+ const step = { overrides: { params: { openPR: false } } };
+ expect(effectiveQuotaBurnSettings(step, saved).params).toEqual({ useWorktree: true, openPR: false });
+ });
+
+ it('reads a step with no reference resolved as pure overrides', () => {
+ expect(effectiveQuotaBurnSettings({ overrides: { model: 'opus' } }, null))
+ .toEqual({ providerId: null, model: 'opus', effort: null, params: {} });
+ });
+});
+
+describe('quotaBurnStepPayload', () => {
+ const stored = {
+ id: 'j1',
+ enabled: true,
+ label: 'Nightly UX',
+ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app1' },
+ jobType: null,
+ overrides: { providerId: null, model: null, effort: null, params: { fileIssues: true } },
+ runOnce: false,
+ // The compat mirrors the GET hands back on every read.
+ model: null,
+ providerId: null,
+ effort: null,
+ params: { fileIssues: true },
+ unavailable: null,
+ };
+
+ it('drops the top-level mirrors that would outrank the overrides bag', () => {
+ // `normalizeQuotaBurnJob` resolves them by PRESENCE, so echoing a stale
+ // mirror back would silently restore a model the user just cleared.
+ const payload = quotaBurnStepPayload({ ...stored, overrides: { ...stored.overrides, model: null }, model: 'opus' });
+ expect(payload).not.toHaveProperty('model');
+ expect(payload).not.toHaveProperty('providerId');
+ expect(payload).not.toHaveProperty('effort');
+ expect(payload).not.toHaveProperty('params');
+ expect(payload.overrides.model).toBeNull();
+ });
+
+ it('keeps a stale step\'s reason so an unrelated edit does not erase it on screen', () => {
+ // The same object is applied to the page's optimistic config; the server
+ // ignores the field and re-derives it from the live catalog.
+ const payload = quotaBurnStepPayload({ ...stored, unavailable: { code: 'disabled', reason: 'task is disabled' } });
+ expect(payload.unavailable).toEqual({ code: 'disabled', reason: 'task is disabled' });
+ expect(quotaBurnStepPayload(stored)).not.toHaveProperty('unavailable');
+ });
+
+ it('sends a legacy step\'s jobType and a reference step\'s taskRef, never both', () => {
+ expect(quotaBurnStepPayload(stored)).toMatchObject({ taskRef: stored.taskRef });
+ expect(quotaBurnStepPayload(stored)).not.toHaveProperty('jobType');
+ const legacy = quotaBurnStepPayload({ id: 'old', jobType: 'agent-prompt', params: { prompt: 'hi' }, overrides: { params: { prompt: 'hi' } } });
+ expect(legacy.jobType).toBe('agent-prompt');
+ expect(legacy).not.toHaveProperty('taskRef');
+ // The prompt survives through the overrides bag rather than the mirror.
+ expect(legacy.overrides.params).toEqual({ prompt: 'hi' });
+ });
+});
+
+describe('taskSourceHref', () => {
+ it('deep-links a built-in task into the Schedule drawer and a custom job to System Tasks', () => {
+ expect(taskSourceHref({ kind: 'builtin', taskType: 'pr-reviewer' })).toBe('/cos/schedule?task=pr-reviewer');
+ expect(taskSourceHref({ kind: 'custom', jobId: 'job-a' })).toBe('/cos/jobs');
+ expect(taskSourceHref(null)).toBe('/cos/schedule');
+ });
+});
+
+// @vitest-environment node
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index b8b1d6a103..cddb4e05fc 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -3,10 +3,11 @@
* quota which would otherwise expire unused.
*
* The loop lives in PortOS, not on any managed app: one schedule, one set of
- * per-provider-family windows, and an ordered burn plan per family. Individual
- * jobs decide what the quota goes to — an agent in a named managed app, or a
- * programmatic PortOS job like rendering the universe bible entries that have
- * no image yet.
+ * per-provider-family windows, and an ordered burn plan per family. A plan step
+ * REFERENCES a scheduled task the user already owns (CoS → Schedule, or a System
+ * Tasks custom job) and layers per-invocation overrides on it — so this page is a
+ * picker over the shared automation catalog, never a second copy of it. New work
+ * is created in Scheduled Tasks and then added here.
*
* The master switch is the consent gate for the whole feature (AGENTS.md's AI
* provider policy): with it off nothing here contacts a provider, and the page
@@ -24,6 +25,7 @@ import { NumberField } from '../components/quotaBurn/fields';
import * as api from '../services/api';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';
+import { buildQuotaBurnTaskCatalog, flattenTaskCatalog } from '../lib/quotaBurnTasks';
import { safeReadJsonSession, safeRemoveSession, safeWriteJsonSession } from '../lib/safeStorage';
import { coalesce } from '../utils/coalesce';
import { timeAgo } from '../utils/formatters';
@@ -37,7 +39,11 @@ export const SAVE_DEBOUNCE_MS = 500;
// is a 10-20s PTY spawn, so this is a handful of polls, not a busy loop.
export const PENDING_POLL_MS = 4000;
-const EMPTY_CATALOG = { jobTypes: [], apps: [], universes: [], imageModes: [], providers: [] };
+// What the burn's OWN catalog endpoint still supplies: the managed apps a step
+// can target and the providers a per-invocation pin may name. The work itself is
+// no longer in here — a step references a scheduled task, and those come from the
+// same two reads the CoS Schedule and System Tasks pages make.
+const EMPTY_CATALOG = { apps: [], providers: [] };
// Where a patch the server never accepted waits for the next visit. Session
// scope, not local: this is a crash buffer for the current tab, and a patch
@@ -59,16 +65,14 @@ const readStashedPatch = () => {
// two need opposite handling of the error state, and both are falsy.
const READ_FAILED = Symbol('quota-burn-read-failed');
-// A catalog the server answered with, but which is missing the job types the
-// form needs, is indistinguishable from a failed fetch as far as the page is
-// concerned — both leave every dropdown empty — so normalize to the same shape
-// and let the caller decide which message to show. Each list is validated
-// rather than merely defaulted: a spread alone lets an explicit `null` through
-// (a partial payload, an older peer), and every consumer of this object reads
-// `.length` on it.
+// A catalog the server answered with, but whose lists are missing, is
+// indistinguishable from a failed fetch as far as the page is concerned — both
+// leave every dropdown empty — so normalize to the same shape and let the caller
+// decide which message to show. Each list is validated rather than merely
+// defaulted: a spread alone lets an explicit `null` through (a partial payload,
+// an older peer), and every consumer of this object reads `.length` on it.
const normalizeCatalog = (data) => ({
...EMPTY_CATALOG,
- ...(data || {}),
...Object.fromEntries(Object.keys(EMPTY_CATALOG).map((key) => [
key, Array.isArray(data?.[key]) ? data[key] : [],
])),
@@ -83,6 +87,11 @@ export default function QuotaBurn() {
const [config, setConfig] = useState(null);
const [status, setStatus] = useState(null);
const [catalog, setCatalog] = useState(EMPTY_CATALOG);
+ // The SHARED scheduled-task catalog, grouped for the picker. It comes from the
+ // same two endpoints CoS → Schedule and System Tasks render, so a burn step can
+ // only ever point at work that exists there — the whole reason this page no
+ // longer has an automation editor of its own.
+ const [taskGroups, setTaskGroups] = useState([]);
const [loading, setLoading] = useState(true);
// Distinct from `loading`: a manual re-read is reported ON the button that
// asked for it, never by replacing the page with a spinner.
@@ -93,11 +102,10 @@ export default function QuotaBurn() {
// it has no plan" — one is retryable and names a cause, the other doesn't.
const [loadError, setLoadError] = useState(null);
// Same `null` = never failed / string = the cause convention as `loadError`,
- // for the SECOND read this page makes. The catalog fetch used to be swallowed
- // outright, which is what left the preset picker missing, "Add job" disabled,
- // and every job row's dropdown empty with nothing on screen saying why — and
- // editing a step against an empty job-type list submits `jobType: ""`, which
- // the strict PUT schema 400s into a stalled save.
+ // for the catalog reads. They used to be swallowed outright, which is what left
+ // every picker on the page empty with nothing on screen saying why — and a step
+ // saved against an empty catalog carries a reference to nothing, which the
+ // strict PUT schema 400s into a stalled save.
const [catalogError, setCatalogError] = useState(null);
// Reported ON the retry button, like `refreshing` — the plan stays rendered.
const [catalogRetrying, setCatalogRetrying] = useState(false);
@@ -184,26 +192,37 @@ export default function QuotaBurn() {
if (editSeqRef.current === seq && !pendingRef.current && !savingRef.current) setConfig(data.config);
}, []);
- // The catalog is the page's second read and fails independently of the plan:
- // the plan can render perfectly while every choice the form offers is empty.
- // `silent: true` for the same reason as `load` — the failure is rendered by
- // the family card's own banner, not the request helper's toast.
+ // Everything the pickers offer, in one pass: the burn's own catalog (apps +
+ // providers) plus the SHARED scheduled-task catalog the steps reference.
const loadCatalog = useCallback(async () => {
- let failure = null;
- const data = await api.getQuotaBurnCatalog({ silent: true })
- .catch((err) => {
- failure = err?.message || 'The request failed.';
- return READ_FAILED;
- });
- if (data === READ_FAILED) {
- setCatalogError(failure);
- return;
- }
- const next = normalizeCatalog(data);
+ const failures = [];
+ const read = (promise) => promise.catch((err) => {
+ failures.push(err?.message || 'The request failed.');
+ return READ_FAILED;
+ });
+ // Three independent reads, all failing independently of the plan: the plan
+ // renders perfectly while every choice the form offers is empty. `silent`
+ // for the same reason as `load` — the failure is rendered by the family
+ // card's own banner, not the request helper's toast.
+ const [burnCatalog, schedule, jobs] = await Promise.all([
+ read(api.getQuotaBurnCatalog({ silent: true })),
+ read(api.getCosSchedule({ silent: true })),
+ read(api.getCosJobs({ silent: true })),
+ ]);
+ const next = normalizeCatalog(burnCatalog === READ_FAILED ? null : burnCatalog);
setCatalog(next);
- // A 200 carrying no job types is a different failure with the same symptom
- // — say so rather than reporting success into an empty form.
- setCatalogError(next.jobTypes.length ? null : 'The server returned no job types.');
+ const groups = buildQuotaBurnTaskCatalog({
+ schedule: schedule === READ_FAILED ? null : schedule,
+ jobs: jobs === READ_FAILED ? [] : (jobs?.jobs || []),
+ apps: next.apps,
+ });
+ setTaskGroups(groups);
+ // A 200 carrying no scheduled task a burn may invoke is a different failure
+ // with the same symptom — say so rather than reporting success into an empty
+ // picker.
+ setCatalogError(failures.length
+ ? failures.join(' ')
+ : flattenTaskCatalog(groups).length ? null : 'The server returned no scheduled tasks a burn can run.');
}, []);
useEffect(() => {
@@ -505,10 +524,10 @@ export default function QuotaBurn() {
</div>
<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 reset
- horizon, 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. 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.
+ horizon, above its reserve, and under its dispatch cap (unlimited by default) runs the first step in its plan that has work waiting — one step
+ per family per cycle. Each step runs an existing scheduled task; removing a step never deletes that task. 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">
@@ -525,6 +544,7 @@ export default function QuotaBurn() {
config={family}
status={(status?.families || []).find((row) => row.id === familyId)}
catalog={catalog}
+ taskGroups={taskGroups}
catalogError={catalogError}
catalogRetrying={catalogRetrying}
onRetryCatalog={retryCatalog}
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index b43c59aed0..fd49ddb75e 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -7,6 +7,14 @@ import QuotaBurn, { PENDING_POLL_MS, SAVE_DEBOUNCE_MS } from './QuotaBurn';
vi.mock('../services/api', () => ({
getQuotaBurn: vi.fn(),
getQuotaBurnCatalog: vi.fn(),
+ // The SHARED scheduled-task catalogs a burn step references. Mocked here (and
+ // asserted as never WRITTEN to below) because the whole point of the reference
+ // model is that this page reads that catalog and never edits it.
+ getCosSchedule: vi.fn(),
+ getCosJobs: vi.fn(),
+ updateCosTaskInterval: vi.fn(),
+ updateCosJob: vi.fn(),
+ deleteCosJob: vi.fn(),
saveQuotaBurn: vi.fn(),
runQuotaBurn: vi.fn(),
rearmQuotaBurn: vi.fn(),
@@ -25,6 +33,27 @@ vi.mock('../components/ui/Toast', () => {
import * as api from '../services/api';
+const NO_OVERRIDES = { providerId: null, model: null, effort: null, params: {} };
+
+// One burn step, in the shape the GET actually hands the page: a reference plus
+// an overrides bag, with the server's compat mirrors alongside — the editor must
+// send the bag and DROP the mirrors, which resolve by presence.
+const step = (overrides = {}) => ({
+ id: 'j1',
+ enabled: true,
+ label: 'Bible images',
+ taskRef: { kind: 'builtin', taskType: 'universe-bible-images', appId: null },
+ jobType: null,
+ runOnce: false,
+ unavailable: null,
+ overrides: { ...NO_OVERRIDES },
+ model: null,
+ providerId: null,
+ effort: null,
+ params: {},
+ ...overrides,
+});
+
const config = {
enabled: false,
checkIntervalMinutes: 30,
@@ -32,7 +61,7 @@ const config = {
grok: {
enabled: true, resetWithinHours: 24, reservePercent: 10,
maxDispatchesPerWindow: 5, priority: 0,
- jobs: [{ id: 'j1', enabled: true, label: 'Bible images', jobType: 'universe-bible-images', model: null, providerId: null, params: {} }],
+ jobs: [step()],
},
codex: { enabled: false, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0, jobs: [] },
},
@@ -47,33 +76,36 @@ const status = {
runs: [{ at: new Date().toISOString(), trigger: 'scheduled', dispatched: false, reason: 'no burnable window' }],
};
-const catalog = {
- families: ['grok', 'codex'],
- jobTypes: [
- { id: 'universe-bible-images', label: 'Universe bible images', description: 'Render missing bible images.', params: [{ key: 'universeId', kind: 'universe', label: 'Universe', default: 'all' }] },
- {
- id: 'agent-prompt',
- label: 'Agent prompt',
- description: 'Queue a CoS agent.',
- params: [
- { key: 'appId', kind: 'app', label: 'Managed app', required: true },
- { key: 'prompt', kind: 'text', label: 'Work prompt', required: true },
- { key: 'openPR', kind: 'boolean', label: 'Open a PR', default: true },
- ],
+// `GET /api/cos/schedule`, trimmed to the fields the picker reads. `ux` acts on
+// one managed app, `universe-bible-images` is programmatic, `repo-sync` sweeps
+// install-wide — the three target shapes the server's schema distinguishes.
+const schedule = {
+ tasks: {
+ ux: {
+ enabled: true,
+ description: 'Audit the interface and file issues.',
+ appOverrides: { a1: { enabled: true }, a2: { enabled: false } },
+ providerId: null,
+ model: null,
+ taskMetadata: { useWorktree: false, openPR: false },
+ fileIssuesCapable: true,
+ defaultFileIssues: true,
},
- ],
- presets: [{
- id: 'ux-audit',
- label: 'UX issues',
- summary: 'Audit the UI and file issues.',
- jobType: 'agent-prompt',
- // Mirrors the real audit posture in server/lib/quotaBurnPresets.js: no
- // worktree (it writes nothing), no code output, nothing to ship.
- params: { prompt: 'Audit the UI. File issues. Change no code.', useWorktree: false, noCodeOutput: true, openPR: false, simplify: false },
- }],
- apps: [{ id: 'a1', name: 'App One' }],
- universes: [{ id: 'u1', name: 'Example Universe' }],
- imageModes: ['codex', 'grok'],
+ 'universe-bible-images': {
+ enabled: true, programmatic: true, appOverrides: {}, taskMetadata: { scope: 'all', maxEntries: 10 },
+ },
+ 'repo-sync': { enabled: true, installWide: true, appOverrides: {} },
+ 'shell-only': { enabled: true, appOverrides: {}, invocation: { userInvokable: false } },
+ },
+};
+
+const cosJobs = { jobs: [{ id: 'job-a', name: 'Nightly changelog', appId: 'a1', enabled: true, type: 'agent' }] };
+
+// What the burn's own catalog endpoint still supplies: target apps and the
+// providers a per-invocation pin may name.
+const catalog = {
+ apps: [{ id: 'a1', name: 'App One' }, { id: 'a2', name: 'App Two' }],
+ providers: [],
};
const renderPage = (path = '/devtools/quota-burn') => render(
@@ -87,6 +119,7 @@ const renderPage = (path = '/devtools/quota-burn') => render(
const setupSaveUser = () => userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
const flushSave = () => act(async () => { await vi.advanceTimersByTimeAsync(SAVE_DEBOUNCE_MS); });
+
// Past the debounce/poll window rather than up to its edge, so a "did not
// happen" assertion runs AFTER the moment the thing would have happened.
const pastSaveWindow = () => act(async () => { await vi.advanceTimersByTimeAsync(SAVE_DEBOUNCE_MS + 100); });
@@ -101,6 +134,8 @@ beforeEach(() => {
globalThis.sessionStorage.clear();
api.getQuotaBurn.mockResolvedValue({ config, status });
api.getQuotaBurnCatalog.mockResolvedValue(catalog);
+ api.getCosSchedule.mockResolvedValue(schedule);
+ api.getCosJobs.mockResolvedValue(cosJobs);
api.saveQuotaBurn.mockResolvedValue({ config });
api.runQuotaBurn.mockResolvedValue({ result: { dispatched: false, reason: 'nothing to burn' } });
api.rearmQuotaBurn.mockResolvedValue({ config, status });
@@ -284,84 +319,167 @@ describe('QuotaBurn page', () => {
));
});
- it('adds a fully-configured job from a preset, inheriting the plan\'s app', async () => {
+ it('offers the SHARED scheduled-task catalog, grouped, and filters it as you type', async () => {
+ // The picker is a view over the same two catalogs CoS → Schedule and System
+ // Tasks render — not a second automation catalog of this page's own.
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ const picker = await screen.findByLabelText('Add a step');
+ const groups = Array.from(picker.querySelectorAll('optgroup')).map((group) => group.label);
+ expect(groups).toEqual(['PortOS scheduled tasks', 'App custom tasks']);
+ expect(Array.from(picker.querySelectorAll('option')).map((option) => option.value))
+ // `shell-only` is not user-invokable, so a burn can never run it.
+ .toEqual(['', 'builtin:repo-sync', 'builtin:universe-bible-images', 'builtin:ux', 'custom:job-a']);
+
+ await user.type(screen.getAllByLabelText('Search tasks')[0], 'changelog');
+ expect(Array.from(picker.querySelectorAll('option')).map((option) => option.value))
+ .toEqual(['', 'custom:job-a']);
+ });
+
+ it('adds a step that REFERENCES the picked task, targeting the app the plan already uses', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
const user = setupSaveUser();
renderPage('/devtools/quota-burn/grok');
- await user.selectOptions(await screen.findByLabelText(/Add a preset job/), 'ux-audit');
+ await user.selectOptions(await screen.findByLabelText('Add a step'), 'builtin:ux');
await flushSave();
- expect(api.saveQuotaBurn).toHaveBeenCalled();
const [patch] = api.saveQuotaBurn.mock.calls.at(-1);
const added = patch.families.grok.jobs.at(-1);
- expect(added.jobType).toBe('agent-prompt');
- expect(added.label).toBe('UX issues');
- expect(added.params.prompt).toContain('File issues');
- // Read-only audit work: it reads the app's checkout in place (no worktree —
- // worktree + no PR is the auto-merge posture), delivers by filing issues,
- // and has no diff to open a PR for or run /simplify against.
- expect(added.params.useWorktree).toBe(false);
- expect(added.params.noCodeOutput).toBe(true);
- expect(added.params.openPR).toBe(false);
+ // A reference, not a copied prompt — and no free-text work of its own.
+ expect(added.taskRef).toEqual({ kind: 'builtin', taskType: 'ux', appId: 'a1' });
+ expect(added).not.toHaveProperty('jobType');
+ expect(added.overrides).toEqual(NO_OVERRIDES);
});
- it('asks before a preset overwrites a work prompt the user already wrote', async () => {
+ it('never sends an appId for a task the server would reject one on', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const user = setupSaveUser();
+ renderPage('/devtools/quota-burn/grok');
+ await user.selectOptions(await screen.findByLabelText('Add a step'), 'builtin:repo-sync');
+ // …and it says so on the row instead of leaving an empty target picker.
+ // Asserted before the save round-trips: the mocked PUT answers with the
+ // pre-existing plan, which is what the page then adopts.
+ expect(await screen.findByText(/Runs install-wide/)).toBeInTheDocument();
+ expect(screen.queryByLabelText('Target app')).not.toBeInTheDocument();
+ await flushSave();
+ const [patch] = api.saveQuotaBurn.mock.calls.at(-1);
+ expect(patch.families.grok.jobs.at(-1).taskRef).toEqual({ kind: 'builtin', taskType: 'repo-sync', appId: null });
+ });
+
+ it('offers a target only for a task that acts on one app, limited to the apps that enabled it', async () => {
const user = userEvent.setup();
+ const uxConfig = {
+ ...config,
+ families: { ...config.families, grok: { ...config.families.grok, jobs: [step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'a1' } })] } },
+ };
+ api.getQuotaBurn.mockResolvedValue({ config: uxConfig, status });
renderPage('/devtools/quota-burn/grok');
await user.click(await screen.findByLabelText('Expand step 1'));
- await user.selectOptions(await screen.findByLabelText('Job type'), 'agent-prompt');
- const promptBox = screen.getByLabelText('Work prompt');
- await user.type(promptBox, 'my own prompt');
- await user.selectOptions(screen.getByLabelText(/Start from a preset/), 'ux-audit');
-
- // Held, not applied — the typed prompt is still on screen behind a confirm.
- expect(promptBox).toHaveValue('my own prompt');
- await user.click(screen.getByRole('button', { name: 'Keep mine' }));
- expect(promptBox).toHaveValue('my own prompt');
-
- await user.selectOptions(screen.getByLabelText(/Start from a preset/), 'ux-audit');
- await user.click(screen.getByRole('button', { name: 'Replace' }));
- expect(promptBox).toHaveValue('Audit the UI. File issues. Change no code.');
+ const target = await screen.findByLabelText('Target app');
+ expect(target).toHaveValue('a1');
+ // App Two's override is OFF, and the server reports `wrong-scope` for it —
+ // offering it would be offering a target the step can never run against.
+ expect(Array.from(target.querySelectorAll('option')).map((option) => option.textContent))
+ .toEqual(['Select an app…', 'App One']);
});
- it('shows which preset a step currently matches, and drops it once the prompt is edited', async () => {
- // The picker used to snap straight back to "Choose a preset…", so applying
- // one looked like a no-op — its only visible effect was a textarea further
- // down the row. The selection is DERIVED from the prompt text (nothing on
- // disk records a preset id), so it stays honest across an edit.
- const user = userEvent.setup();
+ it('shows the EFFECTIVE settings and audit mode, and saves an override without touching the task', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const user = setupSaveUser();
+ const uxConfig = {
+ ...config,
+ families: { ...config.families, grok: { ...config.families.grok, jobs: [step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'a1' } })] } },
+ };
+ api.getQuotaBurn.mockResolvedValue({ config: uxConfig, status });
renderPage('/devtools/quota-burn/grok');
await user.click(await screen.findByLabelText('Expand step 1'));
- await user.selectOptions(await screen.findByLabelText('Job type'), 'agent-prompt');
- const picker = screen.getByLabelText(/Start from a preset/);
- expect(picker).toHaveValue('');
-
- await user.selectOptions(picker, 'ux-audit');
- expect(screen.getByLabelText('Work prompt')).toHaveValue('Audit the UI. File issues. Change no code.');
- expect(picker).toHaveValue('ux-audit');
-
- // Edited away from the preset ⇒ the row no longer IS that preset, and the
- // control must stop claiming it is.
- await user.type(screen.getByLabelText('Work prompt'), ' plus my own note');
- expect(picker).toHaveValue('');
+
+ // Inherited from the task's saved settings: `defaultFileIssues: true`.
+ expect(await screen.findByText(/files issues, changes no code/)).toBeInTheDocument();
+ const mode = screen.getByLabelText('Audit mode');
+ expect(mode).toHaveValue('');
+ expect(mode.querySelector('option').textContent).toContain('Inherit (file issues only)');
+
+ await user.selectOptions(mode, 'false');
+ // The effective line follows the override immediately, before the save lands.
+ expect(await screen.findByText(/does the work/)).toBeInTheDocument();
+ await flushSave();
+ const [patch] = api.saveQuotaBurn.mock.calls.at(-1);
+ expect(patch.families.grok.jobs[0].overrides.params).toEqual({ fileIssues: false });
+ // The referenced task is never written to — that is the whole reference model.
+ expect(api.updateCosTaskInterval).not.toHaveBeenCalled();
+ expect(api.updateCosJob).not.toHaveBeenCalled();
});
- it('keeps the work prompt when the job type picker is clicked through', async () => {
- // Params are carried across a type switch: resetting them destroyed a long
- // hand-written prompt with no confirmation and no undo.
+ it('links out to view / edit / create the source scheduled task instead of editing it here', async () => {
const user = userEvent.setup();
renderPage('/devtools/quota-burn/grok');
- await user.click(await screen.findByLabelText('Expand step 1'));
- await user.selectOptions(await screen.findByLabelText('Job type'), 'agent-prompt');
- await user.type(screen.getByLabelText('Work prompt'), 'keep me');
- await user.selectOptions(screen.getByLabelText('Job type'), 'universe-bible-images');
- await user.selectOptions(screen.getByLabelText('Job type'), 'agent-prompt');
- expect(screen.getByLabelText('Work prompt')).toHaveValue('keep me');
+ // Creating new work is a link out, on the family card, next to the picker.
+ expect(await screen.findByRole('link', { name: /Create an on-demand scheduled task/ }))
+ .toHaveAttribute('href', '/cos/jobs');
+ await user.click(screen.getByLabelText('Expand step 1'));
+ expect(screen.getByRole('link', { name: /View \/ edit the task/ }))
+ .toHaveAttribute('href', '/cos/schedule?task=universe-bible-images');
+ });
+
+ it('renders a stale reference with its reason and NO run affordance', async () => {
+ // The server stamps availability from the live catalog on every read: a step
+ // whose task was deleted keeps its place in the plan and says why it cannot
+ // run — offering a ▶ that can only produce a decline toast is worse.
+ const stale = {
+ ...config,
+ families: {
+ ...config.families,
+ grok: {
+ ...config.families.grok,
+ jobs: [step({
+ taskRef: { kind: 'builtin', taskType: 'deleted-task', appId: null },
+ unavailable: { code: 'unknown-task', reason: 'scheduled task "deleted-task" is not available on this install' },
+ })],
+ },
+ },
+ };
+ api.getQuotaBurn.mockResolvedValue({ config: stale, status });
+ renderPage('/devtools/quota-burn/grok');
+ expect(await screen.findByText(/scheduled task "deleted-task" is not available on this install/)).toBeInTheDocument();
+ expect(screen.queryByLabelText('Run step 1 now')).not.toBeInTheDocument();
+ // It is still editable — the picker is right there to re-point it.
+ expect(screen.getByLabelText('Remove step 1')).toBeInTheDocument();
+ });
+
+ it('gates Run Now on the SAVED plan, not the form input', async () => {
+ // Every run control reads server-side config, so a run fired between the
+ // keystroke and the PUT would burn with the previous settings.
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const user = setupSaveUser();
+ renderPage('/devtools/quota-burn/grok');
+ await user.click(await screen.findByLabelText('Name for step 1'));
+ await user.keyboard('!');
+ expect(screen.getByLabelText('Run step 1 now')).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Evaluate now' })).toBeDisabled();
+ await flushSave();
+ await waitFor(() => expect(screen.getByLabelText('Run step 1 now')).toBeEnabled());
+ });
+
+ it('removes a burn step without deleting the scheduled task it referenced', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ const user = setupSaveUser();
+ renderPage('/devtools/quota-burn/grok');
+ await user.click(await screen.findByLabelText('Remove step 1'));
+ await user.click(screen.getByRole('button', { name: 'Remove' }));
+ await flushSave();
+ // The ONLY call is the plan PUT with the step gone.
+ const [patch] = api.saveQuotaBurn.mock.calls.at(-1);
+ expect(patch.families.grok.jobs).toEqual([]);
+ expect(api.deleteCosJob).not.toHaveBeenCalled();
+ expect(api.updateCosJob).not.toHaveBeenCalled();
+ expect(api.updateCosTaskInterval).not.toHaveBeenCalled();
});
- it('never persists a status field alongside the job config', async () => {
+ it('never persists a status field, or an override mirror, alongside the step', async () => {
// Pending counts live on the STATUS side and reach JobRow as their own prop.
- // If they were merged into the job objects they would have to be stripped
- // back off before every save — the PUT schema is strict and would 400.
+ // The top-level `model`/`params` mirrors are the subtler one: the server
+ // resolves them by PRESENCE, so echoing them back would let a stale mirror
+ // outrank the overrides bag the editor writes.
vi.useFakeTimers({ shouldAdvanceTime: true });
const user = setupSaveUser();
renderPage('/devtools/quota-burn/grok');
@@ -370,8 +488,10 @@ describe('QuotaBurn page', () => {
await flushSave();
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');
+ const saved = patch.families.grok.jobs[0];
+ for (const key of ['pending', 'ranAt', 'model', 'providerId', 'effort', 'params']) {
+ expect(saved).not.toHaveProperty(key);
+ }
});
});
@@ -441,46 +561,45 @@ describe('QuotaBurn run-once steps', () => {
});
/**
- * The catalog is the page's second read, and it fails independently of the
- * plan: the plan renders perfectly while every choice the form offers is empty.
- * Swallowing that failure left the preset picker gone, "Add job" disabled, and
- * every dropdown blank with nothing saying why — and editing a step against an
- * empty job-type list saves `jobType: ""`, which the strict PUT rejects.
+ * The catalog reads fail independently of the plan: the plan renders perfectly
+ * while every choice the pickers offer is empty. Swallowing that left the task
+ * picker with nothing in it and nothing on screen saying why — and a step saved
+ * against an empty catalog references nothing, which the strict PUT rejects.
*/
describe('QuotaBurn catalog failure', () => {
it('names a failed catalog read instead of silently emptying the form', async () => {
- api.getQuotaBurnCatalog.mockRejectedValueOnce(new Error('Catalog request failed'));
+ api.getCosSchedule.mockRejectedValueOnce(new Error('Schedule request failed'));
+ api.getCosJobs.mockRejectedValueOnce(new Error('Jobs request failed'));
renderPage('/devtools/quota-burn/grok');
expect(await screen.findByText('Job choices could not be loaded')).toBeInTheDocument();
- expect(screen.getByText(/Catalog request failed/)).toBeInTheDocument();
- // The controls the catalog feeds are gone or inert — the banner is the only
- // thing on screen that explains either.
- expect(screen.queryByLabelText(/Add a preset job/)).not.toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Add job/ })).toBeDisabled();
+ expect(screen.getByText(/Schedule request failed/)).toBeInTheDocument();
+ // The picker is inert rather than silently empty.
+ expect(screen.getByLabelText('Add a step')).toBeDisabled();
// The plan itself still rendered: a catalog failure is not a page failure.
expect(screen.getByText(/62% left/)).toBeInTheDocument();
});
it('re-fetches the catalog from the banner without a page reload', async () => {
const user = userEvent.setup();
- api.getQuotaBurnCatalog.mockRejectedValueOnce(new Error('Catalog request failed'));
+ api.getCosSchedule.mockRejectedValueOnce(new Error('Schedule request failed'));
renderPage('/devtools/quota-burn/grok');
await user.click(await screen.findByRole('button', { name: 'Retry catalog load' }));
- await waitFor(() => expect(api.getQuotaBurnCatalog).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(api.getCosSchedule).toHaveBeenCalledTimes(2));
// The success clears the banner AND restores the controls it was standing in for.
await waitFor(() => expect(screen.queryByText('Job choices could not be loaded')).not.toBeInTheDocument());
- expect(screen.getByLabelText(/Add a preset job/)).toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Add job/ })).toBeEnabled();
+ expect(screen.getByLabelText('Add a step')).toBeEnabled();
});
- it('treats a catalog that answered with no job types as its own failure', async () => {
- // Same symptom as a thrown read — every dropdown empty — but a different
- // cause, so it must not be reported as a successful load.
- api.getQuotaBurnCatalog.mockResolvedValueOnce({ ...catalog, jobTypes: [] });
+ it('treats a catalog with no burn-invokable task as its own failure', async () => {
+ // Same symptom as a thrown read — an empty picker — but a different cause,
+ // so it must not be reported as a successful load. Every task here is
+ // ineligible or a shell job.
+ api.getCosSchedule.mockResolvedValueOnce({ tasks: { hidden: { enabled: true, invocation: { userInvokable: false } } } });
+ api.getCosJobs.mockResolvedValueOnce({ jobs: [{ id: 'sh', name: 'Sweep', type: 'shell', enabled: true }] });
renderPage('/devtools/quota-burn/grok');
- expect(await screen.findByText(/The server returned no job types\./)).toBeInTheDocument();
+ expect(await screen.findByText(/The server returned no scheduled tasks a burn can run\./)).toBeInTheDocument();
});
it('survives a partial catalog payload whose lists are null', async () => {
@@ -488,16 +607,18 @@ describe('QuotaBurn catalog failure', () => {
// consumer reads `.length` on these lists — so an older peer or a partial
// response would take the whole page down with a TypeError instead of
// reporting an unusable catalog.
- api.getQuotaBurnCatalog.mockResolvedValueOnce({ jobTypes: null, apps: null, universes: null, imageModes: null });
+ api.getQuotaBurnCatalog.mockResolvedValueOnce({ apps: null, providers: null });
+ api.getCosSchedule.mockResolvedValueOnce({ tasks: null });
+ api.getCosJobs.mockResolvedValueOnce({ jobs: null });
renderPage('/devtools/quota-burn/grok');
- expect(await screen.findByText(/The server returned no job types\./)).toBeInTheDocument();
+ expect(await screen.findByText(/The server returned no scheduled tasks a burn can run\./)).toBeInTheDocument();
expect(screen.getByText(/62% left/)).toBeInTheDocument();
});
it('announces the banner to assistive tech rather than only drawing it', async () => {
// It appears after the card is already on screen — the read resolves late,
// and a retry can put it back — so nothing announces it without a live region.
- api.getQuotaBurnCatalog.mockRejectedValueOnce(new Error('Catalog request failed'));
+ api.getCosSchedule.mockRejectedValueOnce(new Error('Schedule request failed'));
renderPage('/devtools/quota-burn/grok');
// Scope to the banner's own text: the first-paint PageSkeleton is also a
// `status` region, so a bare role query would race it.
@@ -508,7 +629,7 @@ describe('QuotaBurn catalog failure', () => {
it('says nothing about the catalog when it loaded', async () => {
renderPage('/devtools/quota-burn/grok');
- await screen.findByLabelText(/Add a preset job/);
+ await screen.findByLabelText('Add a step');
expect(screen.queryByText('Job choices could not be loaded')).not.toBeInTheDocument();
});
});
@@ -846,220 +967,143 @@ describe('QuotaBurn save races', () => {
});
});
-describe('QuotaBurn collapsible jobs', () => {
- it('renders configured jobs in a collapsed state by default with summary details', async () => {
+describe('QuotaBurn collapsible steps', () => {
+ it('renders configured steps collapsed, summarising the task they reference', async () => {
renderPage('/devtools/quota-burn/grok');
expect(await screen.findByDisplayValue('Bible images')).toBeInTheDocument();
- // Compact summary badge shows job type
- expect(screen.getByText(/Universe bible images/)).toBeInTheDocument();
+ // The picker's own <option> carries the same text, so pick the summary span.
+ expect(screen.getAllByText('universe-bible-images').find((node) => node.tagName === 'SPAN')).toBeTruthy();
// Inner fields are collapsed
- expect(screen.queryByLabelText('Job type')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Scheduled task')).not.toBeInTheDocument();
expect(screen.getByLabelText('Expand step 1')).toBeInTheDocument();
});
- it('expands and collapses a single job using its chevron toggle', async () => {
+ it('expands and collapses a single step using its chevron toggle', async () => {
const user = userEvent.setup();
renderPage('/devtools/quota-burn/grok');
- const toggle = await screen.findByLabelText('Expand step 1');
- await user.click(toggle);
+ await user.click(await screen.findByLabelText('Expand step 1'));
- // Now expanded: shows inner fields
- expect(await screen.findByLabelText('Job type')).toBeInTheDocument();
+ expect(await screen.findByLabelText('Scheduled task')).toBeInTheDocument();
expect(screen.getByLabelText('Collapse step 1')).toBeInTheDocument();
- // Click again to collapse
await user.click(screen.getByLabelText('Collapse step 1'));
- expect(screen.queryByLabelText('Job type')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Scheduled task')).not.toBeInTheDocument();
expect(screen.getByLabelText('Expand step 1')).toBeInTheDocument();
});
- it('expands all and collapses all jobs via header control', async () => {
- const twoJobConfig = {
+ it('expands all and collapses all steps via the header control', async () => {
+ const twoStepConfig = {
...config,
families: {
...config.families,
grok: {
...config.families.grok,
- jobs: [
- { id: 'j1', enabled: true, label: 'Job 1', jobType: 'universe-bible-images', params: {} },
- { id: 'j2', enabled: true, label: 'Job 2', jobType: 'agent-prompt', params: {} },
- ],
+ jobs: [step(), step({ id: 'j2', label: 'UX audit', taskRef: { kind: 'builtin', taskType: 'ux', appId: 'a1' } })],
},
},
};
- api.getQuotaBurn.mockResolvedValue({ config: twoJobConfig, status });
+ api.getQuotaBurn.mockResolvedValue({ config: twoStepConfig, status });
const user = userEvent.setup();
renderPage('/devtools/quota-burn/grok');
expect(await screen.findByRole('button', { name: /Expand all/i })).toBeInTheDocument();
expect(screen.queryByLabelText('Collapse step 1')).not.toBeInTheDocument();
- expect(screen.queryByLabelText('Collapse step 2')).not.toBeInTheDocument();
- // Expand all
await user.click(screen.getByRole('button', { name: /Expand all/i }));
expect(screen.getByLabelText('Collapse step 1')).toBeInTheDocument();
expect(screen.getByLabelText('Collapse step 2')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Collapse all/i })).toBeInTheDocument();
- // Collapse all
await user.click(screen.getByRole('button', { name: /Collapse all/i }));
expect(screen.queryByLabelText('Collapse step 1')).not.toBeInTheDocument();
expect(screen.queryByLabelText('Collapse step 2')).not.toBeInTheDocument();
- expect(screen.getByRole('button', { name: /Expand all/i })).toBeInTheDocument();
});
- it('automatically expands newly added jobs for editing', async () => {
+ it('automatically expands a newly added step for editing', async () => {
const user = userEvent.setup();
renderPage('/devtools/quota-burn/grok');
- await user.click(await screen.findByRole('button', { name: /Add job/i }));
+ await user.selectOptions(await screen.findByLabelText('Add a step'), 'builtin:ux');
expect(await screen.findByLabelText('Collapse step 2')).toBeInTheDocument();
});
});
-describe('QuotaBurn preset addition filtering', () => {
- const multiPresetCatalog = {
+describe('QuotaBurn per-invocation overrides', () => {
+ const claudeProviders = {
...catalog,
- presets: [
- { id: 'ux-audit', label: 'UX issues', summary: 'Audit UI.', jobType: 'agent-prompt', params: { prompt: 'Prompt 1' } },
- { id: 'a11y-audit', label: 'A11y issues', summary: 'Audit A11y.', jobType: 'agent-prompt', params: { prompt: 'Prompt 2' } },
- ],
+ providers: [{
+ id: 'claude-code',
+ name: 'Claude Code',
+ type: 'tui',
+ command: 'claude',
+ models: [{ id: 'claude-sonnet-4', name: 'Claude Sonnet 4' }, { id: 'claude-opus-4', name: 'Claude Opus 4' }],
+ }],
};
-
- it('filters preset addition dropdown to only presets not already in the family', async () => {
- const grokWithUx = {
- ...config,
- families: {
- ...config.families,
- grok: {
- ...config.families.grok,
- jobs: [
- { id: 'j1', enabled: true, label: 'UX issues', jobType: 'agent-prompt', params: { prompt: 'Prompt 1' } },
- ],
- },
- },
- };
- api.getQuotaBurn.mockResolvedValue({ config: grokWithUx, status });
- api.getQuotaBurnCatalog.mockResolvedValue(multiPresetCatalog);
-
- renderPage('/devtools/quota-burn/grok');
- const select = await screen.findByLabelText(/Add a preset job/);
- const options = Array.from(select.querySelectorAll('option')).map((o) => o.value);
-
- // 'ux-audit' is already in the list, so only '' (placeholder) and 'a11y-audit' should be available
- expect(options).toEqual(['', 'a11y-audit']);
- });
-
- it('hides preset addition picker when all catalog presets are in the jobs list', async () => {
- const grokWithAll = {
- ...config,
- families: {
- ...config.families,
- grok: {
- ...config.families.grok,
- jobs: [
- { id: 'j1', enabled: true, label: 'UX issues', jobType: 'agent-prompt', params: { prompt: 'Prompt 1' } },
- { id: 'j2', enabled: true, label: 'A11y issues', jobType: 'agent-prompt', params: { prompt: 'Prompt 2' } },
- ],
- },
+ const claudeConfig = (overrides) => ({
+ ...config,
+ families: {
+ ...config.families,
+ claude: {
+ enabled: true, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0,
+ jobs: [step({ id: 'j1', label: 'Audit UI', taskRef: { kind: 'builtin', taskType: 'ux', appId: 'a1' }, overrides })],
},
- };
- api.getQuotaBurn.mockResolvedValue({ config: grokWithAll, status });
- api.getQuotaBurnCatalog.mockResolvedValue(multiPresetCatalog);
-
- renderPage('/devtools/quota-burn/grok');
- expect(await screen.findByDisplayValue('UX issues')).toBeInTheDocument();
- expect(screen.queryByLabelText(/Add a preset job/)).not.toBeInTheDocument();
+ },
});
- it('renders standard model select and effort picker for effort-capable providers', async () => {
- const claudeProviderCatalog = {
- ...catalog,
- providers: [
- {
- id: 'claude-code',
- name: 'Claude Code',
- type: 'tui',
- command: 'claude',
- models: [{ id: 'claude-sonnet-4', name: 'Claude Sonnet 4' }, { id: 'claude-opus-4', name: 'Claude Opus 4' }],
- },
- ],
- };
- const claudeConfig = {
- ...config,
- families: {
- ...config.families,
- claude: {
- enabled: true,
- resetWithinHours: 24,
- reservePercent: 0,
- maxDispatchesPerWindow: 5,
- priority: 0,
- jobs: [
- { id: 'j1', enabled: true, label: 'Audit UI', jobType: 'agent-prompt', model: 'claude-sonnet-4', effort: 'high', params: { appId: 'a1', prompt: 'audit' } },
- ],
- },
- },
- };
- api.getQuotaBurn.mockResolvedValue({ config: claudeConfig, status });
- api.getQuotaBurnCatalog.mockResolvedValue(claudeProviderCatalog);
+ it('pins model and effort into the overrides bag, never the top-level mirrors', async () => {
+ api.getQuotaBurn.mockResolvedValue({ config: claudeConfig({ ...NO_OVERRIDES, model: 'claude-sonnet-4', effort: 'high' }), status });
+ api.getQuotaBurnCatalog.mockResolvedValue(claudeProviders);
vi.useFakeTimers({ shouldAdvanceTime: true });
const user = setupSaveUser();
renderPage('/devtools/quota-burn/claude');
await user.click(await screen.findByLabelText('Expand step 1'));
- const modelSelect = await screen.findByLabelText('Model (optional)');
- expect(modelSelect).toBeInTheDocument();
- expect(modelSelect.tagName).toBe('SELECT');
- expect(modelSelect).toHaveValue('claude-sonnet-4');
-
+ expect(await screen.findByLabelText('Model')).toHaveValue('claude-sonnet-4');
const effortSelect = screen.getByLabelText('Thinking effort');
- expect(effortSelect).toBeInTheDocument();
- expect(effortSelect.tagName).toBe('SELECT');
expect(effortSelect).toHaveValue('high');
- // Change effort to medium and verify auto-save
await user.selectOptions(effortSelect, 'medium');
await flushSave();
- expect(api.saveQuotaBurn).toHaveBeenCalledWith(
- expect.objectContaining({
- families: expect.objectContaining({
- claude: expect.objectContaining({
- jobs: [
- expect.objectContaining({
- id: 'j1',
- model: 'claude-sonnet-4',
- effort: 'medium',
- }),
- ],
- }),
- }),
- }),
- expect.anything(),
- );
+ const [patch] = api.saveQuotaBurn.mock.calls.at(-1);
+ const saved = patch.families.claude.jobs[0];
+ expect(saved.overrides).toMatchObject({ model: 'claude-sonnet-4', effort: 'medium' });
+ expect(saved).not.toHaveProperty('effort');
});
- it('displays model and effort in collapsed step summary badge', async () => {
- const claudeConfig = {
- ...config,
- families: {
- ...config.families,
- claude: {
- enabled: true,
- resetWithinHours: 24,
- reservePercent: 0,
- maxDispatchesPerWindow: 5,
- priority: 0,
- jobs: [
- { id: 'j1', enabled: true, label: '', jobType: 'agent-prompt', model: 'claude-sonnet-4', effort: 'high', params: { appId: 'a1', prompt: 'audit' } },
- ],
- },
- },
- };
- api.getQuotaBurn.mockResolvedValue({ config: claudeConfig, status });
- api.getQuotaBurnCatalog.mockResolvedValue(catalog);
+ it('names what an unset override inherits rather than showing an empty box', async () => {
+ // Presence, not truthiness: an unset override INHERITS the task's saved
+ // setting, and the control has to say which value that is.
+ api.getQuotaBurn.mockResolvedValue({ config: claudeConfig(NO_OVERRIDES), status });
+ api.getQuotaBurnCatalog.mockResolvedValue({
+ ...claudeProviders,
+ });
+ api.getCosSchedule.mockResolvedValue({
+ tasks: { ...schedule.tasks, ux: { ...schedule.tasks.ux, providerId: 'claude-code', model: 'claude-opus-4' } },
+ });
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/claude');
+ await user.click(await screen.findByLabelText('Expand step 1'));
+
+ const model = await screen.findByLabelText('Model');
+ expect(model).toHaveValue('');
+ expect(model.querySelector('option').textContent).toBe('Inherit (claude-opus-4)');
+ expect(screen.getByText(/claude-code · claude-opus-4/)).toBeInTheDocument();
+ });
+
+ it('shows a programmatic task\'s run parameters read-only, with no agent options', async () => {
+ // PortOS executes these itself against its own records — there is no agent,
+ // so worktree/PR/simplify are meaningless, and the parameters are per-type
+ // and live on the task.
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ await user.click(await screen.findByLabelText('Expand step 1'));
+ expect(await screen.findByText(/Run parameters come from the scheduled task: scope=all · maxEntries=10/)).toBeInTheDocument();
+ expect(screen.queryByLabelText('Open PR')).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Audit mode')).not.toBeInTheDocument();
+ });
+ it('displays the referenced task and its pins in the collapsed summary', async () => {
+ api.getQuotaBurn.mockResolvedValue({ config: claudeConfig({ ...NO_OVERRIDES, model: 'claude-sonnet-4', effort: 'high' }), status });
renderPage('/devtools/quota-burn/claude');
- expect(await screen.findByText(/Agent prompt · claude-sonnet-4 · high/)).toBeInTheDocument();
+ expect(await screen.findByText(/ux · App One · claude-sonnet-4 · high/)).toBeInTheDocument();
});
});
diff --git a/docs/API.md b/docs/API.md
index cb12bd3037..67bf85bae2 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -688,7 +688,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/openclaw` | OpenClaw operator chat |
| `/api/rounds` | Rounds (music + Morse training) |
| `/api/ask` | Ask (LLM Q&A) |
-| `/api/quota-burn` | Quota-burn plan, catalog, and runs |
+| `/api/quota-burn` | Quota-burn plan (ordered scheduled-task references + per-invocation overrides), its live status, the app/provider catalog its pickers read, manual runs, and re-arm. The referenced work itself is read from — and only ever edited through — `/api/cos/schedule` and `/api/cos/jobs`. |
| `/api/timeline` | Human-activity timeline (day + events) |
| `/api/games` | Game projects |
| `/api/sprites` | Sprite catalog / export |
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index f11442ddcb..4b31f1d822 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -374,6 +374,6 @@ PostgreSQL itself is not PM2-managed — it runs as the system service (`:5432`)
### Adding CoS Task Types
1. Add the task type to `SELF_IMPROVEMENT_TASK_TYPES` and `DEFAULT_TASK_INTERVALS` in `server/services/taskSchedule.js`.
2. Add its prompt template to `DEFAULT_TASK_PROMPTS` in `server/services/taskPromptDefaults/prompts.js` (bump `PROMPT_VERSIONS` + append the outgoing default to `PREVIOUS_DEFAULT_PROMPTS` if you are changing an existing default).
-3. If it is an audit that should be configurable to **file issues** or **do the work**, add it to `AUDIT_DEFINITIONS` in `server/lib/auditCatalog.js` (and map any matching quota-burn preset via `quotaBurnId`).
+3. If it is an audit that should be configurable to **file issues** or **do the work**, add it to `AUDIT_DEFINITIONS` in `server/lib/auditCatalog.js` (and map any matching legacy quota-burn preset via `quotaBurnId`, so an un-migrated plan converts onto it). Quota Burn picks the new type up for free — its plan references scheduled tasks rather than carrying prompts of its own ([QUOTA-BURN.md](./QUOTA-BURN.md)).
4. If it ALWAYS files findings/plans into the app's work tracker (never implements), add a wording preset to `TRACKER_FILING_PRESETS` in `server/lib/workTracker.js` and reference `{trackerInstructions}` in its prompt template — membership is what makes `resolveTrackerFilingBlock` file on every dispatch.
5. Give it a home in `WORKFLOW_STAGES` (`server/services/workflow.js`) so the Workflow tab doesn't render it under Ambient.
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 3f14cea332..0ce6ba7628 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -19,14 +19,17 @@ Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:
have headroom above `reservePercent` in *every* window on the card, and that have
not spent `maxDispatchesPerWindow` for that window (`-1`, the default, means
no cap — see below). Ties break on `priority` (lower wins).
-4. Runs the **first enabled, unspent job in that family's ordered plan that
- reports pending work** — at most one dispatch per cycle.
+4. Runs the **first enabled, available, unspent step in that family's ordered
+ plan that reports pending work** — at most one dispatch per cycle. The step
+ is dispatched through the referenced task's own invocation path, so the run
+ is indistinguishable from the same task started by hand.
5. Charges the window in `data/cos/quota-burn-dispatches.json` and appends the
outcome (including skips, with reasons) to `data/cos/quota-burn-runs.json`.
Everything fails closed: an unknown reset time, an unsupported provider, a
quota-read error, a card that declares itself unburnable (`burnable: false`, e.g.
-the Image Gen card), or a family with no enabled jobs all mean "do not dispatch".
+the Image Gen card), a family with no enabled steps, or a step whose referenced
+task is gone or switched off all mean "do not dispatch".
## Which window a family burns against
@@ -104,29 +107,121 @@ usage-limit failure, `server/services/quotaBurnDenials.js` blocks that family in
a burn. An analyzer `usage-limit` verdict is trusted only when it came from a
structured provider marker, not a loose keyword sweep over the agent's own
narration.
-- **Bypassable by a forced run** (the ▶ on a job row), which is how a user
+- **Bypassable by a forced run** (the ▶ on a step row), which is how a user
retries a block they believe is stale.
-## Burn jobs
+## Burn steps
-A family's plan is an **ordered list** — that ordering is the configuration ("do
-the missing bible images first, then fall through to agent work"). Each job has
-its own type, optional model/provider pin, and type-specific params.
+A family's plan is an **ordered list of steps**, and that ordering is the
+configuration ("do the missing bible images first, then fall through to agent
+work"). A step does not *contain* work. It **references** a scheduled task the
+user already owns, and layers per-invocation overrides on it:
-| Job type | What it does |
+```jsonc
+{
+ "id": "job-abc",
+ "enabled": true,
+ "label": "Nightly UX sweep", // optional; defaults to the task's own name
+ "taskRef": { "kind": "builtin", "taskType": "ux", "appId": "example-app" },
+ "overrides": { "providerId": null, "model": "opus", "effort": null,
+ "params": { "fileIssues": true } },
+ "runOnce": false
+}
+```
+
+Two reference kinds, discriminated on `kind` (`server/lib/quotaBurnTaskRef.js`):
+
+| `kind` | Points at | Target |
+| --- | --- | --- |
+| `builtin` | A PortOS scheduled task TYPE (`ux`, `security`, `repo-sync`, `universe-bible-images`, …) as configured in **CoS → Schedule** | `appId` names the managed app, when the type acts on one |
+| `custom` | An app **custom scheduled job** (**CoS → System Tasks**), by id | None — the job record owns its own app scope, so a second copy here could disagree with it |
+
+There is no burn-only automation catalog and no burn-only prompt editor. This is
+the point of the model: work is defined **once**, in Scheduled Tasks, and Quota
+Burn decides *when* a family's expiring quota gets spent on it.
+
+### Adding a burn action
+
+1. Create (or find) the work in **CoS → Schedule** (a built-in task type) or
+ **CoS → System Tasks** (a custom job). New burn-only work should be an
+ **on-demand** scheduled task — no interval, so it costs nothing until
+ something asks for it. The page links straight there ("Create an on-demand
+ scheduled task").
+2. On **Dev Tools → Quota Burn**, expand a family and pick it from **Add a step**.
+ The picker is searchable and grouped into *PortOS scheduled tasks* and
+ *App custom tasks*; it matches on the task name, its description, and the apps
+ it can target.
+3. Pick a target app if the task acts on one, then set any per-invocation
+ overrides. The row states the **effective** settings and audit mode before you
+ save or run.
+
+Nothing here writes back to the task, and **removing a step never deletes the
+scheduled task it referenced** — only the step's own order, name, overrides and
+run-once state go away.
+
+### Inheritance and overrides
+
+`overrides` is layered over the referenced task's SAVED settings by
+`effectiveSettings` (`server/services/quotaBurnInvoke.js`), mirrored on the
+client by `effectiveQuotaBurnSettings` (`client/src/lib/quotaBurnTasks.js`):
+
+| Field | Unset (`null`) | Set |
+| --- | --- | --- |
+| `providerId` | Inherits the task's pin, else the family's own resolution | Pins the binary — rejected at save time if it belongs to another quota family |
+| `model` / `effort` | Inherits the task's saved pin | Pins for this burn only |
+| `params` | Inherits the task's whole `taskMetadata` | **Merged key by key** over it, so overriding one run parameter does not blank the rest |
+
+The join is on **presence, not truthiness**: an override the user clears
+normalizes to `null` and goes back to inheriting. That is also why the editor
+sends the `overrides` bag and omits the top-level `model`/`providerId`/`effort`/
+`params` compat mirrors the GET still returns — `normalizeQuotaBurnJob` resolves
+them by presence, so echoing a stale mirror back would silently restore a pin the
+user had just cleared (`quotaBurnStepPayload`).
+
+For an **audit** task type the overrides include the **audit mode** —
+`params.fileIssues`, the same `file issues only` ⇄ `do the work` switch the
+Schedule page shows. The row names the effective mode (and which half it came
+from) before anything runs, because that is the difference between a window spent
+filing issues and a window spent landing code. A **programmatic** task's run
+parameters are per-type and live on the task itself; the row renders them
+read-only with a link to edit them where they belong.
+
+### Eligibility — what a step may point at
+
+The picker only offers, and the runner only dispatches, work a burn can actually
+invoke. `getQuotaBurnTaskCatalog` builds the verdict server-side; the client
+mirrors the same rules so a dead end never appears as a choice:
+
+| Rule | Why |
| --- | --- |
-| `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-describe` | **Programmatic** — no agent. Sends one headless expand prompt per under-described bible entry, pinned to the burning family's own CLI/TUI provider. |
-| `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. |
-
-Both programmatic types are also ordinary **on-demand scheduled tasks** — they
-appear in CoS → Schedule with their own settings and a Run Now button, and a burn
-step and a manual run go through the same handler
-(`server/services/scheduledHandlers/`). They are never clock-due: a fresh install
-spends nothing on them until someone presses Run or adds one to a burn plan.
-Passing the burning `family` is what pins the provider / render backend to the
-subscription being drained; a manual run has no family and resolves the way any
-other scheduled task does.
+| A built-in type whose `invocation.userInvokable` is false is **excluded** | It is not something a user (or a burn) starts |
+| A custom job of type `shell` or `script` is **excluded** (`isBurnEligibleCustomJob`) | It runs a command or a built-in handler and spends no provider quota, which is the only thing a burn is for |
+| A custom job below the `yolo` autonomy level is **refused at dispatch** | It needs an approval an unattended burn cannot give |
+| A **disabled** task or job is offered, with the reason | It is one click from fixed on the page the row links to |
+| A type that requires a managed app is targeted from the apps that **enabled** it | The availability resolver reports `wrong-scope` for any other app |
+| An install-wide or programmatic type takes **no** app | The schema rejects a request from either that names one |
+
+A step that stops being invocable is **retained, never deleted** — its label,
+order, overrides and run-once state are the user's, and a task that comes back
+should find its step exactly as it left it. `resolveQuotaBurnStepAvailability`
+stamps `{ code, reason }` onto the config the page reads (derived per read, never
+persisted — it goes stale the moment a task is re-enabled), and the row renders
+that reason **with no run affordance at all**: offering a ▶ whose only outcome is
+a decline is worse than offering nothing. The codes are `legacy-unmigrated`,
+`unknown-task`, `dangling-job`, `disabled`, `missing-app`, `wrong-scope`, and
+`incompatible`.
+
+### The programmatic bible tasks
+
+`universe-bible-describe` and `universe-bible-images` are ordinary **on-demand
+scheduled tasks** that PortOS executes itself (`server/services/scheduledHandlers/`)
+— no agent, no CoS task, no spawn slot. They appear in CoS → Schedule with their
+own settings and a Run Now button, and a burn step and a manual run go through
+the same handler. They are never clock-due: a fresh install spends nothing on
+them until someone presses Run or adds one to a burn plan. Passing the burning
+`family` is what pins the provider / render backend to the subscription being
+drained; a manual run has no family and resolves the way any other scheduled task
+does.
### Describe before you render
@@ -136,7 +231,7 @@ generic figure that has to be thrown away — and it has already spent the image
quota. Ordering the two describe→images in the family's rotation walks the
backlog into shape first, then renders from something worth rendering.
-The job's `depth` param picks what "described" means, per
+The task's `depth` parameter picks what "described" means, per
`server/lib/universeBibleCompleteness.js`:
- **`core`** — the entry is unusable without these: a character's
@@ -162,7 +257,7 @@ shared in-flight ledger for its 6-hour TTL. Why picks are ranked by blank
declined to fill, are argued at the code site
(`server/services/scheduledHandlers/universeBibleDescribe.js`).
-The image job's opt-in `requireDescribed` is the other half of the pairing: with
+The image task's opt-in `requireDescribed` is the other half of the pairing: with
it on, canon entries with no `core` description are held out of the render
backlog until the describe job has been through them. It defaults **off**, so an
existing plan keeps rendering exactly the backlog it rendered yesterday.
@@ -170,12 +265,12 @@ existing plan keeps rendering exactly the backlog it rendered yesterday.
### 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
+(`rotatePlanAfter`), so an N-step 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
+Each step therefore carries a **`runOnce`** flag (default `false`, so every plan
written before it keeps repeating):
| `runOnce` | Behavior |
@@ -190,14 +285,14 @@ accord instead of looping.
- **The ledger is `data/cos/quota-burn-completions.json`**, `<familyId>:<jobId>`
→ the ISO instant it ran, capped (newest kept) at **twice** the keys a
maxed-out plan can hold — derived from `QUOTA_BURN_FAMILIES` and
- `jobsPerFamily.max`, so pruning can only evict a job already deleted from the
+ `jobsPerFamily.max`, so pruning can only evict a step already deleted from the
plan, never a live one. 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`)
+ it either: it is a capped UI feed, so a step that ran last month has aged out.
+- **Recorded only on a real dispatch.** A step 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
@@ -205,7 +300,7 @@ accord instead of looping.
- **An unreadable ledger fails CLOSED** — `getQuotaBurnCompletions` returns
`null` (not `{}`) for a failed read, so the cycle reports `run-once ledger
unreadable` rather than treating "nothing has run" as fact and re-dispatching
- every one-shot job. `writeLedger` refuses to write over an unread ledger for
+ every one-shot step. `writeLedger` refuses to write over an unread ledger for
the same reason: an empty write erases the completions that survived. Same
posture, and the same `readJSONFileStrict` shape, as `quotaBurnDenials.js`.
- **A finished plan stops costing a quota scrape.** `familyHasRunnableJobs(family,
@@ -218,79 +313,61 @@ accord instead of looping.
predicate** rather than an optional argument on `familyIsConfigured`: array
callbacks pass the index as the second argument, so an overloaded arity turns
`some(familyIsConfigured)` silently wrong.
-- **Re-arm** puts steps back in the rotation: the ↺ on a job row for one step,
+- **Re-arm** puts steps back in the rotation: the ↺ on a step 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, and one line in
-`server/services/quotaBurnJobs/index.js`'s `JOB_MODULES`. The config page builds
-its form from the catalog, so no client change is needed unless the job
-introduces a param kind the form doesn't render yet.
-
-**A PROGRAMMATIC job's module lives in `server/services/scheduledHandlers/`, not
-in `quotaBurnJobs/`.** The two universe-bible actions are ordinary **on-demand
-scheduled tasks** (CoS → Schedule → Run Now) that Quota Burn also dispatches;
-`JOB_MODULES` points at the same handler, so there is one implementation rather
-than a quota-only copy that drifts. A new burn action that PortOS performs itself
-belongs there too — register it in `SCHEDULED_HANDLER_MODULES`, add its task type
-to `PROGRAMMATIC_SCHEDULED_TASK_TYPES` + `DEFAULT_TASK_INTERVALS` in
-`server/services/taskScheduleRegistry.js` (enabled, `ON_DEMAND`, no interval), and
-allow-list its params in `sanitizeTaskMetadata`. The scheduled task's saved
-`taskMetadata` is the params bag; a burn step passes its own `params` plus the
-burning `family`, which is what pins the provider/render backend to that
-subscription. Listing or probing must spend nothing.
-
-Each job module exports `countPending` (side-effect free — the page calls it on
-every load) and `run` (the only thing that may spend quota). `countPending` may
-return an opaque `context` that the runner hands straight to `run`, so a probe
-that scanned every universe bible to produce its count doesn't make `run` repeat
-the scan; `run` must still work without it, because the force path calls it with
-no probe. A job that declines reports `dispatched: false` with a reason and is
-**not** charged against the window's cap.
-
-### Prompt presets
-
-`agent-prompt` jobs can be seeded from `QUOTA_BURN_PROMPT_PRESETS`
-(`server/lib/quotaBurnPresets.js`), served in the config catalog and applied from
-either **Add a preset job** on a family card or **Start from a preset** on a job
-row. Each preset is one narrow audit dimension — the single-focus form of
-`/do:better --issues` — that reads real code, files decision-complete GitHub
-issues, and changes nothing:
-
-| Preset | Focus |
-| --- | --- |
-| UX issues | Interaction friction: unconfirmed destructive controls, invisible save state, unexplained disabled buttons, lost edits, dead ends |
-| Accessibility issues | Keyboard paths, labels, focus management, live-region state, contrast |
-| Mobile & responsive issues | Overflow, touch targets, hover-only information, drawer/modal behavior at small widths |
-| Error & empty-state issues | Swallowed failures, doubled/missing toasts, absent-vs-empty conflation, stale UI, unsaved-work loss |
-| Performance issues | Per-item I/O, repeated scans, unbounded growth, render storms, timers, leaks |
-| Test coverage gaps | Untested guards on irreversible/expensive paths, fixes landed without regression tests, false-green mocking |
-| Dead code & duplication | Unreferenced exports, re-implemented helpers, copy-paste drift (never cross-version compatibility code) |
-| Data & upgrade-safety issues | Missing migrations/seeds, schema-parity drift, version gates, destructive defaults |
-| Docs drift | Doc claims the code contradicts, stale commands, undocumented surfaces |
-| Security issues | Real exposure under the documented threat model — findings that contradict it are noise |
-| API & route contracts | Unvalidated inputs, client/server drift, wrong status/envelope, missing `asyncHandler`, loose schemas |
-| React lifecycle & state | Missing effect teardowns, stale closures, unmounted state updates, derived-state anti-patterns |
-| Logging & observability | Silent catch blocks, log noise on hot paths, errors logged without context, uninstrumented pipelines |
-| Copy & text clarity | Internal jargon in labels, ambiguous action verbs, dead-end error text, broken pluralization |
-
-Presets are **templates**: picking one COPIES its prompt into the job's own
-`params.prompt`, and nothing on disk points back at the preset id. So a contract
-revision reaches configured jobs only through a migration — and the shape of
-that migration matters. Every rendered prompt is two halves split by the
-`## How to run this audit` line: the **mission** above it (what to audit, one
-per preset, essentially stable) and the **contract** below it (how to audit,
-shared, and the half that keeps being revised). `upgradeStoredAuditPrompt`
-matches on the mission and replaces the contract, so a job seeded several
-revisions ago still upgrades; it refuses when the stored contract has lost the
-sentences every shipped render carried, which is how a user's own procedure is
-recognized and left alone. Copy migration 305 for the next contract edit —
-**not** migration 294, whose byte-for-byte rule matched nothing older than one
-revision and silently stranded every real job on a prompt that predated the
-dispatch-label guidance entirely.
+### Adding a NEW kind of burn action (code)
+
+There is no `QUOTA_BURN_JOB_TYPE` to extend any more — `QUOTA_BURN_JOB_CATALOG`
+and `quotaBurnPresets.js` are frozen compatibility inputs, and nothing new
+belongs in them. A new burn action ships as a **scheduled task**, and Quota Burn
+picks it up for free:
+
+- **Agent work** — add the task type (or let the user create a custom job in
+ System Tasks). If it should be configurable to *file issues* vs *do the work*,
+ add it to `AUDIT_DEFINITIONS` in `server/lib/auditCatalog.js`. See
+ `docs/ARCHITECTURE.md` → "Adding CoS Task Types".
+- **Work PortOS performs itself** — register the module in
+ `SCHEDULED_HANDLER_MODULES`, add its task type to
+ `PROGRAMMATIC_SCHEDULED_TASK_TYPES` + `DEFAULT_TASK_INTERVALS` in
+ `server/services/taskScheduleRegistry.js` (enabled, `ON_DEMAND`, no interval),
+ and allow-list its params in `sanitizeTaskMetadata`. The task's saved
+ `taskMetadata` is the params bag; a burn step passes its own overrides plus
+ the burning `family`, which is what pins the provider/render backend to that
+ subscription.
+
+No client change is needed either way: the picker reads the same catalogs the
+Schedule and System Tasks pages do.
+
+A programmatic handler exports `countPending` (side-effect free — the page calls
+it on every load, so listing or probing must spend nothing) and `run` (the only
+thing that may spend quota). `countPending` may return an opaque `context` that
+the runner hands straight to `run`, so a probe that scanned every universe bible
+to produce its count doesn't make `run` repeat the scan; `run` must still work
+without it, because the force path calls it with no probe. A step that declines
+reports `dispatched: false` with a reason and is **not** charged against the
+window's cap.
+
+### Audits — where the wording lives now
+
+The audit dimensions a burn window is usually spent on (UX, accessibility,
+mobile/responsive, error & empty states, performance, test coverage, dead code,
+data & upgrade safety, docs drift, security, API & route contracts, React
+lifecycle, logging, copy clarity) are **scheduled task types**, defined once in
+`AUDIT_DEFINITIONS` (`server/lib/auditCatalog.js`) with their prompts in
+`DEFAULT_TASK_PROMPTS`. A burn step references one and picks its **audit mode**
+per invocation; the wording is edited in CoS → Schedule, where every other
+consumer of that task reads it.
+
+`QUOTA_BURN_PROMPT_PRESETS` (`server/lib/quotaBurnPresets.js`) is what that
+replaced: a burn-only table of prompt templates whose text was **copied** into a
+step's `params.prompt`, with nothing on disk pointing back at the preset id. It
+is retained as a **compatibility input only** — a plan written before the
+reference model still loads, and it is the source the migration reads. Nothing
+new belongs in it, and the config page no longer serves or renders it.
Each audit prompt spends **roughly the first two thirds of the window on
research**: trace each candidate end to end, read the tests and `git log` around
@@ -305,13 +382,16 @@ Contributor labels (`good first issue`, `help wanted`) stay optional, missing
labels are created lazily, category labels (`plan`, `ux`, `bug`, `tests`,
`area:*`, …) are preserved, and the agent reads each new issue's labels back to
repair any that did not stick.
+
### The "lands no code" postures
-An `agent-prompt` job has two of them, and they are not the same thing:
+An agent task has two of them, and they are not the same thing. Both are saved
+`taskMetadata` on the scheduled task; a burn step can override them per
+invocation like any other run parameter:
| Param | Means | Use when |
| --- | --- | --- |
-| `noCodeOutput` | The deliverable is what the agent **does during the run** — files an issue, calls an endpoint. It needs no branch and no isolation because it writes nothing, so it runs in the app's own checkout on whatever branch that is. | The audit presets |
+| `noCodeOutput` | The deliverable is what the agent **does during the run** — files an issue, calls an endpoint. It needs no branch and no isolation because it writes nothing, so it runs in the app's own checkout on whatever branch that is. | The audit task types |
| `discardWorktree` | The job **does** want a scratch checkout (it builds, runs tests, edits to reason) but nothing in it may land: the worktree is removed without merging. | A job that must run a build/test cycle |
Either one forces `openPR`/`simplify` off in the runner (both presuppose a diff
@@ -321,7 +401,7 @@ sets `worktreeChangesExpected: false`, so a run that correctly changed nothing
isn't failed by the idle-complete gate. Both default to `false`, so a job meant
to land code is unaffected.
-The audit presets take the **first** posture: `useWorktree: false` +
+The audit task types take the **first** posture: `useWorktree: false` +
`noCodeOutput: true` + `openPR: false` + `simplify: false`. Isolating a
read-only audit would be worse, not better — `useWorktree: true` with
`openPR: false` is the **auto-merge** posture (`agentWorktreeCleanup.js` merges
@@ -335,58 +415,82 @@ covered the Creative Director agents, which run in the same shape.)
The tradeoff: an audit runs in the user's working copy, so its prompt is
explicit that it must leave the tree and the branch exactly as it found them.
-A job that genuinely needs to build or test should tick `discardWorktree`
+A task that genuinely needs to build or test should tick `discardWorktree`
instead.
-Every numeric bound (windows, reserve, caps, entry limits) lives in
+Every numeric bound (windows, reserve, caps, field lengths) lives in
`QUOTA_BURN_BOUNDS` in `server/lib/quotaBurnConfig.js`, read by the normalizer
-(which clamps an older on-disk plan), the Zod schemas (which reject a bad
-request), and the catalog descriptors the client renders as `min`/`max`.
+(which clamps an older on-disk plan) and by the Zod schemas (which reject a bad
+request), so raising a cap in one place cannot 400 a plan the other would accept.
## Manual runs
- **Evaluate now** runs a full cycle immediately, ignoring the master switch but
respecting every quota gate.
- **Burn now** on a family card scopes that cycle to one family.
-- The ▶ on a job row **forces** that one job past the window/reserve/cap gates.
+- The ▶ on a step row **forces** that one step past the window/reserve/cap gates.
It goes through the same selection, so the run still reports the family's real
remaining percentage and reset time — it is only marked `charge: false`, so it
never eats the family's automatic budget. It **arms on first click** and
dispatches on the confirm: the page has no Save button, so a spend-now control
- sitting among the row's small icons was being hit as if it were one.
+ sitting among the row's small icons was being hit as if it were one. It is
+ **absent entirely** on an unavailable step (the server would decline the
+ dispatch, so a button whose only outcome is a toast is worse than the reason the
+ row already states), and disabled while an edit is unsaved — every run control
+ reads server-side config, so a run fired between the keystroke and the PUT would
+ burn with the previous settings.
## Storage
-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 a
+Six files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json` — ordered steps, each a scheduled-task reference plus its overrides; the referenced tasks themselves live in `data/cos/task-schedule.json` and the app job store, and a burn never writes to either), 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 a
particular machine and provider account, and the "which managed app" targets
differ per machine.
-## Migration from the per-app task type
-
-Before this, quota-burn was a `quota-burn` entry in each managed app's
-`taskTypeOverrides`, which meant two enabled apps ran two independent loops
-racing for the same window budget. Migration `221-quota-burn-global-config.js`
-folds those overrides into the single plan (each app's family prompt becomes an
-`agent-prompt` job pointing back at that app) and removes the dead task type from
-`data/apps.json`. Do not re-add `quota-burn` to `TASK_TYPES`.
+## Migration
+
+**From the per-app task type.** Before the install-level loop, quota-burn was a
+`quota-burn` entry in each managed app's `taskTypeOverrides`, which meant two
+enabled apps ran two independent loops racing for the same window budget.
+Migration `221-quota-burn-global-config.js` folds those overrides into the single
+plan and removes the dead task type from `data/apps.json`. Do not re-add
+`quota-burn` to `TASK_TYPES`.
+
+**From copied prompts to task references.** A plan written before the reference
+model stores a `jobType` and a free-form `params` bag instead of a `taskRef`.
+Those steps still **load** — an install upgrading across the reference model must
+not lose its plan — and `normalizeQuotaBurnJob` marks each one
+`legacy-unmigrated` rather than guessing which scheduled task its copied prompt
+meant. The page renders that reason and no run affordance, so the step keeps its
+place, its order and its name while the conversion service converts it; picking a
+task from the row's own picker converts it by hand at any time. Guessing at
+normalization time would either strand the user's edits or silently duplicate an
+automation, which is why the conversion is a migration rather than a read-time
+inference.
## Code map
| File | Role |
| --- | --- |
-| `server/lib/quotaBurnConfig.js` | Plan shape, job-type catalog, total normalization |
-| `server/lib/universeBibleCompleteness.js` | What "described" means per kind + depth — the field vocabulary the describe job scans with |
-| `server/lib/quotaBurnPresets.js` | Ready-made single-focus audit prompts for `agent-prompt` jobs |
| `server/lib/quotaBurnTaskRef.js` | The step→scheduled-task reference model, its overrides bag, and the availability resolver |
+| `server/lib/quotaBurnConfig.js` | Plan shape, bounds, total normalization (plus the FROZEN legacy job-type catalog) |
+| `server/lib/quotaBurnValidation.js` | The strict PUT schemas — reference shape, target scope, and out-of-family provider pins |
| `server/lib/quotaBurnOrigin.js` | Burn provenance on an on-demand request, and the metadata both on-demand engines stamp from it |
+| `server/lib/taskTargetScope.js` | Which task types act on one app, install-wide, or are programmatic — read by the resolver and the schema |
+| `server/lib/auditCatalog.js` | The audit task types and their file-issues-vs-do-the-work contract |
+| `server/lib/quotaBurnPresets.js` | FROZEN legacy prompt presets — a compatibility input for un-migrated plans |
+| `server/lib/universeBibleCompleteness.js` | What "described" means per kind + depth — the field vocabulary the describe task scans with |
| `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) |
+| `server/services/quotaBurnInvoke.js` | The shared invocation path: builds the task catalog, resolves a step, layers its overrides, enforces the schedule's own gates, and dispatches |
| `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/quotaBurnInvoke.js` | The shared invocation path: resolves a step's reference, enforces the schedule's own gates, and dispatches through canonical task generation |
-| `server/services/quotaBurnJobs/` | The frozen legacy job registry and the `agent-prompt` executor, kept until un-migrated plans are converted |
+| `server/services/quotaBurnRunner.js` | The loop, the cycle, and the status feed (which stamps availability onto the config the page reads) |
| `server/services/scheduledHandlers/` | The programmatic handlers (universe bible descriptions/images) — shared by Scheduled Tasks and Quota Burn |
-| `server/services/quotaBurnRunner.js` | The loop, the cycle, and the status feed |
-| `server/routes/quotaBurn.js` | `/api/quota-burn` |
+| `server/services/quotaBurnJobs/` | The frozen legacy job registry, kept until un-migrated plans are converted |
+| `server/routes/quotaBurn.js` | `/api/quota-burn` — plan, status, apps/providers catalog, manual runs, re-arm |
+| `client/src/lib/quotaBurnTasks.js` | The client's view of the shared task catalog: grouping, search, reference keys, effective settings, and the PUT payload |
+| `client/src/lib/quotaBurnPatch.js` | The optimistic config merge (mirrors `saveQuotaBurnConfig`) and the dispatch-cap sentinel |
| `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 |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 6c199aa710..6c3cd914ce 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -64,7 +64,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.
- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, explicit display aliases keyed by opaque resource identity (never backfilled from records), user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. Guest travel sessions and live chat cursors are ephemeral transport state held only in memory; they are not a new record store or sync category. Explicit guest conversation follows the [guest-chat ADR](decisions/2026-09-05-eidoverse-guest-chat.md). PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
-- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
+- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + an ordered list of steps, each a REFERENCE to a scheduled task (`data/cos/task-schedule.json` or the app job store) plus its per-invocation overrides. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and a step's scheduled-task reference names task types and managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.
- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.
- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).