Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): exclude the completing burn from the in-flight dispatch count

[._.]/ Adam Eivy226a0e85376f
diff --git a/server/services/autonomousJobs/quotaBurnHooks.js b/server/services/autonomousJobs/quotaBurnHooks.js
index 05afbf3b08..4849a76b6c 100644
--- a/server/services/autonomousJobs/quotaBurnHooks.js
+++ b/server/services/autonomousJobs/quotaBurnHooks.js
@@ -40,13 +40,14 @@ function renderPrompt(candidate) {
* `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 } = {}) {
+export async function buildTaskInput({ app, ignoreTaskId = null } = {}) {
if (!app) return { skip: { reason: 'no-app' } };
const config = quotaBurnConfig(app);
// Ledger + in-flight, NOT the bare ledger: a quota-burn task already queued or
// running holds its window slot even though its ledger write lands post-agent
- // (#3179).
- const dispatches = await getEffectiveQuotaBurnDispatches();
+ // (#3179). `ignoreTaskId` drops the run whose completion triggered this
+ // generation — it recorded itself moments ago but still reads `in_progress`.
+ const dispatches = await getEffectiveQuotaBurnDispatches({ ignoreTaskId });
const quotas = await getProviderQuotas({ refresh: true });
const candidates = selectBurnCandidates(quotas, config, { dispatches });
const candidate = candidates[0];
diff --git a/server/services/autonomousJobs/quotaBurnHooks.test.js b/server/services/autonomousJobs/quotaBurnHooks.test.js
index ab69b34a24..c78f22ae5d 100644
--- a/server/services/autonomousJobs/quotaBurnHooks.test.js
+++ b/server/services/autonomousJobs/quotaBurnHooks.test.js
@@ -86,6 +86,12 @@ describe('buildTaskInput (pre-agent)', () => {
expect(getEffectiveQuotaBurnDispatches).toHaveBeenCalled();
expect(selectBurnCandidates).toHaveBeenCalledWith(expect.anything(), expect.anything(), { dispatches: { [DISPATCH_KEY]: 1 } });
});
+
+ it('forwards ignoreTaskId so the completing run is not counted against itself', async () => {
+ await buildTaskInput({ app: APP, ignoreTaskId: 'sys-finishing' });
+
+ expect(getEffectiveQuotaBurnDispatches).toHaveBeenCalledWith({ ignoreTaskId: 'sys-finishing' });
+ });
});
describe('processTaskOutput (post-agent)', () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index fa7a0acd16..d412d6057f 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1433,7 +1433,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore
// agents claim the same slug (2026-05-21 incident). The generator
// returns null on plan-gate / precondition skip; we silently continue.
// Regression-pinned in cos.test.js.
- const task = await generateManagedAppImprovementTaskForType(nextType, app, state);
+ const task = await generateManagedAppImprovementTaskForType(nextType, app, state, { ignoreTaskId });
if (!task) continue;
// Queue-path invariants override the generator's direct-spawn defaults
@@ -1868,11 +1868,11 @@ async function buildImprovementTaskMetadata(taskType, app, interval, taskSchedul
* `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.
*/
-export async function resolveTaskInputHook(app, taskType, taskSchedule) {
+export async function resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId = null } = {}) {
const { getTaskInputHook } = await import('./taskTypeHooks.js');
const inputHook = await getTaskInputHook(taskType);
if (!inputHook) return { skip: false, hookPrompt: null, hookOverride: {}, hookMetadata: null };
- const input = await inputHook({ app, taskType }).catch((err) => {
+ const input = await inputHook({ app, taskType, ignoreTaskId }).catch((err) => {
emitLog('warn', `buildTaskInput hook failed for ${taskType}/${app.name}: ${err.message}`, { appId: app.id, analysisType: taskType });
return { skip: { reason: 'input-hook-error' } };
});
@@ -1923,14 +1923,17 @@ async function resolveClaimWorkRouting(app, taskType, metadata, taskSchedule) {
* The detector keys on the RESOLVED promptTaskType. Returns `{ skip }` and
* mutates `metadata.perpetual` on the actionable path.
*/
-async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule) {
+async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId = null } = {}) {
if (interval.type !== taskSchedule.INTERVAL_TYPES.PERPETUAL
|| taskType === 'branch-reconcile' || taskType === 'issue-reconcile') {
return { skip: false };
}
const { detectActionableWork } = await import('./perpetualWork.js');
const detection = await detectActionableWork(promptTaskType, app, {
- issueAuthorFilter: metadata.issueAuthorFilter || 'self'
+ issueAuthorFilter: metadata.issueAuthorFilter || 'self',
+ // A detector that counts in-flight work must skip the task whose completion
+ // triggered this refill — it is already recorded, just not yet marked done.
+ ignoreTaskId
});
if (detection.actionable) {
await taskSchedule.clearPerpetualPark(taskType, app.id);
@@ -2303,7 +2306,7 @@ function applyProviderModelPins(metadata, interval, hookOverride) {
if (hookOverride.model) { metadata.model = hookOverride.model; }
}
-export async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false } = {}) {
+export async function generateManagedAppImprovementTaskForType(taskType, app, state, { skipPreconditions = false, ignoreTaskId = null } = {}) {
const { updateAppActivity } = await import('./appActivity.js');
const taskSchedule = await import('./taskSchedule.js');
const { getTaskPrompt, getStagePrompt } = await import('./taskPromptService.js');
@@ -2335,7 +2338,11 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// fully OWNS its prompt. `hookOverride` may pin the app's per-app
// provider/model — captured here but APPLIED AFTER the global-interval
// provider/model block below, so the per-app choice wins.
- const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule);
+ // `ignoreTaskId` reaches the hook because a drain-on-completion refill runs
+ // while the completing task is still `in_progress` on disk — a hook that
+ // counts in-flight tasks (quota-burn) must not count the run that just
+ // finished and already recorded itself (#3179).
+ const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId });
if (inputHook.skip) return null;
const { hookPrompt, hookOverride, hookMetadata } = inputHook;
@@ -2347,7 +2354,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// Perpetual (drain-until-done) gate — probes for actionable work before
// building the prompt or burning an agent (branch-/issue-reconcile self-gate
// in their own blocks, so this excludes them).
- const perpetualGate = await applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule);
+ const perpetualGate = await applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId });
if (perpetualGate.skip) return null;
// branch-reconcile: deterministic git/gh pre-step that carries the actionable
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index ba6ba8511a..9a61797c7d 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -842,3 +842,47 @@ describe('resolveTaskInputHook — hookMetadata threading (#3179)', () => {
expect(stampAt).toBeGreaterThan(lastGateAt);
});
});
+
+/**
+ * The drain-on-completion refill regenerates while the just-finished task is
+ * still `in_progress` on disk (agent:completed fires before updateTask). A hook
+ * or detector that counts in-flight work must exclude it, or the completing run
+ * is charged twice — see #3179 and buildImprovementDedupSets' own ignoreTaskId.
+ */
+describe('ignoreTaskId reaches the in-flight-counting gates (#3179)', () => {
+ const body = () => {
+ const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');
+ return GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));
+ };
+
+ it('accepts ignoreTaskId and forwards it to the input hook and the perpetual gate', () => {
+ expect(GEN_SRC).toMatch(/generateManagedAppImprovementTaskForType\(taskType, app, state, \{ skipPreconditions = false, ignoreTaskId = null \} = \{\}\)/);
+ expect(body()).toContain('resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId })');
+ expect(body()).toContain('applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId })');
+ });
+
+ it('queueEligibleImprovementTasks passes its ignoreTaskId down to the generator', () => {
+ // It already forwards the same id to addTask and buildImprovementDedupSets;
+ // the generator was the one path that dropped it.
+ expect(GEN_SRC).toContain('generateManagedAppImprovementTaskForType(nextType, app, state, { ignoreTaskId })');
+ });
+
+ it('the perpetual gate hands ignoreTaskId to the work detector', () => {
+ const start = GEN_SRC.indexOf('async function applyPerpetualWorkGate');
+ const gate = GEN_SRC.slice(start, GEN_SRC.indexOf('\n}', start));
+ expect(gate).toMatch(/detectActionableWork\(promptTaskType, app, \{[\s\S]*ignoreTaskId[\s\S]*\}\)/);
+ });
+
+ it('resolveTaskInputHook passes ignoreTaskId into the hook call', async () => {
+ const seen = [];
+ vi.doMock('./taskTypeHooks.js', () => ({
+ getTaskInputHook: async () => async (args) => { seen.push(args); return { prompt: 'X' }; }
+ }));
+ try {
+ await resolveTaskInputHook({ id: 'app-1', name: 'App One' }, 'quota-burn', { recordExecution: vi.fn() }, { ignoreTaskId: 'sys-finishing' });
+ } finally {
+ vi.doUnmock('./taskTypeHooks.js');
+ }
+ expect(seen[0]).toMatchObject({ taskType: 'quota-burn', ignoreTaskId: 'sys-finishing' });
+ });
+});
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 1538be2cec..0c39b5da66 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -482,9 +482,13 @@ export function hasWorkDetector(taskType) {
registerWorkDetector('claim-issue', detectGithubIssues);
registerWorkDetector('claim-issue-gitlab', detectGitlabIssues);
registerWorkDetector('plan-task', detectPlanTask);
-registerWorkDetector('quota-burn', async (app) => {
+registerWorkDetector('quota-burn', async (app, opts) => {
const { detectQuotaBurn } = await import('./quotaBurn.js');
- return detectQuotaBurn(app);
+ // Forward `ignoreTaskId`: on the drain-on-completion refill the just-finished
+ // burn has already written its ledger entry but still reads `in_progress`, so
+ // without this the detector counts it twice and parks a family that still has
+ // window budget left (#3179).
+ return detectQuotaBurn(app, { ignoreTaskId: opts?.ignoreTaskId || null });
});
/**
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 4c03b79ef0..090d0d157b 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -59,12 +59,21 @@ export const QUOTA_BURN_DISPATCH_KEY_FIELD = 'quotaBurnDispatchKey';
* real quota overspend, the exact thing the cap exists to prevent, and a worse
* failure than the over-counting #3179 fixed.
*
+ * `ignoreTaskId` excludes one task from the in-flight tally — the same exclusion
+ * `buildImprovementDedupSets` takes, for the same reason. `agent:completed` fires
+ * from `completeAgent`, which runs AFTER the output hook wrote this run's ledger
+ * entry but BEFORE the completion flow's `updateTask` marks the task done. So
+ * during the perpetual drain-on-completion refill the just-finished burn is
+ * counted twice — once in the ledger, once as a still-`in_progress` task — and a
+ * family with `maxDispatchesPerWindow: 2` would stop after one run and likely
+ * miss its reset window. Callers on that path pass the completing task's id.
+ *
* 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() {
+export async function getEffectiveQuotaBurnDispatches({ ignoreTaskId = null } = {}) {
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.
@@ -74,6 +83,7 @@ export async function getEffectiveQuotaBurnDispatches() {
return null;
});
for (const task of cosTasks?.tasks || []) {
+ if (ignoreTaskId && task?.id === ignoreTaskId) continue;
if (task?.status !== 'pending' && task?.status !== 'in_progress') continue;
const key = task?.metadata?.[QUOTA_BURN_DISPATCH_KEY_FIELD];
if (typeof key !== 'string' || !key) continue;
@@ -127,7 +137,7 @@ export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatc
.sort((a, b) => a.hoursUntilReset - b.hoursUntilReset || a.family.priority - b.family.priority);
}
-export async function detectQuotaBurn(app, { getQuotas = getProviderQuotas, now = Date.now(), dispatches } = {}) {
+export async function detectQuotaBurn(app, { getQuotas = getProviderQuotas, now = Date.now(), dispatches, ignoreTaskId = null } = {}) {
const config = quotaBurnConfig(app);
const configured = Object.entries(config.families || {})
.filter(([, family]) => family?.enabled === true)
@@ -138,7 +148,7 @@ export async function detectQuotaBurn(app, { getQuotas = getProviderQuotas, now
if (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 getEffectiveQuotaBurnDispatches() });
+ const candidates = selectBurnCandidates(quotas, config, { now, dispatches: dispatches || await getEffectiveQuotaBurnDispatches({ ignoreTaskId }) });
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.js
index fbe61b232d..3cf7d917d7 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -105,4 +105,16 @@ describe('getEffectiveQuotaBurnDispatches', () => {
const { getEffectiveQuotaBurnDispatches } = await loadStore([], { fail: true });
await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 1 });
});
+
+ it('excludes ignoreTaskId so a completing burn is not counted twice', async () => {
+ // The drain-on-completion refill runs between the output hook's ledger write
+ // and the completion flow's updateTask, so the finished burn is BOTH in the
+ // ledger and still `in_progress`. Counting both would consume two slots for
+ // one run — a family capped at 2 would stop after one and miss its window.
+ const tasks = [{ id: 'sys-finishing', status: 'in_progress', metadata: { quotaBurnDispatchKey: 'grok:1' } }];
+ const { getEffectiveQuotaBurnDispatches } = await loadStore(tasks);
+
+ await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2 });
+ await expect(getEffectiveQuotaBurnDispatches({ ignoreTaskId: 'sys-finishing' })).resolves.toEqual({ 'grok:1': 1 });
+ });
});
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index e3c693b0be..59479c79b6 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -5,9 +5,12 @@
* sentinel`. A few need PROGRAMMATIC steps around the agent. A hook module may
* export either or both of:
*
- * - `buildTaskInput({ app, taskType })` — runs BEFORE spawn, inside the task
- * generator. Collects data beyond the base prompt (telemetry, open issues, …)
- * and returns `{ prompt?, providerId?, model?, hookMetadata?, skip? }`:
+ * - `buildTaskInput({ app, taskType, ignoreTaskId })` — runs BEFORE spawn, inside
+ * the task generator. Collects data beyond the base prompt (telemetry, open
+ * issues, …) and returns `{ prompt?, providerId?, model?, hookMetadata?, skip? }`.
+ * `ignoreTaskId` is set on the drain-on-completion refill and names the task
+ * that just finished but is still `in_progress` on disk — a hook that counts
+ * in-flight work must exclude it (see quotaBurnHooks.js):
* • `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