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
make the run-once ledger actually fail closed, and split the family predicate
[._.]/ Adam Eivy3831d6672a5d
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsxindex b52a7ba6cb..7acb4e13a5 100644--- a/client/src/components/quotaBurn/FamilyCard.jsx+++ b/client/src/components/quotaBurn/FamilyCard.jsx@@ -11,7 +11,7 @@ import { Ban, ChevronDown, ChevronRight, Flame, Plus, RotateCcw } from 'lucide-rimport BrailleSpinner from '../BrailleSpinner';import JobRow from './JobRow';import PresetPicker from './PresetPicker';-import { dispatchCapInput, isUnlimitedDispatchCap, jobFromPreset, UNLIMITED_DISPATCHES } from '../../lib/quotaBurnPatch';+import { dispatchCapInput, isUnlimitedDispatchCap, jobFromPreset, quotaBurnJobIsSpent, UNLIMITED_DISPATCHES } from '../../lib/quotaBurnPatch';import { formatDateTime } from '../../utils/formatters';import { NumberField } from './fields';@@ -24,12 +24,12 @@ export default function FamilyCard({// passed to JobRow as their own props — merging them into the job objects// would mean stripping them back off before every save (the PUT schema is// strict). Matched by id so a reorder mid-save can't mis-pair them.- const statusJobs = status?.jobs || [];- const statusFor = (id) => statusJobs.find((row) => row.id === id) || null;- // Gated on the CONFIG's `runOnce` (as JobRow's badge is), so the count matches- // the number of "Ran once" rows on screen rather than counting a stale- // completion on a step the user has since switched back to repeating.- const spentCount = jobs.filter((job) => job.runOnce && statusFor(job.id)?.ranAt).length;+ // Indexed once, not scanned per lookup: this component re-renders on every+ // keystroke (the page holds `config` in state and saves on a trailing+ // debounce), and a linear `find` ran three times per job — the count below+ // plus both props on every row.+ const statusById = new Map((status?.jobs || []).map((row) => [row.id, row]));+ const spentCount = jobs.filter((job) => quotaBurnJobIsSpent(job, statusById.get(job.id)?.ranAt)).length;const patchJobs = (next) => onPatch({ jobs: next });const changeJob = (index, next) => patchJobs(jobs.map((job, i) => (i === index ? next : job)));@@ -65,8 +65,6 @@ export default function FamilyCard({jobType: catalog.jobTypes[0].id,model: null,providerId: null,- // Standing work by default — the pre-`runOnce` behavior, so adding a step- // does the same thing it always did.runOnce: false,params: {},}]);@@ -219,8 +217,8 @@ export default function FamilyCard({index={index}total={jobs.length}catalog={catalog}- pending={statusFor(job.id)?.pending ?? null}- ranAt={statusFor(job.id)?.ranAt ?? null}+ pending={statusById.get(job.id)?.pending ?? null}+ ranAt={statusById.get(job.id)?.ranAt ?? null}actionsBusy={actionsBusy}onChange={(next) => changeJob(index, next)}onMove={moveJob}diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsxindex c18d23ff2c..54d3ac32d7 100644--- a/client/src/components/quotaBurn/JobRow.jsx+++ b/client/src/components/quotaBurn/JobRow.jsx@@ -12,7 +12,7 @@ import ConfirmButtonPair from '../ui/ConfirmButtonPair';import InlineConfirmRow from '../ui/InlineConfirmRow';import JobParamField from './JobParamField';import PresetPicker from './PresetPicker';-import { applyQuotaBurnPreset } from '../../lib/quotaBurnPatch';+import { applyQuotaBurnPreset, quotaBurnJobIsSpent } from '../../lib/quotaBurnPatch';import { timeAgo } from '../../utils/formatters';import { inputClass } from './fields';@@ -42,12 +42,7 @@ export default function JobRow({useEffect(() => { if (actionsBusy) setRunArmed(false); }, [actionsBusy]);const spec = catalog.jobTypes.find((type) => type.id === job.jobType);const idPrefix = `burn-job-${job.id}`;- // A completion is recorded whenever a `run once` step dispatches, and is kept- // even if the checkbox is later cleared — so the badge is gated on the- // checkbox rather than on `ranAt` alone. That way ticking "run once" on a step- // that already ran immediately SHOWS that it is spent (with Re-arm right- // there), instead of silently dropping it out of the rotation.- const spent = Boolean(job.runOnce && ranAt);+ const spent = quotaBurnJobIsSpent(job, ranAt);const setParam = (key, value) => onChange({ ...job, params: { ...job.params, [key]: value } });const promptText = String(job.params?.prompt || '').trim();const hasPromptText = Boolean(promptText);diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 47f1e58763..9a46ff6ce6 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -89,7 +89,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. `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. `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |+| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. || `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.jsindex 7993aee9ca..cec11eb093 100644--- a/client/src/lib/quotaBurnPatch.js+++ b/client/src/lib/quotaBurnPatch.js@@ -62,13 +62,30 @@ export function applyQuotaBurnPreset(job, preset) {export function jobFromPreset(preset, { id, appId = null } = {}) {return applyQuotaBurnPreset({id, enabled: true, label: '', jobType: preset.jobType, model: null, providerId: null,- // Standing work by default, matching a hand-added step — an audit dimension- // is worth re-running as the code changes.+ // Standing work, matching a hand-added step: an audit dimension is worth+ // re-running as the code changes.runOnce: false,params: appId ? { appId } : {},}, preset);}+/**+ * Whether a step has already had its one dispatch — the client's mirror of the+ * server's `jobIsSpent`, taking the row's `ranAt` from the status feed instead+ * of the whole keyed ledger.+ *+ * Gated on the step's OWN `runOnce`, not on `ranAt` alone, and read from the+ * page's optimistic config rather than the server's copy: a completion is kept+ * even after the checkbox is cleared, so ticking "run once" on a step that+ * already ran must SHOW that it is spent (with Re-arm right there) instead of+ * silently dropping it out of the rotation until the next status read.+ *+ * One definition because two components need it — the row renders the badge and+ * the family card counts them — and a rule split across both drifts the first+ * time either changes.+ */+export const quotaBurnJobIsSpent = (job, ranAt) => Boolean(job?.runOnce && ranAt);+/*** `QUOTA_BURN_UNLIMITED_DISPATCHES` in `server/lib/quotaBurnConfig.js`: the* `maxDispatchesPerWindow` value that means the window is not counted at all,diff --git a/client/src/lib/quotaBurnPatch.test.js b/client/src/lib/quotaBurnPatch.test.jsindex c863737f93..ee7424bef7 100644--- a/client/src/lib/quotaBurnPatch.test.js+++ b/client/src/lib/quotaBurnPatch.test.js@@ -5,9 +5,27 @@ import {isUnlimitedDispatchCap,jobFromPreset,mergeQuotaBurnPatch,+ quotaBurnJobIsSpent,UNLIMITED_DISPATCHES,} from './quotaBurnPatch';+describe('quotaBurnJobIsSpent', () => {+ const ranAt = '2026-08-01T00:00:00.000Z';++ it('gates on the step\'s own run-once flag, not on the completion alone', () => {+ // A completion is kept even after the checkbox is cleared, so `ranAt` alone+ // would keep a step the user switched back to repeating looking retired.+ expect(quotaBurnJobIsSpent({ runOnce: true }, ranAt)).toBe(true);+ expect(quotaBurnJobIsSpent({ runOnce: false }, ranAt)).toBe(false);+ expect(quotaBurnJobIsSpent({ runOnce: true }, null)).toBe(false);+ });++ it('reads a missing job or flag as unspent', () => {+ expect(quotaBurnJobIsSpent(undefined, ranAt)).toBe(false);+ expect(quotaBurnJobIsSpent({}, ranAt)).toBe(false);+ });+});+describe('mergeQuotaBurnPatch', () => {it('merges top-level keys and leaves families untouched', () => {expect(mergeQuotaBurnPatch({ enabled: false, checkIntervalMinutes: 30 }, { enabled: true }))diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex d1e5bfe7f1..4ebce930b9 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -296,7 +296,7 @@ describe('QuotaBurn run-once steps', () => {},status: {...status,- families: [{ ...status.families[0], jobs: [{ id: 'j1', ranAt, spent: true, pending: null }] }, status.families[1]],+ families: [{ ...status.families[0], jobs: [{ id: 'j1', ranAt, pending: null }] }, status.families[1]],},};diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex d8f7145cfa..0faf5f62bd 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -150,14 +150,22 @@ accord instead of looping.- **A forced ▶ run bypasses the gate AND still records.** `charge: false` is aboutthe *window's automatic budget*; `runOnce` is a statement about the *work*, andthe work just happened however it was triggered.-- **An unreadable ledger fails CLOSED** — the cycle reports `run-once ledger+- **An unreadable ledger fails CLOSED** — `getQuotaBurnCompletions` returns+ `null` (not `{}`) for a failed read, so the cycle reports `run-once ledgerunreadable` rather than treating "nothing has run" as fact and re-dispatching- every one-shot job on the plan.-- **A finished plan stops costing a quota scrape.** `familyIsActionable(family,+ every one-shot job. `writeLedger` refuses to write over an unread ledger for+ the same reason: an empty write erases the completions that survived. Same+ posture, and the same `readJSONFileStrict` shape, as `quotaBurnDenials.js`.+- **A finished plan stops costing a quota scrape.** `familyHasRunnableJobs(family,completions)` returns false once every enabled job is a spent one-shot, so thecycle returns before the multi-second per-family TUI scrape. The page reports- it as `every enabled job has already run once`, kept distinct from `no enabled- jobs configured` — a finished plan wants Re-arm, an unset one wants a job added.+ it as `every enabled job has already run once` (`PLAN_COMPLETE_SKIP_REASON`,+ shared with the runner's pre-scrape early return so one condition can't be+ worded two ways), kept distinct from `no enabled jobs configured` — a finished+ plan wants Re-arm, an unset one wants a job added. It is a **second named+ predicate** rather than an optional argument on `familyIsConfigured`: array+ callbacks pass the index as the second argument, so an overloaded arity turns+ `some(familyIsConfigured)` silently wrong.- **Re-arm** puts steps back in the rotation: the ↺ on a job row for one step,**Re-arm all** on the plan header for the family. `POST /api/quota-burn/rearm`with `{ familyId, jobId? }`; a `familyId` is required, since a bare "cleardiff --git a/server/lib/README.md b/server/lib/README.mdindex f6ba92e731..5c7c02c454 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -28,7 +28,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |-| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the completion-aware form of `familyIsActionable`). Pure — no storage, no provider I/O. |+| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). 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, `run once` re-arm body). || `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.jsindex 7ecf09835f..bcfeb66b4a 100644--- a/server/lib/quotaBurnConfig.js+++ b/server/lib/quotaBurnConfig.js@@ -305,21 +305,29 @@ export function normalizeQuotaBurnConfig(raw) {}/**- * Whether a family has anything the runner could dispatch: it must be enabled- * AND carry at least one enabled job. An enabled family with an empty job list- * is a half-finished setup, not a burn plan — treating it as actionable would- * spawn a candidate the runner then has to discard, which shows up as a- * confusing "selected, then skipped" cycle in the run log.+ * Whether a family is SET UP to burn: enabled, with at least one enabled job. An+ * enabled family with an empty job list is a half-finished setup, not a burn+ * plan — treating it as actionable would spawn a candidate the runner then has+ * to discard, which shows up as a confusing "selected, then skipped" cycle in+ * the run log.+ */+export function familyIsConfigured(family) {+ return family?.enabled === true && (family.jobs || []).some((job) => job?.enabled !== false);+}++/**+ * Whether a family has anything the runner could dispatch RIGHT NOW: configured,+ * and not every enabled job already spent as a one-shot. A plan made entirely of+ * `run once` work stops being runnable the moment its last step has run.*- * `completions` additionally excludes spent `run once` jobs, so a plan made- * entirely of one-shot work stops being actionable the moment its last job has- * run. Defaulted to `{}` because the two questions have different answers and- * the callers want different ones: the config-only form distinguishes "you- * configured nothing" from "your plan is finished", and the runner needs the- * completion-aware form so an exhausted plan stops paying for a multi-second- * quota scrape every interval, forever.+ * Deliberately a second named predicate rather than an optional second argument+ * on `familyIsConfigured`. The two questions have different answers and callers+ * want different ones — "you configured nothing" needs a job added while "your+ * plan is finished" needs a Re-arm — and an arity-overloaded predicate is a trap+ * with `some`/`filter`/`map`, which pass the INDEX as the second argument and+ * would silently make `completions` a number.*/-export function familyIsActionable(family, completions = {}) {- return family?.enabled === true+export function familyHasRunnableJobs(family, completions = {}) {+ return familyIsConfigured(family)&& (family.jobs || []).some((job) => job?.enabled !== false && !jobIsSpent(job, family.id, completions));}diff --git a/server/lib/quotaBurnConfig.test.js b/server/lib/quotaBurnConfig.test.jsindex d178e9a28e..23ffb0bd2b 100644--- a/server/lib/quotaBurnConfig.test.js+++ b/server/lib/quotaBurnConfig.test.js@@ -4,7 +4,8 @@ import {QUOTA_BURN_JOB_CATALOG,QUOTA_BURN_JOB_TYPES,QUOTA_BURN_UNLIMITED_DISPATCHES,- familyIsActionable,+ familyHasRunnableJobs,+ familyIsConfigured,isUnlimitedDispatchCap,jobIsSpent,normalizeQuotaBurnConfig,@@ -126,28 +127,39 @@ describe('jobIsSpent', () => {});});-describe('familyIsActionable', () => {+describe('familyIsConfigured', () => {it('requires an enabled family AND at least one enabled job', () => {- expect(familyIsActionable({ enabled: false, jobs: [{ enabled: true }] })).toBe(false);- expect(familyIsActionable({ enabled: true, jobs: [] })).toBe(false);- expect(familyIsActionable({ enabled: true, jobs: [{ enabled: false }] })).toBe(false);- expect(familyIsActionable({ enabled: true, jobs: [{ enabled: true }] })).toBe(true);- });-- it('stops being actionable once every enabled job is a spent one-shot', () => {- const family = {- id: 'grok',- enabled: true,- jobs: [{ id: 'j1', enabled: true, runOnce: true }, { id: 'j2', enabled: false }],- };- const ran = { 'grok:j1': '2026-08-01T00:00:00.000Z' };- // The completion-blind form still answers "you configured something" — the- // runner and the page report those as two different verdicts, because a- // finished plan wants Re-arm and an unset one wants a job added.- expect(familyIsActionable(family)).toBe(true);- expect(familyIsActionable(family, ran)).toBe(false);+ expect(familyIsConfigured({ enabled: false, jobs: [{ enabled: true }] })).toBe(false);+ expect(familyIsConfigured({ enabled: true, jobs: [] })).toBe(false);+ expect(familyIsConfigured({ enabled: true, jobs: [{ enabled: false }] })).toBe(false);+ expect(familyIsConfigured({ enabled: true, jobs: [{ enabled: true }] })).toBe(true);+ });+});++describe('familyHasRunnableJobs', () => {+ const family = {+ id: 'grok',+ enabled: true,+ jobs: [{ id: 'j1', enabled: true, runOnce: true }, { id: 'j2', enabled: false }],+ };+ const ran = { 'grok:j1': '2026-08-01T00:00:00.000Z' };++ it('stops being runnable once every enabled job is a spent one-shot', () => {+ // `familyIsConfigured` still answers "you configured something" — the runner+ // and the page report those as two different verdicts, because a finished+ // plan wants Re-arm and an unset one wants a job added.+ expect(familyIsConfigured(family)).toBe(true);+ expect(familyHasRunnableJobs(family, ran)).toBe(false);// One repeating job is enough to keep the plan alive.- expect(familyIsActionable({ ...family, jobs: [...family.jobs, { id: 'j3', enabled: true }] }, ran)).toBe(true);+ expect(familyHasRunnableJobs({ ...family, jobs: [...family.jobs, { id: 'j3', enabled: true }] }, ran)).toBe(true);+ });++ it('is safe to pass straight to some/filter/map', () => {+ // The reason this is a second named predicate rather than an optional second+ // argument: array callbacks pass the INDEX as arg two, which on an+ // arity-overloaded predicate silently becomes the completion ledger.+ expect([family].some(familyHasRunnableJobs)).toBe(true);+ expect([family].filter(familyIsConfigured)).toHaveLength(1);});});diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex a417ac9c60..c44a4bae18 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -20,7 +20,7 @@import { join } from 'path';import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';-import { familyIsActionable, isUnlimitedDispatchCap, normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';+import { familyHasRunnableJobs, familyIsConfigured, isUnlimitedDispatchCap, normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';import { isPlainObject } from '../lib/objects.js';import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';import { classifyWindows, windowLabelOf } from '../lib/quotaWindows.js';@@ -68,6 +68,16 @@ export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {});}+/**+ * The verdict for a plan whose every enabled step is a spent `run once`.+ *+ * Exported because the runner reports the same state from its own pre-quota+ * early return (which must run BEFORE the quota read the ladder needs), and two+ * hand-written wordings for one condition is how the page and the run log end up+ * describing the same plan in two different sentences.+ */+export const PLAN_COMPLETE_SKIP_REASON = 'every enabled job has already run once';+/** 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);@@ -140,11 +150,14 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}// holds even under force.if (!bypassGates) {if (!family.enabled) return { skipReason: 'disabled' };- // Reported as two distinct verdicts, because they call for opposite actions:- // "you configured nothing" wants a job added, while a finished one-shot plan- // wants Re-arm (or nothing at all — it did what it was asked).- if (!familyIsActionable(family)) return { skipReason: 'no enabled jobs configured' };- if (!familyIsActionable(family, completions)) return { skipReason: 'every enabled job has already run once' };+ // One check on the healthy path; the two verdicts are only told apart on the+ // failing branch. They are reported distinctly because they call for+ // opposite actions: "you configured nothing" wants a job added, while a+ // finished one-shot plan wants Re-arm (or nothing at all — it did what it+ // was asked).+ if (!familyHasRunnableJobs(family, completions)) {+ return { skipReason: familyIsConfigured(family) ? PLAN_COMPLETE_SKIP_REASON : 'no enabled jobs configured' };+ }}if (!card) return { skipReason: 'no enabled provider in this family' };if (card.supported === false) return { skipReason: 'provider has no queryable quota surface' };diff --git a/server/services/quotaBurnCompletions.js b/server/services/quotaBurnCompletions.jsindex c374f115b8..26621cacf0 100644--- a/server/services/quotaBurnCompletions.js+++ b/server/services/quotaBurnCompletions.js@@ -16,30 +16,33 @@* account, and each machine's plan names its own managed apps.** Why a ledger rather than a flag on the job: a config PUT replaces a family's- * whole `jobs` array (that is how every reorder and edit saves), so a "已 ran"- * "already ran" flag living on the job would be silently reset by an unrelated edit — and by- * the client's optimistic copy of the plan, which never sees the runner's write- * at all. The run log can't answer it either: it is a capped UI feed (50+ * whole `jobs` array (that is how every reorder and edit saves), so an "already+ * ran" flag living on the job would be silently reset by an unrelated edit — and+ * by the client's optimistic copy of the plan, which never sees the runner's+ * write at all. The run log can't answer it either: it is a capped UI feed (50* entries), so a job that ran last month has already aged out of it.*/import { join } from 'path';-import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';+import { atomicWrite, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { isPlainObject } from '../lib/objects.js';-import { quotaBurnJobKey } from '../lib/quotaBurnConfig.js';+import { QUOTA_BURN_BOUNDS, QUOTA_BURN_FAMILIES, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-completions.json');/**- * Entries kept, newest first. Deliberately larger than the most keys a live plan- * can hold (4 families × the 25-job cap = 100), so pruning can only ever evict- * the record of a job that has since been deleted from the plan — never a live- * one, which would put a spent job back into the rotation behind the user's- * back. Without any bound the file would grow by one dead key for every job the- * user ever adds and removes.+ * Entries kept, newest first — twice the most keys a live plan can hold, so+ * pruning can only ever evict the record of a job that has since been deleted+ * from the plan, never a live one (which would put a spent job back into the+ * rotation behind the user's back). Without any bound the file would grow by one+ * dead key for every job the user ever adds and removes.+ *+ * DERIVED rather than written down: the margin is only real while it tracks the+ * family list and the per-family job cap, and a hardcoded 200 would silently+ * stop covering a live plan the moment either grew.*/-const LEDGER_LIMIT = 200;+const LEDGER_LIMIT = QUOTA_BURN_FAMILIES.length * QUOTA_BURN_BOUNDS.jobsPerFamily.max * 2;// Single tail for the read-modify-write. The scheduler tick and a manual "Run// now" can both finish a dispatch at once; unserialized, the second read would@@ -48,11 +51,23 @@ const LEDGER_LIMIT = 200;// case, not a defense against competing users.const writeQueue = createFileWriteQueue();-/** `<familyId>:<jobId>` → ISO instant of the dispatch that spent the job. */+/**+ * `<familyId>:<jobId>` → ISO instant of the dispatch that spent the job, or+ * `null` when the ledger could not be read.+ *+ * The `null` is load-bearing, and is why this reads STRICTLY (the same posture+ * as `quotaBurnDenials.js`). A failed or corrupt read must not come back as+ * "nothing has run": that re-dispatches every one-shot job on the plan, and the+ * next write then persists that empty ledger over the completions that survived.+ * Callers turn it into a skipped cycle, not a burn.+ */export async function getQuotaBurnCompletions() {- const loaded = await readJSONFile(LEDGER_FILE(), null);- if (!isPlainObject(loaded)) return {};- return Object.fromEntries(Object.entries(loaded).filter(([, at]) => typeof at === 'string' && at));+ const { ok, value } = await readJSONFileStrict(LEDGER_FILE(), {}, { logError: false });+ if (!ok) return null;+ if (!isPlainObject(value)) return {};+ // A hand-edited or half-written entry must not put a truthy non-instant in+ // front of `jobIsSpent`, which would retire that job forever.+ return Object.fromEntries(Object.entries(value).filter(([, at]) => typeof at === 'string' && at));}// Newest first, then capped — `Date.parse` on an unparseable value yields NaN,@@ -64,18 +79,29 @@ const prune = (ledger) => Object.fromEntries(.slice(0, LEDGER_LIMIT),);+/**+ * Read-modify-write inside the queue. `mutate` returns the next ledger, or+ * `null` for "nothing to change" — which skips the write, so re-arming a family+ * that never ran anything costs one read rather than a pointless rewrite.+ * Mirrors `quotaBurnDenials.js#writeLedger`, including the guard that is the+ * whole point: never overwrite a ledger we could not read.+ */+const writeLedger = (mutate) => writeQueue(async () => {+ const ledger = await getQuotaBurnCompletions();+ if (!ledger) return null;+ const next = mutate({ ...ledger });+ if (!next) return null;+ await atomicWrite(LEDGER_FILE(), next);+ return next;+});+/*** Mark one job as having had its run. Idempotent on the key and re-stamps the* instant, so a forced re-run of an already-spent job reports the latest time.*/export async function recordQuotaBurnJobCompletion(familyId, jobId, { now = Date.now() } = {}) {if (!familyId || !jobId) return null;- return writeQueue(async () => {- const ledger = await getQuotaBurnCompletions();- const next = prune({ ...ledger, [quotaBurnJobKey(familyId, jobId)]: new Date(now).toISOString() });- await atomicWrite(LEDGER_FILE(), next);- return next;- });+ return writeLedger((ledger) => prune({ ...ledger, [quotaBurnJobKey(familyId, jobId)]: new Date(now).toISOString() }));}/**@@ -86,13 +112,12 @@ export async function recordQuotaBurnJobCompletion(familyId, jobId, { now = Date*/export async function clearQuotaBurnJobCompletion(familyId, jobId = null) {if (!familyId) return null;- return writeQueue(async () => {- const ledger = await getQuotaBurnCompletions();- const prefix = `${familyId}:`;- const next = Object.fromEntries(Object.entries(ledger).filter(([key]) => (jobId- ? key !== quotaBurnJobKey(familyId, jobId)- : !key.startsWith(prefix))));- await atomicWrite(LEDGER_FILE(), next);- return next;+ return writeLedger((ledger) => {+ const keys = Object.keys(ledger).filter((key) => (jobId+ ? key === quotaBurnJobKey(familyId, jobId)+ : key.split(':')[0] === familyId));+ if (!keys.length) return null;+ for (const key of keys) delete ledger[key];+ return ledger;});}diff --git a/server/services/quotaBurnCompletions.test.js b/server/services/quotaBurnCompletions.test.jsindex 95ebbd2fe1..e43b2dc709 100644--- a/server/services/quotaBurnCompletions.test.js+++ b/server/services/quotaBurnCompletions.test.js@@ -6,6 +6,7 @@ import { join } from 'path';const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-burn-completions-', extraOverrides: (root) => ({ cos: root }) });vi.mock('../lib/fileUtils.js', async (importActual) => makeProxy(await importActual()));+const { QUOTA_BURN_BOUNDS, QUOTA_BURN_FAMILIES } = await import('../lib/quotaBurnConfig.js');const {clearQuotaBurnJobCompletion, getQuotaBurnCompletions, recordQuotaBurnJobCompletion,} = await import('./quotaBurnCompletions.js');@@ -19,10 +20,21 @@ beforeEach(() => rmSync(LEDGER(), { force: true }));afterAll(cleanup);describe('getQuotaBurnCompletions', () => {- it('reads an empty ledger as no completions rather than failing', async () => {+ it('reads an absent ledger as no completions rather than failing', async () => {await expect(getQuotaBurnCompletions()).resolves.toEqual({});});+ it('reports an UNREADABLE ledger as null, not as an empty one', async () => {+ // The distinction the whole fail-closed contract rests on. A corrupt file+ // read as `{}` means "nothing has run", which re-dispatches every one-shot+ // job on the plan — and the next write then persists that empty ledger over+ // the completions that survived. Asserted against the real reader because+ // the runner suite mocks this module, so only this test can catch a+ // non-strict read here.+ writeFileSync(LEDGER(), '{"grok:a": ');+ await expect(getQuotaBurnCompletions()).resolves.toBeNull();+ });+it('drops entries that are not a usable instant', async () => {// A hand-edited or half-written file must not put a truthy non-string in// front of `jobIsSpent`, which would silently retire a job forever.@@ -57,21 +69,35 @@ describe('recordQuotaBurnJobCompletion', () => {await expect(getQuotaBurnCompletions()).resolves.toEqual({});});- it('prunes the oldest entries only, keeping far more than a live plan can hold', async () => {+ it('refuses to write over a ledger it could not read', async () => {+ // Writing here would erase every surviving completion and put the whole+ // one-shot plan back into the rotation.+ writeFileSync(LEDGER(), 'not json at all');+ await expect(recordQuotaBurnJobCompletion('grok', 'job-1', { now: NOW })).resolves.toBeNull();+ expect(readFileSync(LEDGER(), 'utf8')).toBe('not json at all');+ });++ it('prunes the oldest entries only, keeping more than a live plan can hold', async () => {// The cap exists so the file cannot grow by one dead key per deleted job// forever. It must never evict a LIVE key — that would put a spent job back- // into the rotation behind the user's back — so it is set well above the 100- // keys a maxed-out plan (4 families x 25 jobs) can produce.- seed(Object.fromEntries(Array.from({ length: 240 }, (_, index) => [- `grok:old-${index}`, new Date(NOW - (240 - index) * 60_000).toISOString(),+ // into the rotation behind the user's back — so it stays at twice the keys a+ // maxed-out plan can produce, DERIVED from the family list and the job cap+ // rather than written down (a literal stops covering a live plan the moment+ // either constant grows).+ const liveMax = QUOTA_BURN_FAMILIES.length * QUOTA_BURN_BOUNDS.jobsPerFamily.max;+ const limit = liveMax * 2;+ const seeded = limit + 40;+ seed(Object.fromEntries(Array.from({ length: seeded }, (_, index) => [+ `grok:old-${index}`, new Date(NOW - (seeded - index) * 60_000).toISOString(),])));await recordQuotaBurnJobCompletion('grok', 'fresh', { now: NOW });const kept = onDisk();- expect(Object.keys(kept)).toHaveLength(200);+ expect(Object.keys(kept)).toHaveLength(limit);+ expect(limit).toBeGreaterThan(liveMax);expect(kept['grok:fresh']).toBe(new Date(NOW).toISOString());- // Oldest first out: `old-0` is the furthest back, `old-239` the most recent.+ // Oldest first out: `old-0` is the furthest back, the last index the newest.expect(kept['grok:old-0']).toBeUndefined();- expect(kept['grok:old-239']).toBeDefined();+ expect(kept[`grok:old-${seeded - 1}`]).toBeDefined();});});@@ -98,6 +124,14 @@ describe('clearQuotaBurnJobCompletion', () => {expect(Object.keys(onDisk())).toHaveLength(3);});+ it('skips the write entirely when the family has nothing to re-arm', async () => {+ // Re-arm-all on a plan that never ran is the common case; a rewrite that+ // changes nothing is pure I/O.+ const before = readFileSync(LEDGER(), 'utf8');+ await expect(clearQuotaBurnJobCompletion('codex')).resolves.toBeNull();+ expect(readFileSync(LEDGER(), 'utf8')).toBe(before);+ });+it('matches the family on the full key segment, not a bare prefix', async () => {// `grok` must not clear a hypothetical `grok-two` family's entries.seed({ 'grok:a': '2026-08-01T00:00:00.000Z', 'grokish:a': '2026-08-01T00:00:00.000Z' });diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex f733ff3588..e736c60062 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -37,12 +37,12 @@*/import { getProviderQuotas } from './providerUsage.js';-import { getQuotaBurnDispatches, evaluateFamilies, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';+import { getQuotaBurnDispatches, evaluateFamilies, PLAN_COMPLETE_SKIP_REASON, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';-import { familyIsActionable, jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';+import { familyHasRunnableJobs, familyIsConfigured, jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';import { windowLabelOf } from '../lib/quotaWindows.js';import { WAIT } from '../lib/staleWhileRevalidate.js';import { cosEvents } from './cosEvents.js';@@ -231,14 +231,16 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// Read once per cycle and threaded through selection, the gate ladder, and the// dispatch record, so a job spent mid-cycle can't be re-picked by a later// family's walk.- const completions = await getQuotaBurnCompletions().catch((err) => {- // Fail CLOSED for the ONE-SHOT jobs: an unreadable ledger reads as "nothing- // has run", which would re-dispatch every `run once` job on the plan. Better- // to skip the cycle and say so than to redo work the user asked for once.- console.error(`❌ Quota-burn could not read its run-once ledger: ${err.message}`);- return null;- });- if (!completions) return finish({ dispatched: false, reason: 'run-once ledger unreadable' });+ //+ // `null` means the ledger could not be read, which is NOT "nothing has run" —+ // treating it as such would re-dispatch every `run once` job on the plan. Fails+ // CLOSED: skip the cycle and say so rather than redoing work the user asked+ // for exactly once.+ const completions = await getQuotaBurnCompletions();+ if (!completions) {+ console.error('❌ Quota-burn could not read its run-once ledger — skipping this cycle');+ return finish({ dispatched: false, reason: 'run-once ledger unreadable' });+ }// Check the plan BEFORE the quota read. `getProviderQuotas({ wait: WAIT.FRESH })`// spawns a multi-second TUI scrape per enabled family; with no actionable@@ -247,22 +249,22 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// spent `run once` jobs is the same case, which is why `completions` is passed// — without it a finished one-shot plan keeps paying for the scrape forever.//- // A forced run of a NAMED job is exempt: `familyIsActionable` requires an- // enabled family with an enabled, unspent job, but ▶ on a paused job (or a- // paused family, or one that already ran) is exactly the case the force path- // exists to serve — gating it here would make the click a silent no-op before- // selection ever ran.+ // A forced run of a NAMED job is exempt: this requires an enabled family with+ // an enabled, unspent job, but ▶ on a paused job (or a paused family, or one+ // that already ran) is exactly the case the force path exists to serve —+ // gating it here would make the click a silent no-op before selection ever ran.//- // Spelled as arrows, NOT `.some(familyIsActionable)`: `.some` passes the INDEX- // as the second argument, which would land in `completions`.+ // One short-circuiting pass on the healthy path; the second only runs to pick+ // the wording, and only when nothing is runnable. The two are kept distinct+ // because a finished one-shot plan did what it was asked and wants Re-arm,+ // which is not what an unset plan wants (add a job).const targeted = force && familyId;- const configured = Object.values(config.families).filter((family) => familyIsActionable(family));- if (!targeted && !configured.length) return finish({ dispatched: false, reason: 'no families enabled' });- // Kept distinct from "no families enabled": a finished one-shot plan did what- // it was asked, and the action it wants (Re-arm) is not the action an unset- // plan wants (add a job).- if (!targeted && !configured.some((family) => familyIsActionable(family, completions))) {- return finish({ dispatched: false, reason: 'every enabled job has already run once — re-arm a step to run the plan again' });+ const families = Object.values(config.families);+ if (!targeted && !families.some((family) => familyHasRunnableJobs(family, completions))) {+ return finish({+ dispatched: false,+ reason: families.some(familyIsConfigured) ? PLAN_COMPLETE_SKIP_REASON : 'no families enabled',+ });}// Scoped to the one family when the caller named it — a per-family "Run now",@@ -409,7 +411,11 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {}),getQuotaBurnDispatches(),getActiveQuotaBurnBlocks(),- getQuotaBurnCompletions().catch(() => ({})),+ // An unreadable ledger degrades to "no badges" here rather than failing the+ // whole status read — the opposite of the CYCLE's posture, and deliberately+ // so: the cost of being wrong on this path is a missing "Ran once" label,+ // while on the cycle's path it is re-spending quota on finished work.+ getQuotaBurnCompletions().then((ledger) => ledger || {}),getQuotaBurnRuns(),]);@@ -447,11 +453,16 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {// step is finished rather than merely idle.jobs: await Promise.all(family.jobs.map(async (job) => {const ranAt = completions[quotaBurnJobKey(family.id, job.id)] || null;- const spent = jobIsSpent(job, family.id, completions);+ // `jobIsSpent` re-derived from the value just read rather than called —+ // it would rebuild the same key and re-index the same object. Not+ // shipped on the wire either: the client gates its badge on the+ // OPTIMISTIC config it holds, so a just-ticked checkbox reads as spent+ // before the save round-trips, and a server copy would only be a second+ // rule to keep in sync.+ const spent = job.runOnce === true && Boolean(ranAt);return {id: job.id,ranAt,- spent,pending: family.enabled && !spent ? await countJobPending({ job, family }) : null,};})),diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.jsindex d3ca7474ea..c4d44ffe1a 100644--- a/server/services/quotaBurnRunner.test.js+++ b/server/services/quotaBurnRunner.test.js@@ -15,7 +15,7 @@ const state = {blocks: {},completions: {},completed: [],- completionsError: null,+ completionsUnreadable: false,settled: [],settleError: null,};@@ -67,10 +67,9 @@ vi.mock('./quotaBurnDenials.js', async (importActual) => ({// two. `state.completed` records the writes so "a one-shot job marks itself// spent" is assertable without a filesystem round trip.vi.mock('./quotaBurnCompletions.js', () => ({- getQuotaBurnCompletions: vi.fn(async () => {- if (state.completionsError) throw new Error(state.completionsError);- return state.completions;- }),+ // `null` — not a throw — is the module's real "could not read" signal, so the+ // stub speaks the same contract the runner is being tested against.+ getQuotaBurnCompletions: vi.fn(async () => (state.completionsUnreadable ? null : state.completions)),recordQuotaBurnJobCompletion: vi.fn(async (familyId, jobId) => {state.completed.push(`${familyId}:${jobId}`);state.completions = { ...state.completions, [`${familyId}:${jobId}`]: new Date(now).toISOString() };@@ -113,7 +112,7 @@ beforeEach(() => {state.blocks = {};state.completions = {};state.completed = [];- state.completionsError = null;+ state.completionsUnreadable = false;state.settled = [];state.settleError = null;state.jobResult = undefined;@@ -669,7 +668,7 @@ describe('run-once jobs', () => {});it('stops scraping provider quota once every step of a one-shot plan has run', async () => {- // The whole point of threading completions into `familyIsActionable`: a+ // The whole point of threading completions into `familyHasRunnableJobs`: a// finished plan would otherwise pay for a multi-second TUI scrape every// interval, forever, to be told there is nothing to dispatch.const { getProviderQuotas } = await import('./providerUsage.js');@@ -712,7 +711,7 @@ describe('run-once jobs', () => {it('skips the cycle rather than re-running one-shot work when the ledger is unreadable', async () => {// Fails CLOSED: an unreadable ledger reads as "nothing has run", which would// re-dispatch every run-once job on the plan.- state.completionsError = 'EIO';+ state.completionsUnreadable = true;const result = await runQuotaBurnCycle();expect(result).toMatchObject({ dispatched: false, reason: 'run-once ledger unreadable' });expect(state.ran).toEqual([]);@@ -743,7 +742,7 @@ describe('run-once jobs', () => {const { status } = await getQuotaBurnStatus();const grok = status.families.find((family) => family.id === 'grok');- expect(grok.jobs).toEqual([{ id: 'once', ranAt, spent: true, pending: null }]);+ expect(grok.jobs).toEqual([{ id: 'once', ranAt, pending: null }]);expect(countJobPending).not.toHaveBeenCalled();expect(grok.skipReason).toBe('every enabled job has already run once');});