Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: advance reconciliation past blocked batches and report holds
atomantic3b7091683a80
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.jsindex f835920724..3e6ae5f986 100644--- a/client/src/hooks/useOnDemandTaskToast.js+++ b/client/src/hooks/useOnDemandTaskToast.js@@ -21,8 +21,10 @@ const PARK_REASON_LABELS = {'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',- 'drain-cap': 'paused after several back-to-back runs — the rest waits for the next scheduled check',+ 'branches-blocked': 'remaining branches or worktrees need attention',+ 'owner-state-unavailable': 'ownership state could not be read; reconciliation is paused to protect active work',+ 'no-progress': 'remaining items were attempted but did not advance',+ 'drain-cap': 'paused after reaching this run’s dispatch limit','no-detector': 'no work detector for this task'};@@ -128,7 +130,16 @@ export function useOnDemandTaskToast() {// 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) {+ if (c && (c.heldBranches > 0 || c.heldDetached > 0)) {+ const parts = [];+ if (c.heldBranches) parts.push(`${c.heldBranches} branch(es) held`);+ if (c.heldDetached) parts.push(`${c.heldDetached} detached worktree(s) held`);+ if (c.unchangedBranches) parts.push(`${c.unchangedBranches} branch(es) still blocked`);+ const causes = formatSkipCauses(data?.skipCauses);+ countSuffix = ` (${parts.join(', ')}${causes ? ` — ${causes}` : ''})`;+ } else if (c?.unchangedBranches > 0) {+ countSuffix = ` (${c.unchangedBranches} branch(es) still blocked)`;+ } else 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 = [];@@ -145,8 +156,8 @@ export function useOnDemandTaskToast() {countSuffix = ` (0 of ${c.open} open${detail})`;}- const recheckSuffix = data?.parkedUntil- ? ` Next auto-recheck ${timeUntil(data.parkedUntil, 'soon')}.`+ const recheckSuffix = data?.nextAutoRecheckAt+ ? ` Next auto-recheck ${timeUntil(data.nextAutoRecheckAt, 'soon')}.`: '';// Re-checked live on this trigger — say so, since the confusing case is adiff --git a/client/src/hooks/useOnDemandTaskToast.test.jsx b/client/src/hooks/useOnDemandTaskToast.test.jsxindex 63016109c4..61141527dd 100644--- a/client/src/hooks/useOnDemandTaskToast.test.jsx+++ b/client/src/hooks/useOnDemandTaskToast.test.jsx@@ -105,6 +105,24 @@ describe('useOnDemandTaskToast — parked outcome', () => {beforeEach(() => { handlers.clear(); toastSpy.mockClear(); });afterEach(cleanup);+ it.each([undefined, null])('never promises an automatic retry from a park deadline alone (%s)', nextAutoRecheckAt => {+ renderHook(() => useOnDemandTaskToast());+ fire({ taskType: 'branch-reconcile', outcome: 'parked', parkReason: 'no-progress', counts: { unchangedBranches: 4 }, parkedUntil: '2999-01-01T00:00:00Z', nextAutoRecheckAt });+ expect(toastSpy.mock.calls[0][0]).not.toMatch(/auto-recheck|already up to date/);+ expect(toastSpy.mock.calls[0][0]).toMatch(/did not advance.*4 branch\(es\) still blocked/);+ });++ it('shows typed branch holds and an automatic retry only when the server confirms eligibility', () => {+ renderHook(() => useOnDemandTaskToast());+ fire({ taskType: 'branch-reconcile', outcome: 'parked', parkReason: 'branches-blocked',+ counts: { heldBranches: 2, heldDetached: 1, unchangedBranches: 4 }, skipCauses: { 'draft-review-required': 1, 'claim-owner-active': 1, 'worktree-locked': 1 },+ nextAutoRecheckAt: '2999-01-01T00:00:00Z' });+ const message = toastSpy.mock.calls[0][0];+ expect(message).toMatch(/2 branch\(es\) held, 1 detached worktree\(s\) held, 4 branch\(es\) still blocked/);+ expect(message).toMatch(/draft-review-required/);+ expect(message).toMatch(/Next auto-recheck/);+ });+it('renders a bare "no open issues" when the repo is genuinely empty', () => {renderHook(() => useOnDemandTaskToast());fire({diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 7c7f71682a..c0715a499f 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -999,35 +999,47 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId}/**- * 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}}+ * Summarize every surviving hold when reconciliation has nothing dispatchable.+ * Persist counts and typed causes, with the earliest known hold expiry as the+ * next possible wake-up; raw cleanup diagnostics stay out of scheduler state.*/-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.detached && 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';+export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [], detachedWorktrees = [], superseded = [], gated = [] } = {}) {+ // One entry per surviving branch/checkout, even when it appears in both the+ // skipped and detached/superseded projections. Never persist raw error text.+ const holds = new Map();+ const lifts = [];+ const add = (entry, rawCause) => {+ const cause = String(rawCause).split(':', 1)[0];+ holds.set(entry.branch || entry.path, { ...entry, cause: /^[a-z]+(?:-[a-z]+)*$/.test(cause) ? cause : 'cleanup-failed' });+ for (const deadline of [entry.retryAt, entry.holdRetryAt]) {+ const timestamp = Date.parse(deadline);+ if (Number.isFinite(timestamp)) lifts.push(timestamp);+ }+ };+ for (const entry of skipped) {+ if (entry.reason === 'not-merged-on-recheck') continue;+ const cause = entry.reason?.startsWith('delete-failed') ? 'branch-delete-failed' : entry.reason || 'cleanup-failed';+ add(entry, cause);+ }+ for (const entry of detachedWorktrees) add(entry, entry.reason || 'detached-worktree-held');+ for (const entry of superseded) add(entry, entry.holdReason || 'superseded-branch-held');+ for (const entry of wip) add(entry, entry.openPr?.isDraft ? 'draft-review-required' : entry.liveOwnerReason || entry.completionPolicyReason || 'unfinished-work');+ for (const entry of heldLive) if (!holds.has(entry.branch || entry.path)) add(entry, entry.liveOwnerReason || 'live-owner');+ for (const entry of gated) add(entry, entry.openPr?.isDraft ? 'draft-review-required' : 'action-disabled');+ const entries = [...holds.values()];+ const heldBackMerged = skipped.filter(s => !s.detached && s.reason?.startsWith('worktree-'));+ const skipCauses = {};+ for (const entry of entries) skipCauses[entry.cause] = (Object.hasOwn(skipCauses, entry.cause) ? skipCauses[entry.cause] : 0) + 1;+ const counts = entries.length ? {+ heldBranches: entries.filter(entry => !entry.detached && entry.branch).length,+ heldDetached: entries.filter(entry => entry.detached || !entry.branch).length,+ ...(heldBackMerged.length ? { heldBackMerged: heldBackMerged.length } : {})+ } : null;+ const reason = !entries.length ? 'no-in-flight-branches'+ : heldLive.length ? 'branches-held-by-live-owners'+ : heldBackMerged.length === entries.length ? 'merged-branches-held-back' : 'branches-blocked';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.+ reason, heldBackMerged, counts, skipCauses: entries.length ? skipCauses : null,notLaterThan: lifts.length ? new Date(Math.min(...lifts)).toISOString() : null};}@@ -1832,7 +1844,7 @@ export function desiredEndState(state, actions, { prNumber, worktreePath, collis*/export function actionableSignature(actionable) {return actionable- .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}`)+ .map((b) => `${b.branch}:${b.state}:${b.openPr?.number ?? 'none'}${b.tip ? `:${b.tip}` : ''}`).sort().join('|');}diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 0d1d7b2c15..5b66f9dc08 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -2625,7 +2625,7 @@ describe('describeIdleReconcilePark', () => {it('reports a quiet repo when nothing is held', () => {expect(describeIdleReconcilePark([], [])).toEqual({- reason: 'no-in-flight-branches', heldBackMerged: [], counts: null, notLaterThan: null+ reason: 'no-in-flight-branches', heldBackMerged: [], counts: null, skipCauses: null, notLaterThan: null});expect(describeIdleReconcilePark()).toMatchObject({ reason: 'no-in-flight-branches' });});@@ -2639,7 +2639,7 @@ describe('describeIdleReconcilePark', () => {{ 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.counts).toEqual({ heldBackMerged: 2, heldBranches: 2, heldDetached: 0 });expect(out.notLaterThan).toBe('2026-01-13T00:00:00.000Z');expect(out.heldBackMerged).toHaveLength(2);});@@ -2648,18 +2648,18 @@ describe('describeIdleReconcilePark', () => {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 });+ expect(out.counts).toEqual({ heldBackMerged: 1, heldBranches: 2, heldDetached: 0 });});- 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.+ it('reports disabled cleanup and deletion failure as blockers', () => {+ // A branch no longer merged is reclassified next pass. Disabled cleanup+ // and a failed deletion still leave concrete work that must remain visible.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 });+ expect(out).toEqual({ reason: 'branches-blocked', heldBackMerged: [], counts: { heldBranches: 2, heldDetached: 0 }, skipCauses: { 'cleanup-disabled': 1, 'branch-delete-failed': 1 }, notLaterThan: null });});it('ignores an unreadable retryAt rather than parking on NaN', () => {diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex f6a21e98ed..aef296166c 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2072,6 +2072,14 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, t});}+ // A park is a drain brake, not a promise of another automatic run. Read the+ // actual eligibility, including per-app cadence/enablement and manual-only+ // drains, rather than interpreting the stored park deadline as a schedule.+ const readiness = parkInfo+ ? await taskScheduleMod.shouldRunTask(request.taskType, appId).catch(() => null)+ : null;+ const nextAutoRecheckAt = readiness?.nextRunAt || (readiness?.shouldRun ? new Date().toISOString() : null);+cosEvents.emit('schedule:on-demand-empty', {requestId: request.id,taskType: request.taskType,@@ -2082,6 +2090,7 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, tforge,parkReason: parkInfo?.parkReason || null,parkedUntil: parkInfo?.parkedUntil || null,+ nextAutoRecheckAt,actionableCount: parkInfo?.parkActionableCount ?? null,counts: parkInfo?.parkCounts || null,skipCauses: parkInfo?.parkSkipCauses || nulldiff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 6ba349b018..acbc485e6d 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -1110,6 +1110,30 @@ describe('emitOnDemandEmpty', () => {expect(events[0]).toMatchObject({ taskType: 'pr-watcher', outcome: 'idle', reason: null });});+ it.each([+ ['manual', { shouldRun: false, reason: 'on-demand-only' }, null],+ ['disabled app', { shouldRun: false, reason: 'disabled-for-app' }, null],+ ['disabled task', { shouldRun: false, reason: 'disabled' }, null],+ ['app cron', { shouldRun: false, reason: 'cron-cooldown', nextRunAt: '2999-01-02T00:00:00Z' }, '2999-01-02T00:00:00Z'],+ ])('emits only the actual automatic retry for %s', async (_name, readiness, expected) => {+ const events = [];+ const handler = event => events.push(event);+ cosEvents.on('schedule:on-demand-empty', handler);+ const shouldRunTask = vi.fn(async () => readiness);+ try {+ await emitOnDemandEmpty({+ taskScheduleMod: { ...stubMod, shouldRunTask,+ getPerpetualParkInfo: async () => ({ parkedUntil: '2999-01-01T00:00:00Z', parkReason: 'branches-blocked', parkCounts: { heldDetached: 1 }, parkSkipCauses: { 'worktree-locked': 1 } }) },+ request: { id: 'retry-test', taskType: 'branch-reconcile' },+ targetApp: { id: 'app-1', name: 'Example App' },+ taskConfig: { enabled: true, type: 'on-demand', perpetual: false }+ });+ } finally { cosEvents.off('schedule:on-demand-empty', handler); }+ expect(shouldRunTask).toHaveBeenCalledWith('branch-reconcile', 'app-1');+ expect(events[0]).toMatchObject({ outcome: 'parked', nextAutoRecheckAt: expected,+ counts: { heldDetached: 1 }, skipCauses: { 'worktree-locked': 1 } });+ });+// Default: gh is healthy, so no test inherits a previous one's stubbed fault.beforeEach(() => {ghHealth.mockReset();diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.jsindex 2704007c38..c72baa6de1 100644--- a/server/services/cosTaskPreStepBlocks.compose.test.js+++ b/server/services/cosTaskPreStepBlocks.compose.test.js@@ -97,6 +97,8 @@ vi.mock('./cos.js', () => ({import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js';import { getAgents } from './cos.js';+import { getTaskInterval } from './taskSchedule.js';+import { applyPerpetualDrainCap } from './cosTaskPreStepBlocks.js';const APP = { id: 'app-1', name: 'Example App', repoPath: '/tmp/example-repo' };const STATE = { config: { confidenceAutoApproval: { enabled: false }, idleReviewPriority: 'MEDIUM' } };@@ -117,9 +119,12 @@ const generate = () =>describe('generateManagedAppImprovementTaskForType composes the extracted pre-step layer', () => {beforeEach(() => {vi.clearAllMocks();+ parkPerpetual.mockReset().mockResolvedValue();+ recordPerpetualDispatch.mockReset().mockResolvedValue(1);getAgents.mockResolvedValue([]);getPerpetualDrainState.mockResolvedValue({ signature: null, dispatchCount: 0 });reconcileMock.mockResolvedValue(scan());+ getTaskInterval.mockResolvedValue({ type: 'on-demand', perpetual: true, drainDispatchCap: 5, taskMetadata: { branchesPerAgent: 3 } });});it('folds the reconcile pre-step block into the prompt via {inFlightBranches}', async () => {@@ -160,5 +165,87 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-stexpect(await generate()).toBeNull();expect(reconcileMock).not.toHaveBeenCalled();+ expect(parkPerpetual).toHaveBeenCalledWith('branch-reconcile', APP.id, { reason: 'owner-state-unavailable' });+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();});+ it('reaches later branches across a cap and manual retry, then parks the exhausted sweep', async () => {+ const branches = ['__proto__', 'b', 'c', 'd'].map(name => ({ branch: name === '__proto__' ? name : `fix/${name}`, state: 'IN_REVIEW', tip: 'head-1', openPr: { number: 1 } }));+ let persisted = { signature: null, dispatchCount: 0 };+ getPerpetualDrainState.mockImplementation(async () => JSON.parse(JSON.stringify(persisted)));+ recordPerpetualDispatch.mockImplementation(async (_type, _app, signature, { branchAttempts }) => {+ persisted = { signature, dispatchCount: persisted.dispatchCount + 1, branchAttempts };+ });+ parkPerpetual.mockImplementation(async (_type, _app, { branchAttempts }) => {+ persisted = { ...persisted, signature: null, dispatchCount: 0 };+ if (branchAttempts === null) delete persisted.branchAttempts;+ });+ reconcileMock.mockResolvedValue(scan({ inFlight: branches,+ wip: [{ branch: 'fix/draft', openPr: { isDraft: true } }],+ detachedWorktrees: [{ path: '/scratch/checkout', reason: 'worktree-locked' }]+ }));++ const first = await generate();+ expect(first.description).toContain('__proto__');+ expect(first.description).toContain('fix/c');+ expect(first.description).not.toContain('fix/d');+ // The same persisted attempt map survives the real cap gate. Manual reset+ // also retains it (taskSchedule's persistence regression covers that write).+ expect(await applyPerpetualDrainCap(APP, 'branch-reconcile', { perpetual: true, drainDispatchCap: 1 }, {+ getPerpetualDrainState, parkPerpetual+ })).toEqual({ skip: true });+ const second = await generate();+ expect(second.description).toContain('fix/d');+ expect(second.description).not.toContain('__proto__');+ expect(await generate()).toBeNull();+ expect(parkPerpetual).toHaveBeenLastCalledWith('branch-reconcile', APP.id, expect.objectContaining({+ reason: 'no-progress', actionableCount: 4, branchAttempts: null,+ counts: { unchangedBranches: 4, heldBranches: 1, heldDetached: 1 },+ skipCauses: { 'unchanged-after-attempt': 4, 'draft-review-required': 1, 'worktree-locked': 1 }+ }));+ expect(recordPerpetualDispatch).toHaveBeenCalledTimes(2);+ });++ it('retries a changed revision without retrying an unchanged blocked prefix', async () => {+ getPerpetualDrainState.mockResolvedValue({+ signature: 'fix/a:IN_REVIEW:1:old-head', dispatchCount: 1,+ branchAttempts: { 'fix/a': 'fix/a:IN_REVIEW:1:old-head', 'fix/b': 'fix/b:IN_REVIEW:2:same-head', removed: 'stale' }+ });+ reconcileMock.mockResolvedValue(scan({ inFlight: [+ { branch: 'fix/a', state: 'IN_REVIEW', openPr: { number: 1 }, tip: 'new-head' },+ { branch: 'fix/b', state: 'IN_REVIEW', openPr: { number: 2 }, tip: 'same-head' }+ ] }));+ const task = await generate();+ expect(task.description).toContain('fix/a');+ expect(task.description).not.toContain('fix/b');+ expect(recordPerpetualDispatch).toHaveBeenLastCalledWith('branch-reconcile', APP.id, expect.stringContaining('new-head'), {+ branchAttempts: { 'fix/a': 'fix/a:IN_REVIEW:1:new-head', 'fix/b': 'fix/b:IN_REVIEW:2:same-head' }+ });+ });++ it('parks typed draft, owner, detached and cleanup blockers without treating them as an empty repo', async () => {+ reconcileMock.mockResolvedValue(scan({ inFlight: [],+ wip: [+ { branch: 'fix/draft', openPr: { isDraft: true } },+ { branch: 'fix/handoff', completionPolicyReason: 'human-handoff' },+ { branch: 'fix/policy', completionPolicyReason: 'policy-unavailable' }+ ],+ skipped: [+ { branch: 'fix/owned', reason: 'claim-owner-active' },+ { branch: 'fix/delete', reason: 'delete-failed: private diagnostic' },+ { branch: 'fix/backup', reason: 'backup-failed: /private/diagnostic', retryAt: '2030-01-02T00:00:00Z' },+ { path: '/scratch/checkout', detached: true, reason: 'worktree-locked' }+ ],+ detachedWorktrees: [{ path: '/scratch/checkout', reason: 'worktree-locked' }],+ superseded: [{ branch: 'fix/backup', holdReason: 'backup-failed: /private/diagnostic', holdRetryAt: '2030-01-01T00:00:00Z' }]+ }));+ expect(await generate()).toBeNull();+ expect(parkPerpetual).toHaveBeenCalledWith('branch-reconcile', APP.id, expect.objectContaining({+ reason: 'branches-blocked', counts: { heldBranches: 6, heldDetached: 1 },+ notLaterThan: '2030-01-01T00:00:00.000Z',+ skipCauses: { 'draft-review-required': 1, 'claim-owner-active': 1, 'branch-delete-failed': 1, 'worktree-locked': 1, 'backup-failed': 1, 'human-handoff': 1, 'policy-unavailable': 1 }+ }));+ expect(JSON.stringify(parkPerpetual.mock.calls)).not.toContain('/private/diagnostic');+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();+ });+});diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex ff192781e0..4e34236c27 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -393,7 +393,7 @@ const countSuffix = (items, noun, describe) => {* `label` prefixes the log lines (emoji + type); `unit` names the items ("branch(es)").* @returns {Promise<boolean>} true to dispatch; false when the drain was parked*/-export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { signature, actionableCount, label, unit }) {+export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { signature, actionableCount, label, unit, branchAttempts }) {const { signature: lastSignature } = await taskSchedule.getPerpetualDrainState(taskType, app.id);if (signature === lastSignature) {// The park fields, the cleared signature, and the zeroed dispatch budget land@@ -406,7 +406,7 @@ export async function resolveReconcileDrainGate(taskSchedule, taskType, app, { s// 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);+ await taskSchedule.recordPerpetualDispatch(taskType, app.id, signature, ...(branchAttempts ? [{ branchAttempts }] : []));return true;}@@ -429,7 +429,10 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSemitLog('warn', `branch-reconcile skipped for ${app.name}: active agent state unreadable (${err.message})`, { appId: app.id, analysisType: taskType });return null;});- if (!Array.isArray(liveAgents)) return { skip: true };+ if (!Array.isArray(liveAgents)) {+ await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'owner-state-unavailable' });+ return { skip: true };+ }// Claim worktrees use a branch-shaped directory name, not the `agent-*` id// stored on the run, so the live records' workspace basenames join the// ownership set — and a run that cut its own claim tree keeps the source repo@@ -498,15 +501,18 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS// A detached worktree has no branch to list anywhere else, so name it here too.const detachedSuffix = countSuffix(result.detachedWorktrees, 'detached worktree(s) held back', (d) => d.reason);const allActionable = filterActionable(result.inFlight, actions);- const actionable = limitBranchesForAgent(allActionable, metadata.branchesPerAgent);+ const idlePark = describeIdleReconcilePark(result.skipped || [], heldLive, {+ wip: result.wip, detachedWorktrees: result.detachedWorktrees, superseded: result.superseded,+ gated: result.inFlight.filter(branch => !allActionable.includes(branch))+ });if (allActionable.length === 0) {// 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.// "Held back" vs "quiet repo", plus the early-wake deadline — see describeIdleReconcilePark.- const { reason, heldBackMerged, counts, notLaterThan } = describeIdleReconcilePark(result.skipped || [], heldLive);+ const { reason, heldBackMerged, counts, skipCauses, notLaterThan } = idlePark;await taskSchedule.parkPerpetual(taskType, app.id, {- reason, actionableCount: 0, signature: null, counts, notLaterThan+ reason, actionableCount: 0, signature: null, branchAttempts: null, counts, skipCauses, notLaterThan});// Surface merged branches held back by a protection guard so a lingering// worktree isn't an invisible "cleaned 0".@@ -519,13 +525,37 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskSemitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing actionable (cleaned ${result.cleaned.length}${heldSuffix}${gatedSuffix}${heldLiveSuffix}${supersededSuffix}${detachedSuffix})`, { appId: app.id });return { skip: true };}+ // Retain attempted revisions across caps/manual retries. A blocked prefix must+ // not monopolize every window; changed revisions are eligible again, and old+ // entries disappear with their branches. The full-set park ends this sweep.+ const drain = await taskSchedule.getPerpetualDrainState(taskType, app.id);+ const branchAttempts = Object.create(null);+ for (const branch of allActionable) {+ const signature = actionableSignature([branch]);+ if (drain.branchAttempts?.[branch.branch] === signature) branchAttempts[branch.branch] = signature;+ }+ const actionable = limitBranchesForAgent(+ allActionable.filter(b => !Object.hasOwn(branchAttempts, b.branch)), metadata.branchesPerAgent+ );+ if (!actionable.length) {+ await taskSchedule.parkPerpetual(taskType, app.id, {+ reason: 'no-progress', actionableCount: allActionable.length, signature: null, branchAttempts: null,+ counts: { ...idlePark.counts, unchangedBranches: allActionable.length },+ skipCauses: { ...idlePark.skipCauses, 'unchanged-after-attempt': allActionable.length },+ notLaterThan: idlePark.notLaterThan+ });+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: all ${allActionable.length} branch(es) were attempted without further progress`, { appId: app.id });+ return { skip: true };+ }+ for (const branch of actionable) branchAttempts[branch.branch] = actionableSignature([branch]);// Convergence guards — no-progress, then the consecutive-dispatch cap. See// resolveReconcileDrainGate for why one brake isn't enough.const dispatch = await resolveReconcileDrainGate(taskSchedule, taskType, app, {signature: actionableSignature(actionable),actionableCount: actionable.length,label: '🔀 branch-reconcile',- unit: 'branch(es)'+ unit: 'branch(es)',+ branchAttempts});if (!dispatch) return { skip: true };metadata.perpetual = true;diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 09d229066a..0bb89a25dc 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -553,7 +553,7 @@ 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, skipCauses = null, signature, dispatchCount = 0, notLaterThan = null } = {}) {+export async function parkPerpetual(taskType, appId = null, { reason = null, actionableCount = 0, counts = null, skipCauses = null, signature, dispatchCount = 0, notLaterThan = null, branchAttempts } = {}) {const { record, parkedUntil } = await updateSchedule(async (schedule) => {const interval = schedule.tasks[taskType] || {};// Bound HERE, not at the assignment: `parkedUntil` is also what the log line and@@ -563,6 +563,8 @@ export async function parkPerpetual(taskType, appId = null, { reason = null, actconst record = ensureExecutionRecord(schedule, taskType, appId);record.parkedUntil = parkedUntil;record.parkReason = reason;+ if (branchAttempts === null) delete record.branchReconcileAttempts;+ else if (branchAttempts !== undefined) record.branchReconcileAttempts = branchAttempts;record.parkActionableCount = actionableCount;// The detector's candidate breakdown ({ open, inFlight, filtered }). Lets the// UI explain WHY a non-empty queue yields zero claimable work — "0 of N, M@@ -718,7 +720,8 @@ export async function getPerpetualDrainState(taskType, appId = null) {const record = resolveExecutionRecord(schedule, taskType, appId);return {signature: record?.lastActionableSignature ?? null,- dispatchCount: record?.perpetualDispatchCount || 0+ dispatchCount: record?.perpetualDispatchCount || 0,+ ...(record?.branchReconcileAttempts && { branchAttempts: record.branchReconcileAttempts })};}@@ -729,10 +732,11 @@ export async function getPerpetualDrainState(taskType, appId = null) {* a single read-modify-write, so the three facts can never land apart.* @returns {Promise<number>} the new consecutive-dispatch count*/-export async function recordPerpetualDispatch(taskType, appId = null, signature) {+export async function recordPerpetualDispatch(taskType, appId = null, signature, { branchAttempts } = {}) {return updateSchedule(async (schedule) => {const record = ensureExecutionRecord(schedule, taskType, appId);for (const field of PARK_FIELDS) delete record[field];+ if (branchAttempts !== undefined) record.branchReconcileAttempts = branchAttempts;// Mirrors parkPerpetual's signature handling, including the churn detector's// `signatureRepeatCount`. A dispatch only happens when the set CHANGED (an// unchanged one parks instead), so this is always the "new signature ⇒ first@@ -761,6 +765,9 @@ export async function recordPerpetualDispatch(taskType, appId = null, signature)* branch-reconcile/issue-reconcile would re-park `no-progress` against an* unchanged-since-last-run set even though the user explicitly asked to re-drive.*+ * Branch-reconcile retains its attempted revisions: a manual retry must reach+ * the remaining branches before starting another sweep of the blocked prefix.+ ** ONLY a human asking for a re-run may call this. An automated re-issue that* borrows the on-demand lane (the perpetual drain's own completion refill) must* NOT: clearing the convergence signature and the dispatch counter is preciselydiff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex f4ea08c9a3..bea12fc71d 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -238,6 +238,7 @@ describe('taskSchedule', () => {isInstanceFeatureEnabled.mockResolvedValue(true)// Default: no saved schedule → use defaultsreadJSONFile.mockResolvedValue(null)+ writeFile.mockResolvedValue(undefined)})// Cases that freeze the clock restore it here, so a failed assertion inside a@@ -3070,6 +3071,38 @@ describe('taskSchedule', () => {expect(Date.parse(record.parkedUntil)).toBeGreaterThan(Date.now())})+ it('derives retry eligibility from the app cadence and enabled switches, not a stale park', async () => {+ const future = new Date(Date.now() + 3_600_000).toISOString();+ const task = { type: 'on-demand', perpetual: false, autoStart: false, enabled: true };+ const execution = { perApp: { 'app-1': { parkedUntil: future } } };+ mockSchedule({ tasks: { 'branch-reconcile': task }, executions: { 'task:branch-reconcile': execution } });+ expect(await shouldRunTask('branch-reconcile', 'app-1')).toMatchObject({ shouldRun: false, reason: 'on-demand-only' });+ getAppTaskTypeInterval.mockResolvedValueOnce('0 3 * * *');+ parseCronToNextRun.mockReturnValueOnce(new Date(future));+ expect(await shouldRunTask('branch-reconcile', 'app-1')).toMatchObject({ shouldRun: false, reason: 'cron-cooldown', nextRunAt: future });+ isTaskTypeEnabledForApp.mockResolvedValue(false);+ expect(await shouldRunTask('branch-reconcile', 'app-1')).toEqual({ shouldRun: false, reason: 'disabled-for-app' });+ isTaskTypeEnabledForApp.mockResolvedValue(true);+ mockSchedule({ tasks: { 'branch-reconcile': { ...task, enabled: false } }, executions: { 'task:branch-reconcile': execution } });+ expect(await shouldRunTask('branch-reconcile', 'app-1')).toEqual({ shouldRun: false, reason: 'disabled' });+ });++ it('persists branch attempts through cap parks and manual resets, clearing only on sweep exhaustion', async () => {+ let saved = { version: 2, tasks: { 'branch-reconcile': { enabled: true, type: 'on-demand', perpetual: true } }, executions: {}, templates: [] };+ readJSONFile.mockImplementation(async () => JSON.parse(JSON.stringify(saved)));+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });+ const branchAttempts = { 'fix/first': 'fix/first:IN_REVIEW:1:head' };+ await recordPerpetualDispatch('branch-reconcile', 'app-1', 'batch', { branchAttempts });+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'drain-cap', signature: null });+ await resetPerpetualForManualRun('branch-reconcile', 'app-1');+ expect(await getPerpetualDrainState('branch-reconcile', 'app-1')).toEqual({ signature: null, dispatchCount: 0, branchAttempts });+ const counts = { heldBranches: 2, heldDetached: 1 };+ const skipCauses = { 'draft-review-required': 1, 'claim-owner-active': 1, 'worktree-locked': 1 };+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'branches-blocked', counts, skipCauses, branchAttempts: null });+ expect((await getPerpetualDrainState('branch-reconcile', 'app-1')).branchAttempts).toBeUndefined();+ expect(await getPerpetualParkInfo('branch-reconcile', 'app-1')).toMatchObject({ parkReason: 'branches-blocked', parkCounts: counts, parkSkipCauses: skipCauses });+ });+it('parkPerpetual omits parkCounts when no breakdown is provided', async () => {mockSchedule({ tasks: { 'branch-reconcile': { type: 'on-demand', perpetual: true, enabled: true, recheckIntervalMs: 3600000 } } })const record = await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches', actionableCount: 0, signature: null })