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

fix: charge a perpetual drain's dispatch budget only when a task is really produced (#3848)

[._.]/ Adam Eivyd34f25f78752
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 72ea8b8676..dcb3dcc14e 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2147,11 +2147,19 @@ async function resolveClaimWorkRouting(app, taskType, metadata, taskSchedule) {
* the 'perpetual' interval — excluding branch-/issue-reconcile, whose own scan
* IS the detector — a programmatic detector decides whether there's anything to
* claim BEFORE building the (expensive) prompt or burning an agent:
- * - actionable → clear any park, stamp metadata.perpetual (skip cooldown), proceed;
+ * - actionable → stamp metadata.perpetual (skip cooldown), proceed;
* - idle (definitive) → PARK on the recheck cadence, skip;
* - transient probe failure → skip WITHOUT parking so the next tick retries.
- * The detector keys on the RESOLVED promptTaskType. Returns `{ skip }` and
- * mutates `metadata.perpetual` on the actionable path.
+ * The detector keys on the RESOLVED promptTaskType. Returns `{ skip, spendDispatch }`
+ * and mutates `metadata.perpetual` on the actionable path.
+ *
+ * `spendDispatch` is the caller's cue to call `recordPerpetualDispatch` (which
+ * clears the park and spends one unit of the type's `drainDispatchCap` budget in a
+ * single write) — deliberately NOT done here. Gates that run AFTER this one can
+ * still return null with no agent ever spawned (`applyPlanIdMetadata` skips
+ * plan-task when every unchecked item is in-flight or blocked), and charging the
+ * budget for a task that was never created would exhaust a capped drain on
+ * evaluations alone, parking it for `drain-cap` without a single dispatch.
*/
async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, interval, taskSchedule, { ignoreTaskId = null } = {}) {
if (interval.type !== taskSchedule.INTERVAL_TYPES.PERPETUAL
@@ -2166,16 +2174,11 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
ignoreTaskId
});
if (detection.actionable) {
- // Spend one dispatch from the type's `drainDispatchCap` budget (and clear the
- // park in the same write — recordPerpetualDispatch does both). These drains
- // carry no actionable signature (only the reconcile scans produce one), so
- // pass null: the counter is the ONLY convergence brake they have besides the
- // detector going idle, and without an increment here the shared cap gate in
- // applyPerpetualDrainCap would read a budget that never moves.
- await taskSchedule.recordPerpetualDispatch(taskType, app.id, null);
recordPerpetualTransient(taskType, app.id, null);
metadata.perpetual = true;
- return { skip: false };
+ // The dispatch is SPENT BY THE CALLER, once a task is certain — see the note
+ // on `spendDispatch` in the JSDoc above.
+ return { skip: false, spendDispatch: true };
}
if (detection.transient) {
emitLog('debug', `Perpetual ${taskType} skip for ${app.name} (transient: ${detection.reason})`, { appId: app.id });
@@ -2195,9 +2198,9 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
const counts = detection.total != null
? { open: detection.total, inFlight: detection.inFlightCount ?? 0, filtered: detection.filteredCount ?? 0 }
: null;
- // Terminal park — zero the dispatch budget in the same write, so the next drain
- // window starts fresh instead of capping early on a previous window's spend.
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: detection.reason, actionableCount: detection.count, counts, dispatchCount: 0 });
+ // Terminal park — parkPerpetual zeroes the dispatch budget in the same write, so
+ // the next drain window starts fresh instead of capping early on this one's spend.
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: detection.reason, actionableCount: detection.count, counts });
emitLog('info', `Perpetual ${taskType} parked for ${app.name}: ${detection.reason}`, { appId: app.id });
return { skip: true };
}
@@ -2224,14 +2227,19 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
*/
export async function applyPerpetualDrainCap(app, taskType, interval, taskSchedule) {
if (interval.type !== taskSchedule.INTERVAL_TYPES.PERPETUAL) return { skip: false };
- const cap = interval.drainDispatchCap;
- // Absent/null (and any non-numeric hand-edit) ⇒ unbounded.
- if (!Number.isFinite(cap)) return { skip: false };
+ // Coerce before validating: this key is not on the schedule route's allowlist, so
+ // the only way it arrives non-numeric is a hand-edited schedule.json, where `"5"`
+ // is the likeliest shape and reading it as "no cap" would silently unbound the
+ // runaway guard. Anything that still isn't a positive finite number — absent,
+ // null, `""`, `"soon"`, 0, negative — means UNBOUNDED, i.e. exactly the behavior
+ // of a type that never configured the key.
+ const cap = Number(interval.drainDispatchCap ?? NaN);
+ if (!Number.isFinite(cap) || cap <= 0) return { skip: false };
const { dispatchCount } = await taskSchedule.getPerpetualDrainState(taskType, app.id);
if (dispatchCount < cap) return { skip: false };
// One write lands the park, the cleared signature, and the zeroed budget — a
// terminal park must never leave a stale count for the next window.
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'drain-cap', signature: null, dispatchCount: 0 });
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'drain-cap', signature: null });
emitLog('info', `Perpetual ${taskType} parked for ${app.name}: ${dispatchCount} consecutive dispatches reached the drain cap of ${cap} — will re-drive on next recheck`, { appId: app.id });
return { skip: true };
}
@@ -2284,9 +2292,9 @@ export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { s
const { signature: lastSignature } = await taskSchedule.getPerpetualDrainState(taskType, app.id);
if (signature === lastSignature) {
// The park fields, the cleared signature, and the zeroed dispatch budget land
- // in ONE write, so no terminal park can leave a stale count behind for the
- // next drain window to trip over.
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount, signature: null, dispatchCount: 0 });
+ // in ONE write (the budget by parkPerpetual's default), so no terminal park
+ // can leave a stale count behind for the next drain window to trip over.
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount, signature: null });
emitLog('info', `${label} parked for ${app.name}: ${actionableCount} ${unit} unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });
return false;
}
@@ -2367,7 +2375,7 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
// clearing the progress signature so a fresh set later dispatches and zeroing the
// dispatch budget — this drain converged, so the next one gets a full one.
const reason = heldLive.length ? 'branches-held-by-live-owners' : 'no-in-flight-branches';
- await taskSchedule.parkPerpetual(taskType, app.id, { reason, actionableCount: 0, signature: null, dispatchCount: 0 });
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason, actionableCount: 0, signature: null });
// Surface merged branches held back by a protection guard so a lingering
// worktree isn't an invisible "cleaned 0".
const heldSuffix = countSuffix(
@@ -2435,7 +2443,7 @@ async function resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule)
emitLog('info', `🧟 issue-reconcile ${app.name}: ${result.stalled.length} stalled in-progress issue(s) with no merged PR (left for human/branch-reconcile)`, { appId: app.id, analysisType: taskType });
}
if (result.zombies.length === 0) {
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null, dispatchCount: 0 });
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null });
emitLog('info', `🧟 issue-reconcile parked for ${app.name}: no zombie issues`, { appId: app.id });
return { skip: true };
}
@@ -2837,6 +2845,14 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
}
metadata[key] = value;
}
+ // Every gate has now passed and a task is certain, so the perpetual drain can
+ // finally be charged for this hop (and its park cleared). Sits beside
+ // `updateAppActivity` for the same reason that call does: both are "a task was
+ // really produced" side effects, and every `return null` above must skip them.
+ // The reconcile drains spend theirs inside their own block, which no later gate
+ // can skip (their types are outside PLAN_PICK_TASK_TYPES / pr-watcher /
+ // reference-watch), so they are already charged only on real dispatches.
+ if (perpetualGate.spendDispatch) await taskSchedule.recordPerpetualDispatch(taskType, app.id, null);
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.js
index 735cee3dab..61bf6d6397 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -1165,7 +1165,7 @@ describe('resolveReconcileDrainGate', () => {
const ts = fakeSchedule({ signature: 'a:NEEDS_PR:none', dispatchCount: 1 });
expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx())).toBe(false);
expect(ts.parkPerpetual).toHaveBeenCalledWith('branch-reconcile', 'app-1', {
- reason: 'no-progress', actionableCount: 1, signature: null, dispatchCount: 0
+ reason: 'no-progress', actionableCount: 1, signature: null
});
expect(ts.recordPerpetualDispatch).not.toHaveBeenCalled();
});
@@ -1195,14 +1195,20 @@ describe('applyPerpetualDrainCap', () => {
const app = { id: 'app-1', name: 'App One' };
const perpetual = (over = {}) => ({ type: 'perpetual', ...over });
- it('parks drain-cap once the budget is spent, zeroing signature + counter in the park write', async () => {
+ it('parks drain-cap once the budget is spent, clearing the signature in the park write', async () => {
const ts = fakeSchedule(5);
expect(await applyPerpetualDrainCap(app, 'branch-reconcile', perpetual({ drainDispatchCap: 5 }), ts)).toEqual({ skip: true });
+ // The counter is zeroed by parkPerpetual's default — every park ends a window.
expect(ts.parkPerpetual).toHaveBeenCalledWith('branch-reconcile', 'app-1', {
- reason: 'drain-cap', signature: null, dispatchCount: 0
+ reason: 'drain-cap', signature: null
});
});
+ it('reads a hand-edited numeric string as the cap rather than silently unbounding the guard', async () => {
+ const ts = fakeSchedule(5);
+ expect(await applyPerpetualDrainCap(app, 'branch-reconcile', perpetual({ drainDispatchCap: '5' }), ts)).toEqual({ skip: true });
+ });
+
it('spends exactly CAP dispatches before capping', async () => {
const outcomes = [];
for (let dispatchCount = 0; dispatchCount <= 5; dispatchCount += 1) {
@@ -1213,7 +1219,7 @@ describe('applyPerpetualDrainCap', () => {
// The whole reason the cap is per-type: an uncapped claim drain must keep going.
it('never parks a perpetual type with no cap configured, however many hops it has taken', async () => {
- for (const drainDispatchCap of [undefined, null, 'nope']) {
+ for (const drainDispatchCap of [undefined, null, '', 'nope', 0, -1]) {
const ts = fakeSchedule(500);
expect(await applyPerpetualDrainCap(app, 'claim-issue', perpetual({ drainDispatchCap }), ts)).toEqual({ skip: false });
expect(ts.parkPerpetual).not.toHaveBeenCalled();
@@ -1260,14 +1266,23 @@ describe('the drain cap has exactly one implementation, at the choke point', ()
}
});
- it('the work gate spends a dispatch on the actionable path and zeroes the budget when it parks', () => {
+ // The counter must move for the non-reconcile drains or their cap could never
+ // fire — but it must move ONLY when a task is really produced. Gates that run
+ // after the work gate can still return null (applyPlanIdMetadata skips plan-task
+ // when every unchecked item is in-flight), so charging the budget inside the gate
+ // would exhaust a capped drain on evaluations alone.
+ it('the work gate defers its dispatch spend to the caller, which charges it only once a task is certain', () => {
const start = GEN_SRC.indexOf('async function applyPerpetualWorkGate');
const gate = GEN_SRC.slice(start, GEN_SRC.indexOf('\n}', start));
- // Without this the counter never moves for the non-reconcile drains and their
- // cap (when one is configured) could never fire.
- expect(gate).toContain('recordPerpetualDispatch(taskType, app.id, null)');
- // A terminal park must not leave a stale count for the next drain window.
- expect(gate).toMatch(/parkPerpetual\(taskType, app\.id, \{[^}]*dispatchCount: 0[^}]*\}\)/);
+ expect(gate).toContain('spendDispatch: true');
+ expect(gate, 'the gate must not charge the budget itself').not.toContain('recordPerpetualDispatch');
+
+ const genStart = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');
+ const body = GEN_SRC.slice(genStart, GEN_SRC.indexOf('return task;', genStart));
+ const spendIdx = body.indexOf('if (perpetualGate.spendDispatch) await taskSchedule.recordPerpetualDispatch(taskType, app.id, null)');
+ expect(spendIdx, 'the choke point must spend the deferred dispatch').toBeGreaterThan(-1);
+ // Every `return null` gate must precede it — planId is the last one.
+ expect(body.indexOf('planMeta.skipReason')).toBeLessThan(spendIdx);
});
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 0d7024ac3e..b6c2730e05 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1064,12 +1064,18 @@ const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCo
* to land them in the same write it lands the park. A second await after this one
* is a step a future park path can forget — and a stale non-zero dispatch count
* makes the NEXT fresh drain cap out early, which looks exactly like the task
- * silently doing nothing. Note `dispatchCount` is deliberately NOT in
- * `PARK_FIELDS`: `recordPerpetualDispatch` clears those fields mid-drain on every
- * dispatch, and zeroing the counter there would reset the budget before every
- * dispatch, so the cap could never fire.
+ * silently doing nothing.
+ *
+ * `dispatchCount` therefore DEFAULTS to 0: a park ends the drain window by
+ * definition, so zeroing the budget is the invariant, not an opt-in every caller
+ * has to remember. (The churn detector's park in agentChurn.js is exactly the
+ * caller that forgot, leaving the next window to cap early on a spend it never
+ * made.) Note `dispatchCount` is still deliberately NOT in `PARK_FIELDS`:
+ * `recordPerpetualDispatch` clears those fields mid-drain on every dispatch, and
+ * zeroing the counter there would reset the budget before every dispatch, so the
+ * cap could never fire.
*/
-export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, signature, dispatchCount } = {}) {
+export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, signature, dispatchCount = 0 } = {}) {
const schedule = await loadSchedule();
const interval = schedule.tasks[taskType] || {};
const parkedUntil = await computePerpetualRecheckAt(interval);
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index f166aa4521..d52fdf008d 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -1767,14 +1767,19 @@ describe('taskSchedule', () => {
expect(rec.parkReason).toBe('drain-cap')
})
- it('parkPerpetual leaves the dispatch budget alone when the option is omitted', async () => {
+ // Inverted deliberately (#3848): omitting the option used to PRESERVE the
+ // count. A park ends the drain window by definition, so zeroing the budget is
+ // the invariant, not something each call site has to opt into — the churn
+ // detector's park (agentChurn.js) is exactly the caller that forgot, leaving
+ // the next window to cap early on a spend it never made.
+ it('parkPerpetual zeroes the dispatch budget even when the caller omits dispatchCount', async () => {
mockSchedule({
tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
})
- await parkPerpetual('claim-issue', 'app-1', { reason: 'no-actionable-issues', actionableCount: 0 })
+ await parkPerpetual('claim-issue', 'app-1', { reason: 'churn-detected', actionableCount: 12 })
const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:claim-issue'].perApp['app-1']
- expect(rec.perpetualDispatchCount).toBe(4)
+ expect(rec.perpetualDispatchCount).toBeUndefined()
})
it('resetPerpetualForManualRun is a no-op (false) when nothing is cached', async () => {