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

consolidate the drain brakes into single writes and one origin-check home

[._.]/ Adam Eivy3a972c824a3a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index dacd6b83e7..e648a920a0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -7,7 +7,8 @@
- 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 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. Ownership is read from the branch name as well as the worktree, so an agent that has already cleaned up its worktree but is still working is still recognized.
+- 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.
- 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.
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 64725a207c..9e547b5084 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -109,17 +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, dirty, or LIVE worktree → skip + report (never touch)
+ * WIP — local-only, dirty, or LIVE-owned → skip + report (never touch)
*
- * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, abandonedAgentWorktree?:boolean, liveWorktreeReason?:string|null, openPr:({mergeable?:string}|null), prStateUnavailable?:boolean }} input
+ * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, abandonedAgentWorktree?:boolean, liveOwnerReason?: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.
+ * `liveOwnerReason` is `resolveLiveOwnerReason`'s verdict for the branch — non-null
+ * means somebody (an active CoS agent, a live human `/claim`, a deliberate lock) is
+ * working on it right now, whether or not its worktree still exists.
* @returns {'ABANDONED_WIP'|'MERGED'|'CONFLICTED'|'IN_REVIEW'|'NEEDS_PR'|'WIP'}
*/
-export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandonedAgentWorktree, liveWorktreeReason = null, openPr, prStateUnavailable = false }) {
+export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandonedAgentWorktree, liveOwnerReason = 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
@@ -131,17 +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 branch with a LIVE owner belongs to whoever is working on it — an active CoS
+ // agent, a live human `/claim`, or a worktree the user locked. It 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 with a live
+ // owner still belongs in the MERGED bucket, where `cleanupMerged` applies the same
+ // protection and reports it as held back.
+ if (liveOwnerReason) 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
@@ -243,12 +243,11 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,
if (typeof ageMs === 'number' && ageMs >= staleClaimIdleMs) return null;
return 'worktree-human-claim';
}
- // `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.
+ // `instanceof Set`, not truthiness: `getActiveAgentIds()` returns an ARRAY, and a
+ // caller passing it raw would otherwise throw `.has is not a function` mid-cleanup.
+ // Non-Set ⇒ liveness unknown ⇒ not protected here; see isAbandonedAgentWorktree's
+ // JSDoc below for the sentinel rationale, and resolveLiveOwnerReason for the
+ // dispatch side, which fails the other way on purpose.
if (activeAgentIds instanceof Set && activeAgentIds.has(basename)) return 'worktree-active-agent';
return null;
}
@@ -283,21 +282,35 @@ export function isAbandonedAgentWorktree({ path, locked, activeAgentIds }) {
}
/**
- * 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.
+ * Why this branch must be left ALONE this cycle — the dispatch-side counterpart to
+ * `worktreeProtectionReason`'s teardown gate. Three cases that gate doesn't cover:
*
- * `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".
+ * 1. **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 a DISPATCH decision 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.
+ * 2. **A live agent whose worktree is already GONE.** Ownership is in the branch
+ * NAME, not the worktree: CoS branches are `cos/<taskId>/<agentId>` and the
+ * worktree basename is that same `<agentId>`. An agent that removed its worktree
+ * while still running — `/do:pr`'s Phase-7 cleanup does exactly this, before the
+ * session ends — leaves a pushed branch with an open PR and no worktree row, which
+ * otherwise classifies IN_REVIEW and gets handed to the coordinator while its own
+ * agent is still working. That is the bug this whole guard exists to prevent,
+ * surviving in a narrower window. So the branch name is checked too.
+ * 3. A branch with no worktree at all and no live owner is simply free (null).
*
- * @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
+ * @param {{ branch?:string|null, path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null }} input
+ * @returns {string|null} a stable reason slug, or null when nobody owns it
*/
-export function resolveLiveWorktreeReason({ path, locked, activeAgentIds, ageMs }) {
+export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds, ageMs }) {
+ // The branch's own trailing segment is an agent id for CoS branches — checked
+ // FIRST because it holds even after the worktree is gone.
+ const owner = (branch || '').split('/').pop() || '';
+ if (owner.startsWith('agent-') && activeAgentIds instanceof Set && activeAgentIds.has(owner)) {
+ return 'branch-active-agent';
+ }
if (!path) return null;
const reason = worktreeProtectionReason({ path, locked, activeAgentIds, ageMs });
if (reason) return reason;
@@ -645,13 +658,13 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
worktreeAgeMs: 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
+ // Non-null ⇒ somebody owns this branch right now (active CoS agent / live
+ // human claim / locked worktree). Built on the 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.
+ liveOwnerReason: resolveLiveOwnerReason({
+ branch: b.name, path: worktreePath, locked: worktreeLocked, activeAgentIds, ageMs: worktreeAge
}),
behind: divergence.behind,
ahead: divergence.ahead,
@@ -731,9 +744,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[], 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.
+ * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], orphanRemotes:{reaped:string[],reported:object[]}, forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}
+ * A `wip` entry with a `liveOwnerReason` is held because a live agent/claim/lock
+ * owns it — 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
@@ -754,7 +767,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem
if (githubRepoSpec(origin)) {
const forge = await ensureForgeReachable('branch-reconcile', { hostname: githubApiHost(origin.host) });
if (!forge.ok) {
- return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], heldLive: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
+ return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
}
}
@@ -778,13 +791,10 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem
// stays in-flight forever — re-analyzed at full cost on every recheck. Drop it
// out of the actionable set on a cached verdict that still verifies (#3842).
const { actionable: inFlight, superseded } = await applySupersededLedger(repoPath, allInFlight, defaultBranch);
+ // Every WIP entry carries its `liveOwnerReason`, so a caller that needs the
+ // "held by a live owner" subset (to report "the only branches left belong to
+ // running sessions" rather than a bare "nothing actionable") filters `wip` on it.
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 })
@@ -802,7 +812,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, heldLive, skipped, orphanRemotes, prStateUnavailable };
+ return { defaultBranch, cleaned, inFlight, superseded, wip, skipped, orphanRemotes, prStateUnavailable };
}
/**
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index e91cc7a8b4..95953677c6 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, resolveLiveWorktreeReason, gatherDivergence,
+ isAbandonedAgentWorktree, resolveLiveOwnerReason, gatherDivergence,
actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,
branchPriorityRank, prioritizeBranches,
upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes
@@ -108,7 +108,7 @@ describe('classifyBranch', () => {
// 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' };
+ const live = { isMerged: false, hasUpstream: true, worktreeDirty: false, liveOwnerReason: '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');
@@ -116,13 +116,13 @@ describe('classifyBranch', () => {
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
+ liveOwnerReason: '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
+ liveOwnerReason: null, openPr: null
})).toBe('ABANDONED_WIP');
});
it('local-only (no upstream), no PR → WIP', () => {
@@ -354,19 +354,19 @@ describe('isAbandonedAgentWorktree', () => {
});
});
-describe('resolveLiveWorktreeReason', () => {
+describe('resolveLiveOwnerReason', () => {
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');
+ expect(resolveLiveOwnerReason({ path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe('worktree-active-agent');
+ expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe('worktree-locked');
+ expect(resolveLiveOwnerReason({ 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();
+ expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', activeAgentIds: live })).toBeNull();
+ expect(resolveLiveOwnerReason({ path: '/wt/next-issue-42', activeAgentIds: live })).toBeNull();
+ expect(resolveLiveOwnerReason({ path: null, activeAgentIds: live })).toBeNull();
});
// The one case worktreeProtectionReason can't answer: it is only ever called with
@@ -374,12 +374,29 @@ describe('resolveLiveWorktreeReason', () => {
// 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');
+ expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb' })).toBe('worktree-agent-liveness-unknown');
+ expect(resolveLiveOwnerReason({ 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();
+ expect(resolveLiveOwnerReason({ 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();
+ expect(resolveLiveOwnerReason({ path: '/wt/next-issue-42' })).toBeNull();
+ });
+
+ // Ownership lives in the branch NAME (`cos/<taskId>/<agentId>`), so it outlives the
+ // worktree. /do:pr's Phase-7 cleanup removes the worktree while the agent is still
+ // running — without this the branch reads as un-owned, classifies IN_REVIEW, and
+ // the coordinator is dispatched onto a branch its own agent is still pushing to.
+ it('holds a branch whose OWNING agent is live even after its worktree is gone', () => {
+ expect(resolveLiveOwnerReason({ branch: 'cos/task-abc/agent-aaaaaaaa', path: null, activeAgentIds: live }))
+ .toBe('branch-active-agent');
+ // A finished agent's branch is free again.
+ expect(resolveLiveOwnerReason({ branch: 'cos/task-abc/agent-bbbbbbbb', path: null, activeAgentIds: live })).toBeNull();
+ // Non-agent branch names are never owner keys, even by coincidence of suffix.
+ expect(resolveLiveOwnerReason({ branch: 'feature/agent-aaaaaaaa-ui', path: null, activeAgentIds: live })).toBeNull();
+ expect(resolveLiveOwnerReason({ branch: 'main', path: null, activeAgentIds: live })).toBeNull();
+ // Liveness must be authoritative to claim a branch is owned — a non-Set can't
+ // answer, and the branch alone (unlike an agent-* worktree) is not evidence.
+ expect(resolveLiveOwnerReason({ branch: 'cos/task-abc/agent-aaaaaaaa', path: null })).toBeNull();
});
});
@@ -648,13 +665,31 @@ describe('reconcile', () => {
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']]);
+ expect(res.wip.map((b) => [b.branch, b.liveOwnerReason]))
+ .toEqual([['cos/task-y/agent-live1234', 'branch-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([]);
+ expect(after.wip).toEqual([]);
+ });
+
+ // The narrower window the worktree-only check missed: /do:pr Phase-7 removes the
+ // agent's worktree while the agent is still running and still pushing.
+ it('holds a live agent\'s branch when its worktree is ALREADY GONE', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'cos/task-z/agent-live5678', isDefault: false, current: false, tracking: 'origin/cos/task-z/agent-live5678', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]); // worktree already cleaned up
+ git.isBranchMergedInto.mockResolvedValue(false);
+ execGh.mockResolvedValue(JSON.stringify([
+ { number: 4002, headRefName: 'cos/task-z/agent-live5678', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }
+ ]));
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
+
+ const res = await reconcile('/repo', { activeAgentIds: new Set(['agent-live5678']) });
+ expect(res.inFlight).toEqual([]);
+ expect(res.wip.map((b) => b.liveOwnerReason)).toEqual(['branch-active-agent']);
});
// Regression for the "3 orphan cos branches, no active agents, reconcile says
diff --git a/server/services/cos.js b/server/services/cos.js
index 12a4e8d38d..6e036fc3ff 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -881,26 +881,15 @@ 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);
+ // A HUMAN "Run" re-checks live state (park + convergence signature + dispatch
+ // budget all cleared); an automated refill re-issue inherits them, or the drain
+ // has no brakes left. The origin check lives inside applyOnDemandRunResets so
+ // this engine and its two siblings can't drift on it.
+ const userInitiated = await taskScheduleMod.applyOnDemandRunResets(request, targetApp?.id ?? null);
+ const lane = userInitiated ? '' : ' (drain refill)';
if (targetApp) {
- 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).
- 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.) 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);
+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: 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).
@@ -914,12 +903,7 @@ async function spawnDequeuePriority0OnDemand(ctx) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
}
} else {
- 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.
- if (userInitiated) await taskScheduleMod.clearTaskTypeFailurePark(request.taskType);
+ emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });
await taskScheduleMod.recordExecution(`task:${request.taskType}`);
await withStateLock(async () => {
const s = await loadState();
@@ -956,12 +940,16 @@ async function spawnDequeuePriority0OnDemand(ctx) {
capacity.trackSpawn(revived);
emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
}
- } else if (!task) {
+ } else if (!task && userInitiated) {
// Explicit user "Run" produced no task — surface WHY (parked / transient /
// idle) so the trigger isn't a silent no-op. Shared with the sibling
// spawnPriority0OnDemand engine so a request drained by either path gets
// the same feedback. Because we reset the park BEFORE the fresh detection
// above, the outcome classification reflects THIS check.
+ //
+ // `userInitiated` only: a drain refill ends by converging (that's the point),
+ // and nobody is waiting on it, so toasting "nothing to do" for every automated
+ // hop would turn a healthy overnight drain into a pile of notifications.
await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: taskSchedule.tasks[request.taskType] });
}
}
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 2af6c8e23b..ef4836a887 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -870,22 +870,14 @@ 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);
+ // Only a human "Run" may clear the drain's brakes; an automated refill
+ // (origin: 'refill') inherits them. The policy — and the origin check — lives
+ // in applyOnDemandRunResets so this engine and its siblings can't drift.
+ const userInitiated = await taskSchedule.applyOnDemandRunResets(request, targetApp?.id ?? null);
+ const lane = userInitiated ? '' : ' (drain refill)';
if (targetApp) {
- 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).
- 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. A refill carries no
- // such signal and leaves the ledger alone.
- if (userInitiated) await taskSchedule.clearTaskTypeFailurePark(request.taskType, targetApp.id);
+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: 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).
@@ -899,10 +891,7 @@ async function spawnPriority0OnDemand(ctx) {
await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
}
} else {
- 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.
- if (userInitiated) await taskSchedule.clearTaskTypeFailurePark(request.taskType);
+ emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });
await taskSchedule.recordExecution(`task:${request.taskType}`);
await withStateLock(async () => {
const s = await loadState();
@@ -934,9 +923,11 @@ async function spawnPriority0OnDemand(ctx) {
trackSpawn(revived);
emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
}
- } else if (!task) {
+ } else if (!task && userInitiated) {
// Explicit user Run produced no task on THIS engine too — same feedback
// as cos.dequeueNextTask so a request drained here isn't a silent no-op.
+ // An automated refill is skipped for the same reason it is there: it ends
+ // by converging, and nobody is waiting on the toast.
await emitOnDemandEmpty({ taskScheduleMod: taskSchedule, request, targetApp, taskConfig: liveSchedule.tasks[request.taskType] });
}
}
@@ -2203,6 +2194,24 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
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
+ * reports four such sets (held-back worktrees, toggle-gated branches, live-owned
+ * branches, superseded branches) and every one of them must stay visible: a set
+ * that silently reads as "nothing" is how a lingering worktree once hid behind
+ * "cleaned 0" for weeks.
+ * @param {object[]|undefined} items
+ * @param {string} noun - phrase following the count
+ * @param {(item:object)=>string} [describe] - per-item detail, deduped in parens
+ */
+const countSuffix = (items, noun, describe) => {
+ const list = items || [];
+ if (!list.length) return '';
+ const detail = describe ? ` (${[...new Set(list.map(describe))].join(', ')})` : '';
+ return `, ${list.length} ${noun}${detail}`;
+};
+
/**
* Shared convergence gate for the reconcile perpetual drains (branch + issue).
* Both have the same shape — a deterministic scan produced a non-empty actionable
@@ -2221,35 +2230,33 @@ async function applyPerpetualWorkGate(app, taskType, promptTaskType, metadata, i
*
* @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
+ * @param {{id:string, name:string}} app
+ * @param {{ signature:string, actionableCount:number, label:string, unit:string }} ctx
* `label` prefixes the log lines (emoji + type); `unit` names the items ("branch(es)").
- * @returns {Promise<{ dispatch:boolean }>}
+ * @returns {Promise<boolean>} true to dispatch; false when the drain was parked
*/
-export async function resolveReconcileDrainGate(taskSchedule, taskType, appId, { signature, actionableCount, label, unit, appName }) {
+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, appId, { reason, actionableCount, signature: null });
- await taskSchedule.resetPerpetualDispatchCount(taskType, appId);
- emitLog('info', `${label} parked for ${appName}: ${detail}`, { appId });
- return { dispatch: false };
+ 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 lastSignature = await taskSchedule.getPerpetualSignature(taskType, appId);
+ const { signature: lastSignature, dispatchCount } = 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)`);
}
-
- 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`);
+ 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`);
}
- // 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 };
+ // Progress within budget — resume the drain, record the signature, and spend one
+ // dispatch, so the drain runs back-to-back without the post-completion cooldown.
+ await taskSchedule.recordPerpetualDispatch(taskType, app.id, signature);
+ return true;
}
/**
@@ -2309,53 +2316,43 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
// human still has to reap, so name them rather than letting them vanish into a
// quiet park — the invisibility is the same failure mode as a lingering worktree
// reported as "cleaned 0".
- const supersededCount = result.superseded?.length || 0;
- const supersededSuffix = supersededCount
- ? `, ${supersededCount} branch(es) already verified superseded and awaiting human reap`
- : '';
+ const supersededSuffix = countSuffix(result.superseded, '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 heldLive = (result.wip || []).filter((b) => b.liveOwnerReason);
+ const heldLiveSuffix = countSuffix(heldLive, 'branch(es) left to their live owners', (b) => b.liveOwnerReason);
const actionable = filterActionable(result.inFlight, actions);
if (actionable.length === 0) {
// 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.
+ // clearing the progress signature so a fresh set later dispatches and zeroing the
+ // dispatch budget — this drain converged, so the next one gets a full one.
const reason = heldLive.length ? 'branches-held-by-live-owners' : 'no-in-flight-branches';
- await taskSchedule.parkPerpetual(taskType, app.id, { reason, actionableCount: 0, signature: null });
- await taskSchedule.resetPerpetualDispatchCount(taskType, app.id);
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason, actionableCount: 0, signature: null, dispatchCount: 0 });
// 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-'));
- const heldSuffix = heldBack.length
- ? `, ${heldBack.length} merged branch(es) held back (${[...new Set(heldBack.map((s) => s.reason))].join(', ')})`
- : '';
+ const heldSuffix = countSuffix(
+ (result.skipped || []).filter((s) => s.reason?.startsWith('worktree-')),
+ 'merged branch(es) held back', (s) => s.reason
+ );
// In-flight branches that exist but were filtered out by a disabled action
// toggle are the OTHER way "nothing in-flight" can lie — say so, or the user
// sees a park while real branches sit there (the same invisibility that hid
// the abandoned-worktree case).
- const gatedOff = result.inFlight.length;
- const gatedSuffix = gatedOff
- ? `, ${gatedOff} in-flight branch(es) skipped by disabled action toggles (${[...new Set(result.inFlight.map((b) => b.state))].join(', ')})`
- : '';
+ const gatedSuffix = countSuffix(result.inFlight, 'in-flight branch(es) skipped by disabled action toggles', (b) => b.state);
emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing actionable (cleaned ${result.cleaned.length}${heldSuffix}${gatedSuffix}${heldLiveSuffix}${supersededSuffix})`, { appId: app.id });
return { skip: true };
}
// 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, {
+ const dispatch = await resolveReconcileDrainGate(taskSchedule, taskType, app, {
signature: actionableSignature(actionable),
actionableCount: actionable.length,
label: '🔀 branch-reconcile',
- unit: 'branch(es)',
- appName: app.name
+ unit: 'branch(es)'
});
- if (!gate.dispatch) return { skip: true };
+ if (!dispatch) return { skip: true };
metadata.perpetual = true;
const supersededBlock = formatSupersededForPrompt(result.superseded || []);
const block = [
@@ -2400,20 +2397,18 @@ async function resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule)
emitLog('info', `🧟 issue-reconcile ${app.name}: ${result.stalled.length} stalled in-progress issue(s) with no merged PR (left for human/branch-reconcile)`, { appId: app.id, analysisType: taskType });
}
if (result.zombies.length === 0) {
- await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null });
- await taskSchedule.resetPerpetualDispatchCount(taskType, app.id);
+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-zombie-issues', actionableCount: 0, signature: null, dispatchCount: 0 });
emitLog('info', `🧟 issue-reconcile parked for ${app.name}: no zombie issues`, { appId: app.id });
return { skip: true };
}
// Convergence guards — identical to branch-reconcile's (shared helper).
- const gate = await resolveReconcileDrainGate(taskSchedule, taskType, app.id, {
+ const dispatch = await resolveReconcileDrainGate(taskSchedule, taskType, app, {
signature: zombieSignature(result.zombies),
actionableCount: result.zombies.length,
label: '🧟 issue-reconcile',
- unit: 'zombie issue(s)',
- appName: app.name
+ unit: 'zombie issue(s)'
});
- if (!gate.dispatch) return { skip: true };
+ if (!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.js
index df2e09f5fb..ccfb3c4f4b 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -1138,68 +1138,61 @@ describe('ignoreTaskId reaches BOTH completion-continuation generators (#3179)',
* 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); }
- };
- };
+ // Stand-in for the injected taskSchedule module.
+ const fakeSchedule = ({ signature = null, dispatchCount = 0, cap = 5 } = {}) => ({
+ PERPETUAL_DRAIN_DISPATCH_CAP: cap,
+ getPerpetualDrainState: vi.fn(async () => ({ signature, dispatchCount })),
+ parkPerpetual: vi.fn(async () => {}),
+ recordPerpetualDispatch: vi.fn(async () => dispatchCount + 1)
+ });
+ const app = { id: 'app-1', name: 'App One' };
const ctx = (over = {}) => ({
signature: 'a:NEEDS_PR:none', actionableCount: 1,
- label: '🔀 branch-reconcile', unit: 'branch(es)', appName: 'App One', ...over
+ label: '🔀 branch-reconcile', unit: 'branch(es)', ...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);
+ 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();
+ // One write carries all three facts (park cleared, signature recorded, dispatch spent).
+ expect(ts.recordPerpetualDispatch).toHaveBeenCalledWith('branch-reconcile', 'app-1', 'a:NEEDS_PR:none');
+ });
+
+ it('parks no-progress on an unchanged set, clearing signature + counter in the park write', async () => {
+ const ts = fakeSchedule({ signature: 'a:NEEDS_PR:none', dispatchCount: 1 });
+ expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx())).toBe(false);
+ expect(ts.parkPerpetual).toHaveBeenCalledWith('branch-reconcile', 'app-1', {
+ reason: 'no-progress', actionableCount: 1, signature: null, dispatchCount: 0
+ });
+ 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', 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([]);
+ const ts = fakeSchedule({ signature: 'stale-sig', dispatchCount: 5 });
+ expect(await resolveReconcileDrainGate(ts, 'branch-reconcile', app, ctx({ actionableCount: 3 }))).toBe(false);
+ expect(ts.parkPerpetual).toHaveBeenCalledWith('branch-reconcile', 'app-1', {
+ reason: 'drain-cap', actionableCount: 3, 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 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);
+ 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()));
}
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');
+ 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');
});
});
@@ -1215,17 +1208,24 @@ describe('automated drain refills do not clear their own convergence brakes', ()
expect(COS_SRC).toMatch(/triggerOnDemandTask\(plan\.taskType, plan\.appId, \{\s*emit: false, origin: taskScheduleMod\.ON_DEMAND_ORIGINS\.REFILL\s*\}\)/);
});
+ // The origin check lives in taskSchedule.applyOnDemandRunResets (behaviorally
+ // tested there), so what matters HERE is that no engine reaches around it: an
+ // engine calling the reset primitives directly is the exact regression, since
+ // that is the shape the loop had.
for (const [engine, src] of [['cos.dequeueNextTask', () => COS_SRC], ['cosTaskGenerator.spawnPriority0OnDemand', () => GEN_SRC]]) {
- it(`${engine} gates both resets on a user-initiated request`, () => {
+ it(`${engine} resets on-demand state only through applyOnDemandRunResets`, () => {
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).
+ expect(text).toMatch(/const userInitiated = await task[Ss]chedule(Mod)?\.applyOnDemandRunResets\(request, targetApp\?\.id \?\? null\)/);
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\)/);
+ const direct = text.split('\n').filter((l) => l.includes(`.${fn}(request.taskType`));
+ expect(direct, `${engine} must not call ${fn} directly — go through applyOnDemandRunResets`).toEqual([]);
}
});
+
+ // A refill that toasts "nothing to do" turns a healthy overnight drain into a
+ // pile of notifications nobody asked for.
+ it(`${engine} only reports an empty result for a user-initiated request`, () => {
+ expect(src()).toMatch(/\}\s*else if \(!task && userInitiated\) \{/);
+ });
}
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 0a6d6d1891..050706490e 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1026,8 +1026,17 @@ const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCo
* Park a perpetual task: its work-detector reported nothing actionable, so stop
* draining and wait until `parkedUntil` before re-probing. Stamps the park
* fields on the (per-app or global) execution record.
+ *
+ * `signature` and `dispatchCount` are the drain's two convergence brakes, both
+ * settable HERE rather than by a follow-up call, because every terminal park has
+ * to land them in the same write it lands the park. A second await after this one
+ * is a step a future park path can forget — and a stale non-zero dispatch count
+ * makes the NEXT fresh drain cap out early, which looks exactly like the task
+ * silently doing nothing. Note `dispatchCount` is deliberately NOT in
+ * `PARK_FIELDS`: `clearPerpetualPark` runs mid-drain, and zeroing the counter
+ * there would reset the budget before every dispatch, so the cap could never fire.
*/
-export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, signature } = {}) {
+export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, signature, dispatchCount } = {}) {
const schedule = await loadSchedule();
const interval = schedule.tasks[taskType] || {};
const parkedUntil = await computePerpetualRecheckAt(interval);
@@ -1062,6 +1071,12 @@ export async function parkPerpetual(taskType, appId = null, { reason = null, act
record.signatureRepeatCount = 1;
}
}
+ // Same option shape for the consecutive-dispatch budget: `0` (or null) clears it
+ // because this park ended the drain window; `undefined` leaves it alone.
+ if (dispatchCount !== undefined) {
+ if (!dispatchCount) delete record.perpetualDispatchCount;
+ else record.perpetualDispatchCount = dispatchCount;
+ }
await saveSchedule(schedule);
emitLog('info', `Perpetual ${taskType} parked until ${parkedUntil} (${reason || 'idle'})`, { taskType, appId, parkedUntil }, '📅 TaskSchedule');
cosEvents.emit('schedule:perpetual-parked', { taskType, appId, parkedUntil, reason, actionableCount, counts });
@@ -1088,25 +1103,39 @@ export async function getPerpetualParkInfo(taskType, appId = null) {
};
}
-/** Read the last actionable signature recorded for a perpetual drain (or null). */
-export async function getPerpetualSignature(taskType, appId = null) {
+/**
+ * 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
+ * since it last went idle. Read together because they are decided together — two
+ * separate getters also left a read-skew window between the two fields.
+ * @returns {Promise<{ signature:string|null, dispatchCount:number }>}
+ */
+export async function getPerpetualDrainState(taskType, appId = null) {
const schedule = await loadSchedule();
const record = resolveExecutionRecord(schedule, taskType, appId);
- return record?.lastActionableSignature ?? null;
+ return {
+ signature: record?.lastActionableSignature ?? null,
+ dispatchCount: record?.perpetualDispatchCount || 0
+ };
}
/**
- * Record the actionable signature a perpetual drain is dispatching against, so a
- * later cycle that finds the same signature can recognize "no progress" and park
- * instead of re-dispatching an identical run. `null` clears it.
+ * Record that a perpetual drain is dispatching against `signature`: resume the
+ * drain (drop any park), remember the signature so a later cycle can recognize
+ * "same set ⇒ no progress", and spend one dispatch from the cap's budget — all in
+ * a single read-modify-write, so the three facts can never land apart.
+ * @returns {Promise<number>} the new consecutive-dispatch count
*/
-export async function setPerpetualSignature(taskType, appId = null, signature) {
+export async function recordPerpetualDispatch(taskType, appId = null, signature) {
const schedule = await loadSchedule();
const record = ensureExecutionRecord(schedule, taskType, appId);
+ for (const field of PARK_FIELDS) delete record[field];
if (signature == null) delete record.lastActionableSignature;
else record.lastActionableSignature = signature;
+ const count = (record.perpetualDispatchCount || 0) + 1;
+ record.perpetualDispatchCount = count;
await saveSchedule(schedule);
- return record;
+ return count;
}
/**
@@ -1124,44 +1153,15 @@ export async function setPerpetualSignature(taskType, appId = null, signature) {
* 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;
-/**
- * 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.
@@ -1205,6 +1205,37 @@ export async function resetPerpetualForManualRun(taskType, appId = null) {
return changed;
}
+/**
+ * Apply the "a human pressed Run" state resets for one on-demand request — and
+ * apply NOTHING when the request is an automated drain refill.
+ *
+ * This is the single home of that policy. It used to be open-coded in each spawn
+ * engine that drains the on-demand queue, which is how the loop this guards against
+ * got in: the engines could not tell a human "Run Now" from the perpetual drain
+ * re-issuing itself through the same queue, so they cleared the drain's park,
+ * convergence signature, and dispatch budget on every automated hop. There are
+ * THREE consumers of that queue (cos.dequeueNextTask, cosTaskGenerator's
+ * spawnPriority0OnDemand, and the idle-review path), so "remember to check origin
+ * at each call site" is not a durable invariant — calling this instead is.
+ *
+ * @param {{taskType:string, origin?:string}} request - the queued on-demand record
+ * @param {string|null} [appId] - the app scope, or null for a global task
+ * @returns {Promise<boolean>} true when the request was user-initiated (resets
+ * applied) — callers use it to decide whether user-facing feedback is warranted
+ */
+export async function applyOnDemandRunResets(request, appId = null) {
+ if (isRefillRequest(request)) return false;
+ // A user-initiated "Run" must re-check live state, never honor a stale park or
+ // convergence verdict.
+ await resetPerpetualForManualRun(request.taskType, appId);
+ // It also unparks a failure-parked type (#2616): a human explicitly re-running is
+ // an "I've addressed it" signal. A refill carries no such signal from anybody —
+ // gating this too keeps a drain that fails every run from clearing its own
+ // failure park forever.
+ await clearTaskTypeFailurePark(request.taskType, appId);
+ return true;
+}
+
// ============================================================
// Type-level consecutive-failure ledger (#2616)
// ============================================================
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 14bee31c82..a11eae7dd2 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -123,13 +123,11 @@ import {
clearPerpetualPark,
resetPerpetualForManualRun,
getPerpetualParkInfo,
- getPerpetualSignature,
- getPerpetualDispatchCount,
- bumpPerpetualDispatchCount,
- resetPerpetualDispatchCount,
+ getPerpetualDrainState,
+ recordPerpetualDispatch,
+ applyOnDemandRunResets,
isRefillRequest,
ON_DEMAND_ORIGINS,
- setPerpetualSignature,
recordTaskTypeFailure,
recordTaskTypeSuccess,
clearTaskTypeFailurePark,
@@ -1374,6 +1372,42 @@ describe('taskSchedule', () => {
expect(refill.origin).toBe(ON_DEMAND_ORIGINS.REFILL)
})
+ // The policy that used to be open-coded in each spawn engine — which is how the
+ // loop got in. One home, so the three queue consumers can't drift on it.
+ describe('applyOnDemandRunResets', () => {
+ const parked = (extra = {}) => ({
+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
+ 'app-1': {
+ lastRun: null, count: 0,
+ parkedUntil: new Date(Date.now() + 3600000).toISOString(), parkReason: 'no-progress',
+ lastActionableSignature: 'a:NEEDS_PR:none', perpetualDispatchCount: 3,
+ ...extra
+ }
+ } } }
+ })
+
+ it('clears the drain state for a human "Run" and reports it as user-initiated', async () => {
+ mockSchedule(parked())
+ expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile', origin: ON_DEMAND_ORIGINS.USER }, 'app-1')).toBe(true)
+ const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
+ expect(rec.parkedUntil).toBeUndefined()
+ expect(rec.lastActionableSignature).toBeUndefined()
+ expect(rec.perpetualDispatchCount).toBeUndefined()
+ })
+
+ it('clears NOTHING for an automated drain refill — the brakes must survive the hop', async () => {
+ mockSchedule(parked())
+ expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile', origin: ON_DEMAND_ORIGINS.REFILL }, 'app-1')).toBe(false)
+ expect(writeFile).not.toHaveBeenCalled()
+ })
+
+ it('treats a pre-origin request as user-initiated (safe default for a human-filled queue)', async () => {
+ mockSchedule(parked())
+ expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile' }, 'app-1')).toBe(true)
+ })
+ })
+
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)
@@ -1643,30 +1677,65 @@ describe('taskSchedule', () => {
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)
-
+ it('getPerpetualDrainState reads both brakes in one pass (and defaults them)', async () => {
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 } } } }
+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-1', perpetualDispatchCount: 3 }
+ } } }
})
- expect(await bumpPerpetualDispatchCount('branch-reconcile', 'app-1')).toBe(2)
- expect(await getPerpetualDispatchCount('branch-reconcile', 'app-1')).toBe(2)
+ expect(await getPerpetualDrainState('branch-reconcile', 'app-1')).toEqual({ signature: 'sig-1', dispatchCount: 3 })
+ // An app with no record yet is "fresh drain", not undefined.
+ expect(await getPerpetualDrainState('branch-reconcile', 'app-9')).toEqual({ signature: null, dispatchCount: 0 })
+ })
+ it('recordPerpetualDispatch drops the park, records the signature, and spends one dispatch in ONE write', 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, perpetualDispatchCount: 3 } } } }
+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: {
+ 'app-1': { lastRun: null, count: 0, parkedUntil: future, parkReason: 'no-progress', perpetualDispatchCount: 2 }
+ } } }
})
- 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()
+ expect(await recordPerpetualDispatch('branch-reconcile', 'app-1', 'sig-2')).toBe(3)
+ const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
+ expect(rec.parkedUntil).toBeUndefined()
+ expect(rec.parkReason).toBeUndefined()
+ expect(rec.lastActionableSignature).toBe('sig-2')
+ expect(rec.perpetualDispatchCount).toBe(3)
+ // The three facts land TOGETHER: no persisted state exists in which the new
+ // signature is recorded without the park cleared and the dispatch counted.
+ // (loadSchedule may itself write once for prompt self-heal, so this asserts
+ // the invariant rather than a raw write count.)
+ const partial = writeFile.mock.calls
+ .map((c) => JSON.parse(c[1]).executions['task:branch-reconcile']?.perApp?.['app-1'])
+ .filter((r) => r?.lastActionableSignature === 'sig-2')
+ .filter((r) => r.parkedUntil !== undefined || r.perpetualDispatchCount !== 3)
+ expect(partial).toEqual([])
+ })
+
+ // The park has to land the zeroed budget itself: a second await is a step a
+ // future park path can forget, and a stale count caps the NEXT drain early.
+ it('parkPerpetual clears the dispatch budget when handed dispatchCount: 0', async () => {
+ mockSchedule({
+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
+ })
+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'drain-cap', actionableCount: 2, signature: null, dispatchCount: 0 })
+ const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:branch-reconcile'].perApp['app-1']
+ expect(rec.perpetualDispatchCount).toBeUndefined()
+ expect(rec.lastActionableSignature).toBeUndefined()
+ expect(rec.parkReason).toBe('drain-cap')
})
- 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('parkPerpetual leaves the dispatch budget alone when the option is omitted', async () => {
+ mockSchedule({
+ tasks: { 'claim-issue': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },
+ executions: { 'task:claim-issue': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, perpetualDispatchCount: 4 } } } }
+ })
+ await parkPerpetual('claim-issue', 'app-1', { reason: 'no-actionable-issues', actionableCount: 0 })
+ const rec = JSON.parse(writeFile.mock.calls.at(-1)[1]).executions['task:claim-issue'].perApp['app-1']
+ expect(rec.perpetualDispatchCount).toBe(4)
})
it('resetPerpetualForManualRun is a no-op (false) when nothing is cached', async () => {
@@ -1677,37 +1746,13 @@ describe('taskSchedule', () => {
expect(await resetPerpetualForManualRun('claim-issue', 'app-1')).toBe(false)
})
- it('parkPerpetual stores an actionable signature and getPerpetualSignature reads it back', async () => {
+ it('parkPerpetual stores the actionable signature it parked on', async () => {
mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 2, signature: 'a:NEEDS_PR:none|b:IN_REVIEW:5' })
const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('a:NEEDS_PR:none|b:IN_REVIEW:5')
})
- it('getPerpetualSignature returns the stored signature (and null when absent)', async () => {
- mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
- executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-1' } } } }
- })
- expect(await getPerpetualSignature('branch-reconcile', 'app-1')).toBe('sig-1')
- expect(await getPerpetualSignature('branch-reconcile', 'app-2')).toBeNull()
- })
-
- it('setPerpetualSignature writes it, and null clears it', async () => {
- mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } } })
- await setPerpetualSignature('branch-reconcile', 'app-1', 'sig-2')
- let saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
- expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('sig-2')
-
- mockSchedule({
- tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },
- executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'sig-2' } } } }
- })
- await setPerpetualSignature('branch-reconcile', 'app-1', null)
- saved = JSON.parse(writeFile.mock.calls.at(-1)[1])
- expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBeUndefined()
- })
-
it('parkPerpetual with signature:null clears a prior signature (idle park)', async () => {
mockSchedule({
tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },