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: bound back-to-back re-dispatch for every perpetual drain and make a park stop a refill (#3848)

[._.]/ Adam Eivyd2b29877edb5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a04e3a10a7..dfe91e415a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -13,6 +13,7 @@
- Automated reconciliation runs no longer raise a "nothing to do" notification. Only a run you started by hand reports back, so a healthy overnight drain converges quietly instead of leaving a pile of notifications.
- Branch reconciliation no longer mistakes GitHub's mergeability lag for progress. GitHub answers `UNKNOWN` until it finishes computing whether a PR can merge, so consecutive checks of a completely unchanged PR looked like a branch advancing.
- Both reconciliation tasks (branches and stale issues) now stop after a bounded number of back-to-back runs even when each run does make some progress, and wait for their next scheduled check. Nothing is dropped — the remaining work is found again on that check.
+- A task that has parked itself no longer gets restarted anyway the moment its previous run finishes. Parking is what stops a drain-until-done task from running all night, but it was only ever read by the scheduled path — the automatic "keep draining" restart never checked it, so a task could park and be relaunched on the very next completion, indefinitely. That restart now honors the park, and the bounded back-to-back run limit applies to every drain-until-done task rather than only the two reconciliation ones. The claim-and-ship task types are deliberately left unlimited so a healthy overnight run is not throttled, and pressing "Run Now" is unaffected.
- Tapping the notifications bell on a phone now opens a panel that stays on screen. It was anchored to the bell — which sits mid-screen in the sidebar — so the panel ran off the right edge, clipping notification titles and putting every per-item dismiss button and the mark-all/clear-all controls out of reach with nothing to scroll to them.
- The notification panel's "+N more notifications" line is now a "Show N more" button, so the notifications past the first ten can be read and dismissed instead of being permanently unreachable.
- Notification dismiss and "Mark read" buttons are now full-size, always-visible tap targets on touch devices — they were sized to their bare icon, and the dismiss button was only revealed on hover, which a phone has no way to do.
diff --git a/server/services/cos.js b/server/services/cos.js
index fad911c0da..72d79ebc09 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1345,6 +1345,17 @@ async function refillPerpetualForCompletedAgent(agent) {
// the still-`in_progress` completing task; letting triggerOnDemandTask emit
// its event would fire a redundant SECOND dequeue of the same request.
if (!isImprovementEnabled(state)) return;
+ // A PARK STOPS A REFILL (#3848). Park elapse used to be read only by the
+ // SCHEDULED lane, so a drain that parked itself (idle detector, no-progress,
+ // drain cap) could still be re-issued here on the very next completion — the
+ // park meant nothing on the one lane that does the re-dispatching, and the
+ // work-detector re-deciding was the only brake left. A human "Run Now" is
+ // unaffected: applyOnDemandRunResets clears the park first for a USER-origin
+ // request, and only a refill reaches this line with the park intact.
+ if (await taskScheduleMod.isPerpetualParkActive(plan.taskType, plan.appId)) {
+ emitLog('debug', `Perpetual refill for ${plan.taskType} skipped: parked until its recheck cadence`, { appId: plan.appId });
+ return;
+ }
// `origin: 'refill'` — this re-issue borrows the on-demand LANE but is not a
// human pressing Run, so the drain engines must leave the park, the
// convergence signature, and the dispatch counter intact. Without it the
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index eb09f342a5..bffd5a7da8 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1438,7 +1438,7 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
// drain stalls. Pin the ignoreTaskId thread so a refactor can't reintroduce it.
const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
expect(fnIdx, 'refillPerpetualForCompletedAgent must exist').toBeGreaterThan(-1);
- const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 3600);
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 4600);
expect(
/queueEligibleImprovementTasks\(\s*state\s*,\s*cosTaskData\s*,\s*\{\s*ignoreTaskId:\s*agent\?\.taskId\s*\}\s*\)/.test(fnSlice),
'refill must forward { ignoreTaskId: agent?.taskId } to queueEligibleImprovementTasks'
@@ -1456,7 +1456,7 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
// absence of a keyword in a comment (fragile): Improve gate → re-issue →
// return → (only then) the queue lane.
const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
- const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 3600);
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 4600);
expect(
fnSlice.includes('const plan = perpetualRefillPlan(agent, schedule)'),
'refill must resolve the lane via perpetualRefillPlan'
@@ -1499,13 +1499,30 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
).toBe(true);
});
+ it('an unexpired park stops the refill BEFORE it re-issues the drain (#3848)', () => {
+ // The invariant that was missing: park elapse was read only by the SCHEDULED
+ // lane, so a drain that had just parked itself (idle detector / no-progress /
+ // drain cap) was still re-issued on the very next completion — the park meant
+ // nothing on the one lane that does the re-dispatching. A human "Run Now" is
+ // unaffected: applyOnDemandRunResets clears the park for a USER-origin request
+ // before this lane is ever reached.
+ const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 4600);
+ const parkIdx = fnSlice.indexOf('isPerpetualParkActive(plan.taskType, plan.appId)');
+ const triggerIdx = fnSlice.indexOf('triggerOnDemandTask(plan.taskType, plan.appId');
+ expect(parkIdx, 'refill must consult the type+app park before re-issuing').toBeGreaterThan(-1);
+ expect(parkIdx).toBeLessThan(triggerIdx);
+ const returnAfterPark = fnSlice.indexOf('return;', parkIdx);
+ expect(returnAfterPark, 'a live park must return, not fall through to the re-issue').toBeLessThan(triggerIdx);
+ });
+
it('the refill only fires on a SUCCESSFUL completion (no back-to-back spin on failures)', () => {
// Perpetual completions skip the per-app cooldown, so refilling after a failed
// run would spin the daemon through repeated failures (the work-detector still
// sees the same issue as actionable). The refill must bail on a non-success
// result and let task-retry/backoff + the recheck cadence handle failures.
const fnIdx = COS_SRC.indexOf('async function refillPerpetualForCompletedAgent');
- const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 3600);
+ const fnSlice = COS_SRC.slice(fnIdx, fnIdx + 4600);
expect(
/if\s*\(\s*!agent\?\.result\?\.success\s*\)\s*return/.test(fnSlice),
'refill must early-return when the completed agent did not succeed'
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index ef4836a887..72ea8b8676 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2166,7 +2166,13 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
ignoreTaskId
});
if (detection.actionable) {
- await taskSchedule.clearPerpetualPark(taskType, app.id);
+ // 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 };
@@ -2189,11 +2195,47 @@ 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;
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: detection.reason, actionableCount: detection.count, counts });
+ // 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 });
emitLog('info', `Perpetual ${taskType} parked for ${app.name}: ${detection.reason}`, { appId: app.id });
return { skip: true };
}
+/**
+ * The ONE consecutive-dispatch cap for every perpetual drain, checked at the
+ * choke point all four spawn engines funnel through.
+ *
+ * Every perpetual drain re-issues itself the moment its run completes, so
+ * "keeps finding work" and "is stuck in a loop" look identical one cycle at a
+ * time. The bound is per type (`interval.drainDispatchCap`, from
+ * DEFAULT_TASK_INTERVALS) rather than global because the right number differs by
+ * an order of magnitude: the reconcile scans finish a handful of branches a day
+ * and cap at 5, while a healthy claim-issue drain should keep going all night —
+ * so an absent/null cap means UNBOUNDED and leaves that drain's behavior alone.
+ *
+ * Runs BEFORE the work detector and the reconcile scans, so a capped drain parks
+ * without paying for a `gh`/`git` scan it is going to discard. That also means the
+ * cap now preempts the reconcile gate's `no-progress` brake once the budget is
+ * spent; both are terminal parks on the same recheck cadence, so the only
+ * difference is which reason is recorded.
+ *
+ * @returns {Promise<{skip:boolean}>}
+ */
+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 };
+ 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 });
+ 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 };
+}
+
/**
* `, N <noun> (reason, reason)` for a park/dispatch log line — or `''` when the set
* is empty, so a caller can concatenate it unconditionally. The reconcile park log
@@ -2216,16 +2258,19 @@ const countSuffix = (items, noun, describe) => {
* Shared convergence gate for the reconcile perpetual drains (branch + issue).
* Both have the same shape — a deterministic scan produced a non-empty actionable
* set and now has to decide whether driving it AGAIN is progress or a loop — so
- * both get the same two brakes, in order:
+ * both get the same brake:
*
- * 1. `no-progress` — the set is byte-identical to the one the last dispatch was
- * handed, so another identical coordinator would do exactly what the last one
- * already failed to accomplish.
- * 2. `drain-cap` — the set keeps CHANGING but never empties. Brake 1 can't see
- * this: each cycle looks like honest progress. The cap bounds the drain
- * anyway, because "made some progress" is not a licence to run forever.
+ * `no-progress` — the set is byte-identical to the one the last dispatch was
+ * handed, so another identical coordinator would do exactly what the last one
+ * already failed to accomplish.
*
- * Either park clears the signature and the counter, so the next recheck starts a
+ * The second brake — `drain-cap`, for a set that keeps CHANGING but never empties,
+ * which this one cannot see because each cycle looks like honest progress — is NOT
+ * here: it lives in `applyPerpetualDrainCap` at the shared choke point, so every
+ * perpetual drain gets it rather than only these two (#3848). Having it in both
+ * places was two implementations of one rule.
+ *
+ * The park clears the signature and the counter, so the next recheck starts a
* clean window and nothing is dropped — the work is still there to be found.
*
* @param {object} taskSchedule - the taskSchedule module (injected, as the callers do)
@@ -2236,21 +2281,14 @@ const countSuffix = (items, noun, describe) => {
* @returns {Promise<boolean>} true to dispatch; false when the drain was parked
*/
export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { signature, actionableCount, label, unit }) {
- // Both brakes park in ONE write — the park fields, the cleared signature, and the
- // zeroed dispatch budget land together, so no terminal park can leave a stale
- // count behind for the next drain window to trip over.
- const parkAndStop = async (reason, detail) => {
- await taskSchedule.parkPerpetual(taskType, app.id, { reason, actionableCount, signature: null, dispatchCount: 0 });
- emitLog('info', `${label} parked for ${app.name}: ${detail}`, { appId: app.id });
- return false;
- };
-
- const { signature: lastSignature, dispatchCount } = await taskSchedule.getPerpetualDrainState(taskType, app.id);
+ const { signature: lastSignature } = await taskSchedule.getPerpetualDrainState(taskType, app.id);
if (signature === lastSignature) {
- return parkAndStop('no-progress', `${actionableCount} ${unit} unchanged since last run (no progress — will re-drive on next recheck)`);
- }
- if (dispatchCount >= taskSchedule.PERPETUAL_DRAIN_DISPATCH_CAP) {
- return parkAndStop('drain-cap', `${dispatchCount} consecutive dispatches with ${actionableCount} ${unit} still actionable — drain cap reached, will re-drive on next recheck`);
+ // 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 });
+ 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;
}
// Progress within budget — resume the drain, record the signature, and spend one
@@ -2672,6 +2710,12 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// gating, and the forge-specific author-filter directive below.
const promptTaskType = await resolveClaimWorkRouting(app, taskType, metadata, taskSchedule);
+ // Consecutive-dispatch cap for EVERY perpetual drain (#3848). First, because a
+ // capped drain must not pay for a work-detector probe or a reconcile git/gh scan
+ // it is only going to discard.
+ const drainCap = await applyPerpetualDrainCap(app, taskType, interval, taskSchedule);
+ if (drainCap.skip) return null;
+
// 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).
diff --git a/server/services/cosTaskGenerator.referenceWatch.test.js b/server/services/cosTaskGenerator.referenceWatch.test.js
index 5f08de7a46..48b15460bf 100644
--- a/server/services/cosTaskGenerator.referenceWatch.test.js
+++ b/server/services/cosTaskGenerator.referenceWatch.test.js
@@ -51,7 +51,6 @@ vi.mock('./taskSchedule.js', () => ({
// taskSchedule surface this suite sees — it has to track the real module's drain
// API or a future test here that reaches the reconcile gate gets
// "not a function" instead of a stub.
- PERPETUAL_DRAIN_DISPATCH_CAP: 5,
getPerpetualDrainState: vi.fn(async () => ({ signature: null, dispatchCount: 0 })),
recordPerpetualDispatch: vi.fn(async () => 1),
}));
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index ccfb3c4f4b..735cee3dab 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -35,8 +35,9 @@ vi.mock('./github.js', async (importActual) => ({
checkGhHealth: (...a) => ghHealth(...a),
}));
-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, recordPerpetualTransient, buildJiraTicketTask, buildImprovementDedupSets, normalizeWorkItemRef, buildTargetWorkItemBlock, resolveTaskInputHook, resolveReconcileDrainGate } from './cosTaskGenerator.js';
+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, recordPerpetualTransient, buildJiraTicketTask, buildImprovementDedupSets, normalizeWorkItemRef, buildTargetWorkItemBlock, resolveTaskInputHook, resolveReconcileDrainGate, applyPerpetualDrainCap } from './cosTaskGenerator.js';
import { cosEvents } from './cosEvents.js';
+import { DEFAULT_TASK_INTERVALS } from './taskSchedule.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -1132,15 +1133,16 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',
/**
* The perpetual reconcile drains (branch- and issue-reconcile) re-issue themselves
- * after every completed run, so their only brakes are the two this gate applies.
- * On 2026-08-12 both were missing in practice — the refill rode the on-demand lane,
- * which reset the convergence signature on every hop — and ~40 branch-reconcile
- * coordinators ran between 05:19 and 08:47 against the same two branches.
+ * after every completed run, so their brakes are all that stands between them and
+ * a runaway. On 2026-08-12 the signature brake was missing in practice — the refill
+ * rode the on-demand lane, which reset the convergence signature on every hop —
+ * and ~40 branch-reconcile coordinators ran between 05:19 and 08:47 against the
+ * same two branches. The consecutive-dispatch cap is NOT this gate's job any more
+ * (#3848): it moved to applyPerpetualDrainCap so every perpetual drain gets it.
*/
describe('resolveReconcileDrainGate', () => {
// Stand-in for the injected taskSchedule module.
- const fakeSchedule = ({ signature = null, dispatchCount = 0, cap = 5 } = {}) => ({
- PERPETUAL_DRAIN_DISPATCH_CAP: cap,
+ const fakeSchedule = ({ signature = null, dispatchCount = 0 } = {}) => ({
getPerpetualDrainState: vi.fn(async () => ({ signature, dispatchCount })),
parkPerpetual: vi.fn(async () => {}),
recordPerpetualDispatch: vi.fn(async () => dispatchCount + 1)
@@ -1151,7 +1153,7 @@ describe('resolveReconcileDrainGate', () => {
label: '🔀 branch-reconcile', unit: 'branch(es)', ...over
});
- it('dispatches when the set advanced and the budget is unspent', async () => {
+ it('dispatches when the set advanced', async () => {
const ts = fakeSchedule({ signature: 'a:NEEDS_PR:none|b:IN_REVIEW:5', dispatchCount: 2 });
expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx())).toBe(true);
expect(ts.parkPerpetual).not.toHaveBeenCalled();
@@ -1168,31 +1170,104 @@ describe('resolveReconcileDrainGate', () => {
expect(ts.recordPerpetualDispatch).not.toHaveBeenCalled();
});
- // The brake the no-progress guard cannot supply: every cycle looks like honest
- // progress, so only a hard budget ends it.
- it('parks drain-cap once the consecutive-dispatch budget is spent, even on real progress', async () => {
- const ts = fakeSchedule({ signature: 'stale-sig', dispatchCount: 5 });
- expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx({ actionableCount: 3 }))).toBe(false);
+ // Exactly one implementation of the cap survives, and it is not this one — an
+ // advanced set dispatches here no matter how much budget has been spent, because
+ // applyPerpetualDrainCap already ran (and returned) at the choke point.
+ it('no longer applies a dispatch cap of its own', async () => {
+ const ts = fakeSchedule({ signature: 'stale-sig', dispatchCount: 99 });
+ expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx({ actionableCount: 3 }))).toBe(true);
+ expect(ts.parkPerpetual).not.toHaveBeenCalled();
+ });
+});
+
+/**
+ * The ONE consecutive-dispatch cap, at the choke point every spawn engine funnels
+ * through. Per type so a bound that suits the reconcile scans (a handful of
+ * branches a day) cannot throttle a healthy claim-issue drain to five issues a
+ * window — the claim drains ship with no cap at all and stay unbounded (#3848).
+ */
+describe('applyPerpetualDrainCap', () => {
+ const fakeSchedule = (dispatchCount = 0) => ({
+ INTERVAL_TYPES: { PERPETUAL: 'perpetual' },
+ getPerpetualDrainState: vi.fn(async () => ({ signature: null, dispatchCount })),
+ parkPerpetual: vi.fn(async () => {})
+ });
+ 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 () => {
+ const ts = fakeSchedule(5);
+ expect(await applyPerpetualDrainCap(app, 'branch-reconcile', perpetual({ drainDispatchCap: 5 }), ts)).toEqual({ skip: true });
expect(ts.parkPerpetual).toHaveBeenCalledWith('branch-reconcile', 'app-1', {
- reason: 'drain-cap', actionableCount: 3, signature: null, dispatchCount: 0
+ reason: 'drain-cap', signature: null, dispatchCount: 0
});
- // Nothing recorded as dispatched, so the next recheck re-drives from scratch.
- expect(ts.recordPerpetualDispatch).not.toHaveBeenCalled();
});
it('spends exactly CAP dispatches before capping', async () => {
const outcomes = [];
for (let dispatchCount = 0; dispatchCount <= 5; dispatchCount += 1) {
- const ts = fakeSchedule({ signature: `sig-${dispatchCount}`, dispatchCount, cap: 5 });
- outcomes.push(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx()));
+ outcomes.push((await applyPerpetualDrainCap(app, 'branch-reconcile', perpetual({ drainDispatchCap: 5 }), fakeSchedule(dispatchCount))).skip);
+ }
+ expect(outcomes).toEqual([false, false, false, false, false, true]);
+ });
+
+ // 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']) {
+ const ts = fakeSchedule(500);
+ expect(await applyPerpetualDrainCap(app, 'claim-issue', perpetual({ drainDispatchCap }), ts)).toEqual({ skip: false });
+ expect(ts.parkPerpetual).not.toHaveBeenCalled();
+ // Unbounded types must not even pay for the state read.
+ expect(ts.getPerpetualDrainState).not.toHaveBeenCalled();
+ }
+ });
+
+ it('ignores non-perpetual intervals entirely', async () => {
+ const ts = fakeSchedule(500);
+ expect(await applyPerpetualDrainCap(app, 'branch-reconcile', { type: 'daily', drainDispatchCap: 5 }, ts)).toEqual({ skip: false });
+ expect(ts.getPerpetualDrainState).not.toHaveBeenCalled();
+ });
+});
+
+/**
+ * The cap is checked ONCE, at the single point all four spawn engines funnel
+ * through, and BEFORE the detectors/scans it would only discard the results of.
+ */
+describe('the drain cap has exactly one implementation, at the choke point', () => {
+ it('generateManagedAppImprovementTaskForType applies it ahead of the work gate and the reconcile scans', () => {
+ const start = GEN_SRC.indexOf('export async function generateManagedAppImprovementTaskForType');
+ const body = GEN_SRC.slice(start, GEN_SRC.indexOf('return task;', start));
+ const capIdx = body.indexOf('applyPerpetualDrainCap(app, taskType, interval, taskSchedule)');
+ expect(capIdx, 'the choke point must apply the per-type drain cap').toBeGreaterThan(-1);
+ expect(capIdx).toBeLessThan(body.indexOf('applyPerpetualWorkGate('));
+ expect(capIdx).toBeLessThan(body.indexOf('resolveBranchReconcileBlock('));
+ expect(capIdx).toBeLessThan(body.indexOf('resolveIssueReconcileBlock('));
+ });
+
+ it('no second cap implementation reads PERPETUAL_DRAIN_DISPATCH_CAP or re-parks drain-cap', () => {
+ // The reconcile gate used to carry its own copy; the constant now only names
+ // the DEFAULT_TASK_INTERVALS value for the two reconcile types.
+ expect(GEN_SRC).not.toContain('PERPETUAL_DRAIN_DISPATCH_CAP');
+ expect(GEN_SRC.match(/reason: 'drain-cap'/g) || []).toHaveLength(1);
+ });
+
+ it("the reconcile types ship a cap and the claim drains deliberately do not", () => {
+ for (const taskType of ['branch-reconcile', 'issue-reconcile']) {
+ expect(DEFAULT_TASK_INTERVALS[taskType].drainDispatchCap).toBe(5);
+ }
+ for (const taskType of ['claim-issue', 'claim-work', 'plan-task']) {
+ expect(DEFAULT_TASK_INTERVALS[taskType].drainDispatchCap).toBeUndefined();
}
- expect(outcomes).toEqual([true, true, true, true, true, false]);
});
- it('checks no-progress BEFORE the cap, so a stuck set parks with the accurate reason', async () => {
- const ts = fakeSchedule({ signature: 'a:NEEDS_PR:none', dispatchCount: 9 });
- await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx());
- expect(ts.parkPerpetual.mock.calls[0][2].reason).toBe('no-progress');
+ it('the work gate spends a dispatch on the actionable path and zeroes the budget when it parks', () => {
+ 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[^}]*\}\)/);
});
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 029681bd5c..2bbd4bd6b7 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -256,6 +256,38 @@ const NON_COMMITTING_COORDINATOR_METADATA = { useWorktree: false, openPR: false,
// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)
const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true, pipeline: { stages: [{ name: 'Codebase Review', promptKey: 'code-reviewer-review', readOnly: true, providerId: null, model: null, precondition: { fileNotExists: 'REVIEW.md' } }, { name: 'Triage & Implement', promptKey: 'code-reviewer-implement', readOnly: false, providerId: null, model: null, precondition: { fileExists: 'REVIEW.md' } }] } } };
+/**
+ * Default `drainDispatchCap` for the reconcile drains: how many times a perpetual
+ * drain may dispatch back-to-back before it is parked regardless of how much
+ * progress it reports.
+ *
+ * The `lastActionableSignature` guard stops the drain only when a full cycle
+ * changes NOTHING. It cannot stop a drain whose set keeps changing without ever
+ * emptying — a branch that oscillates between two states, a coordinator that opens
+ * a PR one run and closes it the next, a repo where new work arrives as fast as it
+ * is finished. Those are indistinguishable from healthy progress one cycle at a
+ * time, and on 2026-08-12 that shape ran ~40 coordinator agents between 05:19 and
+ * 08:47 against the same two branches. So progress buys more cycles, not unlimited
+ * ones: past the cap the drain parks until its recheck cadence, which is a delay,
+ * never a dropped item — the branches are still there and the next recheck sees
+ * them. Five is enough for a legitimately long drain (open PR → CI → merge →
+ * cleanup) to finish a couple of branches per window.
+ *
+ * The count is very nearly "consecutive dispatches": every terminal park and every
+ * manual re-run zero it. The one gap is a FAILED run — it neither refills nor
+ * parks, so its spent dispatches carry into the next scheduled window and that
+ * window caps early. It self-heals within one window (the next park zeroes it), and
+ * erring toward capping early is the safe direction for a runaway guard.
+ *
+ * Why the cap is PER TYPE (`drainDispatchCap`) and not one global number: five is
+ * ample for finishing branches (a handful per day) but would throttle a HEALTHY
+ * claim-issue drain to five issues per recheck window — a real regression for a
+ * drain the user relies on running productively overnight. So the claim drains
+ * ship without the key at all (absent/`null` ⇒ unbounded, their work-detector's
+ * idle park remains the only brake) and only the reconcile scans carry a number.
+ */
+export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;
+
export const DEFAULT_TASK_INTERVALS = {
'security': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
'code-quality': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },
@@ -283,7 +315,7 @@ export const DEFAULT_TASK_INTERVALS = {
// SIBLING worktrees, never in its own cwd — hence the shared non-committing
// -coordinator posture above. Off by default — enabling it is the user's
// explicit consent to let it drive PRs on a schedule.
- 'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true } },
+ 'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true } },
// issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with
// their PR already MERGED and no live claim anywhere — a partial ship left the
// claim marker on, so the queue (which skips `in-progress`) never re-picks the
@@ -299,7 +331,7 @@ export const DEFAULT_TASK_INTERVALS = {
// issue-state mutation is its whole deliverable — hence the shared
// non-committing-coordinator posture above. Off by default — enabling it is the
// user's explicit consent to let it mutate issue state on a schedule.
- 'issue-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, autoClose: true } },
+ 'issue-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 4 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, autoClose: true } },
'console-errors': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },
'dependency-updates': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
'documentation': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },
@@ -1103,6 +1135,22 @@ export async function getPerpetualParkInfo(taskType, appId = null) {
};
}
+/**
+ * Is this type+app parked with an UNEXPIRED `parkedUntil`?
+ *
+ * `getPerpetualParkInfo` reports the park record whether or not it has elapsed —
+ * an elapsed park is deliberately left on disk (it reads as "due right now"), so
+ * its mere presence is not a stop signal. This is the elapse-aware question, and
+ * it is what the completion refill asks before re-issuing a drain: a park means
+ * "stop draining until the recheck cadence", and until #3848 the refill lane
+ * never asked, so a park could not stop a refill hop.
+ */
+export async function isPerpetualParkActive(taskType, appId = null) {
+ const schedule = await loadSchedule();
+ const record = resolveExecutionRecord(schedule, taskType, appId);
+ return parkedUntilMs(record) > Date.now();
+}
+
/**
* A perpetual drain's convergence state, read in ONE pass: the actionable
* signature its last dispatch was handed, and how many times it has dispatched
@@ -1149,30 +1197,6 @@ export async function recordPerpetualDispatch(taskType, appId = null, signature)
return count;
}
-/**
- * How many times a perpetual drain may dispatch back-to-back before it is parked
- * regardless of how much progress it reports.
- *
- * The `lastActionableSignature` guard stops the drain only when a full cycle
- * changes NOTHING. It cannot stop a drain whose set keeps changing without ever
- * emptying — a branch that oscillates between two states, a coordinator that opens
- * a PR one run and closes it the next, a repo where new work arrives as fast as it
- * is finished. Those are indistinguishable from healthy progress one cycle at a
- * time, and on 2026-08-12 that shape ran ~40 coordinator agents between 05:19 and
- * 08:47 against the same two branches. So progress buys more cycles, not unlimited
- * ones: past the cap the drain parks until its recheck cadence, which is a delay,
- * never a dropped item — the branches are still there and the next recheck sees
- * them. Five is enough for a legitimately long drain (open PR → CI → merge →
- * cleanup) to finish a couple of branches per window.
- *
- * The count is very nearly "consecutive dispatches": every terminal park and every
- * manual re-run zero it. The one gap is a FAILED run — it neither refills nor
- * parks, so its spent dispatches carry into the next scheduled window and that
- * window caps early. It self-heals within one window (the next park zeroes it), and
- * erring toward capping early is the safe direction for a runaway guard.
- */
-export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;
-
/**
* Clear a perpetual task's park so the drain resumes (its work-detector found
* actionable work). No-op (and no write) when there's nothing parked.
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 01a092b378..fa97d16084 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -123,6 +123,7 @@ import {
clearPerpetualPark,
resetPerpetualForManualRun,
getPerpetualParkInfo,
+ isPerpetualParkActive,
getPerpetualDrainState,
recordPerpetualDispatch,
applyOnDemandRunResets,
@@ -1634,6 +1635,28 @@ describe('taskSchedule', () => {
expect(await getPerpetualParkInfo('claim-issue', 'unknown-app')).toBeNull()
})
+ // The elapse-aware question the completion refill asks (#3848). It must differ
+ // from getPerpetualParkInfo's "is there a park record": an ELAPSED park is
+ // deliberately left on disk (it reads as "due right now"), so treating its
+ // presence as a stop signal would wedge the drain until something cleared it.
+ it('isPerpetualParkActive is true only while parkedUntil is in the future', async () => {
+ const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ const past = new Date(Date.now() - 60 * 60 * 1000).toISOString()
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: {
+ 'app-parked': { lastRun: null, count: 0, parkedUntil: future },
+ 'app-elapsed': { lastRun: null, count: 0, parkedUntil: past },
+ 'app-unparked': { lastRun: null, count: 0 }
+ } } }
+ })
+ expect(await isPerpetualParkActive('claim-issue', 'app-parked')).toBe(true)
+ expect(await isPerpetualParkActive('claim-issue', 'app-elapsed')).toBe(false)
+ expect(await isPerpetualParkActive('claim-issue', 'app-unparked')).toBe(false)
+ expect(await isPerpetualParkActive('claim-issue', 'unknown-app')).toBe(false)
+ expect(await isPerpetualParkActive('unknown-type', 'app-parked')).toBe(false)
+ })
+
it('parkPerpetual omits parkCounts when no breakdown is provided', async () => {
mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })