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

report branch-reconcile's real park state instead of "no branches in flight"

[._.]/ Adam Eivy8e5da7effe46
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.js
index 723b09ac4c..db4f00d7bd 100644
--- a/client/src/hooks/useOnDemandTaskToast.js
+++ b/client/src/hooks/useOnDemandTaskToast.js
@@ -16,6 +16,7 @@ const PARK_REASON_LABELS = {
'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',
+ 'merged-branches-held-back': 'every remaining branch is already merged and waiting on a protected worktree',
'no-zombie-issues': 'no stale issues to reconcile',
'no-actionable-plan-items': 'no unblocked PLAN items',
'no-progress': 'already up to date',
@@ -83,7 +84,12 @@ export function useOnDemandTaskToast() {
// when the detector reported a denominator (open > 0).
const c = data?.counts;
let countSuffix = '';
- if (c && typeof c.open === 'number' && c.open > 0) {
+ // branch-reconcile's breakdown instead names merged branches whose worktree
+ // a protection guard still holds — the park is a wait, not an empty repo, so
+ // the count has to show or the toast reads as "nothing exists".
+ if (c && typeof c.heldBackMerged === 'number' && c.heldBackMerged > 0) {
+ countSuffix = ` (${c.heldBackMerged} merged branch(es) held back)`;
+ } else if (c && typeof c.open === 'number' && c.open > 0) {
const parts = [];
if (c.inFlight) parts.push(`${c.inFlight} in-flight`);
if (c.filtered) parts.push(`${c.filtered} filtered`);
diff --git a/client/src/hooks/useOnDemandTaskToast.test.jsx b/client/src/hooks/useOnDemandTaskToast.test.jsx
index f48dac7558..976163d6a2 100644
--- a/client/src/hooks/useOnDemandTaskToast.test.jsx
+++ b/client/src/hooks/useOnDemandTaskToast.test.jsx
@@ -95,6 +95,34 @@ describe('useOnDemandTaskToast — parked outcome', () => {
expect(msg).not.toMatch(/0 of/);
});
+ // branch-reconcile's park used to report 'no-in-flight-branches' while merged
+ // branches sat behind a protected worktree — "nothing to do" for a task the
+ // user could see had work queued, which reads as the task not running at all.
+ it('names the merged branches held back rather than claiming nothing is in flight', () => {
+ renderHook(() => useOnDemandTaskToast());
+ fire({
+ taskType: 'branch-reconcile', appName: 'App One', outcome: 'parked',
+ parkReason: 'merged-branches-held-back', counts: { heldBackMerged: 4 },
+ parkedUntil: new Date(Date.now() + 5 * 24 * 3600 * 1000).toISOString()
+ });
+ const [msg] = toastSpy.mock.calls[0];
+ expect(msg).toMatch(/already merged and waiting on a protected worktree/);
+ expect(msg).toMatch(/4 merged branch\(es\) held back/);
+ expect(msg).not.toMatch(/no branches in flight/);
+ });
+
+ it('still reads as a genuinely empty repo when nothing is held back', () => {
+ renderHook(() => useOnDemandTaskToast());
+ fire({
+ taskType: 'branch-reconcile', appName: 'App One', outcome: 'parked',
+ parkReason: 'no-in-flight-branches', counts: null,
+ parkedUntil: new Date(Date.now() + 23 * 3600 * 1000).toISOString()
+ });
+ const [msg] = toastSpy.mock.calls[0];
+ expect(msg).toMatch(/no branches in flight/);
+ expect(msg).not.toMatch(/held back/);
+ });
+
it('explains the author-filter trap (not "no open issues") when open issues exist but none match the filter', () => {
renderHook(() => useOnDemandTaskToast());
// The detector reports filtered: 0 on this path (the issues were excluded by
diff --git a/server/lib/README.md b/server/lib/README.md
index 993aca0d56..163ebcfc16 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -272,7 +272,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. |
| `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. |
| `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |
-| `worktreeOwnership.js` | Pure ownership gate for destructive worktree operations. `worktreeOwnershipReason()` applies explicit root, agent-id, claim, lock, and active-agent policies; `worktreeAgentId()` is separator-safe; `isHumanClaimWorktree()` and `isAgentWorktreeId()` make the protected namespaces explicit. |
+| `worktreeOwnership.js` | Pure ownership gate for destructive worktree operations. `worktreeOwnershipReason()` applies explicit root, agent-id, claim, lock, and active-agent policies; `worktreeAgentId()` is separator-safe; `isHumanClaimWorktree()` and `isAgentWorktreeId()` make the protected namespaces explicit; `worktreeHoldExpiresAt()` names when a hold lapses on its own (the stale-claim window) so callers can wait exactly that long. |
| `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |
## Curated static data
diff --git a/server/lib/worktreeOwnership.js b/server/lib/worktreeOwnership.js
index f2ab756b79..b379e21e5b 100644
--- a/server/lib/worktreeOwnership.js
+++ b/server/lib/worktreeOwnership.js
@@ -90,3 +90,33 @@ export function worktreeOwnershipReason({
}
return null;
}
+
+/**
+ * When a hold reported by `worktreeOwnershipReason` lifts on its OWN, as an ISO
+ * instant — or null when only an outside change can clear it.
+ *
+ * Lives here, next to the gate, because the expiry is the same policy as the
+ * hold: the stale-claim window (`ageMs >= staleClaimIdleMs`) is the one gate keyed
+ * to a clock, so this is the only module that can name the deadline without
+ * re-deriving it from a returned slug. A lock, a live agent, and unknown
+ * liveness all end at times nothing here can predict.
+ *
+ * The slug alone is not enough to answer this, which is the other reason it
+ * belongs here: a claim worktree that is ALSO locked reports
+ * `worktree-human-claim` (first match wins), and its hold does NOT lift when the
+ * claim window lapses. So the window is re-asked with the deadline already
+ * crossed, and only a tree that comes back free gets an expiry.
+ *
+ * Pure. Takes the same options object as `worktreeOwnershipReason`.
+ * @param {object} [options] - plus `nowMs` for the clock
+ * @returns {string|null} ISO timestamp
+ */
+export function worktreeHoldExpiresAt({ nowMs = Date.now(), ...options } = {}) {
+ const { ageMs, staleClaimIdleMs } = options;
+ if (worktreeOwnershipReason(options) !== 'worktree-human-claim') return null;
+ if (!Number.isFinite(ageMs) || !Number.isFinite(staleClaimIdleMs)) return null;
+ const remaining = staleClaimIdleMs - ageMs;
+ if (remaining <= 0) return null;
+ if (worktreeOwnershipReason({ ...options, ageMs: staleClaimIdleMs }) !== null) return null;
+ return new Date(nowMs + remaining).toISOString();
+}
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 120af9e9a5..1ffc3de15e 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -26,7 +26,7 @@ import { stat } from 'node:fs/promises';
import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } from './git.js';
import { execGit } from '../lib/execGit.js';
import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';
-import { isAgentWorktreeId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';
+import { isAgentWorktreeId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';
import { execGh, ensureForgeReachable } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
@@ -245,6 +245,30 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,
});
}
+/**
+ * When `worktreeProtectionReason`'s hold on this worktree lapses by itself, as an
+ * ISO instant — or null when it takes an outside change (a lock released, an
+ * agent exiting) that we cannot schedule.
+ *
+ * The exact mirror of the gate above, so cleanup can report not just THAT a
+ * merged branch was held back but WHEN it stops being held. Policy lives in
+ * worktreeOwnership.js; this only supplies this caller's defaults.
+ *
+ * @param {{ path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null, staleClaimIdleMs?:number }} input
+ * @returns {string|null} ISO timestamp
+ */
+export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS }) {
+ if (!path) return null;
+ return worktreeHoldExpiresAt({
+ path,
+ locked,
+ activeAgentIds,
+ allowStaleClaim: true,
+ ageMs,
+ staleClaimIdleMs,
+ });
+}
+
/**
* Is this worktree a CoS agent workspace whose agent is no longer running?
*
@@ -688,6 +712,40 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
return inputs;
}
+/**
+ * How an idle reconcile should PARK — the reason, the breakdown, and the instant
+ * the park may end early.
+ *
+ * "Nothing actionable" has three very different meanings and they used to
+ * collapse into one: branches belong to sessions still running, merged branches
+ * are queued behind a protected worktree, or the repo really is quiet. Only the
+ * last is "nothing to do". Reporting it for the middle case is what made a task
+ * with four stale claim branches waiting on it read as though it had stopped
+ * running — the persisted state said zero of everything.
+ *
+ * Pure.
+ * @param {{reason?:string, retryAt?:string|null}[]} [skipped] - cleanupMerged's skips
+ * @param {object[]} [heldLive] - WIP branches with a liveOwnerReason
+ * @returns {{reason:string, heldBackMerged:object[], counts:{heldBackMerged:number}|null, notLaterThan:string|null}}
+ */
+export function describeIdleReconcilePark(skipped = [], heldLive = []) {
+ // Only worktree-* skips are a HOLD; 'not-merged-on-recheck' and 'cleanup-disabled'
+ // mean the branch was never eligible, so they must not read as pending work.
+ const heldBackMerged = skipped.filter((s) => s.reason?.startsWith('worktree-'));
+ const lifts = heldBackMerged.map((entry) => Date.parse(entry.retryAt)).filter(Number.isFinite);
+ const reason = heldLive.length
+ ? 'branches-held-by-live-owners'
+ : heldBackMerged.length ? 'merged-branches-held-back' : 'no-in-flight-branches';
+ return {
+ reason,
+ heldBackMerged,
+ counts: heldBackMerged.length ? { heldBackMerged: heldBackMerged.length } : null,
+ // The soonest hold to lapse is when this park may end early; entries with no
+ // (or an unreadable) deadline simply don't vote, leaving the normal cadence.
+ notLaterThan: lifts.length ? new Date(Math.min(...lifts)).toISOString() : null
+ };
+}
+
/**
* Deterministically clean up fully-merged branches: remove the lingering
* worktree, then delete the local branch. Safety gates (ALL must hold):
@@ -701,7 +759,8 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
* @param {object[]} merged - gathered inputs whose state === 'MERGED'
* @param {{ activeAgentIds?: Set<string> }} [opts] - CoS agents currently running;
* their worktrees are never torn down even when the branch is merged + clean.
- * @returns {Promise<{cleaned:string[], skipped:{branch:string,reason:string}[]}>}
+ * @returns {Promise<{cleaned:string[], skipped:{branch:string,reason:string,retryAt?:string}[]}>}
+ * A skip carries `retryAt` when its hold is known to lift at a specific time.
*/
export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds = new Set() } = {}) {
const cleaned = [];
@@ -718,11 +777,14 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
// an active CoS agent workspace — even if its branch is merged and clean. An
// abandoned claim worktree (merged + clean + older than STALE_CLAIM_IDLE_MS)
// falls through and IS reaped; that's the "cleaned 0 forever" leak this fixes.
- const protectedReason = worktreeProtectionReason({
- path: b.worktreePath, locked: b.worktreeLocked, activeAgentIds, ageMs: b.worktreeAgeMs
- });
+ const gate = { path: b.worktreePath, locked: b.worktreeLocked, activeAgentIds, ageMs: b.worktreeAgeMs };
+ const protectedReason = worktreeProtectionReason(gate);
if (protectedReason) {
- skipped.push({ branch: b.branch, reason: protectedReason });
+ // Carry WHEN the hold lifts when it lifts on a clock (a claim worktree
+ // still inside its grace window). Without it the caller can only park on
+ // the recheck cadence and the two waits stack — see boundParkedUntil.
+ const retryAt = worktreeProtectionExpiresAt(gate);
+ skipped.push({ branch: b.branch, reason: protectedReason, ...(retryAt ? { retryAt } : {}) });
continue;
}
const dirty = await isWorktreeDirty(b.worktreePath);
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 1749c3aa57..412d0021c4 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -63,7 +63,7 @@ import {
isAbandonedAgentWorktree, resolveLiveOwnerReason, gatherDivergence,
actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,
limitBranchesForAgent,
- branchPriorityRank, prioritizeBranches,
+ branchPriorityRank, prioritizeBranches, worktreeProtectionExpiresAt, describeIdleReconcilePark,
upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes
} from './branchReconcile.js';
import * as git from './git.js';
@@ -230,17 +230,38 @@ describe('cleanupMerged', () => {
expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'claim/issue-1933', { local: true });
});
- it('still protects a RECENT claim worktree even when merged + clean', async () => {
+ it('still protects a RECENT claim worktree even when merged + clean, and says when the hold lifts', async () => {
git.isBranchMergedInto.mockResolvedValue(true);
execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean
+ const before = Date.now();
const res = await cleanupMerged('/repo', 'main', [
{ branch: 'claim/issue-9999', worktreePath: '/repo/data/cos/worktrees/claim-issue-9999', worktreeAgeMs: 60 * 1000 } // 1 min old
]);
expect(res.cleaned).toEqual([]);
- expect(res.skipped).toEqual([{ branch: 'claim/issue-9999', reason: 'worktree-human-claim' }]);
+ expect(res.skipped).toHaveLength(1);
+ expect(res.skipped[0]).toMatchObject({ branch: 'claim/issue-9999', reason: 'worktree-human-claim' });
+ // The whole point of retryAt: the caller can park until the grace window
+ // lapses instead of sleeping to the next recheck. ~7 days minus 1 minute out.
+ const retryMs = Date.parse(res.skipped[0].retryAt);
+ expect(retryMs).toBeGreaterThan(before + 6.9 * 24 * 60 * 60 * 1000);
+ expect(retryMs).toBeLessThanOrEqual(Date.now() + 7 * 24 * 60 * 60 * 1000);
expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
expect(git.deleteBranch).not.toHaveBeenCalled();
});
+
+ it('omits retryAt for holds that do NOT lift on a clock', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ const res = await cleanupMerged('/repo', 'main', [
+ { branch: 'locked-b', worktreePath: '/wt/locked', worktreeLocked: true, worktreeAgeMs: 60 * 1000 },
+ { branch: 'active-b', worktreePath: '/repo/data/cos/worktrees/agent-abc12345', worktreeAgeMs: 60 * 1000 }
+ ], { activeAgentIds: new Set(['agent-abc12345']) });
+ // A lock and a running agent both end at a time nothing here can predict —
+ // inventing one would park the drain past a hold that may already be gone.
+ expect(res.skipped).toEqual([
+ { branch: 'locked-b', reason: 'worktree-locked' },
+ { branch: 'active-b', reason: 'worktree-active-agent' }
+ ]);
+ });
});
describe('worktreeProtectionReason', () => {
@@ -1424,3 +1445,105 @@ describe('orphaned remote branches', () => {
});
});
});
+
+describe('worktreeProtectionExpiresAt', () => {
+ const DAY = 24 * 60 * 60 * 1000;
+ const CLAIM = '/repo/data/cos/worktrees/claim-issue-42';
+ const at = (over = {}) => worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, ...over });
+
+ it('dates a claim hold to the end of its grace window', () => {
+ const before = Date.now();
+ const ms = Date.parse(at());
+ // 7-day default window, 2 days elapsed ⇒ ~5 days out.
+ expect(ms).toBeGreaterThanOrEqual(before + 5 * DAY);
+ expect(ms).toBeLessThanOrEqual(Date.now() + 5 * DAY);
+ });
+
+ it('returns null for holds nothing can schedule', () => {
+ // A locked or agent-owned tree lifts when a human or a process decides to,
+ // not on a clock — promising a time would be a guess.
+ expect(at({ locked: true })).toBeNull();
+ expect(worktreeProtectionExpiresAt({
+ path: '/repo/data/cos/worktrees/agent-abc12345', ageMs: 2 * DAY, activeAgentIds: new Set(['agent-abc12345'])
+ })).toBeNull();
+ expect(worktreeProtectionExpiresAt({ path: null, ageMs: 2 * DAY })).toBeNull();
+ });
+
+ it('returns null when the age is unknown rather than guessing one', () => {
+ // An unmeasured age must not date the window from zero — that would park a
+ // full window out on a tree that may already be reapable.
+ for (const ageMs of [null, undefined, NaN, 'old']) expect(at({ ageMs })).toBeNull();
+ });
+
+ it('returns null once the window has already lapsed', () => {
+ expect(at({ ageMs: 9 * DAY })).toBeNull();
+ });
+
+ it('gives no expiry to a claim worktree that is ALSO locked', () => {
+ // The reason slug says 'worktree-human-claim' (first match wins), but the
+ // lock outlives the grace window — deriving the date from the slug alone
+ // would promise a lift that never happens.
+ expect(worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, locked: true })).toBeNull();
+ });
+
+ it('gives no expiry to a non-claim worktree that is not held at all', () => {
+ expect(worktreeProtectionExpiresAt({ path: '/repo/data/cos/worktrees/agent-abc12345', ageMs: 2 * DAY, activeAgentIds: new Set() })).toBeNull();
+ });
+});
+
+describe('describeIdleReconcilePark', () => {
+ const CLAIM_HOLD = { branch: 'claim/issue-4348', reason: 'worktree-human-claim', retryAt: '2026-01-15T00:00:00.000Z' };
+
+ it('reports a quiet repo when nothing is held', () => {
+ expect(describeIdleReconcilePark([], [])).toEqual({
+ reason: 'no-in-flight-branches', heldBackMerged: [], counts: null, notLaterThan: null
+ });
+ expect(describeIdleReconcilePark()).toMatchObject({ reason: 'no-in-flight-branches' });
+ });
+
+ it('names merged branches held back, with the count and the earliest lift', () => {
+ // The regression this exists for: four merged claim branches queued behind a
+ // grace window used to persist as 'no-in-flight-branches' / zero counts, so
+ // the task read as idle — indistinguishable from not running at all.
+ const out = describeIdleReconcilePark([
+ CLAIM_HOLD,
+ { branch: 'claim/issue-4442', reason: 'worktree-human-claim', retryAt: '2026-01-13T00:00:00.000Z' }
+ ], []);
+ expect(out.reason).toBe('merged-branches-held-back');
+ expect(out.counts).toEqual({ heldBackMerged: 2 });
+ expect(out.notLaterThan).toBe('2026-01-13T00:00:00.000Z');
+ expect(out.heldBackMerged).toHaveLength(2);
+ });
+
+ it('live owners outrank a held-back merge — a running session is why it is idle', () => {
+ const out = describeIdleReconcilePark([CLAIM_HOLD], [{ branch: 'cos/x', liveOwnerReason: 'worktree-active-agent' }]);
+ expect(out.reason).toBe('branches-held-by-live-owners');
+ // The held-back set still travels, so the log/UI can name both.
+ expect(out.counts).toEqual({ heldBackMerged: 1 });
+ });
+
+ it('ignores skips that are not holds', () => {
+ // 'cleanup-disabled' (a toggle) and 'not-merged-on-recheck' (never eligible)
+ // are not pending work — counting them would invent a queue that does not exist.
+ const out = describeIdleReconcilePark([
+ { branch: 'a', reason: 'cleanup-disabled' },
+ { branch: 'b', reason: 'not-merged-on-recheck' },
+ { branch: 'c', reason: 'delete-failed: boom' }
+ ], []);
+ expect(out).toEqual({ reason: 'no-in-flight-branches', heldBackMerged: [], counts: null, notLaterThan: null });
+ });
+
+ it('ignores an unreadable retryAt rather than parking on NaN', () => {
+ const out = describeIdleReconcilePark([
+ { branch: 'a', reason: 'worktree-human-claim', retryAt: 'not-a-date' },
+ { branch: 'b', reason: 'worktree-human-claim', retryAt: '2026-01-14T00:00:00.000Z' }
+ ], []);
+ expect(out.notLaterThan).toBe('2026-01-14T00:00:00.000Z');
+ });
+
+ it('holds with no scheduled lift park on the normal cadence', () => {
+ const out = describeIdleReconcilePark([{ branch: 'a', reason: 'worktree-locked' }], []);
+ expect(out.reason).toBe('merged-branches-held-back');
+ expect(out.notLaterThan).toBeNull();
+ });
+});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index fd042cc3ce..c386ad27fe 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2571,7 +2571,7 @@ export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { s
*/
async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule) {
if (taskType !== 'branch-reconcile') return { skip: false, block: '' };
- const { reconcile, filterActionable, limitBranchesForAgent, formatInFlightForPrompt, actionableSignature } = await import('./branchReconcile.js');
+ const { reconcile, filterActionable, limitBranchesForAgent, formatInFlightForPrompt, actionableSignature, describeIdleReconcilePark } = await import('./branchReconcile.js');
const { formatSupersededForPrompt } = await import('./supersededLedger.js');
const { getActiveAgentIds } = await import('./agentState.js');
// Action toggles were merged (global → per-app override) + value-constrained
@@ -2630,14 +2630,14 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
// Definitive idle: nothing in-flight to drive. Park on the recheck cadence,
// 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 });
+ // "Held back" vs "quiet repo", plus the early-wake deadline — see describeIdleReconcilePark.
+ const { reason, heldBackMerged, counts, notLaterThan } = describeIdleReconcilePark(result.skipped || [], heldLive);
+ await taskSchedule.parkPerpetual(taskType, app.id, {
+ reason, actionableCount: 0, signature: null, counts, notLaterThan
+ });
// Surface merged branches held back by a protection guard so a lingering
// worktree isn't an invisible "cleaned 0".
- const heldSuffix = countSuffix(
- (result.skipped || []).filter((s) => s.reason?.startsWith('worktree-')),
- 'merged branch(es) held back', (s) => s.reason
- );
+ const heldSuffix = countSuffix(heldBackMerged, '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
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index aab5c5c8a5..08be7f315c 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -900,7 +900,7 @@ export async function updateTaskInterval(taskType, settings) {
const records = [exec, ...Object.values(exec.perApp || {})];
for (const rec of records) {
if (parkedUntilMs(rec) > nowMs) {
- rec.parkedUntil = await computePerpetualRecheckAt(merged);
+ rec.parkedUntil = boundParkedUntil(await computePerpetualRecheckAt(merged), rec.parkNotLaterThan);
}
}
}
@@ -990,6 +990,35 @@ export async function computePerpetualRecheckAt(interval, fromMs = Date.now()) {
return new Date(fromMs + ms).toISOString();
}
+/**
+ * Shorten a computed park so it cannot sleep past a moment the caller already
+ * KNOWS the situation changes on its own.
+ *
+ * The recheck cadence is a poll interval — the right default when nothing is
+ * known about *when* new work appears. But some parks wait on a deadline the
+ * detector can name: branch-reconcile holds a merged branch whose claim worktree
+ * is still inside its grace window, and that hold lifts at a computable instant.
+ * Parking past it compounds two waits (the grace window, then the next cron
+ * fire) into a stall several times longer than either — on a weekly recheck a
+ * 7-day hold becomes up to 14 days of a task that looks idle.
+ *
+ * Only ever SHORTENS: a bound that is unparseable, already elapsed, or later
+ * than the recheck is ignored, so a bad bound can never extend a park (nor spin
+ * one into a hot retry loop).
+ *
+ * @param {string} recheckAt - ISO timestamp from computePerpetualRecheckAt
+ * @param {string|null|undefined} notLaterThan - ISO instant the hold self-lifts
+ * @param {number} [nowMs]
+ * @returns {string} ISO timestamp
+ */
+export function boundParkedUntil(recheckAt, notLaterThan, nowMs = Date.now()) {
+ const bound = Date.parse(notLaterThan);
+ const recheck = Date.parse(recheckAt);
+ if (!Number.isFinite(bound) || !Number.isFinite(recheck)) return recheckAt;
+ if (bound <= nowMs || bound >= recheck) return recheckAt;
+ return new Date(bound).toISOString();
+}
+
/**
* Numeric ms of a record's perpetual park, or 0 when it carries none (or an
* unparseable timestamp). The single reader of `parkedUntil` — every park
@@ -1109,7 +1138,7 @@ function resolveExecutionRecord(schedule, taskType, appId = null) {
// Every field parkPerpetual stamps for a park. Kept as one list so the clear /
// reset paths can't drift from what park writes (adding a park field here is the
// single edit that keeps all three in sync).
-const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCounts', 'parkedAt'];
+const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCounts', 'parkNotLaterThan', 'parkedAt'];
/**
* Park a perpetual task: its work-detector reported nothing actionable, so stop
@@ -1123,6 +1152,10 @@ const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCo
* makes the NEXT fresh drain cap out early, which looks exactly like the task
* silently doing nothing.
*
+ * `notLaterThan` is an optional ISO instant at which the caller knows the hold
+ * lifts on its own; the park is shortened to it when that is sooner than the
+ * recheck cadence, and ignored otherwise.
+ *
* `dispatchCount` therefore DEFAULTS to 0: a park ends the drain window by
* definition, so zeroing the budget is the invariant, not an opt-in every caller
* has to remember. The churn detector's park in agentChurn.js relies on this
@@ -1132,10 +1165,13 @@ const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCo
* zeroing the counter there would reset the budget before every dispatch, so the
* cap could never fire.
*/
-export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, signature, dispatchCount = 0 } = {}) {
+export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, signature, dispatchCount = 0, notLaterThan = null } = {}) {
const schedule = await loadSchedule();
const interval = schedule.tasks[taskType] || {};
- const parkedUntil = await computePerpetualRecheckAt(interval);
+ // Bound HERE, not at the assignment: `parkedUntil` is also what the log line and
+ // the schedule:perpetual-parked event publish, and a change whose whole point is
+ // an honest "when will this actually run" must not report the un-shortened time.
+ const parkedUntil = boundParkedUntil(await computePerpetualRecheckAt(interval), notLaterThan);
const record = ensureExecutionRecord(schedule, taskType, appId);
record.parkedUntil = parkedUntil;
record.parkReason = reason;
@@ -1146,6 +1182,12 @@ export async function parkPerpetual(taskType, appId = null, { reason = null, act
// breakdown (e.g. the reconcile scans), so the field is left off the record.
if (counts != null) record.parkCounts = counts;
else delete record.parkCounts;
+ // The self-expiry has to OUTLIVE this call: updateTaskInterval restamps every
+ // un-elapsed park from the new cadence, and without a remembered bound it would
+ // stretch a correctly-shortened park back out — reintroducing the stacking this
+ // option exists to remove, via an unrelated settings edit.
+ if (notLaterThan) record.parkNotLaterThan = notLaterThan;
+ else delete record.parkNotLaterThan;
record.parkedAt = new Date().toISOString();
// A drain that parks because a full cycle made NO progress (branch-reconcile's
// 'no-progress' park) records the actionable signature it was stuck on, so the
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index db4dc8202d..ca25240b11 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -140,8 +140,10 @@ import {
MANAGED_AGENT_OPTIONS,
stripManagedAgentOptionsFromOverride,
TASK_TYPE_DESCRIPTIONS,
- REFERENCE_WATCH_AUDITED_VERSION
+ REFERENCE_WATCH_AUDITED_VERSION,
+ boundParkedUntil
} from './taskSchedule.js'
+import { cosEvents } from './cosEvents.js'
// Prompt getters moved to taskPromptService.js (issue #744 split, #1083 cycle
// break). taskSchedule.js re-exports the version constants but not the getters.
@@ -1762,6 +1764,78 @@ describe('taskSchedule', () => {
expect(await isPerpetualParkActive('unknown-type', 'app-parked')).toBe(false)
})
+ // branch-reconcile knows exactly when a claim worktree's grace window lapses.
+ // Sleeping past it stacked the hold and the recheck cadence into a stall
+ // several times longer than either — the shape that made a task with four
+ // stale claim branches queued behind it look like it had stopped running.
+ // (parseCronToNextRun is pinned off so the interval path is what runs; a
+ // sibling test leaves it returning a year-2999 date.)
+ it('parkPerpetual honours notLaterThan when the hold lifts before the recheck', async () => {
+ parseCronToNextRun.mockReturnValue(null)
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
+ const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ const record = await parkPerpetual('branch-reconcile', 'app-1', {
+ reason: 'merged-branches-held-back', actionableCount: 0, signature: null,
+ counts: { heldBackMerged: 4 }, notLaterThan: soon
+ })
+ expect(record.parkedUntil).toBe(soon)
+ expect(record.parkReason).toBe('merged-branches-held-back')
+ expect(record.parkCounts).toEqual({ heldBackMerged: 4 })
+ })
+
+ // The record, the log line and the schedule:perpetual-parked event all read
+ // from one value. Bounding only the record's copy would keep publishing the
+ // un-shortened time — a "parked until" the task no longer honours.
+ it('parkPerpetual publishes the SHORTENED time on the parked event, not the raw cadence', async () => {
+ parseCronToNextRun.mockReturnValue(null)
+ cosEvents.emit.mockClear()
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 7 * 24 * 3600000 } } })
+ const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ const record = await parkPerpetual('branch-reconcile', 'app-1', {
+ reason: 'merged-branches-held-back', actionableCount: 0, signature: null, notLaterThan: soon
+ })
+ const parked = cosEvents.emit.mock.calls.find(([name]) => name === 'schedule:perpetual-parked')
+ expect(parked?.[1].parkedUntil).toBe(soon)
+ expect(parked[1].parkedUntil).toBe(record.parkedUntil)
+ })
+
+ // A cadence edit restamps every un-elapsed park. Without the bound
+ // remembered ON the record, that edit stretches a correctly-shortened park
+ // back out — the stacking this option exists to remove, reintroduced by an
+ // unrelated settings change.
+ it('a shortened park survives a recheck-cadence edit', async () => {
+ parseCronToNextRun.mockReturnValue(null)
+ const soon = new Date(Date.now() + 60 * 60 * 1000).toISOString()
+ 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, parkedUntil: soon, parkNotLaterThan: soon, parkReason: 'merged-branches-held-back' }
+ } } }
+ })
+ await updateTaskInterval('branch-reconcile', { recheckIntervalMs: 30 * 24 * 3600000 })
+ const info = await getPerpetualParkInfo('branch-reconcile', 'app-1')
+ expect(info.parkedUntil).toBe(soon)
+ })
+
+ it('parkPerpetual drops parkNotLaterThan when no bound is given', async () => {
+ parseCronToNextRun.mockReturnValue(null)
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
+ expect(record.parkNotLaterThan).toBeUndefined()
+ })
+
+ it('parkPerpetual ignores a notLaterThan that is later than the recheck', async () => {
+ parseCronToNextRun.mockReturnValue(null)
+ mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
+ const far = new Date(Date.now() + 30 * 24 * 3600000).toISOString()
+ const record = await parkPerpetual('branch-reconcile', 'app-1', {
+ reason: 'merged-branches-held-back', actionableCount: 0, signature: null, notLaterThan: far
+ })
+ // The configured hourly cadence stands — a distant hold must not stretch it.
+ expect(Date.parse(record.parkedUntil)).toBeLessThanOrEqual(Date.now() + 3600000)
+ expect(Date.parse(record.parkedUntil)).toBeGreaterThan(Date.now())
+ })
+
it('parkPerpetual omits parkCounts when no breakdown is provided', async () => {
mockSchedule({ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } } })
const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })
@@ -2292,3 +2366,35 @@ describe('taskSchedule', () => {
})
})
})
+
+describe('boundParkedUntil', () => {
+ const NOW = Date.parse('2026-01-10T00:00:00.000Z')
+ const RECHECK = '2026-01-17T05:30:00.000Z' // a weekly cron fire
+
+ it('shortens a park to a hold that lifts before the next recheck', () => {
+ expect(boundParkedUntil(RECHECK, '2026-01-12T00:00:00.000Z', NOW)).toBe('2026-01-12T00:00:00.000Z')
+ })
+
+ it('keeps the recheck when the hold outlasts it', () => {
+ // The bound only ever shortens — a later deadline must not stretch the park
+ // past the cadence the user configured.
+ expect(boundParkedUntil(RECHECK, '2026-02-01T00:00:00.000Z', NOW)).toBe(RECHECK)
+ })
+
+ it('ignores a bound that is absent or unparseable', () => {
+ for (const bound of [null, undefined, '', 'soon', 42]) {
+ expect(boundParkedUntil(RECHECK, bound, NOW)).toBe(RECHECK)
+ }
+ })
+
+ it('ignores a bound that has already elapsed rather than parking in the past', () => {
+ // A stale bound must not collapse the park to "retry immediately" — that
+ // turns a converged drain into a hot loop against the same held branches.
+ expect(boundParkedUntil(RECHECK, '2026-01-09T00:00:00.000Z', NOW)).toBe(RECHECK)
+ expect(boundParkedUntil(RECHECK, new Date(NOW).toISOString(), NOW)).toBe(RECHECK)
+ })
+
+ it('returns the recheck unchanged when it is itself unparseable', () => {
+ expect(boundParkedUntil('never', '2026-01-12T00:00:00.000Z', NOW)).toBe('never')
+ })
+})