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

quota-burn editor: arm the per-job run, and seed work prompts from audit presets

[._.]/ Adam Eivy94e456a76e27
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bce756d302..85f0121365 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -47,3 +47,5 @@
- **Manuscript issue tabs show which issues hold an unsaved edit.** Sections only persist onBlur, so typing in issue 3 and tabbing to issue 7 left the pending text with no cue anywhere on screen. The saved-content baselines the unload guard already tracked are now state rather than a bare ref, so the tab strip subscribes to them: an issue with content drifting from its last server-confirmed save gets a dot (and an "unsaved edits" tooltip) that clears when the save lands — and stays put when the save fails. (#3399)
- **Switching manuscript formats no longer discards an unsaved section edit.** Sections save onBlur, but a format switch replaced the whole section list — and its baselines — so an edit that hadn't blurred (or whose save had failed) was dropped, and switching back refetched the server's older text. The switch now flushes pending saves first and aborts if one fails, leaving the text and its tab dot on screen. Saves are also queued per section, so the blur save and the switch's flush can't PATCH the same text twice and snapshot a redundant version. (#3399)
- **"Continue Today's Routine" no longer dead-ends on the drill you just finished.** The handler navigated straight to the top recommendation's deep link with no check that it pointed somewhere else — and a sub-50% run makes the drill just missed the very item the scheduler resurfaces first, so Continue on Element Flash re-navigated to the URL already in the address bar and left the completion panel untouched. A self-referential recommendation now restarts the drill in place: a `run` nonce goes into the query string (preserving unrelated params like Morse's `?ref=`) and flows into the key of every surface the handler drives — Elements, Morse, Wordplay, and memory practice — so the drill remounts for a fresh run. Recommendations pointing elsewhere navigate exactly as before, and the comparison is path-only so a deep link carrying its own query string is still recognized as self-referential. (#3428)
+- **Quota-burn plan editor: nothing spends or destroys on one click any more.** The row's ▶ force-dispatched the job past the window/reserve/cap gates on a single click, sitting in a strip of small icons on a page that has no Save button — so it reads as "save" and got hit by accident. It now arms first, like the row's delete (and arming either disarms the other). Two more one-click losses went with it: the job-type picker no longer wipes `params`, so clicking through it can't silently destroy a long work prompt, and a preset asks before overwriting prompt text the user wrote. The page header now says "Changes save automatically" / "Saving changes…" — the missing feedback that sent people hunting for a save button in the first place. The step-name box also stopped using the job-type label ("Agent prompt") as its placeholder, which made it look like a second prompt field next to the real Work prompt, and a collapsed family card now shows its job count so "healthy window, no plan" is visible without expanding.
+- **Quota-burn work prompts ship with presets.** A burn window is spent unattended, so a blank "what should this provider spend its remaining quota on?" textarea was the weakest part of the feature. Ten ready-made prompts (`server/lib/quotaBurnPresets.js`, served in the config catalog) each run ONE narrow audit — UX, accessibility, mobile, failure paths, performance, test gaps, dead code, data/upgrade safety, docs drift, security — the single-focus form of `/do:better --issues`: read real code in a bounded slice, de-dupe against open issues, file at most five decision-complete GitHub issues, change nothing. They set `openPR: false` / `simplify: false` (no diff to ship) and `useWorktree: true` (an audit must not dirty the primary checkout), and include a `curl` fallback so a `gh` network failure doesn't end the window having filed nothing. Add one from a family card ("Add a preset job", inheriting the plan's app) or a job row ("Start from a preset"). Presets are templates — picking one copies the text into the job, so editing a preset never rewrites a configured job on any install.
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsx
index 0b0ed4696b..37c01e35b0 100644
--- a/client/src/components/quotaBurn/FamilyCard.jsx
+++ b/client/src/components/quotaBurn/FamilyCard.jsx
@@ -9,6 +9,8 @@
import { ChevronDown, ChevronRight, Flame, Plus } from 'lucide-react';
import JobRow from './JobRow';
+import PresetPicker from './PresetPicker';
+import { jobFromPreset } from '../../lib/quotaBurnPatch';
import { NumberField, TextField } from './fields';
export default function FamilyCard({
@@ -36,8 +38,9 @@ export default function FamilyCard({
// 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;
+ const nextJobId = () => `job-${Date.now().toString(36)}`;
const addJob = () => patchJobs([...jobs, {
- id: `job-${Date.now().toString(36)}`,
+ id: nextJobId(),
enabled: true,
label: '',
jobType: catalog.jobTypes[0].id,
@@ -45,6 +48,14 @@ export default function FamilyCard({
providerId: null,
params: {},
}]);
+ // 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.
+ const inheritedAppId = [...new Set(jobs.map((job) => job.params?.appId).filter(Boolean))];
+ const addPresetJob = (preset) => patchJobs([...jobs, jobFromPreset(preset, {
+ id: nextJobId(),
+ appId: inheritedAppId.length === 1 ? inheritedAppId[0] : null,
+ })]);
return (
<div className="rounded border border-port-border bg-port-card/40">
@@ -68,6 +79,15 @@ export default function FamilyCard({
<span className="text-xs text-gray-500">{status?.skipReason || 'not evaluated yet'}</span>
)}
+ {/* A collapsed card otherwise says nothing about whether this family has
+ a plan at all — and a family with zero enabled jobs can never burn,
+ no matter how healthy its window looks. */}
+ <span className="text-[11px] text-gray-500">
+ {jobs.length
+ ? `${jobs.length} job${jobs.length === 1 ? '' : 's'} · ${jobs.filter((job) => job.enabled !== false).length} enabled`
+ : 'no jobs'}
+ </span>
+
<div className="ml-auto flex items-center gap-2">
<button
type="button"
@@ -116,6 +136,15 @@ export default function FamilyCard({
<Plus size={13} /> Add job
</button>
</div>
+ <div className="sm:max-w-md">
+ <PresetPicker
+ id={`burn-${familyId}-preset`}
+ label="Add a preset job"
+ presets={catalog.presets}
+ onPick={addPresetJob}
+ hint="Single-focus audits that read the code, file GitHub issues, and change nothing — safe work for an unattended window."
+ />
+ </div>
{!jobs.length && (
<p className="text-xs text-gray-500">No jobs yet — this family will never burn until one is added.</p>
)}
diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsx
index f6b2700cb9..e8ccef12a9 100644
--- a/client/src/components/quotaBurn/JobRow.jsx
+++ b/client/src/components/quotaBurn/JobRow.jsx
@@ -7,8 +7,12 @@
*/
import { useState } from 'react';
-import { ArrowDown, ArrowUp, Check, Play, Trash2 } from 'lucide-react';
+import { ArrowDown, ArrowUp, Play, Trash2 } from 'lucide-react';
+import ConfirmButtonPair from '../ui/ConfirmButtonPair';
+import InlineConfirmRow from '../ui/InlineConfirmRow';
import JobParamField from './JobParamField';
+import PresetPicker from './PresetPicker';
+import { applyQuotaBurnPreset } from '../../lib/quotaBurnPatch';
import { inputClass } from './fields';
export default function JobRow({
@@ -20,9 +24,20 @@ export default function JobRow({
// stray click on the trash icon would drop it from the persisted plan with no
// undo.
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);
const spec = catalog.jobTypes.find((type) => type.id === job.jobType);
const idPrefix = `burn-job-${job.id}`;
const setParam = (key, value) => onChange({ ...job, params: { ...job.params, [key]: value } });
+ const hasPromptText = Boolean(String(job.params?.prompt || '').trim());
+ const applyPreset = (preset) => { setPendingPreset(null); onChange(applyQuotaBurnPreset(job, preset)); };
const optionsFor = (descriptor) => ({
app: catalog.apps,
universe: catalog.universes,
@@ -42,21 +57,42 @@ export default function JobRow({
<input
className={`${inputClass} flex-1 min-w-40 mt-0`}
value={job.label || ''}
- placeholder={spec?.label || 'Job name'}
+ placeholder={spec ? `Step name (defaults to “${spec.label}”)` : 'Step name'}
aria-label={`Name for step ${index + 1}`}
onChange={(event) => onChange({ ...job, label: event.target.value })}
/>
<div className="flex items-center gap-1">
<button type="button" className="p-1 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="p-1 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>
- <button type="button" className="p-1 text-port-accent hover:text-white disabled:opacity-30" disabled={actionsBusy} onClick={() => onRun(job)} aria-label={`Run step ${index + 1} now`} title="Run this job now, ignoring the reset window"><Play size={14} /></button>
+ {runArmed ? (
+ // `warning`, not `error`: forcing a run is expensive-but-safe, and
+ // it must not look identical to the delete confirm beside it.
+ <ConfirmButtonPair
+ prompt="Spend now?"
+ confirmText="Run"
+ confirmIcon={Play}
+ cancelText="Cancel"
+ tone="warning"
+ busy={actionsBusy}
+ ariaLabel={`Confirm running step ${index + 1} now`}
+ onConfirm={() => { setRunArmed(false); onRun(job); }}
+ onCancel={() => setRunArmed(false)}
+ />
+ ) : (
+ <button type="button" className="p-1 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>
+ )}
{armed ? (
- <>
- <button type="button" className="p-1 text-red-400 hover:text-red-300" onClick={() => onRemove(index)} aria-label={`Confirm removing step ${index + 1}`} title="Click to confirm — this discards the job's prompt"><Check size={14} /></button>
- <button type="button" className="text-[11px] text-gray-400 hover:text-white px-1" onClick={() => setArmed(false)}>Cancel</button>
- </>
+ <ConfirmButtonPair
+ prompt="Discards its prompt."
+ confirmText="Delete"
+ confirmIcon={Trash2}
+ cancelText="Cancel"
+ ariaLabel={`Confirm removing step ${index + 1}`}
+ onConfirm={() => onRemove(index)}
+ onCancel={() => setArmed(false)}
+ />
) : (
- <button type="button" className="p-1 text-red-400 hover:text-red-300 disabled:opacity-30" onClick={() => setArmed(true)} aria-label={`Remove step ${index + 1}`}><Trash2 size={14} /></button>
+ <button type="button" className="p-1 text-red-400 hover:text-red-300 disabled:opacity-30" onClick={() => { setRunArmed(false); setArmed(true); }} aria-label={`Remove step ${index + 1}`}><Trash2 size={14} /></button>
)}
</div>
</div>
@@ -68,7 +104,11 @@ export default function JobRow({
id={`${idPrefix}-type`}
className={inputClass}
value={job.jobType}
- onChange={(event) => onChange({ ...job, jobType: event.target.value, params: {} })}
+ // 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>
@@ -83,6 +123,14 @@ export default function JobRow({
onChange={(event) => onChange({ ...job, model: event.target.value || null })}
/>
</label>
+ <PresetPicker
+ id={`${idPrefix}-preset`}
+ label="Start from a preset (optional)"
+ presets={catalog.presets}
+ jobType={job.jobType}
+ hint="Fills the work prompt below with a ready-made single-focus audit that files issues and changes no code."
+ onPick={(preset) => (hasPromptText ? setPendingPreset(preset) : applyPreset(preset))}
+ />
{(spec?.params || []).map((descriptor) => (
<JobParamField
key={descriptor.key}
@@ -95,6 +143,17 @@ export default function JobRow({
))}
</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)}
+ />
+ )}
+
{spec?.description && <p className="text-[11px] text-gray-500">{spec.description}</p>}
{pending && (
<p className={`text-[11px] ${pending.count > 0 ? 'text-emerald-400' : 'text-gray-500'}`}>
diff --git a/client/src/components/quotaBurn/PresetPicker.jsx b/client/src/components/quotaBurn/PresetPicker.jsx
new file mode 100644
index 0000000000..f728f6fa4e
--- /dev/null
+++ b/client/src/components/quotaBurn/PresetPicker.jsx
@@ -0,0 +1,47 @@
+/**
+ * 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.
+ *
+ * A one-shot ACTION, not a bound field: the select snaps back to its placeholder
+ * after firing, because the job it seeded is editable afterward and nothing on
+ * disk records which preset it came from — leaving a preset name selected would
+ * claim the row still matches text the user may have rewritten.
+ */
+
+import { inputClass } from './fields';
+
+export default function PresetPicker({ id, label, presets, jobType = null, onPick, disabled = false, hint }) {
+ // Presets declare the job type they seed, so a plan with several job types
+ // only ever offers the ones that can apply here.
+ const rows = (presets || []).filter((preset) => !jobType || preset.jobType === jobType);
+ if (!rows.length) return null;
+
+ return (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {label}
+ <select
+ id={id}
+ className={inputClass}
+ value=""
+ disabled={disabled}
+ 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/lib/README.md b/client/src/lib/README.md
index 97bd987663..02263c0cde 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -84,7 +84,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
| `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. |
+| `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. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |
diff --git a/client/src/lib/quotaBurnPatch.js b/client/src/lib/quotaBurnPatch.js
index 34aa4edda2..49f36ab214 100644
--- a/client/src/lib/quotaBurnPatch.js
+++ b/client/src/lib/quotaBurnPatch.js
@@ -26,3 +26,38 @@ export function mergeQuotaBurnPatch(base, patch) {
else delete merged.families;
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.
+ */
+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,
+ params: appId ? { appId } : {},
+ }, preset);
+}
diff --git a/client/src/lib/quotaBurnPatch.test.js b/client/src/lib/quotaBurnPatch.test.js
index 17f0ba50b9..93dc279988 100644
--- a/client/src/lib/quotaBurnPatch.test.js
+++ b/client/src/lib/quotaBurnPatch.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { mergeQuotaBurnPatch } from './quotaBurnPatch';
+import { applyQuotaBurnPreset, jobFromPreset, mergeQuotaBurnPatch } from './quotaBurnPatch';
describe('mergeQuotaBurnPatch', () => {
it('merges top-level keys and leaves families untouched', () => {
@@ -38,3 +38,54 @@ describe('mergeQuotaBurnPatch', () => {
expect(mergeQuotaBurnPatch(null, { enabled: true })).toEqual({ enabled: true });
});
});
+
+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);
+ });
+});
+
+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,
+ 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');
+ });
+});
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index 457d4b59d7..d4a588ddd4 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -164,6 +164,12 @@ export default function QuotaBurn() {
<div className="space-y-4">
<header className="flex flex-wrap items-center gap-3">
<h1 className="text-xl font-semibold text-white flex items-center gap-2"><Flame size={20} className="text-orange-400" /> Quota Burn</h1>
+ {/* There is no Save button on this page, and nothing else said so — the
+ silence is what makes people reach for the nearest button-shaped
+ thing (the per-job ▶, which spends quota) to "commit" an edit. */}
+ <span className={`text-[11px] ${unsaved ? 'text-amber-300' : 'text-gray-500'}`} aria-live="polite">
+ {unsaved ? 'Saving changes…' : 'Changes save automatically'}
+ </span>
<button
type="button"
className="inline-flex items-center gap-1 text-xs text-gray-300 hover:text-white"
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index 6804cc0d1c..e5274d1ef9 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -39,8 +39,24 @@ 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 }] },
+ {
+ 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 },
+ ],
+ },
],
+ presets: [{
+ id: 'ux-audit',
+ label: 'UX issues',
+ summary: 'Audit the UI and file issues.',
+ jobType: 'agent-prompt',
+ params: { prompt: 'Audit the UI. File issues. Change no code.', useWorktree: true, openPR: false, simplify: false },
+ }],
apps: [{ id: 'a1', name: 'App One' }],
universes: [{ id: 'u1', name: 'Example Universe' }],
imageModes: ['codex', 'grok'],
@@ -87,15 +103,62 @@ describe('QuotaBurn page', () => {
expect(screen.getByText(/Ready — 4 bible entries have no image/)).toBeInTheDocument();
});
- it('force-runs a single job from its row', async () => {
+ it('force-runs a single job from its row only after the arm click is confirmed', async () => {
const user = userEvent.setup();
renderPage('/devtools/quota-burn/grok');
+ // First click only arms — a stray click on this icon must not spend quota.
await user.click(await screen.findByLabelText('Run step 1 now'));
+ expect(api.runQuotaBurn).not.toHaveBeenCalled();
+ await user.click(await screen.findByRole('button', { name: 'Run' }));
await waitFor(() => expect(api.runQuotaBurn).toHaveBeenCalledWith(
{ familyId: 'grok', jobId: 'j1', force: true }, { silent: true },
));
});
+ it('adds a fully-configured job from a preset, inheriting the plan\'s app', async () => {
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ await user.selectOptions(await screen.findByLabelText(/Add a preset job/), 'ux-audit');
+ await waitFor(() => 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: no PR to open and no diff for /simplify to clean.
+ expect(added.params.openPR).toBe(false);
+ });
+
+ it('asks before a preset overwrites a work prompt the user already wrote', async () => {
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ 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.');
+ });
+
+ 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.
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ 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');
+ });
+
it('never persists a status field alongside the job config', 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
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index d1a56ba343..7ed5e78b47 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -51,6 +51,35 @@ 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 |
+
+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 editing the
+text here never rewrites a configured job on any install (no migration needed) —
+and an improved prompt reaches an existing job only when the user re-picks it.
+They set `openPR: false` / `simplify: false` (there is no diff to ship) and
+`useWorktree: true` (an audit must not dirty the primary checkout).
+
Every numeric bound (windows, reserve, caps, entry limits) 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
@@ -64,7 +93,9 @@ request), and the catalog descriptors the client renders as `min`/`max`.
- The ▶ on a job row **forces** that one job 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.
+ 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.
## Storage
@@ -86,6 +117,7 @@ folds those overrides into the single plan (each app's family prompt becomes an
| File | Role |
| --- | --- |
| `server/lib/quotaBurnConfig.js` | Plan shape, job-type catalog, total normalization |
+| `server/lib/quotaBurnPresets.js` | Ready-made single-focus audit prompts for `agent-prompt` jobs |
| `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/quotaBurnJobs/` | The job registry and its modules |
diff --git a/server/lib/README.md b/server/lib/README.md
index 5f6d1c1fe4..c5dece4cb8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -28,6 +28,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Pure — no storage, no provider I/O. |
+| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |
| `quotaReset.js` | Normalizes provider quota reset timestamps and computes time remaining without treating unknown values as imminent resets. |
| `appleHealthValidation.js` | Apple Health import payloads. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 6cd2a6e116..a766d73745 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -112,6 +112,7 @@ export * from './promptTemplate.js';
export * from './providerModels.js';
export * from './providerTranscriptUsage.js';
export * from './quotaBurnConfig.js';
+export * from './quotaBurnPresets.js';
export * from './quotaBurnValidation.js';
export * from './quotaReset.js';
export * from './opencodeConfig.js';
diff --git a/server/lib/quotaBurnPresets.js b/server/lib/quotaBurnPresets.js
new file mode 100644
index 0000000000..2c4d9cf27c
--- /dev/null
+++ b/server/lib/quotaBurnPresets.js
@@ -0,0 +1,445 @@
+/**
+ * Ready-made work prompts for `agent-prompt` burn jobs.
+ *
+ * A burn window is a use-it-or-lose-it budget, and the thing it is worst at is
+ * open-ended "do something useful" work: an agent with a vague prompt spends a
+ * whole window rediscovering the repo. These presets are the opposite — each 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. That shape suits an unattended window: the output is a queue another
+ * agent can drain later, so a burn that lands at 3am needs no review to be safe.
+ *
+ * TEMPLATES, not references. Picking a preset COPIES its prompt into the job's
+ * own `params.prompt`, which the user then edits freely. Nothing on disk points
+ * back at a preset id, so editing the text here never rewrites a configured job
+ * on any install and there is no migration to write — the cost is that an
+ * improved prompt reaches existing jobs only when the user re-picks the preset.
+ *
+ * Pure module: strings only, no I/O. `routes/quotaBurn.js` serves the list in
+ * the config catalog; the client's preset picker applies one to a job row.
+ */
+
+import { QUOTA_BURN_JOB_TYPE } from './quotaBurnConfig.js';
+
+/** Params every audit preset sets, and why they differ from the job defaults. */
+const AUDIT_PARAMS = Object.freeze({
+ // Read-only work still gets an isolated checkout: an audit that wanders into
+ // an edit must not dirty (or switch the branch of) the primary working copy
+ // the user has open.
+ useWorktree: true,
+ // No code changes means no PR and nothing for /simplify to clean up. Leaving
+ // these on makes the agent hunt for a diff to ship and end the window
+ // confused.
+ openPR: false,
+ simplify: false,
+});
+
+/**
+ * The half of every audit prompt that is about HOW to audit rather than WHAT to
+ * audit. Written once so a lesson learned from one bad run (a preset that filed
+ * forty nits, or one that quietly stopped at the first `gh` failure) fixes every
+ * preset at once.
+ */
+const auditContract = ({ labels, dedupeSearch }) => `
+## How to run this audit
+
+1. **Pick a bounded slice and say so first.** Do NOT attempt the whole
+ repository. Choose one coherent area (a feature directory, a route group, a
+ handful of related screens) — prefer one that recent audit issues have not
+ already covered — and open your report by naming the slice in one line.
+2. **Read the actual code.** Every finding must cite \`path/to/file.js:LINE\` and
+ describe a concrete, reproducible failure: what a user does, in what state,
+ and what goes wrong. Delete any finding you cannot state that way — that
+ filter is the whole point of this job.
+3. **De-duplicate before filing.** Run
+ \`gh issue list --state open --limit 200 --search "${dedupeSearch}"\` (and a
+ plain keyword search per finding). If it is already filed, skip it; comment on
+ the existing issue only when you have genuinely new evidence.
+4. **File each surviving finding as its own issue.** Use
+ \`gh issue create --title "..." --body-file <file> --label ...\`. Suggested
+ labels: ${labels}. Run \`gh label list\` first and use only labels that exist.
+ One problem per issue — never a bundle.
+5. **Bodies must be decision-complete**, in this shape:
+ - **Problem** — what is wrong, with file:line references.
+ - **Impact** — the user-visible consequence, not the code smell.
+ - **Fix** — the approach you have DECIDED on, with the files it touches. If
+ the only obstacle was a design choice, make the call and state it with a
+ one-line rationale. Do not file a question.
+ - **Acceptance criteria** — checkboxes another agent can verify cold.
+6. **Cap yourself at 5 issues.** A handful of well-evidenced, ready-to-work
+ issues is worth more than a wall of nits, and a long tail of low-value issues
+ costs a human real triage time. Fewer than 5 real problems? File fewer.
+7. **Change no code.** No commits, no branches, no pull requests. The deliverable
+ is the filed issues.
+8. **Report at the end**: the slice you audited, each issue number and title, and
+ anything you deliberately did not file and why.
+
+If \`gh\` cannot reach the network (errors like "bad file descriptor" or a
+connect timeout), do not give up silently — fall back to the REST API with the
+token from the local keyring:
+\`TOK=$(command gh auth token)\` then
+\`curl -sS -H "Authorization: Bearer $TOK" -H "Accept: application/vnd.github+json" -d @body.json https://api.github.com/repos/<owner>/<repo>/issues\`.
+A window spent finding real problems and filing none is a wasted window.
+
+Read this repository's \`CLAUDE.md\` (and any nested per-directory ones covering
+the slice) before you start, and honor its conventions and its explicitly
+declared non-issues — a finding that contradicts a documented project decision
+is noise, not a bug.`.trim();
+
+const auditPreset = ({ id, label, summary, labels, dedupeSearch, mission }) => Object.freeze({
+ id,
+ label,
+ summary,
+ jobType: QUOTA_BURN_JOB_TYPE.AGENT_PROMPT,
+ params: Object.freeze({ ...AUDIT_PARAMS, prompt: `${mission.trim()}\n\n${auditContract({ labels, dedupeSearch })}\n` }),
+});
+
+/**
+ * The catalog the config page offers. Order is presentation order; ids are
+ * stable because a job may record which preset seeded it for display.
+ */
+export const QUOTA_BURN_PROMPT_PRESETS = Object.freeze([
+ auditPreset({
+ id: 'ux-audit',
+ label: 'UX issues',
+ summary: 'Audit the UI for interaction friction and file the fixes as issues.',
+ labels: '`ux`, `area:ui`, `plan`',
+ dedupeSearch: 'ux audit',
+ mission: `
+# UX audit — file issues, change nothing
+
+You are auditing this application's USER EXPERIENCE and filing what you find as
+GitHub issues. You are not fixing anything this run.
+
+Work from the UI code (components, pages, drawers, forms) and reason about it as
+the person using it, not as the person who wrote it. Hunt specifically for:
+
+- **Controls that do something surprising.** An icon-only button that spends
+ money, deletes data, or dispatches work with no confirmation, no label, and no
+ distinction from the harmless controls beside it.
+- **Invisible state.** A surface that auto-saves with nothing on screen saying
+ so; a mutation with no confirmation; a background job whose progress is
+ guessable only from a spinner; "did that work?" moments generally.
+- **Disabled with no reason.** A button greyed out where the only explanation is
+ a \`title\` tooltip (invisible on touch) or nothing at all.
+- **Lost work.** Navigation, tab switches, or drawer closes that discard an
+ unsaved edit; forms that clear on error; optimistic updates that silently
+ revert.
+- **Dead ends.** Empty states that suggest no next action, errors that state a
+ failure without a remedy, filters that can produce a blank screen with no way
+ back.
+- **Inconsistency with the rest of the app.** The same concept spelled two ways,
+ a hand-rolled clone of a shared component, a flow that breaks the conventions
+ the project's UI docs describe.
+- **Reachability.** A view that cannot be linked to, bookmarked, or reached from
+ the command palette / navigation because its selection lives in local state.
+
+Prefer one high-traffic screen audited deeply over ten skimmed.`,
+ }),
+
+ auditPreset({
+ id: 'a11y-audit',
+ label: 'Accessibility issues',
+ summary: 'Keyboard, screen-reader, focus, and contrast gaps in the UI.',
+ labels: '`ux`, `area:ui`, `plan`',
+ dedupeSearch: 'accessibility a11y',
+ mission: `
+# Accessibility audit — file issues, change nothing
+
+Audit this application's UI for accessibility defects and file them as GitHub
+issues. No code changes this run.
+
+Look for the failures that actually lock someone out:
+
+- **Click handlers with no keyboard path** — a \`div\`/\`span\`/icon with
+ \`onClick\` and no \`role\`, \`tabIndex\`, or Enter/Space handling.
+- **Unlabeled controls** — icon-only buttons with no \`aria-label\`, inputs whose
+ label is styled text rather than a real \`<label htmlFor>\`/\`id\` pair, form
+ fields whose only cue is a placeholder.
+- **Focus management** — modals and drawers that do not take focus, do not
+ restore it on close, or let Tab escape behind the overlay; a destructive
+ confirm the keyboard reaches before the cancel.
+- **State that only exists visually** — validation errors, async status, and
+ live updates that never reach a screen reader (no \`aria-live\`,
+ \`aria-invalid\`, \`aria-expanded\`, \`aria-busy\`).
+- **Contrast and sizing** — low-contrast secondary text against the app's
+ background, text below ~12px carrying real meaning, meaning conveyed by color
+ alone.
+- **Motion and autoplay** — animation or autoplaying media that ignores
+ \`prefers-reduced-motion\`.
+
+Verify each finding against the file rather than assuming a pattern is wrong —
+many components already handle this correctly through a shared helper, and
+re-filing those wastes the window.`,
+ }),
+
+ auditPreset({
+ id: 'mobile-audit',
+ label: 'Mobile & responsive issues',
+ summary: 'Small-screen layout, touch targets, and hover-only affordances.',
+ labels: '`ux`, `area:ui`, `plan`',
+ dedupeSearch: 'mobile responsive',
+ mission: `
+# Mobile / responsive audit — file issues, change nothing
+
+Audit this application's UI on small screens and file what breaks as GitHub
+issues. No code changes this run.
+
+Read the components' layout classes and reason about a ~375px-wide viewport:
+
+- **Horizontal overflow** — fixed pixel widths, wide tables/grids/code blocks
+ with no scroll container, a page body that scrolls sideways.
+- **Touch targets** — interactive elements smaller than ~44px, or packed so
+ tightly that the destructive one sits under the thumb.
+- **Hover-only information** — anything whose meaning lives in a \`title\` or a
+ hover tooltip, which touch users never see. Disabled-button explanations and
+ icon-only controls are the usual offenders.
+- **Modals, drawers, and menus** that assume desktop width instead of becoming a
+ full-screen sheet, or whose scroll region is the page rather than the panel.
+- **Above the fold** — the primary action of a screen pushed below a stack of
+ configuration on a short viewport.
+- **Breakpoint drift** — responsive utility classes referencing breakpoints the
+ build does not define, so the style silently never applies.
+
+Name the exact screens you checked; a claim about "the app" that cites no
+component is not a finding.`,
+ }),
+
+ auditPreset({
+ id: 'resilience-audit',
+ label: 'Error & empty-state issues',
+ summary: 'Failure paths: silent catches, double toasts, stale data, lost edits.',
+ labels: '`bug`, `ux`, `plan`',
+ dedupeSearch: 'error handling empty state',
+ mission: `
+# Failure-path audit — file issues, change nothing
+
+Audit what this application does when things go WRONG, and file the gaps as
+GitHub issues. No code changes this run.
+
+The happy path is usually fine; look at the other branches:
+
+- **Swallowed failures** — a \`.catch()\` that returns a fallback and shows the
+ user nothing, so a failed save looks exactly like a successful one.
+- **Doubled or missing feedback** — a request helper that toasts AND a caller
+ that toasts (two toasts for one failure), or a mutation that toasts neither.
+- **Absent vs. empty conflated** — a fetch that failed rendering as "you have
+ none", a cache that cannot tell "not loaded" from "loaded, legitimately zero",
+ a merge where a missing key clears a value the user set.
+- **Stale UI after a mutation** — a list that keeps the deleted row, a detail
+ view still showing pre-save values, a status that never clears on failure.
+- **Unsaved-work loss** — a debounced save dropped on unmount, an edit discarded
+ by a tab switch or a refetch that overwrites in-flight typing.
+- **Retry and recovery** — a transient failure that latches a control off for
+ the life of the page, with no way to re-arm short of a reload.
+
+For each finding, state the failure trigger concretely (which call, failing how)
+and what the user sees instead of the truth.`,
+ }),
+
+ auditPreset({
+ id: 'perf-audit',
+ label: 'Performance issues',
+ summary: 'Hot-path waste: render storms, N+1 reads, unbounded lists, polling.',
+ labels: '`bugs-perf`, `plan`',
+ dedupeSearch: 'performance slow',
+ mission: `
+# Performance audit — file issues, change nothing
+
+Audit this application for real performance defects and file them as GitHub
+issues. No code changes this run.
+
+Chase work that scales badly, not micro-optimizations:
+
+- **Per-item I/O in a loop** — a request handler that reads or queries once per
+ record where one batched read would do.
+- **Repeated expensive scans** — the same directory walk, file parse, or
+ aggregation performed twice in one request, or on every poll.
+- **Unbounded growth** — lists, logs, caches, or in-memory maps with no cap;
+ responses that serialize an entire collection to render a picker that needs
+ two fields.
+- **Render storms** — state updated on every keystroke or every socket frame
+ with no debounce/batching, context values rebuilt each render, expensive
+ derived values recomputed unmemoized in a hot component.
+- **Timers and polling** — intervals that keep running after unmount, poll
+ frequencies far tighter than the data changes, backoff-free retry loops.
+- **Leaks** — subscriptions, listeners, PTYs, or GPU/media resources allocated
+ without a matching teardown.
+
+Quantify the cost where you can ("N universes ⇒ N file reads per page load") —
+a finding with a magnitude is one someone can prioritize.`,
+ }),
+
+ auditPreset({
+ id: 'test-gap-audit',
+ label: 'Test coverage gaps',
+ summary: 'Untested logic where a regression would cost data, money, or quota.',
+ labels: '`tests`, `plan`',
+ dedupeSearch: 'test coverage',
+ mission: `
+# Test-gap audit — file issues, change nothing
+
+Find the places where this repository's tests would NOT catch a regression that
+matters, and file them as GitHub issues. No code changes this run — you are
+specifying the tests, not writing them.
+
+Rank candidates by what a silent break would cost:
+
+- **Irreversible or expensive paths first** — anything that deletes or
+ overwrites user data, spends provider quota or money, writes to a shared
+ store, or ships something outward.
+- **Guards and gates** — a condition that exists specifically to prevent a past
+ incident, with no test asserting it still holds.
+- **Branchy pure logic** — normalizers, mergers, and validators whose tests only
+ cover the happy shape, leaving the absent/empty/malformed cases unasserted.
+- **Recently fixed bugs** — walk recent fix commits; a fix landed without a
+ regression test is the highest-value gap on this list.
+- **Shape-dense code** — where reviewers keep finding a new failing input,
+ propose a property test over generated inputs rather than more example cases.
+- **False green** — suites so heavily mocked that they would pass against a
+ broken implementation, or that assert a call happened but never its arguments.
+
+Each issue should name the file under test, the specific cases to assert, and
+where the test file belongs.`,
+ }),
+
+ auditPreset({
+ id: 'simplify-audit',
+ label: 'Dead code & duplication',
+ summary: 'Unused exports, copy-paste drift, and helpers that should be reused.',
+ labels: '`code-quality`, `plan`',
+ dedupeSearch: 'dead code duplication',
+ mission: `
+# Dead-code and duplication audit — file issues, change nothing
+
+Find code this repository would be better without, and file the removals as
+GitHub issues. No code changes this run.
+
+- **Unreferenced code** — exports with no importer, components rendered from
+ nowhere, feature flags with one branch permanently dead, config keys nothing
+ reads. Verify with a repo-wide search before filing; a dynamic or
+ string-keyed reference is easy to miss and a wrong removal is expensive.
+- **Re-implemented helpers** — a local function that duplicates something the
+ project's shared library catalogs already provide. Cite both, and propose the
+ reuse.
+- **Copy-paste drift** — near-identical blocks that have diverged, where one copy
+ has a fix the other never got. That divergence is a latent bug; say which copy
+ is correct.
+- **Modules that outgrew their file** — one file holding several unrelated
+ concerns, or a component whose body has swallowed logic that belongs in a
+ hook or a pure helper. Propose the split, with the new file names.
+- **Stale scaffolding** — commented-out blocks, TODOs whose work already
+ shipped, migration or compatibility shims whose trigger can no longer occur.
+
+Note carefully: cross-version and cross-install compatibility code is NOT dead
+code, even when this install no longer hits it. Read the project's rules on
+migrations and version gates before proposing any such removal.`,
+ }),
+
+ auditPreset({
+ id: 'data-safety-audit',
+ label: 'Data & upgrade-safety issues',
+ summary: 'Migrations, schema parity, and cross-version compatibility gaps.',
+ labels: '`bug`, `area:database`, `plan`',
+ dedupeSearch: 'migration schema compatibility',
+ mission: `
+# Data and upgrade-safety audit — file issues, change nothing
+
+Audit this repository for changes that could corrupt, lose, or strand user data
+across upgrades and machines, and file them as GitHub issues. No code changes
+this run.
+
+- **Format changes without a migration** — a stored shape the code now expects
+ that an older install's files or rows do not have, with nothing to convert
+ them and no defensive read path.
+- **Missing seeds and defaults** — a new stored artifact with no shipped
+ reference copy, so a fresh install starts broken.
+- **Schema parity drift** — a field added to a sanitizer, writer, or payload but
+ never to the validation schema (or the reverse), so a valid record is rejected
+ or an invalid one is stored.
+- **Version gates** — cross-machine or cross-version payloads whose meaning
+ changed without the version marker moving, letting a newer peer feed something
+ an older one will mis-handle.
+- **Destructive defaults** — an exclude/cleanup/reset path whose pattern is
+ broader than intended, a delete that is not scoped, a write that clobbers a
+ field it never read.
+- **Read-modify-write races between two paths** that mutate the same record or
+ file and can drop one another's changes.
+
+State the upgrade scenario explicitly for each finding: which install, holding
+what, upgrading to what, and what breaks.`,
+ }),
+
+ auditPreset({
+ id: 'docs-audit',
+ label: 'Docs drift',
+ summary: 'Docs and onboarding steps the code no longer matches.',
+ labels: '`documentation`, `plan`',
+ dedupeSearch: 'docs documentation drift',
+ mission: `
+# Documentation-drift audit — file issues, change nothing
+
+Find where this repository's documentation and its code disagree, and file the
+corrections as GitHub issues. No code changes this run — including no doc edits.
+
+Verify claims against the source rather than reading docs on their own:
+
+- **Setup and run instructions** that name commands, scripts, ports, or
+ environment variables the code no longer uses (or omits ones now required).
+- **Architecture docs** describing a module layout, data location, or flow that
+ has since moved.
+- **Convention docs** stating a rule the codebase has broadly stopped following —
+ say which is now correct, the rule or the code, and why.
+- **Undocumented surfaces** — a feature, endpoint, config key, or failure mode a
+ new contributor cannot discover from the docs at all.
+- **Examples that would fail** if pasted into a terminal today.
+- **Stale references** — links to files that moved, issues long closed, or
+ external resources that no longer exist.
+
+Prioritize the docs a newcomer hits first; a wrong README costs more than a
+wrong deep-dive.`,
+ }),
+
+ auditPreset({
+ id: 'security-audit',
+ label: 'Security issues (in-threat-model)',
+ summary: 'Real exposure for this deployment model — no boilerplate hardening.',
+ labels: '`bug`, `plan`',
+ dedupeSearch: 'security',
+ mission: `
+# Security audit — file issues, change nothing
+
+Audit this repository for security defects that are REAL under its actual threat
+model, and file them as GitHub issues. No code changes this run.
+
+Read the project's documented security model FIRST and treat it as binding. If
+it declares something a non-issue for this deployment (an omitted control, a
+documented default, an accepted risk), do not file it — a window spent re-filing
+an explicitly closed concern is worse than a window spent idle.
+
+What is worth filing:
+
+- **Secrets in the wrong place** — credentials, tokens, or keys that could reach
+ a commit, a log line, a bundled client asset, a shared artifact, or an
+ outbound request that had no business carrying them.
+- **Command and path injection** — user-controlled input reaching a shell, a
+ path join, or a dynamic import without validation; an allowlist that a crafted
+ value can walk out of.
+- **Destructive operations with too little scoping** — a delete, overwrite, or
+ reset whose target is computed rather than constrained, especially where a
+ test or dev path could aim it at real data.
+- **Trust boundaries that are actually crossed** — data arriving from another
+ machine, a third-party API, or a model response being used without validation
+ where a malformed or hostile value would do damage.
+- **Dependency exposure** — a known-vulnerable package on a path that actually
+ processes untrusted input (not a transitive dev-only advisory).
+
+Every finding needs a plausible attacker or accident story that ends in real
+harm. "Best practice says otherwise" is not one.`,
+ }),
+]);
+
+/** Look up a preset by id. Returns `null` for an unknown id — never throws. */
+export function findQuotaBurnPreset(id) {
+ return QUOTA_BURN_PROMPT_PRESETS.find((preset) => preset.id === id) || null;
+}
diff --git a/server/lib/quotaBurnPresets.test.js b/server/lib/quotaBurnPresets.test.js
new file mode 100644
index 0000000000..2435654f64
--- /dev/null
+++ b/server/lib/quotaBurnPresets.test.js
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import { QUOTA_BURN_PROMPT_PRESETS, findQuotaBurnPreset } from './quotaBurnPresets.js';
+import { QUOTA_BURN_BOUNDS, QUOTA_BURN_JOB_CATALOG, QUOTA_BURN_JOB_TYPES, normalizeQuotaBurnJob } from './quotaBurnConfig.js';
+import { quotaBurnConfigUpdateSchema } from './quotaBurnValidation.js';
+
+const presetJob = (preset) => ({
+ id: 'j1', enabled: true, label: preset.label, jobType: preset.jobType, model: null, providerId: null,
+ params: { appId: 'app-1', ...preset.params },
+});
+
+describe('QUOTA_BURN_PROMPT_PRESETS', () => {
+ it('exposes unique ids with a label, a summary, and a real prompt', () => {
+ expect(QUOTA_BURN_PROMPT_PRESETS.length).toBeGreaterThan(0);
+ const ids = QUOTA_BURN_PROMPT_PRESETS.map((preset) => preset.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {
+ expect(preset.label.trim()).not.toBe('');
+ expect(preset.summary.trim()).not.toBe('');
+ expect(preset.params.prompt.trim().length).toBeGreaterThan(200);
+ }
+ });
+
+ it('only seeds job types the catalog actually offers, with params that type declares', () => {
+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {
+ expect(QUOTA_BURN_JOB_TYPES).toContain(preset.jobType);
+ const spec = QUOTA_BURN_JOB_CATALOG.find((type) => type.id === preset.jobType);
+ const known = new Set(spec.params.map((descriptor) => descriptor.key));
+ // A param the job type does not read is dead weight the runner ignores —
+ // the preset would look configured and behave as if it were not.
+ expect(Object.keys(preset.params).filter((key) => !known.has(key))).toEqual([]);
+ }
+ });
+
+ it('survives job normalization with the prompt intact', () => {
+ // The normalizer slices strings at `paramLength.max`. A preset that grew past
+ // it would be stored truncated — mid-sentence, with nothing on screen saying
+ // so — which is exactly the failure this bound makes silent.
+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {
+ expect(preset.params.prompt.length).toBeLessThanOrEqual(QUOTA_BURN_BOUNDS.paramLength.max);
+ const normalized = normalizeQuotaBurnJob(presetJob(preset));
+ expect(normalized).not.toBeNull();
+ expect(normalized.params.prompt).toBe(preset.params.prompt);
+ }
+ });
+
+ it('passes the config PUT schema, so a preset job can actually be saved', () => {
+ const body = { families: { claude: { jobs: QUOTA_BURN_PROMPT_PRESETS.map(presetJob) } } };
+ expect(() => quotaBurnConfigUpdateSchema.parse(body)).not.toThrow();
+ });
+
+ it('configures audit presets as read-only work', () => {
+ // These prompts file issues and change nothing. Leaving openPR/simplify on
+ // sends the agent hunting for a diff to ship at the end of a window where
+ // there is none.
+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {
+ expect(preset.params.openPR).toBe(false);
+ expect(preset.params.simplify).toBe(false);
+ expect(preset.params.useWorktree).toBe(true);
+ }
+ });
+
+ it('tells the agent to file issues, cap its output, and not change code', () => {
+ for (const preset of QUOTA_BURN_PROMPT_PRESETS) {
+ const prompt = preset.params.prompt;
+ expect(prompt).toMatch(/gh issue create/);
+ expect(prompt).toMatch(/gh issue list/);
+ expect(prompt.toLowerCase()).toMatch(/no commits, no branches, no pull requests/);
+ expect(prompt).toMatch(/Cap yourself at 5 issues/);
+ }
+ });
+});
+
+describe('findQuotaBurnPreset', () => {
+ it('finds a known preset and returns null for anything else', () => {
+ expect(findQuotaBurnPreset(QUOTA_BURN_PROMPT_PRESETS[0].id)).toBe(QUOTA_BURN_PROMPT_PRESETS[0]);
+ expect(findQuotaBurnPreset('nope')).toBeNull();
+ expect(findQuotaBurnPreset(undefined)).toBeNull();
+ });
+});
diff --git a/server/routes/quotaBurn.js b/server/routes/quotaBurn.js
index 2f1f774d5d..15f34359e7 100644
--- a/server/routes/quotaBurn.js
+++ b/server/routes/quotaBurn.js
@@ -8,6 +8,7 @@ import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, quotaBurnConfigUpdateSchema, quotaBurnRunSchema } from '../lib/validation.js';
import { QUOTA_BURN_JOB_CATALOG } from '../lib/quotaBurnConfig.js';
+import { QUOTA_BURN_PROMPT_PRESETS } from '../lib/quotaBurnPresets.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { saveQuotaBurnConfig } from '../services/quotaBurnStore.js';
import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';
@@ -39,6 +40,10 @@ router.get('/catalog', asyncHandler(async (_req, res) => {
]);
res.json({
jobTypes: QUOTA_BURN_JOB_CATALOG,
+ // Prompt templates for `agent-prompt` jobs. Served rather than bundled into
+ // the client so the wording is one server-side edit — and so a job the user
+ // has already tuned is never overwritten by a newer version of the text.
+ presets: QUOTA_BURN_PROMPT_PRESETS,
apps: (apps || []).map((app) => ({ id: app.id, name: app.name })),
universes,
// Exactly the modes the media job queue can dispatch — the burn job enqueues