Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
close the upgrade path that armed quota-burn without consent, and three gates that never fired
[._.]/ Adam Eivy65c884099aa4
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsxindex d4034dcbd6..457d4b59d7 100644--- a/client/src/pages/QuotaBurn.jsx+++ b/client/src/pages/QuotaBurn.jsx@@ -19,6 +19,7 @@ import { Flame, RefreshCw } from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';import FamilyCard from '../components/quotaBurn/FamilyCard';+import { NumberField } from '../components/quotaBurn/fields';import * as api from '../services/api';import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';import { coalesce } from '../utils/coalesce';@@ -55,6 +56,10 @@ export default function QuotaBurn() {// flight, and two overlapping saves can land out of order and leave the page// showing a value the server does not hold.const editSeqRef = useRef(0);+ // One retry per failed patch, and a self-reference so the failure branch can+ // re-arm the debounce it lives inside.+ const retriedRef = useRef(false);+ const persistRef = useRef(null);const load = useCallback(async (refresh = false) => {const seq = editSeqRef.current;@@ -91,8 +96,21 @@ export default function QuotaBurn() {// `unsaved` must stay true so the run buttons keep reflecting that the// server does not have these values.pendingRef.current = mergeQuotaBurnPatch(patch, pendingRef.current);+ // Retry ONCE. Without it a single transient blip latches every run+ // control off for the life of the page (nothing else re-arms the+ // debounce, and the only hint is a title tooltip that touch never shows).+ // Bounded at one because a rejected patch will just be rejected again —+ // past that, tell the user plainly and let their next edit re-arm it.+ if (!retriedRef.current) {+ retriedRef.current = true;+ persistRef.current?.();+ } else {+ retriedRef.current = false;+ toast.error('Changes are still unsaved — edit a field to retry.');+ }return;}+ retriedRef.current = false;// The server's normalization is authoritative — adopt what it stored, but// only while no newer keystroke has landed. Then re-read status so pending// counts and skip reasons match the saved plan.@@ -104,6 +122,8 @@ export default function QuotaBurn() {if (!pendingRef.current) setUnsaved(false);}, SAVE_DEBOUNCE_MS), [load]);+ persistRef.current = persist;+useEffect(() => () => {persist.cancel();// Flush, don't drop. `cancel()` alone discards everything typed in the last@@ -173,19 +193,19 @@ export default function QuotaBurn() {<label htmlFor="quota-burn-enabled" className="text-sm text-white">Run the quota-burn loop automatically</label>- <label htmlFor="quota-burn-interval" className="text-xs text-gray-400 ml-auto flex items-center gap-2">- Check every- <input+ {/* NumberField, not a bare input — an emptied box must not commit+ `Number('') === 0`, which is below this field's server minimum of+ 5 and 400s the whole coalesced save. */}+ <div className="ml-auto flex items-end gap-2 text-xs text-gray-400">+ <NumberFieldid="quota-burn-interval"- type="number"- min="5"- max="720"- className="w-20 bg-port-bg border border-port-border rounded p-1.5 text-white text-xs"+ label="Check every (minutes)"value={config.checkIntervalMinutes}- onChange={(event) => save({ checkIntervalMinutes: Number(event.target.value) })}+ min={5}+ max={720}+ onChange={(next) => save({ checkIntervalMinutes: next })}/>- minutes- </label>+ </div></div><p className="text-xs text-gray-400">One loop for this install. Each provider family burns only inside its reset window, above its reserve, and within itsdiff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex 39935f933d..d1a56ba343 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -68,8 +68,7 @@ request), and the catalog descriptors the client renders as `min`/`max`.## Storage-The plan, the dispatch ledger, and the run log all live machine-locally under-`data/cos/` and are intentionally **not federated**: quota belongs to a+Four 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`), and 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). They are not federated: quota belongs to aparticular machine and provider account, and the "which managed app" targetsdiffer per machine.diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 927b72ba1c..71ca04cf6f 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -56,7 +56,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.- 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 companion `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days) and `data/cos/quota-burn-runs.json` (capped run log) are `ephemeral-file` — regenerable telemetry. 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 + 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 three 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), and `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). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.---diff --git a/scripts/migrations/221-quota-burn-global-config.js b/scripts/migrations/221-quota-burn-global-config.jsindex 6bd71d030f..dc41ce0545 100644--- a/scripts/migrations/221-quota-burn-global-config.js+++ b/scripts/migrations/221-quota-burn-global-config.js@@ -66,7 +66,7 @@ const writeJsonAtomic = async (abs, value) => {* @returns {{ config: object|null, touchedAppIds: string[] }} `config` is null* when no app configured a family (nothing to migrate).*/-export function buildGlobalPlan(apps) {+export function buildGlobalPlan(apps, { scheduleArmed = true } = {}) {const families = {};const touchedAppIds = [];let jobSeq = 0;@@ -76,13 +76,19 @@ export function buildGlobalPlan(apps) {touchedAppIds.push(app.id);const configured = override.taskMetadata?.families;if (!configured || typeof configured !== 'object') continue;- // The OLD shape had TWO independent switches: the task type had to be- // enabled for the app (`isTaskTypeEnabledForApp` reads `override.enabled`)- // AND the family had to be enabled inside `taskMetadata.families`. Reading- // only the family flag would arm a burn on an install that configured a- // family, tried it, then switched the whole task type off — unrequested- // provider spend on upgrade. Both must be true.- const appArmed = override.enabled === true;+ // The OLD shape had THREE independent switches, all of which had to be on+ // for a single token to be spent:+ // 1. the install-wide schedule — `shouldRunTask` returns+ // `{ shouldRun: false, reason: 'disabled' }` unless+ // `task-schedule.json`'s `tasks['quota-burn'].enabled` is true, and the+ // shipped default was FALSE (`scheduleArmed`)+ // 2. the per-app task-type override (`isTaskTypeEnabledForApp` reads+ // `override.enabled`)+ // 3. the per-family flag inside `taskMetadata.families`+ // Reading fewer than all three arms a burn on an install that configured a+ // family and never turned the feature on — unrequested provider spend on+ // upgrade, which CLAUDE.md's AI Provider Usage Policy forbids outright.+ const appArmed = scheduleArmed && override.enabled === true;for (const [familyId, value] of Object.entries(configured)) {if (!FAMILIES.includes(familyId) || !value || typeof value !== 'object') continue;const armed = appArmed && value.enabled === true;@@ -155,23 +161,30 @@ export function buildGlobalPlan(apps) {}/**- * Drop the dead `quota-burn` entry from the install-wide schedule file. Runs- * even when no app carried an override — an install could have flipped the type- * on globally and never scoped it to an app.+ * Read the install-wide schedule switch, then drop the dead `quota-burn` entry+ * from the schedule file. Returns `{ armed, pruned }`.+ *+ * `armed` MUST be read before the prune — it is switch #1 of the three the old+ * shape required, and pruning first would delete the only record of whether+ * this install had ever turned quota-burn on. An ABSENT entry reads as armed:+ * `loadSchedule` merges `DEFAULT_TASK_INTERVALS` over what's on disk, so a file+ * predating the type simply inherited the default — the per-app switches are+ * then the deciding vote, exactly as they were at runtime.*/-async function pruneScheduleFile(rootDir) {+async function readAndPruneSchedule(rootDir) {const scheduleFile = join(rootDir, 'data', 'cos', 'task-schedule.json');const schedule = await readJson(scheduleFile);- if (!schedule?.tasks || !Object.hasOwn(schedule.tasks, 'quota-burn')) return false;+ if (!schedule?.tasks || !Object.hasOwn(schedule.tasks, 'quota-burn')) return { armed: true, pruned: false };+ const armed = schedule.tasks['quota-burn']?.enabled === true;const { 'quota-burn': _dropped, ...tasks } = schedule.tasks;await writeJsonAtomic(scheduleFile, { ...schedule, tasks });- console.log('🔥 migration 221: removed the dead quota-burn entry from the CoS schedule');- return true;+ console.log(`🔥 migration 221: removed the dead quota-burn entry from the CoS schedule (was ${armed ? 'enabled' : 'disabled'})`);+ return { armed, pruned: true };}export default {async up({ rootDir }) {- const prunedSchedule = await pruneScheduleFile(rootDir);+ const { armed: scheduleArmed, pruned: prunedSchedule } = await readAndPruneSchedule(rootDir);const appsFile = join(rootDir, 'data', 'apps.json');const data = await readJson(appsFile);const appsMap = data?.apps && typeof data.apps === 'object' ? data.apps : null;@@ -181,7 +194,7 @@ export default {}const apps = Object.entries(appsMap).map(([id, app]) => ({ id, ...app }));- const { config, touchedAppIds } = buildGlobalPlan(apps);+ const { config, touchedAppIds } = buildGlobalPlan(apps, { scheduleArmed });if (!touchedAppIds.length) {console.log('🔥 migration 221: no app carries a quota-burn override — nothing to migrate');return { ok: true, reason: 'no-overrides', prunedSchedule };diff --git a/scripts/migrations/221-quota-burn-global-config.test.js b/scripts/migrations/221-quota-burn-global-config.test.jsindex 897279a985..6719ed88f0 100644--- a/scripts/migrations/221-quota-burn-global-config.test.js+++ b/scripts/migrations/221-quota-burn-global-config.test.js@@ -171,3 +171,56 @@ describe('buildGlobalPlan enabled semantics', () => {expect(config.checkIntervalMinutes).toBe(720);});});++describe('buildGlobalPlan install-wide schedule switch', () => {+ it('stays silent when the task type was never enabled install-wide', () => {+ // The old shape needed THREE switches on: the install-wide schedule+ // (shipped default FALSE), the per-app override, and the per-family flag.+ // Reading only the last two arms a burn on an install that configured a+ // family in the per-app panel and never turned the feature on — spending+ // provider quota on upgrade with no user action.+ const { config } = buildGlobalPlan(+ [app('a1', { grok: { enabled: true, prompt: 'Refactor X' } })],+ { scheduleArmed: false },+ );+ expect(config.enabled).toBe(false);+ expect(config.families.grok.enabled).toBe(false);+ expect(config.families.grok.jobs[0].enabled).toBe(false);+ });+});++describe('migration 221 reads the schedule switch before pruning it', () => {+ let rootDir;+ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-221b-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ });+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });++ const write = (rel, value) => writeFile(join(rootDir, ...rel), JSON.stringify(value));++ it('does not arm a plan whose schedule entry was disabled', async () => {+ // pruneScheduleFile runs first and DELETES the entry — reading `armed`+ // after it would lose the only record of whether this install ever ran.+ await write(['data', 'apps.json'], {+ apps: { a1: { taskTypeOverrides: { 'quota-burn': { enabled: true, taskMetadata: { families: { grok: { enabled: true, prompt: 'x' } } } } } } },+ });+ await write(['data', 'cos', 'task-schedule.json'], { version: 2, tasks: { 'quota-burn': { enabled: false } } });++ await migration.up({ rootDir });+ const plan = JSON.parse(await readFile(join(rootDir, 'data', 'cos', 'quota-burn.json'), 'utf-8'));+ expect(plan.enabled).toBe(false);+ expect(plan.families.grok.enabled).toBe(false);+ });++ it('arms a plan whose schedule entry WAS enabled', async () => {+ await write(['data', 'apps.json'], {+ apps: { a1: { taskTypeOverrides: { 'quota-burn': { enabled: true, taskMetadata: { families: { grok: { enabled: true, prompt: 'x' } } } } } } },+ });+ await write(['data', 'cos', 'task-schedule.json'], { version: 2, tasks: { 'quota-burn': { enabled: true } } });++ await migration.up({ rootDir });+ const plan = JSON.parse(await readFile(join(rootDir, 'data', 'cos', 'quota-burn.json'), 'utf-8'));+ expect(plan.enabled).toBe(true);+ });+});diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex 3b32eefbc4..15a9b20ccd 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -78,11 +78,52 @@ function selectLimit(card, family, now) {.sort((a, b) => a.hours - b.hours)[0] || null;}-/** Headroom the family is willing to spend: what's left, minus its reserve. */+/** Headroom the family is willing to spend on ONE window: what's left, minus its reserve. */export function burnBudgetRemaining(limit, family) {return Math.max(0, Number(limit?.percentRemaining) - family.reservePercent);}+/**+ * The window with the LEAST headroom among everything in scope — what the+ * reserve is actually protecting.+ *+ * Checking only the soonest-resetting window (which is what selection keys on)+ * makes the reserve inert for every provider that reports two: claude, codex and+ * agy each expose a short rolling window AND a weekly one on the same card, and+ * the short one is always the soonest. A card at `session: 100%` / `week: 2%`+ * with a 40% reserve would pass the gate on the session number and drain a+ * weekly allowance already far below the floor the user set — while the field's+ * own hint reads "Never spend below this much headroom".+ */+function tightestBudget(card, family) {+ const scoped = (card.limits || []).filter((limit) =>+ (!family.scope || limit.scope === family.scope) && Number.isFinite(Number(limit?.percentRemaining)));+ if (!scoped.length) return null;+ return scoped.reduce((tightest, limit) =>+ (burnBudgetRemaining(limit, family) < burnBudgetRemaining(tightest, family) ? limit : tightest));+}++/**+ * The ledger key for one window: `<family>:<resetEpoch rounded to the hour>`.+ *+ * The rounding is load-bearing. Antigravity states its reset only as a RELATIVE+ * string ("Refreshes in 4h 57m"), which `parseAgyUsage` turns into+ * `now + duration` — so an exact-epoch key drifts by a minute or two on every+ * scrape and each cycle mints a FRESH key with a count of zero. The per-window+ * cap then never engages: an agy family would burn once per tick forever+ * (~48/day at the default interval) while the page's "1/5 used" badge showed+ * 0/5, and the ledger accumulated a dead key per cycle. Rounding to the hour+ * collapses that drift into one bucket. The residual cost is a window whose true+ * reset sits within a scrape's drift of a half-hour boundary, which can straddle+ * two buckets and allow one extra dispatch — a bounded overshoot, versus an+ * unbounded one.+ */+const HOUR_MS = 60 * 60 * 1000;+export function windowKey(familyId, limit, { now = Date.now() } = {}) {+ const epoch = normalizeResetAt(limit, { now }).epochMs;+ return `${familyId}:${Math.round(epoch / HOUR_MS) * HOUR_MS}`;+}+/*** THE gate ladder. Evaluates one family against its live quota card and returns* either a burn candidate or the reason it isn't one — never both, never@@ -133,8 +174,11 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}// forced run can't invent one either, so this gate holds even under bypass.if (!selected) return { skipReason: 'no window states a reset time' };- const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now }).epochMs}`;+ const dispatchKey = windowKey(family.id, selected.limit, { now });const dispatchesUsed = Number(dispatches[dispatchKey] || 0);+ // The reserve guards the TIGHTEST window in scope, not the one selection+ // happens to key on (see `tightestBudget`).+ const tightest = tightestBudget(card, family) || selected.limit;// The three gates a forced run is allowed past. Evaluated regardless so the// ordering (and the wording) stays in one place; only the return is skipped.@@ -146,8 +190,9 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}if (dispatchesUsed >= family.maxDispatchesPerWindow) {return { skipReason: `dispatch cap reached (${dispatchesUsed}/${family.maxDispatchesPerWindow})` };}- if (burnBudgetRemaining(selected.limit, family) <= 0) {- return { skipReason: `${selected.limit.percentRemaining}% left is at or below the ${family.reservePercent}% reserve` };+ if (burnBudgetRemaining(tightest, family) <= 0) {+ const which = tightest.label || tightest.scope || 'window';+ return { skipReason: `${which} at ${tightest.percentRemaining}% left is at or below the ${family.reservePercent}% reserve` };}}diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.jsindex e63b662022..4f776c3624 100644--- a/server/services/quotaBurn.test.js+++ b/server/services/quotaBurn.test.js@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { burnBudgetRemaining, evaluateFamilies, selectBurnCandidates } from './quotaBurn.js';+import { burnBudgetRemaining, evaluateFamilies, selectBurnCandidates, windowKey } from './quotaBurn.js';import { normalizeQuotaBurnConfig } from '../lib/quotaBurnConfig.js';const NOW = Date.parse('2026-07-26T12:00:00.000Z');@@ -184,3 +184,48 @@ describe('recordQuotaBurnDispatch', () => {expect(next).toEqual({ 'grok:not-a-number': 1, [`grok:${NOW}`]: 1 });});});++describe('windowKey', () => {+ it('collapses a provider that reports its reset only as a relative duration', () => {+ // Antigravity states "Refreshes in 4h 57m", which parseAgyUsage turns into+ // `now + duration` — so an exact-epoch key drifts a minute or two on every+ // scrape and each cycle mints a FRESH key with a count of zero. The cap+ // would never engage: ~48 burns/day against a maxDispatchesPerWindow of 5,+ // with the page's badge stuck at 0/5.+ const base = Date.parse('2026-07-26T16:57:00.000Z');+ const drifted = Date.parse('2026-07-26T16:56:20.500Z');+ expect(windowKey('agy', { resetsAt: new Date(base).toISOString() }, { now: NOW }))+ .toBe(windowKey('agy', { resetsAt: new Date(drifted).toISOString() }, { now: NOW }));+ });++ it('still separates genuinely different windows', () => {+ expect(windowKey('grok', { resetsAt: '2026-07-26T18:00:00.000Z' }, { now: NOW }))+ .not.toBe(windowKey('grok', { resetsAt: '2026-07-27T18:00:00.000Z' }, { now: NOW }));+ });+});++describe('reserve across every window', () => {+ const twoWindow = (sessionLeft, weekLeft) => ({+ family: 'claude', supported: true,+ limits: [+ { key: 'session', scope: 'session', label: '5-hour', resetsAt: '2026-07-26T15:00:00.000Z', percentRemaining: sessionLeft },+ { key: 'week', scope: 'week', label: 'Weekly', resetsAt: '2026-08-01T00:00:00.000Z', percentRemaining: weekLeft },+ ],+ });+ const family = normalizeQuotaBurnConfig({+ families: { claude: { enabled: true, resetWithinHours: 24, reservePercent: 40, jobs: [job()] } },+ });++ it('refuses to drain the WEEKLY window just because the session window is full', () => {+ // Claude/codex/agy all expose a short window AND a weekly one, and the short+ // one is always the soonest — so checking only the selected limit made the+ // reserve inert for every provider that has two.+ const verdict = evaluateFamilies([twoWindow(100, 2)], family, { now: NOW })[0];+ expect(verdict.candidate).toBeUndefined();+ expect(verdict.skipReason).toMatch(/Weekly at 2% left is at or below the 40% reserve/);+ });++ it('burns when EVERY in-scope window is above the reserve', () => {+ expect(evaluateFamilies([twoWindow(100, 90)], family, { now: NOW })[0].candidate).toBeTruthy();+ });+});diff --git a/server/services/quotaBurnJobs/index.js b/server/services/quotaBurnJobs/index.jsindex 381df6bf7a..b7fe05bbf0 100644--- a/server/services/quotaBurnJobs/index.js+++ b/server/services/quotaBurnJobs/index.js@@ -59,9 +59,9 @@ export async function countJobPending({ job, family }) {* treats it as "this job declined", moves on, and logs the reason — a burn that* failed to start must not charge the window's cap.*/-export async function runBurnJob({ job, family, candidate, context }) {+export async function runBurnJob({ job, family, candidate, context, force = false }) {const mod = await load(job?.jobType);if (!mod) return { dispatched: false, reason: `unknown job type: ${job?.jobType}` };- return mod.run({ params: job.params, job, family, candidate, context })+ return mod.run({ params: job.params, job, family, candidate, context, force }).catch((err) => ({ dispatched: false, reason: `job failed: ${err.message}` }));}diff --git a/server/services/quotaBurnJobs/universeBibleImages.js b/server/services/quotaBurnJobs/universeBibleImages.jsindex e8d995fa44..f72f0dc07b 100644--- a/server/services/quotaBurnJobs/universeBibleImages.js+++ b/server/services/quotaBurnJobs/universeBibleImages.js@@ -120,7 +120,7 @@ async function collect(params, inFlight = new Set()) {// (nothing dedupes them on write), so a case-insensitive dedupe here keeps// one row from expanding into several renders and blowing past the cap.const rows = dedupeByLabel(findMissingImageEntries(universe, { scope }))- .filter((row) => !inFlight.has(inFlightKey(universe.id, row.label)));+ .filter((row) => !inFlight.has(inFlightKey(universe.id, row)));total += rows.length;if (!rows.length || picked) continue;picked = { universe, rows: rows.slice(0, max) };@@ -128,7 +128,11 @@ async function collect(params, inFlight = new Set()) {return { picked, total, max };}-export const inFlightKey = (universeId, label) => `${universeId}:${String(label).toLowerCase()}`;+// Keyed on the same identity `dedupeByLabel` uses. Label alone would let one+// enqueued variation hide an unrelated canon entry that happens to share its+// name for six hours — dropping it from both the pick AND the backlog count.+export const inFlightKey = (universeId, row) =>+ `${universeId}:${row.kind}:${row.categoryKey || ''}:${String(row.label).toLowerCase()}`;/*** One row per case-insensitive label within a category/trunk. `compilePrompts`@@ -190,13 +194,15 @@ export async function countPending({ params, family } = {}) {* CODEX's image quota, not silently fall through to the install default and* burn a different provider's.*/-export async function run({ params, job, family, context } = {}) {+export async function run({ params, job, family, context, force = false } = {}) {const mode = resolveRenderMode({ params, family });if (!mode) return { dispatched: false, reason: `${family?.id} renders no images — pick a render backend on this job` };// Reuse the probe's scan when the runner supplied it; the page's force path// calls run() with no probe, so fall back to scanning here.- const { picked, total, max } = context ?? await collect(params, await getQuotaBurnInFlight());+ // A forced run ignores the cooldown: the user clicked ▶ on this exact job, and+ // 'already queued' is the state they are most likely trying to push past.+ const { picked, total, max } = context ?? await collect(params, force ? new Set() : await getQuotaBurnInFlight());if (!picked) return { dispatched: false, reason: 'no bible entries are missing images' };const { selection, canonSelection, sheetSelection } = buildRenderSelection(picked.rows);@@ -215,7 +221,7 @@ export async function run({ params, job, family, context } = {}) {// fills in when the render completes, so this cooldown is the only thing// stopping the next cycle from re-selecting the same entries and spending the// window's whole cap re-rendering them.- await recordQuotaBurnInFlight(picked.rows.map((row) => inFlightKey(picked.universe.id, row.label)));+ await recordQuotaBurnInFlight(picked.rows.map((row) => inFlightKey(picked.universe.id, row)));console.log(`🔥 Quota-burn rendered ${result.promptCount} bible image(s) for "${picked.universe.name}" via ${result.mode}`);return {diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex 05178e8446..4e9010f34d 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -56,13 +56,22 @@ const selectJobs = (family, { jobId = null, force = false } = {}) =>*/async function dispatchFromCandidate(candidate, { jobId = null, force = false } = {}) {const attempts = [];+ // A forced run of a NAMED job skips the pending probe entirely and calls the+ // job directly. The probe exists to pick which job in the plan to run; when+ // the user has already picked one, letting it veto the click reproduces the+ // silent no-op the force path exists to fix — one gate later. It bites hardest+ // on `universe-bible-images`, whose 6-hour in-flight cooldown makes the probe+ // report zero for entries that are merely already queued, with no way to+ // override it from the page. `force` is threaded into the job so it can relax+ // its own cooldown too.+ const targeted = force && jobId;for (const job of selectJobs(candidate.family, { jobId, force })) {- const pending = await countJobPending({ job, family: candidate.family });- if (!(pending.count > 0)) {+ const pending = targeted ? null : await countJobPending({ job, family: candidate.family });+ if (pending && !(pending.count > 0)) {attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });continue;}- const result = await runBurnJob({ job, family: candidate.family, candidate, context: pending.context });+ const result = await runBurnJob({ job, family: candidate.family, candidate, context: pending?.context, force });if (!result.dispatched) {attempts.push({ jobId: job.id, jobType: job.jobType, skipped: result.reason || 'declined' });continue;diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.jsindex eeec806e01..5466d06257 100644--- a/server/services/quotaBurnRunner.test.js+++ b/server/services/quotaBurnRunner.test.js@@ -302,3 +302,25 @@ describe('interval clock', () => {expect(getProviderQuotas).toHaveBeenCalled();});});++describe('forced run bypasses the pending probe', () => {+ it('calls the job directly instead of letting its own probe veto the click', async () => {+ // The probe exists to PICK a job. When the user already picked one, letting+ // it veto reproduces the silent no-op the force path exists to fix, one+ // gate later — it bites hardest on universe-bible-images, whose 6h+ // in-flight cooldown reports zero for entries that are merely queued.+ const { countJobPending } = await import('./quotaBurnJobs/index.js');+ state.pending = { second: { count: 0, detail: 'already queued' } };+ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'second', force: true });+ expect(countJobPending).not.toHaveBeenCalled();+ expect(result.dispatched).toBe(true);+ expect(state.ran.map((entry) => entry.jobId)).toEqual(['second']);+ });++ it('still probes on an unforced cycle', async () => {+ const { countJobPending } = await import('./quotaBurnJobs/index.js');+ state.pending = { first: { count: 1 } };+ await runQuotaBurnCycle();+ expect(countJobPending).toHaveBeenCalled();+ });+});