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
fix([issue-3179]): count a quota-burn dispatch when its agent runs, not when it is considered
[._.]/ Adam Eivy8601771929ef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..b4857b1af1--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,5 @@+# Unreleased Changes++## Quota burn++- **[issue-3179] Quota-burn no longer spends window budget on runs that never happened** — a scheduled quota-burn run counted against the family's per-window dispatch cap as soon as it was considered, even when it was subsequently skipped and no agent was ever started. Those phantom dispatches ate the budget, so a family configured for e.g. 5 burns per reset window could fire far fewer — and a family capped at 1 could never fire at all, because the skipped run consumed the only slot before the next gate re-read it. A burn is now counted once its agent has actually run, and a burn that is queued or in progress holds its slot in the meantime, so the cap stays accurate without letting a second app or a repeated "Run" overshoot it.diff --git a/server/services/autonomousJobs/quotaBurnHooks.js b/server/services/autonomousJobs/quotaBurnHooks.jsindex 630245c4a6..1fbd7df224 100644--- a/server/services/autonomousJobs/quotaBurnHooks.js+++ b/server/services/autonomousJobs/quotaBurnHooks.js@@ -1,6 +1,6 @@import { getAllProviders } from '../providers.js';import { getProviderQuotas } from '../providerUsage.js';-import { getQuotaBurnDispatches, recordQuotaBurnDispatch, selectBurnCandidates, quotaBurnConfig, QUOTA_BURN_TASK_TYPE } from '../quotaBurn.js';+import { getEffectiveQuotaBurnDispatches, recordQuotaBurnDispatch, selectBurnCandidates, quotaBurnConfig, QUOTA_BURN_TASK_TYPE, QUOTA_BURN_DISPATCH_KEY_FIELD } from '../quotaBurn.js';function providerForFamily(providers, family) {const available = (providers || []).filter((provider) =>@@ -29,11 +29,23 @@ function renderPrompt(candidate) {* Programmatic pre-agent hook. It refreshes quota readings immediately before* dispatch, pins an agent-capable provider in the selected family, and returns* a skip instead of spawning when any prerequisite is missing.+ *+ * Deliberately does NOT write the dispatch ledger (#3179). Several gates in+ * `cosTaskGenerator.js#buildImprovementTask` run AFTER this hook returns —+ * claim-work routing, the perpetual-work gate, branch-/issue-reconcile,+ * reference-watch, the PLAN.md gate — and any of them can still `return null`+ * and skip creating the task, with no agent ever spawned. A ledger write here+ * therefore burned a slot of `family.maxDispatchesPerWindow` on a dispatch that+ * never happened. Instead the resolved `dispatchKey` is handed back as+ * `hookMetadata`, which the generator stamps onto the task only once every gate+ * has passed, and `processTaskOutput` below records it post-agent.*/export async function buildTaskInput({ app } = {}) {if (!app) return { skip: { reason: 'no-app' } };const config = quotaBurnConfig(app);- const ledger = await getQuotaBurnDispatches();+ // Ledger + in-flight: a quota-burn task already queued or running holds its+ // window slot even though its ledger write lands post-agent (#3179).+ const ledger = await getEffectiveQuotaBurnDispatches();const quotas = await getProviderQuotas({ refresh: true });const candidates = selectBurnCandidates(quotas, config, { dispatches: ledger });const candidate = candidates[0];@@ -46,12 +58,50 @@ export async function buildTaskInput({ app } = {}) {);if (!provider) return { skip: { reason: 'no-enabled-agent-provider-in-family' } };- await recordQuotaBurnDispatch(candidate.dispatchKey);return {prompt: renderPrompt(candidate),providerId: provider.id,model: candidate.family.model || null,+ hookMetadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: candidate.dispatchKey },};}+/**+ * Programmatic post-agent hook. Records the dispatch against the family's+ * reset-window ledger — the ONLY place that write happens (#3179). By the time+ * the finalize chokepoint runs this, an agent was actually spawned, which is the+ * real event `family.maxDispatchesPerWindow` is meant to bound.+ *+ * Runs regardless of `success`: the provider quota was consumed the moment the+ * agent ran, whether or not its run exited clean. A window's budget must count+ * failed burns too, otherwise a family that keeps erroring out would dispatch+ * without limit.+ *+ * Returns NO structured outcome, on purpose. `resolveProgrammaticIoVerdict`+ * (agentFinalization.js) reads an output hook's outcome as the task type's+ * success criterion, and quota-burn has none to offer: its agent does arbitrary+ * user-configured work with no `.agent-done` payload contract, so nothing here+ * evaluates the agent's output. Handing back no outcome keeps that verdict at+ * the "undeclared" null sentinel, leaving quota-burn exit-code-judged exactly as+ * it was before this hook existed. Do NOT return an object to make this "more+ * informative" — that would declare a criterion this hook never checked.+ *+ * For the same reason the ledger write must not throw. finalizeAgent turns a+ * thrown output hook into `{ ran: true, threw: true }`, which rejects the run's+ * success criterion AND records a `hook-error` against the per-type+ * consecutive-failure ledger that auto-parks a task type — so a transient+ * ENOSPC/EACCES writing one JSON file could park quota-burn entirely. A failed+ * write is environmental, not a bad run; log and move on, exactly as the+ * verdict's own docstring prescribes for a hook whose side effect couldn't land.+ */+export async function processTaskOutput({ task } = {}) {+ const dispatchKey = task?.metadata?.[QUOTA_BURN_DISPATCH_KEY_FIELD];+ // Absent key = this task predates the metadata thread, or generation never+ // resolved a candidate. Nothing to record; never invent a ledger entry.+ if (typeof dispatchKey !== 'string' || !dispatchKey) return;+ await recordQuotaBurnDispatch(dispatchKey)+ .then(() => console.log(`🔥 Recorded quota-burn dispatch for ${dispatchKey}`))+ .catch((err) => console.error(`❌ Failed to record quota-burn dispatch for ${dispatchKey}: ${err.message}`));+}+export const __test = { providerForFamily, renderPrompt, QUOTA_BURN_TASK_TYPE };diff --git a/server/services/autonomousJobs/quotaBurnHooks.test.js b/server/services/autonomousJobs/quotaBurnHooks.test.jsnew file mode 100644index 0000000000..7ab6e18725--- /dev/null+++ b/server/services/autonomousJobs/quotaBurnHooks.test.js@@ -0,0 +1,147 @@+/**+ * Tests for the quota-burn programmatic-I/O hooks (#3179).+ *+ * The behavior under test is WHEN the dispatch ledger is written. It used to be+ * written inside `buildTaskInput`, before the task generator had finished+ * gating — so any downstream skip (perpetual-work, branch-/issue-reconcile,+ * reference-watch, PLAN.md) permanently consumed a slot of+ * `family.maxDispatchesPerWindow` for an agent that never ran. The write now+ * happens once, post-agent, in `processTaskOutput`.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const recordQuotaBurnDispatch = vi.fn().mockResolvedValue({});+const selectBurnCandidates = vi.fn();+const getEffectiveQuotaBurnDispatches = vi.fn().mockResolvedValue({});+const getProviderQuotas = vi.fn().mockResolvedValue([]);+const getAllProviders = vi.fn();++vi.mock('../quotaBurn.js', () => ({+ QUOTA_BURN_TASK_TYPE: 'quota-burn',+ QUOTA_BURN_DISPATCH_KEY_FIELD: 'quotaBurnDispatchKey',+ getEffectiveQuotaBurnDispatches: (...args) => getEffectiveQuotaBurnDispatches(...args),+ recordQuotaBurnDispatch: (...args) => recordQuotaBurnDispatch(...args),+ selectBurnCandidates: (...args) => selectBurnCandidates(...args),+ quotaBurnConfig: (app) => app?.taskTypeOverrides?.['quota-burn']?.taskMetadata || { families: {} },+}));+vi.mock('../providerUsage.js', () => ({ getProviderQuotas: (...args) => getProviderQuotas(...args) }));+vi.mock('../providers.js', () => ({ getAllProviders: (...args) => getAllProviders(...args) }));++const { buildTaskInput, processTaskOutput } = await import('./quotaBurnHooks.js');+const { QUOTA_BURN_DISPATCH_KEY_FIELD } = await import('../quotaBurn.js');+const { generateTasksMarkdown, parseTasksMarkdown } = await import('../../lib/taskParser.js');++const DISPATCH_KEY = 'grok:1753574400000';+const APP = { id: 'app-1', name: 'App One', taskTypeOverrides: { 'quota-burn': { taskMetadata: { families: { grok: { enabled: true, prompt: 'Burn it.' } } } } } };+const CANDIDATE = {+ family: { id: 'grok', reservePercent: 20, maxDispatchesPerWindow: 2, prompt: 'Burn it.', model: 'grok-4' },+ limit: { label: 'Weekly', scope: 'week', percentRemaining: 50 },+ hoursUntilReset: 6,+ dispatchKey: DISPATCH_KEY,+};++beforeEach(() => {+ vi.clearAllMocks();+ selectBurnCandidates.mockReturnValue([CANDIDATE]);+ getAllProviders.mockResolvedValue([{ id: 'grok-cli', enabled: true, type: 'cli' }]);+});++describe('buildTaskInput (pre-agent)', () => {+ it('hands the dispatch key back as hookMetadata WITHOUT writing the ledger', async () => {+ const input = await buildTaskInput({ app: APP });++ expect(input.hookMetadata).toEqual({ [QUOTA_BURN_DISPATCH_KEY_FIELD]: DISPATCH_KEY });+ expect(input.providerId).toBe('grok-cli');+ expect(input.model).toBe('grok-4');+ expect(input.prompt).toContain('Burn it.');+ // The whole point of #3179: nothing is recorded until an agent actually runs.+ expect(recordQuotaBurnDispatch).not.toHaveBeenCalled();+ });++ it('records nothing on any skip path', async () => {+ await expect(buildTaskInput({})).resolves.toMatchObject({ skip: { reason: 'no-app' } });++ selectBurnCandidates.mockReturnValue([]);+ await expect(buildTaskInput({ app: APP })).resolves.toMatchObject({ skip: { reason: 'no-burnable-provider-quota' } });++ selectBurnCandidates.mockReturnValue([CANDIDATE]);+ getAllProviders.mockResolvedValue([{ id: 'other', enabled: true, type: 'cli' }]);+ await expect(buildTaskInput({ app: APP })).resolves.toMatchObject({ skip: { reason: 'no-enabled-agent-provider-in-family' } });++ expect(recordQuotaBurnDispatch).not.toHaveBeenCalled();+ });++ it('selects against the ledger PLUS in-flight tasks, not the bare ledger', async () => {+ // With the write deferred to processTaskOutput, an already-queued burn is+ // invisible to the raw ledger — so candidate selection has to consult the+ // effective count or a sibling app (or a second on-demand Run) would dispatch+ // straight past maxDispatchesPerWindow.+ getEffectiveQuotaBurnDispatches.mockResolvedValue({ [DISPATCH_KEY]: 1 });++ await buildTaskInput({ app: APP });++ expect(getEffectiveQuotaBurnDispatches).toHaveBeenCalled();+ expect(selectBurnCandidates).toHaveBeenCalledWith(expect.anything(), expect.anything(), { dispatches: { [DISPATCH_KEY]: 1 } });+ });+});++describe('processTaskOutput (post-agent)', () => {+ const task = { metadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: DISPATCH_KEY } };++ // The quota was consumed the moment the agent ran, so a failed run counts too.+ it.each([true, false])('records the dispatch exactly once on a run with success=%s', async (success) => {+ await processTaskOutput({ appId: 'app-1', success, payload: null, task });++ expect(recordQuotaBurnDispatch).toHaveBeenCalledTimes(1);+ expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY);+ });++ it('swallows a ledger write failure instead of throwing', async () => {+ // A thrown output hook is read as `{ ran: true, threw: true }` — which+ // rejects the run's success criterion AND records a `hook-error` against the+ // per-type failure ledger that auto-parks a task type. A full disk must not+ // park quota-burn, so an environmental write failure stays a log line.+ recordQuotaBurnDispatch.mockRejectedValueOnce(new Error('ENOSPC'));++ await expect(processTaskOutput({ appId: 'app-1', success: true, task })).resolves.toBeUndefined();+ });++ it('no-ops when the task carries no dispatch key (task predating the metadata thread)', async () => {+ await processTaskOutput({ success: true, task: { metadata: {} } });+ await processTaskOutput({ success: true, task: {} });+ await processTaskOutput({ success: true });+ await processTaskOutput();+ // A non-string key must not be coerced into a ledger entry either.+ await processTaskOutput({ success: true, task: { metadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: { id: 'grok' } } } });+ await processTaskOutput({ success: true, task: { metadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: '' } } });++ expect(recordQuotaBurnDispatch).not.toHaveBeenCalled();+ });++ it('reads a dispatch key that survived the COS-TASKS.md round-trip', async () => {+ // The key only reaches this hook by riding in the task's PERSISTED metadata,+ // so the markdown format has to carry it intact. Two ways it could silently+ // fail: `parseMetadataLine` keys on `\w+` (fine for the camelCase field), and+ // it splits on the FIRST colon — while a dispatch key is `<family>:<epochMs>`+ // and so contains one. A greedy value capture is what makes that work; this+ // pins it, because a regression would look like a hook that just never fires.+ const built = await buildTaskInput({ app: APP });+ const persisted = { id: 'sys-abc', status: 'pending', priority: 'MEDIUM', description: 'quota burn', metadata: { app: 'app-1', analysisType: 'quota-burn', ...built.hookMetadata } };+ const [reparsed] = parseTasksMarkdown(generateTasksMarkdown([persisted], true));++ expect(reparsed.metadata[QUOTA_BURN_DISPATCH_KEY_FIELD]).toBe(DISPATCH_KEY);++ await processTaskOutput({ appId: 'app-1', success: true, task: reparsed });+ expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY);+ });++ it('returns no structured outcome, so quota-burn stays exit-code-judged', async () => {+ // Registering an output hook must NOT start declaring a success criterion for+ // a task type whose agent has no `.agent-done` payload contract.+ // resolveProgrammaticIoVerdict maps a non-object outcome to the "undeclared"+ // null sentinel (pinned in agentFinalization.successCriteria.test.js), which+ // keeps task-learning falling back to the exit code exactly as before.+ expect(await processTaskOutput({ appId: 'app-1', success: true, task })).toBeUndefined();+ });+});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 5259a1ab96..fa7a0acd16 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -23,6 +23,7 @@ import { readFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers, resolveReviewUsernames, resolveOptionalReviewers, resolveReviewerMaxRounds, resolveReviewerModels, reviewerModelsFromDefaults, buildReviewersCsv, LOCAL_LLM_REVIEWERS, SWARM_COUNT_MIN } from '../lib/validation.js';+import { isPlainObject } from '../lib/objects.js';import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';import { getDomainMode } from '../lib/domainAutonomy.js';@@ -1860,13 +1861,17 @@ async function buildImprovementTaskMetadata(taskType, app, interval, taskSchedul* Run a task type's registered buildTaskInput hook (taskTypeHooks.js) for* deterministic pre-agent data collection. Returns `{ skip: true }` when the* hook opts out (execution recorded so cadence advances), otherwise- * `{ skip: false, hookPrompt, hookOverride }` — the hook may fully own the- * rendered prompt and/or pin the app's per-app provider/model.+ * `{ skip: false, hookPrompt, hookOverride, hookMetadata }` — the hook may fully+ * own the rendered prompt, pin the app's per-app provider/model, and hand back a+ * metadata bag to stamp onto the created task.+ *+ * `hookMetadata` is normalized to null unless the hook returned a real object,+ * so the caller's "stamp it" check can't be tripped by a stray primitive.*/-async function resolveTaskInputHook(app, taskType, taskSchedule) {+export async function resolveTaskInputHook(app, taskType, taskSchedule) {const { getTaskInputHook } = await import('./taskTypeHooks.js');const inputHook = await getTaskInputHook(taskType);- if (!inputHook) return { skip: false, hookPrompt: null, hookOverride: {} };+ if (!inputHook) return { skip: false, hookPrompt: null, hookOverride: {}, hookMetadata: null };const input = await inputHook({ app, taskType }).catch((err) => {emitLog('warn', `buildTaskInput hook failed for ${taskType}/${app.name}: ${err.message}`, { appId: app.id, analysisType: taskType });return { skip: { reason: 'input-hook-error' } };@@ -1879,7 +1884,8 @@ async function resolveTaskInputHook(app, taskType, taskSchedule) {return {skip: false,hookPrompt: input?.prompt || null,- hookOverride: { providerId: input?.providerId || null, model: input?.model || null }+ hookOverride: { providerId: input?.providerId || null, model: input?.model || null },+ hookMetadata: isPlainObject(input?.hookMetadata) ? input.hookMetadata : null};}@@ -2331,7 +2337,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// provider/model block below, so the per-app choice wins.const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule);if (inputHook.skip) return null;- const { hookPrompt, hookOverride } = inputHook;+ const { hookPrompt, hookOverride, hookMetadata } = inputHook;// claim-work single-source router: `taskType` stays 'claim-work' for// interval/cadence/recording; `promptTaskType` drives prompt selection, PLAN@@ -2431,9 +2437,29 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stconst approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`, metadata);- // All gates passed — record the rotation-pointer advance + emit the- // generation log. Deferred from the top of the function (see note there);- // every `return null` above this point intentionally leaves both untouched.+ // All gates passed — stamp the buildTaskInput hook's metadata bag, record the+ // rotation-pointer advance, and emit the generation log. Deferred from the top+ // of the function (see note there); every `return null` above this point+ // intentionally leaves all three untouched.+ //+ // The hook bag lands HERE, below the last gate, precisely so a hook can defer a+ // side effect keyed on it until the task is certain to exist (rationale in+ // autonomousJobs/quotaBurnHooks.js#buildTaskInput, #3179).+ //+ // Generator-computed keys always win. Stamping last would otherwise let a hook+ // silently clobber a decision made a few lines earlier — `analysisType` is the+ // dangerous one, since resolveTaskHookType reads it to dispatch the output hook,+ // so a collision would stop the very hook that asked for the bag from ever+ // running. Hooks pin provider/model and own the prompt through their own return+ // fields; the bag is for values that must SURVIVE to processTaskOutput, not an+ // override channel. Dropped collisions are logged rather than merged silently.+ for (const [key, value] of Object.entries(hookMetadata || {})) {+ if (key in metadata) {+ emitLog('warn', `Ignoring ${taskType} hookMetadata key '${key}' for ${app.name}: it would overwrite generator-owned task metadata`, { appId: app.id, analysisType: taskType });+ continue;+ }+ metadata[key] = value;+ }await updateAppActivity(app.id, { lastImprovementType: taskType });emitLog('info', `Generating improvement task for ${app.name}: ${taskType}`, { appId: app.id, analysisType: taskType });diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex b1dddc18e0..ba6ba8511a 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -28,7 +28,7 @@ vi.mock('./codeReview.js', async (importActual) => ({getCodeReviewDefaults: vi.fn(async () => ({ reviewers: ['copilot'], usernames: ['alice'], optionalReviewers: [] })),}));-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, buildJiraTicketTask, buildImprovementDedupSets, normalizeWorkItemRef, buildTargetWorkItemBlock } from './cosTaskGenerator.js';+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, buildJiraTicketTask, buildImprovementDedupSets, normalizeWorkItemRef, buildTargetWorkItemBlock, resolveTaskInputHook } from './cosTaskGenerator.js';import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';@@ -752,3 +752,93 @@ describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy theiexpect(GEN_SRC).toMatch(/buildImprovementDedupSets\(existingTasks/);});});++/**+ * `hookMetadata` is the channel a buildTaskInput hook uses to defer a side+ * effect until the task is CERTAIN to exist (#3179). quota-burn rides its+ * resolved dispatch key across on it so the ledger is written post-agent, rather+ * than inside the input hook where any of the gates below it could still skip+ * task creation and burn window budget on a dispatch that never ran.+ */+describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {+ const app = { id: 'app-1', name: 'App One' };+ const taskSchedule = { recordExecution: vi.fn() };++ // resolveTaskInputHook resolves the hook through a DYNAMIC import, so a+ // per-test doMock reaches it without a file-wide module mock.+ const withInputHook = async (buildTaskInput, fn) => {+ vi.doMock('./taskTypeHooks.js', () => ({ getTaskInputHook: async () => buildTaskInput }));+ try {+ return await fn();+ } finally {+ vi.doUnmock('./taskTypeHooks.js');+ }+ };++ it('threads a hook metadata bag through alongside the prompt and provider pins', async () => {+ const resolved = await withInputHook(+ async () => ({ prompt: 'BURN', providerId: 'grok-cli', model: 'grok-4', hookMetadata: { quotaBurnDispatchKey: 'grok:123' } }),+ () => resolveTaskInputHook(app, 'quota-burn', taskSchedule)+ );+ expect(resolved).toMatchObject({+ skip: false,+ hookPrompt: 'BURN',+ hookOverride: { providerId: 'grok-cli', model: 'grok-4' },+ hookMetadata: { quotaBurnDispatchKey: 'grok:123' }+ });+ });++ it('normalizes a missing or non-object bag to null so the caller never stamps a primitive', async () => {+ const cases = [undefined, null, 'grok:123', 42, ['grok:123']];+ for (const hookMetadata of cases) {+ const resolved = await withInputHook(+ async () => ({ prompt: 'BURN', hookMetadata }),+ () => resolveTaskInputHook(app, 'quota-burn', taskSchedule)+ );+ expect(resolved.hookMetadata, `hookMetadata: ${JSON.stringify(hookMetadata)}`).toBeNull();+ }+ });++ it('returns a null bag for a task type that registers no input hook', async () => {+ const resolved = await withInputHook(null, () => resolveTaskInputHook(app, 'performance', taskSchedule));+ expect(resolved).toEqual({ skip: false, hookPrompt: null, hookOverride: {}, hookMetadata: null });+ });++ it('carries no bag on a skip — the task is never created, so nothing may be stamped', async () => {+ const resolved = await withInputHook(+ async () => ({ skip: { reason: 'no-burnable-provider-quota' } }),+ () => resolveTaskInputHook(app, 'quota-burn', taskSchedule)+ );+ expect(resolved).toEqual({ skip: true });+ expect(taskSchedule.recordExecution).toHaveBeenCalledWith('quota-burn', 'app-1');+ });++ it('drops a bag key that would overwrite generator-owned metadata', () => {+ // The bag is stamped LAST, so a naive Object.assign would let a hook silently+ // win over a decision made a few lines earlier. `analysisType` is the sharp+ // edge: resolveTaskHookType reads it to dispatch the output hook, so a+ // collision would stop the very hook that asked for the bag from running.+ const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));+ expect(body).toContain('for (const [key, value] of Object.entries(hookMetadata || {}))');+ expect(body).toContain('if (key in metadata)');+ // A plain merge would reintroduce the clobber.+ expect(body).not.toContain('Object.assign(metadata, hookMetadata)');+ });++ it('stamps the bag onto metadata BELOW every gate that can still skip task creation', () => {+ // The ordering IS the fix. Source-pinned because it is invisible to a unit+ // test of the generator's happy path: moving the Object.assign above any+ // `return null` would silently restore the #3179 bug — a hook side effect+ // keyed on the stamped metadata would fire for a task that is never built.+ const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');+ expect(start, 'generateManagedAppImprovementTaskForType must exist').toBeGreaterThan(-1);+ const body = GEN_SRC.slice(start);+ const stampAt = body.indexOf('Object.entries(hookMetadata || {})');+ expect(stampAt, 'the hookMetadata stamp must exist').toBeGreaterThan(-1);+ // Bound the scan to this function: `return task;` ends it.+ const lastGateAt = body.slice(0, body.indexOf('return task;')).lastIndexOf('return null;');+ expect(lastGateAt, 'the gate chain must exist').toBeGreaterThan(-1);+ expect(stampAt).toBeGreaterThan(lastGateAt);+ });+});diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex 7a3d93c0d0..4c03b79ef0 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -34,6 +34,54 @@ export async function recordQuotaBurnDispatch(key) {return next;}+/**+ * The task-metadata key a resolved `dispatchKey` rides across on, from the+ * pre-agent `buildTaskInput` hook to the post-agent `processTaskOutput` that+ * writes the ledger (#3179). Lives here, beside the ledger it guards, so the+ * producer, the consumer, and the in-flight count below can't drift on spelling.+ */+export const QUOTA_BURN_DISPATCH_KEY_FIELD = 'quotaBurnDispatchKey';++/**+ * Dispatch counts to select the next burn candidate against: the persisted+ * ledger PLUS every quota-burn task already queued or running that carries a+ * dispatch key but has not reached its post-agent ledger write yet.+ *+ * Counting the in-flight tasks is what keeps the window cap honest now that the+ * ledger is written post-agent (#3179). The ledger write used to happen during+ * generation, which incidentally serialized sibling candidates — the next reader+ * always saw it. Deferring the write opens a gap between "task created" and+ * "dispatch recorded", and two paths generate inside that gap: the per-app+ * improvement loop runs once per managed app while `dispatchKey` is+ * `<family>:<resetEpoch>` (app-independent, one global ledger), and an on-demand+ * "Run" calls the generator directly, bypassing the per-app pending-task cap+ * entirely. Without this, either could dispatch past `maxDispatchesPerWindow` —+ * real quota overspend, the exact thing the cap exists to prevent, and a worse+ * failure than the over-counting #3179 fixed.+ *+ * An unreadable task file degrades to the ledger-only count rather than throwing:+ * COS-TASKS.md is the file the whole CoS queue reads, so if it is unavailable+ * nothing is dispatching anyway, and failing the probe closed would wedge+ * quota-burn until the next 12-hourly recheck.+ */+export async function getEffectiveQuotaBurnDispatches() {+ const counts = { ...(await getQuotaBurnDispatches()) };+ // Lazy import: cosTaskStore pulls a heavy graph (state, code review, merge),+ // and quotaBurn.js is imported by the perpetual-work detector on a hot path.+ const { getCosTasks } = await import('./cosTaskStore.js');+ const cosTasks = await getCosTasks().catch((err) => {+ console.error(`❌ Quota-burn in-flight probe failed, falling back to the ledger alone: ${err.message}`);+ return null;+ });+ for (const task of cosTasks?.tasks || []) {+ if (task?.status !== 'pending' && task?.status !== 'in_progress') continue;+ const key = task?.metadata?.[QUOTA_BURN_DISPATCH_KEY_FIELD];+ if (typeof key !== 'string' || !key) continue;+ counts[key] = Number(counts[key] || 0) + 1;+ }+ return counts;+}+function normalizedFamily(id, value) {if (!value || typeof value !== 'object' || value.enabled !== true) return null;const config = { ...DEFAULT_QUOTA_BURN_FAMILY, ...value };@@ -90,7 +138,7 @@ export async function detectQuotaBurn(app, { getQuotas = getProviderQuotas, nowif (configuredCards.length && configuredCards.every((card) => card?.error)) {return { actionable: false, count: 0, transient: true, reason: 'all-provider-quota-checks-failed' };}- const candidates = selectBurnCandidates(quotas, config, { now, dispatches: dispatches || await getQuotaBurnDispatches() });+ const candidates = selectBurnCandidates(quotas, config, { now, dispatches: dispatches || await getEffectiveQuotaBurnDispatches() });return candidates.length? { actionable: true, count: candidates.length, reason: `${candidates[0].family.id} resets in ${Math.ceil(candidates[0].hoursUntilReset)}h`, candidates }: { actionable: false, count: 0, reason: 'no-family-within-reset-window' };diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.jsindex 7fd81cefe1..fbe61b232d 100644--- a/server/services/quotaBurn.test.js+++ b/server/services/quotaBurn.test.js@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { detectQuotaBurn, selectBurnCandidates } from './quotaBurn.js';import { sanitizeTaskMetadata } from '../lib/validation.js';@@ -57,3 +57,52 @@ describe('quota-burn metadata validation', () => {expect(sanitizeTaskMetadata({ families: { grok: { reservePercent: 101 } } })).toBeNull();});});++/**+ * The window cap is only honest if a burn that has been QUEUED but whose agent+ * has not finalized yet still holds its slot. The ledger write moved post-agent+ * (#3179), so the raw ledger no longer covers that gap on its own.+ */+describe('getEffectiveQuotaBurnDispatches', () => {+ const loadStore = async (tasks, { fail = false } = {}) => {+ vi.resetModules();+ vi.doMock('./cosTaskStore.js', () => ({+ getCosTasks: fail ? async () => { throw new Error('unreadable'); } : async () => ({ tasks }),+ }));+ vi.doMock('../lib/fileUtils.js', async (importActual) => ({+ ...(await importActual()),+ readJSONFile: async () => ({ 'grok:1': 1 }),+ }));+ return import('./quotaBurn.js');+ };++ const burnTask = (status, key) => ({ id: `sys-${status}`, status, metadata: { quotaBurnDispatchKey: key } });++ afterEach(() => { vi.doUnmock('./cosTaskStore.js'); vi.doUnmock('../lib/fileUtils.js'); vi.resetModules(); });++ it('adds pending and in_progress burns on top of the persisted ledger', async () => {+ const { getEffectiveQuotaBurnDispatches } = await loadStore([+ burnTask('pending', 'grok:1'),+ burnTask('in_progress', 'codex:2'),+ ]);+ // grok:1 = 1 persisted + 1 queued; codex:2 = 0 persisted + 1 running.+ await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2, 'codex:2': 1 });+ });++ it('ignores terminal tasks and tasks carrying no dispatch key', async () => {+ const { getEffectiveQuotaBurnDispatches } = await loadStore([+ burnTask('completed', 'grok:1'),+ burnTask('blocked', 'grok:1'),+ { id: 'sys-other', status: 'pending', metadata: { analysisType: 'performance' } },+ { id: 'sys-empty', status: 'pending', metadata: { quotaBurnDispatchKey: '' } },+ ]);+ // A completed burn already wrote its ledger entry — counting it would+ // double-charge the window; a blocked one never dispatched.+ await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 1 });+ });++ it('degrades to the ledger alone when the task file cannot be read', async () => {+ const { getEffectiveQuotaBurnDispatches } = await loadStore([], { fail: true });+ await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 1 });+ });+});diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.jsindex ef99135b9b..e3c693b0be 100644--- a/server/services/taskTypeHooks.js+++ b/server/services/taskTypeHooks.js@@ -7,9 +7,18 @@** - `buildTaskInput({ app, taskType })` — runs BEFORE spawn, inside the task* generator. Collects data beyond the base prompt (telemetry, open issues, …)- * and returns `{ prompt?, providerId?, model?, skip? }`:+ * and returns `{ prompt?, providerId?, model?, hookMetadata?, skip? }`:* • `prompt` — a fully-rendered prompt that REPLACES the template.* • `providerId` / `model` — pin the agent's provider/model (per-app choice).+ * • `hookMetadata` — a free-form bag merged into the task's persisted+ * `metadata`, so a value resolved pre-agent survives to `processTaskOutput`.+ * The generator applies it only AFTER every gate that can still skip task+ * creation has passed, so a hook can safely defer a side effect until the+ * task really exists (quota-burn's dispatch ledger, #3179) instead of+ * performing it speculatively here. Untyped by design — a passthrough, not+ * a schema; keep the keys namespaced to the task type. A key that collides+ * with generator-computed metadata is DROPPED with a warning, so the bag+ * can't overwrite `analysisType`, provider pins, or plan ids.* • `skip: { reason }` — short-circuit: no agent is spawned.** - `processTaskOutput({ appId, success, payload, workspacePath, agentId, task }, deps?)`@@ -138,7 +147,8 @@ export function isNonCommittingCoordinatorTask(task) {/*** Resolve the pre-agent input hook for a task type, or null if it has none.- * `buildTaskInput({ app, taskType })` → `{ prompt?, providerId?, model?, skip? }`.+ * `buildTaskInput({ app, taskType })` → `{ prompt?, providerId?, model?, hookMetadata?, skip? }`+ * (see the module header for each field's contract).*/export async function getTaskInputHook(taskType) {const mod = await loadHookModule(taskType);