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
stop branch-reconcile from re-dispatching itself all night when branches remain
[._.]/ Adam Eivy24c1c15d0c04
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 28c38ddae3..dacd6b83e7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,6 +6,10 @@## Fixed- Voice dictation into the Shell terminal no longer garbles what you said. Apple dictation streams progressively refined guesses and rewrites what it already typed ("determin" → "determine" → "determines"); the terminal forwarded every insertion but none of the matching deletions, so a dictated sentence arrived at the prompt as an accumulating pile-up ("ddedeterdetermindeterminedetermines if any code…"). Dictation edits are now translated into the deletions and insertions a terminal understands, so the prompt shows the sentence you dictated.+- The Branch & PR Reconciliation task no longer re-launches itself indefinitely when branches are left behind. Its drain re-issued itself through the same queue a human "Run Now" uses, and that queue's handler cleared the convergence state on every hop — so the "nothing changed, stop" brake was wiped before it could ever apply, and the task spawned roughly forty coordinator agents in one night against the same two branches. Automated re-issues now inherit that state, so an unchanged branch set parks after one cycle as designed.+- Branch reconciliation now leaves branches alone while their session is still running. A live agent's (or live `/claim`'s) branch with a clean worktree and an open PR was treated as work to finish, so the reconciler raced the running session's commits — and every push it made counted as "progress" that earned another reconciliation run. Those branches are now reported and skipped, and a reconcile whose only remaining branches are live is finished rather than retried.+- 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.- 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/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.jsindex e3daab95f2..723b09ac4c 100644--- a/client/src/hooks/useOnDemandTaskToast.js+++ b/client/src/hooks/useOnDemandTaskToast.js@@ -15,9 +15,11 @@ const PARK_REASON_LABELS = {'owner-is-org': 'the "owner" filter matches an org, which can\'t author issues — set it to "self" or "any"','owner-is-group': 'the "owner" filter matches a group, which can\'t author issues — set it to "self" or "any"','no-in-flight-branches': 'no branches in flight',+ 'branches-held-by-live-owners': 'the only branches left belong to sessions still running — nothing to finish','no-zombie-issues': 'no stale issues to reconcile','no-actionable-plan-items': 'no unblocked PLAN items','no-progress': 'already up to date',+ 'drain-cap': 'paused after several back-to-back runs — the rest waits for the next scheduled check','no-detector': 'no work detector for this task'};diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex d62303e2a9..64725a207c 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -109,14 +109,17 @@ const PR_LIST_LIMIT = 200;* CONFLICTED — open PR with merge conflicts → agent resolves* IN_REVIEW — open PR, otherwise → agent drives to merge* NEEDS_PR — pushed, not merged, no PR, clean → agent verifies + opens PR- * WIP — local-only or dirty worktree → skip + report (never touch)+ * WIP — local-only, dirty, or LIVE worktree → skip + report (never touch)*- * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, abandonedAgentWorktree?:boolean, openPr:({mergeable?:string}|null), prStateUnavailable?:boolean }} input+ * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, abandonedAgentWorktree?:boolean, liveWorktreeReason?:string|null, openPr:({mergeable?:string}|null), prStateUnavailable?:boolean }} input* `prStateUnavailable` means the forge could not be READ this cycle — distinct* from `openPr: null` ("the forge answered: no open PR").+ * `liveWorktreeReason` is `resolveLiveWorktreeReason`'s verdict for the branch's+ * worktree — non-null means somebody (an active CoS agent, a live human+ * `/claim`, a deliberate lock) is working in it right now.* @returns {'ABANDONED_WIP'|'MERGED'|'CONFLICTED'|'IN_REVIEW'|'NEEDS_PR'|'WIP'}*/-export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandonedAgentWorktree, openPr, prStateUnavailable = false }) {+export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandonedAgentWorktree, liveWorktreeReason = null, openPr, prStateUnavailable = false }) {// A dead agent's worktree that still holds uncommitted work is the ONE dirty// case that must be driven rather than skipped — and it must be caught BEFORE// the `isMerged` test, because an agent that exited without committing leaves@@ -128,6 +131,17 @@ export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandoned// indefinitely while every run logged "nothing in-flight".if (worktreeDirty && abandonedAgentWorktree) return 'ABANDONED_WIP';if (isMerged) return 'MERGED';+ // A branch checked out in a LIVE worktree belongs to whoever is working in it —+ // an active CoS agent, a live human `/claim`, or a worktree the user locked. Its+ // branch will keep moving (commits, a PR opened, a rebase) for as long as that+ // session runs, so handing it to the coordinator is wrong twice over: the agent+ // races the live session's git operations, and every push the live session makes+ // re-advances the drain's progress signature, which is exactly how the perpetual+ // drain came to re-dispatch itself dozens of times in one night. Clean or dirty,+ // PR or no PR: report it and never touch it. Checked AFTER `isMerged` on purpose+ // — a merged branch in a live worktree still belongs in the MERGED bucket, where+ // `cleanupMerged` applies the same protection and reports it as held back.+ if (liveWorktreeReason) return 'WIP';// A worktree with real uncommitted changes is NEVER handed to the coordinator// agent — even for a branch with an open PR. The agent's per-state actions// (rebase/resolve/merge) run git operations that could stash/reset/checkout@@ -229,7 +243,13 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,if (typeof ageMs === 'number' && ageMs >= staleClaimIdleMs) return null;return 'worktree-human-claim';}- if (activeAgentIds?.has(basename)) return 'worktree-active-agent';+ // `instanceof Set`, not a truthiness check: a caller that hands over a plain+ // ARRAY of ids (an easy mistake — `getActiveAgentIds()` itself returns one) would+ // otherwise throw `activeAgentIds.has is not a function` from inside a cleanup+ // pass. Same sentinel discipline as isAbandonedAgentWorktree; a non-Set means+ // liveness is unknown, which this gate answers "not protected" and+ // resolveLiveWorktreeReason then upgrades for agent worktrees.+ if (activeAgentIds instanceof Set && activeAgentIds.has(basename)) return 'worktree-active-agent';return null;}@@ -262,6 +282,30 @@ export function isAbandonedAgentWorktree({ path, locked, activeAgentIds }) {return !activeAgentIds.has(basename);}+/**+ * Why this worktree must be left ALONE this cycle — the dispatch-side counterpart+ * to `worktreeProtectionReason`'s teardown gate, with one extra case it doesn't+ * need: liveness we could not determine.+ *+ * `worktreeProtectionReason` is only ever called with an authoritative+ * `activeAgentIds` Set (cleanupMerged defaults it to an empty one), so a missing+ * Set reads there as "no agents running" and returns null. For the classifier that+ * default is backwards: an `agent-*` worktree whose owner's liveness is UNKNOWN+ * must be presumed live, exactly as `isAbandonedAgentWorktree` presumes it. Fail+ * safe toward not-touching, never toward "nobody's home".+ *+ * @param {{ path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null }} input+ * @returns {string|null} a stable reason slug, or null when the worktree is free+ */+export function resolveLiveWorktreeReason({ path, locked, activeAgentIds, ageMs }) {+ if (!path) return null;+ const reason = worktreeProtectionReason({ path, locked, activeAgentIds, ageMs });+ if (reason) return reason;+ const basename = path.split('/').pop() || '';+ if (basename.startsWith('agent-') && !(activeAgentIds instanceof Set)) return 'worktree-agent-liveness-unknown';+ return null;+}+/*** A worktree's real (non-lockfile) uncommitted paths, or [] when clean/unreadable.* @param {string} worktreePath@@ -601,6 +645,14 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIdworktreeAgeMs: worktreeAge,worktreeDirty,dirtyPaths,+ // Non-null ⇒ somebody is working in this worktree right now (active CoS+ // agent / live human claim / locked). Same predicate `cleanupMerged` uses to+ // refuse a teardown, reused by the classifier to refuse a DISPATCH — the two+ // must agree, or the reconciler protects a worktree from deletion and then+ // hands its branch to an agent that rebases underneath the live session.+ liveWorktreeReason: resolveLiveWorktreeReason({+ path: worktreePath, locked: worktreeLocked, activeAgentIds, ageMs: worktreeAge+ }),behind: divergence.behind,ahead: divergence.ahead,collisionPaths: divergence.collisionPaths,@@ -679,7 +731,9 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge* branches left on `origin` that nothing local points at; off, they are only* reported — see `reapOrphanedRemotes`. `activeAgentIds` protects in-use CoS* agent worktrees.- * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], orphanRemotes:{reaped:string[],reported:object[]}, forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}+ * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], heldLive:object[], skipped:{branch:string,reason:string}[], orphanRemotes:{reaped:string[],reported:object[]}, forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}+ * `heldLive` is the `wip` subset held because a live agent/claim/lock owns the+ * branch's worktree — the "leave it alone, this reconcile IS done" case.* `forgeUnavailable: true` means the cycle was SKIPPED before it started because* the `gh` probe failed; `prStateUnavailable: true` means it ran but a gh read* failed mid-cycle. Either way an empty `inFlight` says nothing about the repo@@ -700,7 +754,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRemif (githubRepoSpec(origin)) {const forge = await ensureForgeReachable('branch-reconcile', { hostname: githubApiHost(origin.host) });if (!forge.ok) {- return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };+ return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], heldLive: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };}}@@ -725,6 +779,12 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem// out of the actionable set on a cached verdict that still verifies (#3842).const { actionable: inFlight, superseded } = await applySupersededLedger(repoPath, allInFlight, defaultBranch);const wip = classified.filter((c) => c.state === 'WIP');+ // The subset of `wip` that is WIP because somebody is working in it RIGHT NOW.+ // Split out so the caller can say "the only branches left belong to running+ // agents" — a finished reconcile, not a mysteriously quiet one. Without this the+ // hold is indistinguishable from "no branches at all" in the park log, which is+ // the same invisibility that once hid abandoned worktrees behind "cleaned 0".+ const heldLive = wip.filter((c) => c.liveWorktreeReason);const { cleaned, skipped } = cleanup? await cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds })@@ -742,7 +802,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem? await reapOrphanedRemotes(repoPath, defaultBranch, { reap: reapRemotes }): { reaped: [], reported: [] };- return { defaultBranch, cleaned, inFlight, superseded, wip, skipped, orphanRemotes, prStateUnavailable };+ return { defaultBranch, cleaned, inFlight, superseded, wip, heldLive, skipped, orphanRemotes, prStateUnavailable };}/**@@ -956,12 +1016,21 @@ export function desiredEndState(state, actions, { prNumber, worktreePath, collis* blocked on human review / red CI) produces an identical signature, which the* generator treats as "no progress → park" instead of re-dispatching an* identical coordinator back-to-back. Order-independent (sorted).+ *+ * Deliberately does NOT include `openPr.mergeable`. GitHub computes mergeability+ * asynchronously and answers `UNKNOWN` until it lands, so that field flaps+ * UNKNOWN → MERGEABLE → UNKNOWN across consecutive reads of a completely static+ * PR — which this guard would read as PROGRESS and re-dispatch on forever. It also+ * carries no information the signature loses: `CONFLICTING` is what makes+ * `classifyBranch` return CONFLICTED, so every real mergeability transition+ * already shows up in `state`.+ ** @param {object[]} actionable - post-filterActionable branches* @returns {string}*/export function actionableSignature(actionable) {return actionable- .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}:${b.openPr?.mergeable ?? 'none'}`)+ .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}`).sort().join('|');}diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 59ddb8ae62..e91cc7a8b4 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -58,7 +58,7 @@ vi.mock('../lib/fileUtils.js', () => ({import {classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,- isAbandonedAgentWorktree, gatherDivergence,+ isAbandonedAgentWorktree, resolveLiveWorktreeReason, gatherDivergence,actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,branchPriorityRank, prioritizeBranches,upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes@@ -104,6 +104,27 @@ describe('classifyBranch', () => {expect(classifyBranch({ isMerged: false, openPr: { mergeable: 'MERGEABLE' }, hasUpstream: true, worktreeDirty: true })).toBe('WIP');expect(classifyBranch({ isMerged: false, openPr: { mergeable: 'CONFLICTING' }, hasUpstream: true, worktreeDirty: true })).toBe('WIP');});+ // A branch somebody is working in right now keeps moving on its own; dispatching+ // an agent onto it both races the live session and re-advances the drain's+ // progress signature every cycle (the overnight re-dispatch loop).+ it('clean worktree of a LIVE owner → WIP, even with an open PR', () => {+ const live = { isMerged: false, hasUpstream: true, worktreeDirty: false, liveWorktreeReason: 'worktree-active-agent' };+ expect(classifyBranch({ ...live, openPr: { mergeable: 'MERGEABLE' } })).toBe('WIP');+ expect(classifyBranch({ ...live, openPr: { mergeable: 'CONFLICTING' } })).toBe('WIP');+ expect(classifyBranch({ ...live, openPr: null })).toBe('WIP');+ });+ it('a live worktree does NOT hide a merged branch from cleanup (MERGED still wins)', () => {+ expect(classifyBranch({+ isMerged: true, hasUpstream: true, worktreeDirty: false,+ liveWorktreeReason: 'worktree-active-agent', openPr: null+ })).toBe('MERGED');+ });+ it('an ABANDONED agent worktree is still driven (its owner is not live)', () => {+ expect(classifyBranch({+ isMerged: false, hasUpstream: true, worktreeDirty: true, abandonedAgentWorktree: true,+ liveWorktreeReason: null, openPr: null+ })).toBe('ABANDONED_WIP');+ });it('local-only (no upstream), no PR → WIP', () => {expect(classifyBranch({ isMerged: false, openPr: null, hasUpstream: false, worktreeDirty: false })).toBe('WIP');});@@ -333,6 +354,35 @@ describe('isAbandonedAgentWorktree', () => {});});+describe('resolveLiveWorktreeReason', () => {+ const live = new Set(['agent-aaaaaaaa']);++ it('reports the same reasons the teardown gate refuses on', () => {+ expect(resolveLiveWorktreeReason({ path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe('worktree-active-agent');+ expect(resolveLiveWorktreeReason({ path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe('worktree-locked');+ expect(resolveLiveWorktreeReason({ path: '/wt/claim-fix-thing', activeAgentIds: live })).toBe('worktree-human-claim');+ });++ it('is null for a free worktree, a dead agent, and no worktree at all', () => {+ expect(resolveLiveWorktreeReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: live })).toBeNull();+ expect(resolveLiveWorktreeReason({ path: '/wt/next-issue-42', activeAgentIds: live })).toBeNull();+ expect(resolveLiveWorktreeReason({ path: null, activeAgentIds: live })).toBeNull();+ });++ // The one case worktreeProtectionReason can't answer: it is only ever called with+ // an authoritative Set, so a missing one reads there as "nobody is running". For a+ // DISPATCH decision that default is backwards — presume live, like+ // isAbandonedAgentWorktree does.+ it('presumes an agent worktree is live when liveness is UNKNOWN', () => {+ expect(resolveLiveWorktreeReason({ path: '/wt/agent-bbbbbbbb' })).toBe('worktree-agent-liveness-unknown');+ expect(resolveLiveWorktreeReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: ['agent-cccccccc'] })).toBe('worktree-agent-liveness-unknown');+ // …but an authoritative empty Set really does mean nothing is running.+ expect(resolveLiveWorktreeReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: new Set() })).toBeNull();+ // and a non-agent worktree is nobody's live session either way.+ expect(resolveLiveWorktreeReason({ path: '/wt/next-issue-42' })).toBeNull();+ });+});+describe('gatherDivergence', () => {// Drives execGit by subcommand so each probe can be answered independently.const mockGit = ({ counts = '3\t2', mergeBase = 'base1', defaultChanged = '', branchChanged = '' } = {}) => {@@ -578,6 +628,35 @@ describe('reconcile', () => {expect(res.wip.map((i) => i.branch)).toEqual(['wip-local']);});+ // The overnight re-dispatch loop's other half: a RUNNING agent's branch, clean+ // and with an open PR, classified IN_REVIEW and was handed to the coordinator —+ // which then raced the live session's pushes, each of which re-advanced the+ // drain's progress signature. It belongs in heldLive, not inFlight.+ it('holds a LIVE agent\'s branch out of the in-flight set even with an open PR', async () => {+ git.getBranches.mockResolvedValue([+ { name: 'cos/task-y/agent-live1234', isDefault: false, current: false, tracking: 'origin/cos/task-y/agent-live1234', merged: false }+ ]);+ wt.listWorktrees.mockResolvedValue([+ { path: '/repo/data/cos/worktrees/agent-live1234', branch: 'refs/heads/cos/task-y/agent-live1234' }+ ]);+ git.isBranchMergedInto.mockResolvedValue(false);+ execGh.mockResolvedValue(JSON.stringify([+ { number: 4001, headRefName: 'cos/task-y/agent-live1234', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }+ ]));+ // Clean worktree — the agent has committed and pushed but is still running.+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 });++ const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-live1234']) });+ expect(res.inFlight).toEqual([]);+ expect(res.heldLive.map((b) => [b.branch, b.liveWorktreeReason]))+ .toEqual([['cos/task-y/agent-live1234', 'worktree-active-agent']]);+ // …and the SAME repo with that agent gone is actionable again, so the hold is+ // the liveness answer and not an unconditional "cos branches are off-limits".+ const after = await reconcile('/repo', { activeAgentIds: new Set() });+ expect(after.inFlight.map((i) => i.state)).toEqual(['IN_REVIEW']);+ expect(after.heldLive).toEqual([]);+ });+// Regression for the "3 orphan cos branches, no active agents, reconcile says// nothing in flight" report: surface the branch instead of silently skipping it,// and — critically — do NOT delete the worktree holding the only copy of the work.@@ -935,10 +1014,22 @@ describe('actionableSignature', () => {expect(actionableSignature(two)).not.toBe(actionableSignature(one));});- it('changes when an IN_REVIEW PR becomes mergeable (readiness advanced within the same state)', () => {+ // GitHub computes mergeability asynchronously and answers UNKNOWN until it+ // lands, so this field flaps across consecutive reads of a completely static PR.+ // Counting that as progress is what let the drain re-dispatch ~40 coordinators in+ // one night against two unchanged branches, so `mergeable` is deliberately OUT of+ // the signature. Nothing is lost: CONFLICTING is what makes classifyBranch return+ // CONFLICTED, so every real mergeability transition still shows up in `state`.+ it('ignores openPr.mergeable — GitHub flaps UNKNOWN → MERGEABLE with no real change', () => {const unknown = [{ branch: 'a', state: 'IN_REVIEW', openPr: { number: 3, mergeable: 'UNKNOWN' } }];const mergeable = [{ branch: 'a', state: 'IN_REVIEW', openPr: { number: 3, mergeable: 'MERGEABLE' } }];- expect(actionableSignature(unknown)).not.toBe(actionableSignature(mergeable));+ expect(actionableSignature(unknown)).toBe(actionableSignature(mergeable));+ });++ it('still changes when mergeability turns into a real state change (IN_REVIEW → CONFLICTED)', () => {+ const review = [{ branch: 'a', state: 'IN_REVIEW', openPr: { number: 3, mergeable: 'MERGEABLE' } }];+ const conflicted = [{ branch: 'a', state: 'CONFLICTED', openPr: { number: 3, mergeable: 'CONFLICTING' } }];+ expect(actionableSignature(review)).not.toBe(actionableSignature(conflicted));});it('empty set yields an empty signature', () => {diff --git a/server/services/cos.js b/server/services/cos.jsindex 3b97f9a217..12a4e8d38d 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -881,18 +881,26 @@ async function spawnDequeuePriority0OnDemand(ctx) {await taskScheduleMod.clearOnDemandRequest(request.id);+ // A HUMAN "Run" clears the drain's brakes; an automated refill re-issue must+ // not (see ON_DEMAND_ORIGINS). Requests written before `origin` existed have+ // none and read as user-initiated, which is the safe default for a queue that+ // is almost always human-filled.+ const userInitiated = !taskScheduleMod.isRefillRequest(request);+if (targetApp) {- emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${userInitiated ? '' : ' (drain refill)'}`, { requestId: request.id, appId: targetApp.id });// A user-initiated "Run" must re-check live state, never honor a stale// park or convergence signature — resetting both up front guarantees the// detector/reconcile below runs fresh and dispatches on live state (and,// if still idle, re-stamps a park reflecting THIS check).- await taskScheduleMod.resetPerpetualForManualRun(request.taskType, targetApp.id);+ if (userInitiated) await taskScheduleMod.resetPerpetualForManualRun(request.taskType, targetApp.id);// A manual "Run" also unparks a failure-parked type (#2616) — clear this// app's consecutive-failure ledger. (Mirrors the sibling// spawnPriority0OnDemand engine in cosTaskGenerator.js; either engine may- // drain a given on-demand request, so both must unpark.)- await taskScheduleMod.clearTaskTypeFailurePark(request.taskType, targetApp.id);+ // drain a given on-demand request, so both must unpark.) A refill is not an+ // "I've addressed it" signal from anybody, so it leaves the ledger alone —+ // otherwise a drain that fails every run resets its own failure park forever.+ if (userInitiated) await taskScheduleMod.clearTaskTypeFailurePark(request.taskType, targetApp.id);// Advance the cooldown eagerly (deduped per app per cycle), but defer// binding the active agent until a task is produced — a null result// here must not strand `activeAgentId` (issue #978).@@ -906,11 +914,12 @@ async function spawnDequeuePriority0OnDemand(ctx) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);}} else {- emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });- // Same fresh-check guarantee as the app-scoped branch above.- await taskScheduleMod.resetPerpetualForManualRun(request.taskType);+ emitLog('info', `Processing on-demand improvement: ${request.taskType}${userInitiated ? '' : ' (drain refill)'}`, { requestId: request.id });+ // Same fresh-check guarantee as the app-scoped branch above — and the same+ // refill exemption.+ if (userInitiated) await taskScheduleMod.resetPerpetualForManualRun(request.taskType);// Manual re-run unparks a failure-parked type (global scope) — #2616.- await taskScheduleMod.clearTaskTypeFailurePark(request.taskType);+ if (userInitiated) await taskScheduleMod.clearTaskTypeFailurePark(request.taskType);await taskScheduleMod.recordExecution(`task:${request.taskType}`);await withStateLock(async () => {const s = await loadState();@@ -1347,7 +1356,14 @@ 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;- await taskScheduleMod.triggerOnDemandTask(plan.taskType, plan.appId, { emit: false });+ // `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+ // refill wipes its own convergence state on every hop and the drain never+ // parks while one actionable item remains.+ await taskScheduleMod.triggerOnDemandTask(plan.taskType, plan.appId, {+ emit: false, origin: taskScheduleMod.ON_DEMAND_ORIGINS.REFILL+ });return;}diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex e97ff41c75..eb09f342a5 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -1464,10 +1464,14 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {expect(/plan\.lane === 'onDemand'/.test(fnSlice), 'refill must branch on the on-demand lane').toBe(true);const improveGateIdx = fnSlice.indexOf('if (!isImprovementEnabled(state)) return;');- const triggerIdx = fnSlice.indexOf('triggerOnDemandTask(plan.taskType, plan.appId, { emit: false })');+ // `emit: false` avoids a redundant second dequeue; `origin: REFILL` marks the+ // re-issue as automated so the on-demand engines do NOT clear the drain's park /+ // convergence signature / dispatch counter on its behalf.+ const triggerMatch = /triggerOnDemandTask\(plan\.taskType, plan\.appId, \{\s*emit: false, origin: taskScheduleMod\.ON_DEMAND_ORIGINS\.REFILL\s*\}\)/.exec(fnSlice);+ const triggerIdx = triggerMatch ? triggerMatch.index : -1;const queueIdx = fnSlice.indexOf('queueEligibleImprovementTasks(state, cosTaskData');expect(improveGateIdx, 'manual lane must gate on isImprovementEnabled').toBeGreaterThan(-1);- expect(triggerIdx, 'manual lane must re-issue via triggerOnDemandTask(plan.taskType, plan.appId, { emit: false }) — emit:false avoids a redundant second dequeue').toBeGreaterThan(-1);+ expect(triggerIdx, 'manual lane must re-issue via triggerOnDemandTask(plan.taskType, plan.appId, { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })').toBeGreaterThan(-1);expect(queueIdx, 'scheduled queue lane must still exist').toBeGreaterThan(-1);// Improve gate precedes the re-issue; the manual lane returns before the queue lane.expect(improveGateIdx).toBeLessThan(triggerIdx);@@ -1484,7 +1488,7 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {// engine's addTask must forward the dequeue's ignoreTaskId.const engIdx = COS_SRC.indexOf('async function spawnDequeuePriority0OnDemand');expect(engIdx, 'spawnDequeuePriority0OnDemand must exist').toBeGreaterThan(-1);- const engSlice = COS_SRC.slice(engIdx, engIdx + 5600);+ const engSlice = COS_SRC.slice(engIdx, engIdx + 6400);expect(/onDemand:\s*true/.test(engSlice),'on-demand engine must stamp metadata.onDemand: true before addTask'diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 3ef87e0e66..2af6c8e23b 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -870,16 +870,22 @@ async function spawnPriority0OnDemand(ctx) {await taskSchedule.clearOnDemandRequest(request.id);+ // Mirrors cos.dequeueNextTask: only a human "Run" may clear the drain's+ // brakes. An automated drain refill (origin: 'refill') rides the same queue+ // and must inherit the live park / signature / dispatch count.+ const userInitiated = !taskSchedule.isRefillRequest(request);+if (targetApp) {- emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}`, { requestId: request.id, appId: targetApp.id });+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${userInitiated ? '' : ' (drain refill)'}`, { requestId: request.id, appId: targetApp.id });// A user-initiated "Run" must re-check live state — reset any park + the// reconcile convergence signature so the detector below runs fresh (see// cos.dequeueNextTask for the full rationale).- await taskSchedule.resetPerpetualForManualRun(request.taskType, targetApp.id);+ if (userInitiated) await taskSchedule.resetPerpetualForManualRun(request.taskType, targetApp.id);// A manual "Run" also unparks a failure-parked type (#2616): the user// explicitly re-running is an "I've addressed it" signal, so clear the- // per-type consecutive-failure ledger for this app.- await taskSchedule.clearTaskTypeFailurePark(request.taskType, targetApp.id);+ // per-type consecutive-failure ledger for this app. A refill carries no+ // such signal and leaves the ledger alone.+ if (userInitiated) await taskSchedule.clearTaskTypeFailurePark(request.taskType, targetApp.id);// Advance the cooldown eagerly (deduped per app per cycle), but defer// binding the active agent until a task is produced — a null result// here must not strand `activeAgentId` (issue #978).@@ -893,10 +899,10 @@ async function spawnPriority0OnDemand(ctx) {await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);}} else {- emitLog('info', `Processing on-demand improvement: ${request.taskType}`, { requestId: request.id });- await taskSchedule.resetPerpetualForManualRun(request.taskType);+ emitLog('info', `Processing on-demand improvement: ${request.taskType}${userInitiated ? '' : ' (drain refill)'}`, { requestId: request.id });+ if (userInitiated) await taskSchedule.resetPerpetualForManualRun(request.taskType);// Manual re-run unparks a failure-parked type (global scope) — #2616.- await taskSchedule.clearTaskTypeFailurePark(request.taskType);+ if (userInitiated) await taskSchedule.clearTaskTypeFailurePark(request.taskType);await taskSchedule.recordExecution(`task:${request.taskType}`);await withStateLock(async () => {const s = await loadState();@@ -2197,6 +2203,55 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, ireturn { skip: true };}+/**+ * 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:+ *+ * 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.+ *+ * Either 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)+ * @param {string} taskType+ * @param {string} appId+ * @param {{ signature:string, actionableCount:number, label:string, unit:string, appName:string }} ctx+ * `label` prefixes the log lines (emoji + type); `unit` names the items ("branch(es)").+ * @returns {Promise<{ dispatch:boolean }>}+ */+export async function resolveReconcileDrainGate(taskSchedule, taskType, appId, { signature, actionableCount, label, unit, appName }) {+ const parkAndStop = async (reason, detail) => {+ await taskSchedule.parkPerpetual(taskType, appId, { reason, actionableCount, signature: null });+ await taskSchedule.resetPerpetualDispatchCount(taskType, appId);+ emitLog('info', `${label} parked for ${appName}: ${detail}`, { appId });+ return { dispatch: false };+ };++ const lastSignature = await taskSchedule.getPerpetualSignature(taskType, appId);+ if (signature === lastSignature) {+ return parkAndStop('no-progress', `${actionableCount} ${unit} unchanged since last run (no progress — will re-drive on next recheck)`);+ }++ const dispatches = await taskSchedule.getPerpetualDispatchCount(taskType, appId);+ if (dispatches >= taskSchedule.PERPETUAL_DRAIN_DISPATCH_CAP) {+ return parkAndStop('drain-cap', `${dispatches} consecutive dispatches with ${actionableCount} ${unit} still actionable — drain cap reached, will re-drive on next recheck`);+ }++ // Progress within budget — resume the drain, record the signature, count the+ // dispatch, and skip the post-completion cooldown so it drains back-to-back.+ await taskSchedule.clearPerpetualPark(taskType, appId);+ await taskSchedule.setPerpetualSignature(taskType, appId, signature);+ await taskSchedule.bumpPerpetualDispatchCount(taskType, appId);+ return { dispatch: true };+}+/*** branch-reconcile deterministic pre-step: run the peer-safe reconcile on the* app's repo (remove fully-merged orphaned local branches + worktrees, classify@@ -2258,11 +2313,22 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskScheduleconst supersededSuffix = supersededCount? `, ${supersededCount} branch(es) already verified superseded and awaiting human reap`: '';+ // Branches somebody is actively working in (a running CoS agent, a live human+ // /claim, a locked worktree) are classified WIP and never reach `inFlight` — the+ // reconcile is DONE when they are all that's left, not stuck. Named in the park+ // log so "nothing actionable" doesn't read as "no branches exist".+ const heldLive = result.heldLive || [];+ const heldLiveSuffix = heldLive.length+ ? `, ${heldLive.length} branch(es) left to their live owners (${[...new Set(heldLive.map((b) => b.liveWorktreeReason))].join(', ')})`+ : '';const actionable = filterActionable(result.inFlight, actions);if (actionable.length === 0) {- // Definitive idle: nothing in-flight to drive. Park on the recheck cadence- // and clear the progress signature so a fresh set later dispatches.- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-in-flight-branches', actionableCount: 0, signature: null });+ // Definitive idle: nothing in-flight to drive. Park on the recheck cadence,+ // clear the progress signature so a fresh set later dispatches, and zero the+ // dispatch counter — this drain converged, so the next one gets a full budget.+ const reason = heldLive.length ? 'branches-held-by-live-owners' : 'no-in-flight-branches';+ await taskSchedule.parkPerpetual(taskType, app.id, { reason, actionableCount: 0, signature: null });+ await taskSchedule.resetPerpetualDispatchCount(taskType, app.id);// Surface merged branches held back by a protection guard so a lingering// worktree isn't an invisible "cleaned 0".const heldBack = (result.skipped || []).filter((s) => s.reason?.startsWith('worktree-'));@@ -2277,30 +2343,26 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskScheduleconst gatedSuffix = gatedOff? `, ${gatedOff} in-flight branch(es) skipped by disabled action toggles (${[...new Set(result.inFlight.map((b) => b.state))].join(', ')})`: '';- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing actionable (cleaned ${result.cleaned.length}${heldSuffix}${gatedSuffix}${supersededSuffix})`, { appId: app.id });- return { skip: true };- }- // Convergence guard — kills the back-to-back re-dispatch loop WITHOUT stalling- // slow PRs. Signature UNCHANGED → park + CLEAR the signature so the next- // recheck re-drives; CHANGED → progress, keep draining.- const signature = actionableSignature(actionable);- const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);- if (signature === lastSignature) {- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: actionable.length, signature: null });- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: ${actionable.length} branch(es) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing actionable (cleaned ${result.cleaned.length}${heldSuffix}${gatedSuffix}${heldLiveSuffix}${supersededSuffix})`, { appId: app.id });return { skip: true };}- // New or advanced actionable set — drive it. Resume the drain, record the- // signature, skip the post-completion cooldown so progress drains back-to-back.- await taskSchedule.clearPerpetualPark(taskType, app.id);- await taskSchedule.setPerpetualSignature(taskType, app.id, signature);+ // Convergence guards — no-progress, then the consecutive-dispatch cap. See+ // resolveReconcileDrainGate for why one brake isn't enough.+ const gate = await resolveReconcileDrainGate(taskSchedule, taskType, app.id, {+ signature: actionableSignature(actionable),+ actionableCount: actionable.length,+ label: '🔀 branch-reconcile',+ unit: 'branch(es)',+ appName: app.name+ });+ if (!gate.dispatch) return { skip: true };metadata.perpetual = true;const supersededBlock = formatSupersededForPrompt(result.superseded || []);const block = [formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions }),supersededBlock].filter(Boolean).join('\n');- emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)${supersededSuffix}`, { appId: app.id, analysisType: taskType });+ emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)${heldLiveSuffix}${supersededSuffix}`, { appId: app.id, analysisType: taskType });return { skip: false, block };}@@ -2339,19 +2401,19 @@ async function resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule)}if (result.zombies.length === 0) {await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null });+ await taskSchedule.resetPerpetualDispatchCount(taskType, app.id);emitLog('info', `🧟 issue-reconcile parked for ${app.name}: no zombie issues`, { appId: app.id });return { skip: true };}- // Convergence guard — identical to branch-reconcile's.- const signature = zombieSignature(result.zombies);- const lastSignature = await taskSchedule.getPerpetualSignature(taskType, app.id);- if (signature === lastSignature) {- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-progress', actionableCount: result.zombies.length, signature: null });- emitLog('info', `🧟 issue-reconcile parked for ${app.name}: ${result.zombies.length} zombie issue(s) unchanged since last run (no progress — will re-drive on next recheck)`, { appId: app.id });- return { skip: true };- }- await taskSchedule.clearPerpetualPark(taskType, app.id);- await taskSchedule.setPerpetualSignature(taskType, app.id, signature);+ // Convergence guards — identical to branch-reconcile's (shared helper).+ const gate = await resolveReconcileDrainGate(taskSchedule, taskType, app.id, {+ signature: zombieSignature(result.zombies),+ actionableCount: result.zombies.length,+ label: '🧟 issue-reconcile',+ unit: 'zombie issue(s)',+ appName: app.name+ });+ if (!gate.dispatch) return { skip: true };metadata.perpetual = true;const block = formatZombiesForPrompt(result.zombies, {fullName: result.fullName, forge: result.forge, autoClose,diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 901ef3ee10..df2e09f5fb 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -35,7 +35,7 @@ vi.mock('./github.js', async (importActual) => ({checkGhHealth: (...a) => ghHealth(...a),}));-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, recordPerpetualTransient, buildJiraTicketTask, buildImprovementDedupSets, normalizeWorkItemRef, buildTargetWorkItemBlock, resolveTaskInputHook } from './cosTaskGenerator.js';+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitOnDemandEmpty, recordPerpetualTransient, buildJiraTicketTask, buildImprovementDedupSets, normalizeWorkItemRef, buildTargetWorkItemBlock, resolveTaskInputHook, resolveReconcileDrainGate } from './cosTaskGenerator.js';import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';@@ -1129,3 +1129,103 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',expect(COS_SRC).toContain('generateIdleReviewTask(state, { ignoreTaskId })');});});++/**+ * 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.+ */+describe('resolveReconcileDrainGate', () => {+ // Minimal stand-in for the injected taskSchedule module, with a mutable record.+ const fakeSchedule = ({ signature = null, dispatches = 0, cap = 5 } = {}) => {+ const calls = { parked: [], resets: 0, bumps: 0, cleared: 0, signatures: [] };+ return {+ calls,+ PERPETUAL_DRAIN_DISPATCH_CAP: cap,+ getPerpetualSignature: async () => signature,+ getPerpetualDispatchCount: async () => dispatches,+ parkPerpetual: async (_t, _a, opts) => { calls.parked.push(opts); },+ resetPerpetualDispatchCount: async () => { calls.resets += 1; },+ bumpPerpetualDispatchCount: async () => { calls.bumps += 1; },+ clearPerpetualPark: async () => { calls.cleared += 1; },+ setPerpetualSignature: async (_t, _a, sig) => { calls.signatures.push(sig); }+ };+ };+ const ctx = (over = {}) => ({+ signature: 'a:NEEDS_PR:none', actionableCount: 1,+ label: '🔀 branch-reconcile', unit: 'branch(es)', appName: 'App One', ...over+ });++ it('dispatches when the set advanced and the budget is unspent', async () => {+ const ts = fakeSchedule({ signature: 'a:NEEDS_PR:none|b:IN_REVIEW:5', dispatches: 2 });+ expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', 'app-1', ctx())).toEqual({ dispatch: true });+ expect(ts.calls.parked).toEqual([]);+ expect(ts.calls.signatures).toEqual(['a:NEEDS_PR:none']);+ expect(ts.calls.bumps).toBe(1);+ expect(ts.calls.cleared).toBe(1);+ });++ it('parks no-progress on an unchanged set, clearing signature + counter', async () => {+ const ts = fakeSchedule({ signature: 'a:NEEDS_PR:none', dispatches: 1 });+ expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', 'app-1', ctx())).toEqual({ dispatch: false });+ expect(ts.calls.parked).toEqual([{ reason: 'no-progress', actionableCount: 1, signature: null }]);+ expect(ts.calls.resets).toBe(1);+ expect(ts.calls.bumps).toBe(0);+ });++ // 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', dispatches: 5 });+ expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', 'app-1', ctx({ actionableCount: 3 }))).toEqual({ dispatch: false });+ expect(ts.calls.parked).toEqual([{ reason: 'drain-cap', actionableCount: 3, signature: null }]);+ expect(ts.calls.resets).toBe(1);+ expect(ts.calls.bumps).toBe(0);+ // Nothing was recorded as dispatched, so the next recheck re-drives from scratch.+ expect(ts.calls.signatures).toEqual([]);+ });++ it('spends exactly CAP dispatches before capping', async () => {+ const outcomes = [];+ for (let dispatches = 0; dispatches <= 5; dispatches += 1) {+ const ts = fakeSchedule({ signature: `sig-${dispatches}`, dispatches, cap: 5 });+ outcomes.push((await resolveReconcileDrainGate(ts, 'branch-reconcile', 'app-1', ctx())).dispatch);+ }+ 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', dispatches: 9 });+ await resolveReconcileDrainGate(ts, 'branch-reconcile', 'app-1', ctx());+ expect(ts.calls.parked[0].reason).toBe('no-progress');+ });+});++/**+ * The loop's root cause: the drain's completion refill re-issues itself through the+ * on-demand lane, and BOTH on-demand engines treated every request as a human "Run"+ * — resetting the park, the convergence signature, and the dispatch counter, i.e.+ * every brake the drain has. Either engine may drain a given request, so both must+ * gate the reset on origin.+ */+describe('automated drain refills do not clear their own convergence brakes', () => {+ it('the refill stamps origin: refill', () => {+ expect(COS_SRC).toMatch(/triggerOnDemandTask\(plan\.taskType, plan\.appId, \{\s*emit: false, origin: taskScheduleMod\.ON_DEMAND_ORIGINS\.REFILL\s*\}\)/);+ });++ for (const [engine, src] of [['cos.dequeueNextTask', () => COS_SRC], ['cosTaskGenerator.spawnPriority0OnDemand', () => GEN_SRC]]) {+ it(`${engine} gates both resets on a user-initiated request`, () => {+ const text = src();+ expect(text).toMatch(/const userInitiated = !task[Ss]chedule(Mod)?\.isRefillRequest\(request\)/);+ // Every reset call in the engine must be behind the flag — an ungated one is+ // the exact regression (a refill wiping the signature it must inherit).+ for (const fn of ['resetPerpetualForManualRun', 'clearTaskTypeFailurePark']) {+ const calls = text.split('\n').filter((l) => l.includes(`.${fn}(request.taskType`));+ expect(calls.length, `${fn} call sites in ${engine}`).toBeGreaterThan(0);+ for (const line of calls) expect(line, `${fn} must be gated on userInitiated`).toMatch(/if \(userInitiated\)/);+ }+ });+ }+});diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 41e63c0489..0a6d6d1891 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -1109,6 +1109,59 @@ export async function setPerpetualSignature(taskType, appId = null, signature) {return record;}+/**+ * 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.+ */+export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;++/**+ * How many times this perpetual drain has dispatched since it last went idle.+ * Consecutive by construction: every terminal park (`resetPerpetualDispatchCount`)+ * and every manual re-run zeroes it.+ */+export async function getPerpetualDispatchCount(taskType, appId = null) {+ const schedule = await loadSchedule();+ const record = resolveExecutionRecord(schedule, taskType, appId);+ return record?.perpetualDispatchCount || 0;+}++/** Count one dispatch of a perpetual drain; returns the new count. */+export async function bumpPerpetualDispatchCount(taskType, appId = null) {+ const schedule = await loadSchedule();+ const record = ensureExecutionRecord(schedule, taskType, appId);+ const count = (record.perpetualDispatchCount || 0) + 1;+ record.perpetualDispatchCount = count;+ await saveSchedule(schedule);+ return count;+}++/**+ * Zero a perpetual drain's consecutive-dispatch counter — the drain reached a+ * terminal state (nothing actionable, no progress, or the cap itself), so the next+ * dispatch starts a fresh window. No-op (and no write) when already zero.+ */+export async function resetPerpetualDispatchCount(taskType, appId = null) {+ const schedule = await loadSchedule();+ const record = resolveExecutionRecord(schedule, taskType, appId);+ if (!record || !record.perpetualDispatchCount) return false;+ delete record.perpetualDispatchCount;+ await saveSchedule(schedule);+ return true;+}+/*** 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.@@ -1130,6 +1183,14 @@ export async function clearPerpetualPark(taskType, appId = null) {* "Run" honor the user's intent to re-check now: without clearing the signature,* branch-reconcile/issue-reconcile would re-park `no-progress` against an* unchanged-since-last-run set even though the user explicitly asked to re-drive.+ *+ * ONLY a human asking for a re-run may call this. An automated re-issue that+ * borrows the on-demand lane (the perpetual drain's own completion refill) must+ * NOT: clearing the convergence signature and the dispatch counter is precisely+ * what removes every brake the drain has, and the drain then re-dispatches for as+ * long as one actionable item exists. That is the loop that ran ~40 branch-reconcile+ * coordinators overnight on 2026-08-12. See `origin` on the on-demand request.+ ** Returns true when it cleared anything.*/export async function resetPerpetualForManualRun(taskType, appId = null) {@@ -1137,7 +1198,7 @@ export async function resetPerpetualForManualRun(taskType, appId = null) {const record = resolveExecutionRecord(schedule, taskType, appId);if (!record) return false;let changed = false;- for (const field of [...PARK_FIELDS, 'lastActionableSignature', 'signatureRepeatCount']) {+ for (const field of [...PARK_FIELDS, 'lastActionableSignature', 'signatureRepeatCount', 'perpetualDispatchCount']) {if (record[field] !== undefined) { delete record[field]; changed = true; }}if (changed) await saveSchedule(schedule);@@ -1725,7 +1786,20 @@ export async function deleteTemplateTask(templateId) {// On-Demand Requests// ============================================================-export async function triggerOnDemandTask(taskType, appId = null, { emit = true } = {}) {+/**+ * Who asked for an on-demand run. `'user'` (the default, and what any request+ * already on disk from before this field existed reads as) means a human pressed+ * Run: the drain engines reset the park, the convergence signature, and the+ * dispatch counter so the check runs against live state. `'refill'` means the+ * perpetual drain re-issued ITSELF through the same lane after a completed run —+ * automated, and therefore NOT allowed to clear its own brakes.+ */+export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill' };++/** Is this on-demand request an automated drain refill rather than a human "Run"? */+export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;++export async function triggerOnDemandTask(taskType, appId = null, { emit = true, origin = ON_DEMAND_ORIGINS.USER } = {}) {const schedule = await loadSchedule();// Cheap per-task-type check first; the master-flag check pays a state.json read.@@ -1751,6 +1825,7 @@ export async function triggerOnDemandTask(taskType, appId = null, { emit = trueid: `demand-${Date.now().toString(36)}`,taskType,appId,+ origin,requestedAt: new Date().toISOString()};diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 8797ff2efe..14bee31c82 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -124,6 +124,11 @@ import {resetPerpetualForManualRun,getPerpetualParkInfo,getPerpetualSignature,+ getPerpetualDispatchCount,+ bumpPerpetualDispatchCount,+ resetPerpetualDispatchCount,+ isRefillRequest,+ ON_DEMAND_ORIGINS,setPerpetualSignature,recordTaskTypeFailure,recordTaskTypeSuccess,@@ -1355,6 +1360,28 @@ describe('taskSchedule', () => {expect(result.appId).toBe('critical-mass')expect(result.id).toMatch(/^demand-/)})++ // The drain's completion refill re-issues itself through this same queue. It+ // must be distinguishable from a human "Run", because the engines clear the+ // park + convergence signature + dispatch counter for a human and MUST NOT for+ // a refill — that reset is what let branch-reconcile re-dispatch all night.+ it('stamps origin: user by default and refill when the drain re-issues itself', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ expect((await triggerOnDemandTask('branch-reconcile', 'app-1')).origin).toBe(ON_DEMAND_ORIGINS.USER)++ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ const refill = await triggerOnDemandTask('branch-reconcile', 'app-1', { emit: false, origin: ON_DEMAND_ORIGINS.REFILL })+ expect(refill.origin).toBe(ON_DEMAND_ORIGINS.REFILL)+ })++ it('isRefillRequest only matches an explicit refill origin', () => {+ expect(isRefillRequest({ origin: ON_DEMAND_ORIGINS.REFILL })).toBe(true)+ expect(isRefillRequest({ origin: ON_DEMAND_ORIGINS.USER })).toBe(false)+ // A request queued before `origin` existed reads as user-initiated — the safe+ // default for a queue that is otherwise human-filled.+ expect(isRefillRequest({ taskType: 'branch-reconcile' })).toBe(false)+ expect(isRefillRequest(null)).toBe(false)+ })})describe('getScheduleStatus', () => {@@ -1596,12 +1623,12 @@ describe('taskSchedule', () => {expect(await clearPerpetualPark('claim-issue', 'app-1')).toBe(false)})- it('resetPerpetualForManualRun drops BOTH the park and the convergence signature', async () => {+ it('resetPerpetualForManualRun drops the park, the convergence signature, AND the dispatch count', async () => {const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()mockSchedule({tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {- 'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', lastActionableSignature: 'a:NEEDS_PR:none' }+ 'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', lastActionableSignature: 'a:NEEDS_PR:none', perpetualDispatchCount: 4 }} } }})expect(await resetPerpetualForManualRun('branch-reconcile', 'app-1')).toBe(true)@@ -1610,6 +1637,36 @@ describe('taskSchedule', () => {expect(rec.parkedUntil).toBeUndefined()expect(rec.parkReason).toBeUndefined()expect(rec.lastActionableSignature).toBeUndefined()+ // A human asking to re-run gets a full dispatch budget, not the tail of the+ // previous window — otherwise a drain that just hit the cap would park again+ // on its first cycle.+ expect(rec.perpetualDispatchCount).toBeUndefined()+ })++ it('bumpPerpetualDispatchCount counts consecutive dispatches and reset zeroes it', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ expect(await bumpPerpetualDispatchCount('branch-reconcile', 'app-1')).toBe(1)++ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 1 } } } }+ })+ expect(await bumpPerpetualDispatchCount('branch-reconcile', 'app-1')).toBe(2)+ expect(await getPerpetualDispatchCount('branch-reconcile', 'app-1')).toBe(2)++ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 3 } } } }+ })+ expect(await resetPerpetualDispatchCount('branch-reconcile', 'app-1')).toBe(true)+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].perpetualDispatchCount).toBeUndefined()+ })++ it('getPerpetualDispatchCount is 0 for an unknown task/app and reset is a no-op there', async () => {+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })+ expect(await getPerpetualDispatchCount('branch-reconcile', 'app-9')).toBe(0)+ expect(await resetPerpetualDispatchCount('branch-reconcile', 'app-9')).toBe(false)})it('resetPerpetualForManualRun is a no-op (false) when nothing is cached', async () => {