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

feat: unify branch cleanup with reconciliation

[._.]/ Adam Eivy042c67bad703
diff --git a/.changelog/next/changed-agent-78048091.md b/.changelog/next/changed-agent-78048091.md
new file mode 100644
index 0000000000..e60324e804
--- /dev/null
+++ b/.changelog/next/changed-agent-78048091.md
@@ -0,0 +1 @@
+- Branch reconciliation now cleans merged worktrees first, limits each coordinator to a configured branch batch, and absorbs the legacy branch-cleanup schedule.
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index 309fba05d4..c120a0a650 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -308,6 +308,17 @@ export const SWARM_COUNT_OPTIONS = [
{ value: 6, label: '6 in parallel', description: 'Claim and ship up to 6 independent issues per run, merges serialized' }
];
+// branch-reconcile coordinator batch size (taskMetadata.branchesPerAgent).
+// Keep this separate from claim-issue's swarm controls: one coordinator gets a
+// prioritized branch batch, while issue claiming fans out one agent per issue.
+export const BRANCHES_PER_AGENT_DEFAULT = 3;
+export const BRANCHES_PER_AGENT_TASK_TYPES = new Set(['branch-reconcile']);
+export const BRANCHES_PER_AGENT_OPTIONS = [1, 2, 3, 4, 5, 6].map((value) => ({
+ value,
+ label: `${value} branch${value === 1 ? '' : 'es'} per agent`,
+ description: `Give each branch-reconcile coordinator up to ${value} prioritized branch${value === 1 ? '' : 'es'} per run`
+}));
+
export const DEFAULT_REVIEWER = 'copilot';
export const DEFAULT_REVIEWERS = ['copilot'];
diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
index 1d12506640..935bf7dd3b 100644
--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
@@ -1,7 +1,7 @@
import { useState, memo } from 'react';
import AppIcon from '../../../AppIcon';
import CronInput from '../../../CronInput';
-import { AGENT_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES, PR_COMPLETION_OPTIONS, pinnedPrCompletion, prCompletionOption, SWARM_COUNT_OPTIONS, SWARM_TASK_TYPES, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';
+import { AGENT_OPTIONS, BRANCHES_PER_AGENT_DEFAULT, BRANCHES_PER_AGENT_OPTIONS, BRANCHES_PER_AGENT_TASK_TYPES, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES, PR_COMPLETION_OPTIONS, pinnedPrCompletion, prCompletionOption, SWARM_COUNT_OPTIONS, SWARM_TASK_TYPES, toggleAppMetadataOverride, agentOptionButtonClass } from '../../constants';
import { isCronExpression, describeCron } from '../../../../utils/cronHelpers';
import ToggleSwitch from '../../../ToggleSwitch';
import { INTERVAL_LABELS, setMetadataOverride } from './scheduleConstants';
@@ -62,6 +62,7 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
// on) and 2..6; only 1 / out-of-range / non-integer are dropped. Inherit is
// the absent key, distinct from a stored 0.
const handleSwarmCountChange = (raw) => handleOverrideChange('swarmCount', raw === '' ? '' : Number(raw));
+ const handleBranchesPerAgentChange = (raw) => handleOverrideChange('branchesPerAgent', raw === '' ? '' : Number(raw));
return (
<div className="flex flex-col sm:flex-row sm:flex-wrap sm:items-center gap-2 sm:gap-3 py-2 px-3 rounded hover:bg-port-card/30">
@@ -186,6 +187,22 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
</select>
)}
+ {BRANCHES_PER_AGENT_TASK_TYPES.has(taskType) && (
+ <select
+ value={override?.taskMetadata?.branchesPerAgent ?? ''}
+ onChange={(e) => handleBranchesPerAgentChange(e.target.value)}
+ disabled={updating}
+ aria-label={`Branches per agent for ${app.name}`}
+ title="How many prioritized branches this app's coordinator receives per run"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white min-w-[120px] min-h-[40px]"
+ >
+ <option value="">Inherit ({BRANCHES_PER_AGENT_OPTIONS.find(o => o.value === (globalTaskMetadata?.branchesPerAgent || BRANCHES_PER_AGENT_DEFAULT))?.label})</option>
+ {BRANCHES_PER_AGENT_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ )}
+
<div className="hidden sm:block">
<ToggleSwitch
enabled={isEnabled}
diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx
index 5cdd11f0b5..2f0cab909c 100644
--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx
+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.test.jsx
@@ -5,11 +5,11 @@ import AppOverrideRow from './AppOverrideRow';
const APP = { id: 'app-1', name: 'Acme' };
-function renderRow({ globalTaskMetadata = {}, override = null, onUpdate = vi.fn().mockResolvedValue(undefined) } = {}) {
+function renderRow({ globalTaskMetadata = {}, override = null, onUpdate = vi.fn().mockResolvedValue(undefined), taskType = 'feature-ideas' } = {}) {
render(
<AppOverrideRow
app={APP}
- taskType="feature-ideas"
+ taskType={taskType}
globalIntervalType="daily"
globalTaskMetadata={globalTaskMetadata}
managedAgentOptions={[]}
@@ -70,3 +70,17 @@ describe('AppOverrideRow — After opening PR override', () => {
expect(onUpdate).toHaveBeenCalledWith('app-1', 'feature-ideas', { taskMetadata: null });
});
});
+
+describe('AppOverrideRow — branch-reconcile batch size', () => {
+ it('allows an app to inherit or override the global branch batch', async () => {
+ const onUpdate = renderRow({
+ taskType: 'branch-reconcile',
+ globalTaskMetadata: { branchesPerAgent: 3 },
+ override: { taskMetadata: { branchesPerAgent: 2 } }
+ });
+ const select = screen.getByLabelText('Branches per agent for Acme');
+ expect(select).toHaveValue('2');
+ await act(async () => { fireEvent.change(select, { target: { value: '' } }); });
+ expect(onUpdate).toHaveBeenCalledWith('app-1', 'branch-reconcile', { taskMetadata: null });
+ });
+});
diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
index 92cb03cc59..b20d19c078 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.test.jsx
@@ -29,12 +29,12 @@ const baseConfig = {
status: { nextRunAt: '2999-01-01T00:00:00Z' },
};
-function renderCard(overrides = {}, props = {}) {
+function renderCard(overrides = {}, props = {}, taskType = 'code-review') {
const onTrigger = vi.fn();
const onConfigure = vi.fn();
render(
<AppTaskCard
- taskType="code-review"
+ taskType={taskType}
config={{ ...baseConfig, ...overrides }}
onTrigger={onTrigger}
onConfigure={onConfigure}
@@ -121,6 +121,12 @@ describe('AppTaskCard', () => {
expect(screen.queryByText(/^×\d/)).toBeNull();
});
+ it('shows the configured branch batch badge on branch-reconcile', () => {
+ renderCard({ taskMetadata: { branchesPerAgent: 4 } }, {}, 'branch-reconcile');
+ expect(screen.getByText('×4')).toBeTruthy();
+ expect(screen.getByTitle(/up to 4 branch/)).toBeTruthy();
+ });
+
it('omits the quick model pins when no onUpdate handler is supplied', () => {
renderCard({}, { providers });
expect(screen.queryByLabelText('Provider')).toBeNull();
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 67af38c626..94b71d07a6 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -1,7 +1,7 @@
import { useState, useEffect, useMemo } from 'react';
import { RotateCcw, AlertCircle } from 'lucide-react';
import CronInput from '../../../CronInput';
-import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE, IMPLICIT_PR_COMPLETION, PR_AUTHOR_FILTER_OPTIONS, PR_COMPLETION_OPTIONS, pinnedPrCompletion, prCompletionOption, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES, SWARM_COUNT_OPTIONS, SWARM_TASK_TYPES } from '../../constants';
+import { AGENT_OPTIONS, BRANCHES_PER_AGENT_DEFAULT, BRANCHES_PER_AGENT_OPTIONS, BRANCHES_PER_AGENT_TASK_TYPES, DEFAULT_REVIEW_STOP_MODE, IMPLICIT_PR_COMPLETION, PR_AUTHOR_FILTER_OPTIONS, PR_COMPLETION_OPTIONS, pinnedPrCompletion, prCompletionOption, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TYPES, SWARM_COUNT_OPTIONS, SWARM_TASK_TYPES } from '../../constants';
import ReviewerPicker from '../../ReviewerPicker';
import Banner from '../../../ui/Banner';
import InfoTooltip from '../../../ui/InfoTooltip';
@@ -147,6 +147,14 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
setUpdating(false);
};
+ const handleBranchesPerAgentChange = async (value) => {
+ setUpdating(true);
+ await onUpdate(taskType, {
+ taskMetadata: { ...(config.taskMetadata || {}), branchesPerAgent: value }
+ });
+ setUpdating(false);
+ };
+
// '' drops the key so the task inherits its app's `defaultPrCompletion` —
// which works because no DEFAULT_TASK_INTERVALS entry ships a `prCompletion`
// for loadSchedule to merge back underneath. The legacy `reviewLoop` bit is
@@ -403,6 +411,27 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
</div>
)}
+ {BRANCHES_PER_AGENT_TASK_TYPES.has(taskType) && (
+ <div>
+ <label htmlFor={`branches-per-agent-${taskType}`} className="text-sm text-gray-400 block mb-2">Branches per agent</label>
+ <select
+ id={`branches-per-agent-${taskType}`}
+ value={config.taskMetadata?.branchesPerAgent || BRANCHES_PER_AGENT_DEFAULT}
+ onChange={(e) => handleBranchesPerAgentChange(Number(e.target.value))}
+ disabled={updating}
+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm"
+ >
+ {BRANCHES_PER_AGENT_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ <p className="text-xs text-gray-500 mt-1">
+ {BRANCHES_PER_AGENT_OPTIONS.find(o => o.value === (config.taskMetadata?.branchesPerAgent || BRANCHES_PER_AGENT_DEFAULT))?.description}.
+ {' '}Branches are prioritized deterministically; the next drain picks up the remainder after this batch progresses.
+ </p>
+ </div>
+ )}
+
<PromptEditor
config={config}
promptValue={promptValue}
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
index cb8b22c447..5d88803e51 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.test.jsx
@@ -32,10 +32,10 @@ const BASE_CONFIG = {
status: {},
};
-function renderControls({ taskMetadata, onUpdate = vi.fn() } = {}) {
+function renderControls({ taskMetadata, onUpdate = vi.fn(), taskType = 'feature-ideas' } = {}) {
render(
<GlobalConfigControls
- taskType="feature-ideas"
+ taskType={taskType}
config={{ ...BASE_CONFIG, taskMetadata }}
onUpdate={onUpdate}
onTrigger={() => {}}
@@ -108,3 +108,15 @@ describe('GlobalConfigControls — After opening PR', () => {
expect(screen.getByTestId('reviewer-picker')).toBeInTheDocument();
});
});
+
+describe('GlobalConfigControls — branch-reconcile batch size', () => {
+ it('shows the safe default and persists a selected branch batch', () => {
+ const onUpdate = renderControls({ taskType: 'branch-reconcile', taskMetadata: { cleanupMerged: true } });
+ const select = screen.getByLabelText('Branches per agent');
+ expect(select).toHaveValue('3');
+ fireEvent.change(select, { target: { value: '5' } });
+ expect(onUpdate).toHaveBeenCalledWith('branch-reconcile', {
+ taskMetadata: { cleanupMerged: true, branchesPerAgent: 5 }
+ });
+ });
+});
diff --git a/client/src/components/cos/tabs/schedule/TaskHeader.jsx b/client/src/components/cos/tabs/schedule/TaskHeader.jsx
index 52a11c1f89..06ca5ac4ad 100644
--- a/client/src/components/cos/tabs/schedule/TaskHeader.jsx
+++ b/client/src/components/cos/tabs/schedule/TaskHeader.jsx
@@ -1,4 +1,4 @@
-import { GitMerge, Users } from 'lucide-react';
+import { GitBranch, GitMerge, Users } from 'lucide-react';
import { badge, statusDot, getTaskStatusGroup, pipelineStages } from './scheduleConstants';
import IntervalBadge from './IntervalBadge';
@@ -13,6 +13,8 @@ export default function TaskHeader({ taskType, config }) {
// shows its own override select).
const swarmCount = config.taskMetadata?.swarmCount;
const swarmOn = Number.isInteger(swarmCount) && swarmCount >= 2;
+ const branchesPerAgent = config.taskMetadata?.branchesPerAgent;
+ const branchBatchOn = taskType === 'branch-reconcile' && Number.isInteger(branchesPerAgent) && branchesPerAgent > 0;
return (
<div className="flex items-start gap-2">
<span className={`mt-1.5 w-2 h-2 rounded-full shrink-0 ${statusDot(group)}`} title={group} aria-hidden="true" />
@@ -24,6 +26,12 @@ export default function TaskHeader({ taskType, config }) {
×{swarmCount}
</span>
)}
+ {branchBatchOn && (
+ <span className={badge('cyan')} title={`Branch-reconcile batch — up to ${branchesPerAgent} branch(es) per coordinator run`}>
+ <GitBranch size={11} className="inline mr-0.5" />
+ ×{branchesPerAgent}
+ </span>
+ )}
{stages?.length > 0 && (
<span className={badge('purple')} title={stages.map(s => s.name).join(' → ')}>
<GitMerge size={11} className="inline mr-0.5" />
diff --git a/scripts/migrations/274-merge-branch-cleanup-into-reconcile.js b/scripts/migrations/274-merge-branch-cleanup-into-reconcile.js
new file mode 100644
index 0000000000..38e731f746
--- /dev/null
+++ b/scripts/migrations/274-merge-branch-cleanup-into-reconcile.js
@@ -0,0 +1,126 @@
+/**
+ * Retire the standalone branch-cleanup task in favor of branch-reconcile.
+ *
+ * branch-reconcile now begins with the deterministic merged-and-clean worktree
+ * reaper, so keeping a second scheduled coordinator creates two competing
+ * owners for the same local branches. Move any existing global task and
+ * per-app enablement into branch-reconcile, then remove the old task key. The
+ * migration intentionally does not copy the old weekly interval or prompt:
+ * reconcile's perpetual drain and its safe cleanup-first pass are the new
+ * contract. An enabled legacy task keeps the combined task enabled; otherwise
+ * an upgrade could silently turn off cleanup that was already scheduled. A
+ * non-null provider/model pin also carries forward when the new task still has
+ * its default null pin, while an explicit target pin wins.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const SCHEDULE_REL = 'data/cos/task-schedule.json';
+const APPS_REL = 'data/apps.json';
+const LEGACY_TASK = 'branch-cleanup';
+const TARGET_TASK = 'branch-reconcile';
+const CARRY_FIELDS = ['enabled', 'providerId', 'model'];
+
+const isObject = (value) => value && typeof value === 'object' && !Array.isArray(value);
+const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
+
+async function readJson(path) {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+}
+
+async function writeJson(path, value) {
+ await writeFile(path, `${JSON.stringify(value, null, 2)}\n`);
+}
+
+/**
+ * Merge the legacy global task into an existing target. Preserve an active
+ * legacy schedule and carry non-null legacy pins into default-null target
+ * fields; explicit target pins remain authoritative. Pure and exported for
+ * migration tests.
+ */
+export function mergeTaskConfig(legacy, target) {
+ const next = isObject(target) ? { ...target } : {};
+ if (legacy?.enabled === true) next.enabled = true;
+ for (const field of CARRY_FIELDS) {
+ if (field === 'enabled') {
+ if (!hasOwn(next, field) && hasOwn(legacy, field)) next[field] = legacy[field];
+ continue;
+ }
+ if ((!hasOwn(next, field) || next[field] == null) && legacy[field] != null) next[field] = legacy[field];
+ }
+ return next;
+}
+
+/**
+ * Move app-level enablement and provider pins while leaving the new task's
+ * perpetual cadence and action metadata to the branch-reconcile defaults.
+ * Pure and exported for migration tests.
+ */
+export function mergeAppOverride(legacy, target) {
+ const next = isObject(target) ? { ...target } : {};
+ if (legacy?.enabled === true) next.enabled = true;
+ for (const field of CARRY_FIELDS) {
+ if (field === 'enabled') {
+ if (!hasOwn(next, field) && hasOwn(legacy, field)) next[field] = legacy[field];
+ continue;
+ }
+ if ((!hasOwn(next, field) || next[field] == null) && legacy[field] != null) next[field] = legacy[field];
+ }
+ return next;
+}
+
+export default {
+ async up({ rootDir }) {
+ const schedulePath = join(rootDir, SCHEDULE_REL);
+ const schedule = await readJson(schedulePath);
+ let taskMigrated = false;
+
+ if (isObject(schedule?.tasks) && hasOwn(schedule.tasks, LEGACY_TASK)) {
+ const legacy = isObject(schedule.tasks[LEGACY_TASK]) ? schedule.tasks[LEGACY_TASK] : {};
+ if (hasOwn(schedule.tasks, TARGET_TASK)) {
+ schedule.tasks[TARGET_TASK] = mergeTaskConfig(legacy, schedule.tasks[TARGET_TASK]);
+ } else {
+ const migrated = mergeTaskConfig(legacy, null);
+ if (Object.keys(migrated).length > 0) schedule.tasks[TARGET_TASK] = migrated;
+ }
+ delete schedule.tasks[LEGACY_TASK];
+ await writeJson(schedulePath, schedule);
+ taskMigrated = true;
+ console.log('📝 branch-cleanup: merged global schedule into branch-reconcile');
+ }
+
+ const appsPath = join(rootDir, APPS_REL);
+ const apps = await readJson(appsPath);
+ let migratedApps = 0;
+ if (isObject(apps?.apps)) {
+ for (const app of Object.values(apps.apps)) {
+ if (!isObject(app?.taskTypeOverrides) || !hasOwn(app.taskTypeOverrides, LEGACY_TASK)) continue;
+ const legacy = isObject(app.taskTypeOverrides[LEGACY_TASK])
+ ? app.taskTypeOverrides[LEGACY_TASK]
+ : {};
+ const target = hasOwn(app.taskTypeOverrides, TARGET_TASK)
+ ? app.taskTypeOverrides[TARGET_TASK]
+ : null;
+ app.taskTypeOverrides[TARGET_TASK] = mergeAppOverride(legacy, target);
+ delete app.taskTypeOverrides[LEGACY_TASK];
+ migratedApps += 1;
+ }
+ if (migratedApps > 0) {
+ await writeJson(appsPath, apps);
+ console.log(`📝 branch-cleanup: moved app overrides for ${migratedApps} app(s)`);
+ }
+ }
+
+ return { taskMigrated, migratedApps, updated: (taskMigrated ? 1 : 0) + migratedApps };
+ }
+};
diff --git a/scripts/migrations/274-merge-branch-cleanup-into-reconcile.test.js b/scripts/migrations/274-merge-branch-cleanup-into-reconcile.test.js
new file mode 100644
index 0000000000..a87b76ab0d
--- /dev/null
+++ b/scripts/migrations/274-merge-branch-cleanup-into-reconcile.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration, { mergeAppOverride, mergeTaskConfig } from './274-merge-branch-cleanup-into-reconcile.js';
+
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
+
+describe('migration 274 — branch-cleanup → branch-reconcile', () => {
+ let rootDir;
+ let schedulePath;
+ let appsPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-274-'));
+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });
+ schedulePath = join(rootDir, 'data', 'cos', 'task-schedule.json');
+ appsPath = join(rootDir, 'data', 'apps.json');
+ });
+
+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));
+
+ it('preserves enabled cleanup and fills default target pins without copying cadence', () => {
+ expect(mergeTaskConfig(
+ { enabled: true, providerId: 'legacy-provider', model: 'legacy-model' },
+ { enabled: false, providerId: null, type: 'perpetual' }
+ )).toEqual({ enabled: true, providerId: 'legacy-provider', type: 'perpetual', model: 'legacy-model' });
+ });
+
+ it('moves app enablement without copying the retired weekly cadence', () => {
+ expect(mergeAppOverride(
+ { enabled: true, interval: 'weekly', providerId: 'legacy-provider' },
+ null
+ )).toEqual({ enabled: true, providerId: 'legacy-provider' });
+ });
+
+ it('merges the global task and each app override, then removes legacy keys', async () => {
+ writeJson(schedulePath, {
+ version: 2,
+ tasks: {
+ 'branch-cleanup': { enabled: true, providerId: 'legacy-provider', model: 'legacy-model', type: 'weekly' },
+ 'branch-reconcile': { enabled: false, type: 'perpetual', taskMetadata: { branchesPerAgent: 2 } }
+ }
+ });
+ writeJson(appsPath, {
+ apps: {
+ 'app-a': {
+ taskTypeOverrides: {
+ 'branch-cleanup': { enabled: true, interval: 'weekly', providerId: 'legacy-provider' },
+ 'branch-reconcile': { enabled: false, taskMetadata: { branchesPerAgent: 1 } }
+ }
+ },
+ 'app-b': { taskTypeOverrides: { 'branch-cleanup': { enabled: false } } }
+ }
+ });
+
+ const result = await migration.up({ rootDir });
+ expect(result).toEqual({ taskMigrated: true, migratedApps: 2, updated: 3 });
+
+ const schedule = readJson(schedulePath);
+ expect(schedule.tasks['branch-cleanup']).toBeUndefined();
+ expect(schedule.tasks['branch-reconcile']).toMatchObject({
+ enabled: true,
+ providerId: 'legacy-provider',
+ model: 'legacy-model',
+ type: 'perpetual',
+ taskMetadata: { branchesPerAgent: 2 }
+ });
+
+ const apps = readJson(appsPath).apps;
+ expect(apps['app-a'].taskTypeOverrides['branch-cleanup']).toBeUndefined();
+ expect(apps['app-a'].taskTypeOverrides['branch-reconcile']).toEqual({
+ enabled: true,
+ providerId: 'legacy-provider',
+ taskMetadata: { branchesPerAgent: 1 }
+ });
+ expect(apps['app-b'].taskTypeOverrides['branch-reconcile']).toEqual({ enabled: false });
+ });
+
+ it('is idempotent when the retired keys are already gone', async () => {
+ writeJson(schedulePath, { version: 2, tasks: { 'branch-reconcile': { enabled: false } } });
+ writeJson(appsPath, { apps: { 'app-a': { taskTypeOverrides: { 'branch-reconcile': { enabled: false } } } } });
+
+ expect(await migration.up({ rootDir })).toEqual({ taskMigrated: false, migratedApps: 0, updated: 0 });
+ });
+});
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 8f3d231852..5a5d807646 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1437,6 +1437,13 @@ export const ISSUE_AUTHOR_FILTERS = ['self', 'collaborators', 'owner', 'any'];
export const SWARM_COUNT_MIN = 2;
export const SWARM_COUNT_MAX = 6;
+// branch-reconcile coordinator batch size. Unlike claim-issue's swarm count,
+// this is the number of already-classified branches one coordinator receives
+// in a run. A one-branch batch is valid, and the scheduler supplies the default
+// when the key is absent so old task records remain compatible.
+export const BRANCHES_PER_AGENT_MIN = 1;
+export const BRANCHES_PER_AGENT_MAX = 6;
+
// POST /api/cos/tasks/slashdo — a `/do:*` button click from an app's Agent
// Operations panel. The run-settings fields are PICKED from createCosTaskSchema
// rather than restated, so the drawer's provider/model/effort/simplify/reviewer
@@ -1576,6 +1583,18 @@ export function sanitizeTaskMetadata(raw) {
clean.swarmCount = raw.swarmCount;
hasKeys = true;
}
+ // `branchesPerAgent` bounds the branch-reconcile prompt to a deterministic
+ // prefix of the prioritized in-flight set. It is separate from swarmCount:
+ // branch-reconcile runs one coordinator over a batch, while claim-issue fans
+ // out independent issue agents. Absent means inherit; there is no "off"
+ // value because the task default intentionally supplies a safe batch size.
+ if (Object.prototype.hasOwnProperty.call(raw, 'branchesPerAgent')
+ && Number.isInteger(raw.branchesPerAgent)
+ && raw.branchesPerAgent >= BRANCHES_PER_AGENT_MIN
+ && raw.branchesPerAgent <= BRANCHES_PER_AGENT_MAX) {
+ clean.branchesPerAgent = raw.branchesPerAgent;
+ hasKeys = true;
+ }
// Pass through pipeline config (validated shape: object with stages array)
if (raw.pipeline && typeof raw.pipeline === 'object' && Array.isArray(raw.pipeline.stages)) {
clean.pipeline = raw.pipeline;
diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.js
index ba1704f6c1..a0f170fce6 100644
--- a/server/lib/cosValidation.test.js
+++ b/server/lib/cosValidation.test.js
@@ -57,6 +57,19 @@ describe('cosValidation effort field', () => {
});
});
+describe('branch-reconcile batch metadata', () => {
+ it('keeps integer batch sizes from 1 through 6', () => {
+ expect(sanitizeTaskMetadata({ branchesPerAgent: 1 })).toEqual({ branchesPerAgent: 1 });
+ expect(sanitizeTaskMetadata({ branchesPerAgent: 6 })).toEqual({ branchesPerAgent: 6 });
+ });
+
+ it('drops zero, fractional, string, and unbounded batch sizes', () => {
+ for (const branchesPerAgent of [0, 7, 1.5, '3', null]) {
+ expect(sanitizeTaskMetadata({ branchesPerAgent })).toBeNull();
+ }
+ });
+});
+
describe('cosValidation autonomous-job effort field', () => {
it('accepts every EFFORT_LEVELS value on create and rejects unknown values', () => {
for (const effort of EFFORT_LEVELS) {
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index cd0af0e8e8..53e225a89a 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -25,7 +25,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 } from './worktreeManager.js';
+import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';
import { isAgentWorktreeId, worktreeOwnershipReason } from '../lib/worktreeOwnership.js';
import { execGh, ensureForgeReachable } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
@@ -754,6 +754,18 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
* and the caller must retry rather than park on it (#3358).
*/
export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRemotes = false, activeAgentIds = new Set() } = {}) {
+ // Worktree cleanup is the first reconcile step, before any forge probe. It
+ // only removes a tree after proving both that it is completely clean and
+ // that every branch commit is already in the default branch (including
+ // squash/rebase-equivalent merges). Keeping this pass ahead of gh means a
+ // temporary forge outage cannot strand locally-provable completed work.
+ const worktreeCleanup = cleanup
+ ? await reapMergedWorktrees(repoPath, { activeAgentIds, includeClaudeTrees: true }).catch(() => ({ reaped: [] }))
+ : { reaped: [] };
+ const cleanedWorktrees = (worktreeCleanup.reaped || [])
+ .map((entry) => typeof entry === 'string' ? entry : entry?.branch)
+ .filter(Boolean);
+
// On a GitHub repo every classification below depends on PR state, so an
// unreadable forge makes the whole pass a guess — skip with one line rather
// than report a quiet repo. Probed against THIS repo's API host
@@ -768,7 +780,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: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
+ return { defaultBranch: null, cleaned: cleanedWorktrees, inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
}
}
@@ -797,9 +809,10 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem
// running sessions" rather than a bare "nothing actionable") filters `wip` on it.
const wip = classified.filter((c) => c.state === 'WIP');
- const { cleaned, skipped } = cleanup
+ const { cleaned: cleanedBranches, skipped } = cleanup
? await cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds })
: { cleaned: [], skipped: merged.map((m) => ({ branch: m.branch, reason: 'cleanup-disabled' })) };
+ const cleaned = [...new Set([...cleanedWorktrees, ...cleanedBranches])];
// Runs AFTER cleanupMerged on purpose: that step deletes merged local branches
// and leaves their `origin/*` counterpart behind, which is precisely the orphan
@@ -1046,15 +1059,34 @@ export function actionableSignature(actionable) {
.join('|');
}
+/**
+ * Select the deterministic prefix a single coordinator should receive. The
+ * reconciler has already prioritized the full set, so slicing here preserves
+ * that ordering and lets the next drain dispatch pick up the remainder after
+ * this batch makes progress. Absent/invalid limits retain the legacy all-at-once
+ * behavior for hand-authored task records that predate the setting.
+ * @param {object[]} inFlight
+ * @param {number} branchesPerAgent
+ * @returns {object[]}
+ */
+export function limitBranchesForAgent(inFlight, branchesPerAgent) {
+ if (!Array.isArray(inFlight)) return [];
+ if (!Number.isInteger(branchesPerAgent) || branchesPerAgent < 1) return inFlight;
+ return inFlight.slice(0, branchesPerAgent);
+}
+
/**
* Render the actionable in-flight branch set into the coordinator prompt body
* (injected as `{inFlightBranches}`).
* @param {object[]} inFlight - actionable branches (post-filterActionable)
- * @param {{ defaultBranch:string, actions:object }} ctx
+ * @param {{ defaultBranch:string, actions:object, branchesPerAgent?:number }} ctx
* @returns {string}
*/
-export function formatInFlightForPrompt(inFlight, { defaultBranch, actions }) {
+export function formatInFlightForPrompt(inFlight, { defaultBranch, actions, branchesPerAgent } = {}) {
const lines = [`Default branch: \`${defaultBranch}\`. Branches to reconcile (${inFlight.length}):`, ''];
+ if (Number.isInteger(branchesPerAgent) && branchesPerAgent > 0) {
+ lines.splice(1, 0, `This coordinator run is limited to up to ${branchesPerAgent} branch(es); finish every branch listed below before reporting done.`);
+ }
for (const b of inFlight) {
const pr = b.openPr ? ` — PR #${b.openPr.number} (${b.openPr.mergeable})${b.openPr.url ? ` ${b.openPr.url}` : ''}` : ' — no PR';
lines.push(`### \`${b.branch}\` [${b.state}]${pr}`);
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index f67bac7fe9..48eeb6df17 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -22,6 +22,7 @@ vi.mock('../lib/execGit.js', () => ({
vi.mock('./worktreeManager.js', () => ({
listWorktrees: vi.fn(async () => []),
forceRemoveWorktreeDir: vi.fn(async () => {}),
+ reapMergedWorktrees: vi.fn(async () => ({ reaped: [], skipped: [] })),
// Real pure classifier semantics: empty porcelain = clean, and every non-empty
// line is a real change path (the suite never feeds it lockfile churn). The
// paths matter — gatherDivergence intersects them with the default branch's
@@ -61,6 +62,7 @@ import {
classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState, worktreeProtectionReason,
isAbandonedAgentWorktree, resolveLiveOwnerReason, gatherDivergence,
actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,
+ limitBranchesForAgent,
branchPriorityRank, prioritizeBranches,
upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes
} from './branchReconcile.js';
@@ -81,6 +83,7 @@ beforeEach(() => {
git.getDefaultBranch.mockResolvedValue('main');
git.deleteBranch.mockResolvedValue({ branch: 'x', results: { local: 'deleted' } });
wt.forceRemoveWorktreeDir.mockResolvedValue(undefined);
+ wt.reapMergedWorktrees.mockResolvedValue({ reaped: [], skipped: [] });
execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
tryReadFileMock.mockResolvedValue(null);
});
@@ -591,7 +594,20 @@ describe('unreachable forge (#3358)', () => {
expect(res.cleaned).toEqual(['feature/x']);
});
- it('skips the whole cycle (never touches git) when the gh probe is not ok', async () => {
+ it('runs clean-and-merged worktree cleanup before a forge probe', async () => {
+ wt.reapMergedWorktrees.mockResolvedValueOnce({ reaped: [{ branch: 'feature/done' }], skipped: [] });
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
+
+ const res = await reconcile('/repo');
+ expect(res.cleaned).toEqual(['feature/done']);
+ expect(wt.reapMergedWorktrees).toHaveBeenCalledWith('/repo', {
+ activeAgentIds: new Set(), includeClaudeTrees: true
+ });
+ expect(wt.reapMergedWorktrees.mock.invocationCallOrder[0])
+ .toBeLessThan(ensureForgeReachableMock.mock.invocationCallOrder[0]);
+ });
+
+ it('skips branch classification when the gh probe is not ok', async () => {
ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
const res = await reconcile('/repo');
expect(res.forgeUnavailable).toBe(true);
@@ -599,7 +615,8 @@ describe('unreachable forge (#3358)', () => {
expect(res.inFlight).toEqual([]);
expect(res.cleaned).toEqual([]);
// Crucially: no branch enumeration and no deletion happened, so the empty
- // result can't be mistaken for "the repo is clean".
+ // result can't be mistaken for "the repo is clean". The cleanup-first pass
+ // still ran, but had no candidates in this case.
expect(git.getBranches).not.toHaveBeenCalled();
expect(git.deleteBranch).not.toHaveBeenCalled();
});
@@ -855,6 +872,21 @@ describe('actionOn', () => {
});
});
+describe('limitBranchesForAgent', () => {
+ it('keeps the prioritized prefix and leaves the input untouched', () => {
+ const input = [{ branch: 'claim/1' }, { branch: 'feature/2' }, { branch: 'fix/3' }];
+ expect(limitBranchesForAgent(input, 2)).toEqual(input.slice(0, 2));
+ expect(input).toHaveLength(3);
+ });
+
+ it('preserves legacy all-at-once behavior for an absent or invalid limit', () => {
+ const input = [{ branch: 'a' }, { branch: 'b' }];
+ expect(limitBranchesForAgent(input)).toBe(input);
+ expect(limitBranchesForAgent(input, 0)).toBe(input);
+ expect(limitBranchesForAgent(input, 1.5)).toBe(input);
+ });
+});
+
describe('filterActionable', () => {
const inFlight = [
{ branch: 'a', state: 'NEEDS_PR' },
@@ -1087,6 +1119,14 @@ describe('formatInFlightForPrompt', () => {
expect(block).toContain('- Do: ');
});
+ it('states the configured batch limit when supplied', () => {
+ const block = formatInFlightForPrompt(
+ [{ branch: 'next/issue-1', state: 'NEEDS_PR' }],
+ { defaultBranch: 'main', actions: {}, branchesPerAgent: 3 }
+ );
+ expect(block).toContain('limited to up to 3 branch(es)');
+ });
+
// The collision set gets its own line, not just prose inside the Do: text, so
// the agent can open those files directly instead of re-deriving the set.
it('surfaces drift and the collision files as their own lines', () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index f69a77315f..a54967e7a8 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2467,7 +2467,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, formatInFlightForPrompt, actionableSignature } = await import('./branchReconcile.js');
+ const { reconcile, filterActionable, limitBranchesForAgent, formatInFlightForPrompt, actionableSignature } = 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
@@ -2520,8 +2520,9 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
// log so "nothing actionable" doesn't read as "no branches exist".
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) {
+ const allActionable = filterActionable(result.inFlight, actions);
+ const actionable = limitBranchesForAgent(allActionable, metadata.branchesPerAgent);
+ 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.
@@ -2553,10 +2554,17 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
metadata.perpetual = true;
const supersededBlock = formatSupersededForPrompt(result.superseded || []);
const block = [
- formatInFlightForPrompt(actionable, { defaultBranch: result.defaultBranch, actions }),
+ formatInFlightForPrompt(actionable, {
+ defaultBranch: result.defaultBranch,
+ actions,
+ branchesPerAgent: metadata.branchesPerAgent
+ }),
supersededBlock
].filter(Boolean).join('\n');
- emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)${heldLiveSuffix}${supersededSuffix}`, { appId: app.id, analysisType: taskType });
+ const batchSuffix = allActionable.length > actionable.length
+ ? ` (selected ${actionable.length} of ${allActionable.length})`
+ : '';
+ emitLog('info', `🔀 branch-reconcile dispatching for ${app.name}: ${actionable.length} in-flight branch(es)${batchSuffix}${heldLiveSuffix}${supersededSuffix}`, { appId: app.id, analysisType: taskType });
return { skip: false, block };
}
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 4537ea5a21..2c84d921ad 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -23,6 +23,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { cosEvents, emitLog } from './cosEvents.js';
import { atomicWrite, DAY, ensureDir, HOUR, readJSONFile, PATHS, safeDate } from '../lib/fileUtils.js';
+import { BRANCHES_PER_AGENT_MAX, BRANCHES_PER_AGENT_MIN } from '../lib/cosValidation.js';
import { isPlainObject } from '../lib/objects.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
@@ -180,7 +181,7 @@ async function getPerformanceAdjustedInterval(taskType, baseIntervalMs) {
// Unified default interval settings for all task types
export const SELF_IMPROVEMENT_TASK_TYPES = [
'security', 'code-quality', 'test-coverage', 'performance',
- 'accessibility', 'branch-cleanup', 'branch-reconcile', 'issue-reconcile', 'console-errors', 'dependency-updates', 'documentation',
+ 'accessibility', 'branch-reconcile', 'issue-reconcile', 'console-errors', 'dependency-updates', 'documentation',
'ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'claim-issue', 'claim-work', 'error-handling',
'typing', 'release-check', 'pr-reviewer', 'code-reviewer-a', 'code-reviewer-b',
'jira-sprint-manager', 'jira-status-report', 'do-replan',
@@ -231,8 +232,8 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
];
// Shared taskMetadata posture for the NON-COMMITTING COORDINATOR types
-// (NON_COMMITTING_COORDINATOR_TASK_TYPES in taskTypeHooks.js — branch-cleanup /
-// branch-reconcile / issue-reconcile / jira-status-report). Each delivers its work
+// (NON_COMMITTING_COORDINATOR_TASK_TYPES in taskTypeHooks.js — branch-reconcile /
+// issue-reconcile / jira-status-report). Each delivers its work
// as a SIDE EFFECT in the app's live checkout — a deleted branch, a merged PR, a
// relabeled issue, a posted report — and by design produces no commit of its own.
// Two code-shipping criteria therefore have to be switched off or every SUCCESSFUL
@@ -240,8 +241,8 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// * `useWorktree`/`openPR` — explicitly false (not merely absent) so
// applyAppWorktreeDefault's `=== undefined` checks can't fill them from the
// app's `defaultOpenPR`/`defaultUseWorktree`. A worktree these tasks never cd
-// into is at best unused and at worst harmful (it holds refs branch-cleanup is
-// trying to delete), and the implied PR expectation fails the run at finalize
+// into is at best unused and at worst harmful (it hides sibling refs the
+// reconcile scan must inspect), and the implied PR expectation fails the run at finalize
// with `pr-missing` — there is no code to open a PR for. Locked in
// MANAGED_AGENT_OPTIONS below so a per-app override can't re-attach them.
// `readOnly: true` is NOT a substitute: it gates worktree CREATION
@@ -252,6 +253,12 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// A guard test in taskSchedule.test.js asserts every member of that set carries
// this posture, so a new coordinator type can't be added to one list only.
const NON_COMMITTING_COORDINATOR_METADATA = { useWorktree: false, openPR: false, worktreeChangesExpected: false };
+// Migration 274 removes branch-cleanup from new schedules, but a partially
+// upgraded install may still load its stored task before the migration runs.
+// Keep its safety posture available without making it a newly-shipped task.
+const LEGACY_MANAGED_TASK_METADATA = {
+ 'branch-cleanup': NON_COMMITTING_COORDINATOR_METADATA
+};
// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)
const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true, pipeline: { stages: [{ name: 'Codebase Review', promptKey: 'code-reviewer-review', readOnly: true, providerId: null, model: null, precondition: { fileNotExists: 'REVIEW.md' } }, { name: 'Triage & Implement', promptKey: 'code-reviewer-implement', readOnly: false, providerId: null, model: null, precondition: { fileExists: 'REVIEW.md' } }] } } };
@@ -287,6 +294,7 @@ const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, we
* idle park remains the only brake) and only the reconcile scans carry a number.
*/
export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;
+export const DEFAULT_BRANCHES_PER_AGENT = 3;
export const DEFAULT_TASK_INTERVALS = {
'security': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
@@ -294,28 +302,27 @@ export const DEFAULT_TASK_INTERVALS = {
'test-coverage': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
'performance': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null },
'accessibility': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },
- // branch-cleanup deletes merged local/remote branches in the app's LIVE checkout
- // (its prompt `cd`s to {repoPath} and runs `git branch -d` / `git push --delete`),
- // hence the shared non-committing-coordinator posture above.
- 'branch-cleanup': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA } },
- // branch-reconcile finishes THIS machine's in-flight LOCAL branches per app
- // (open a PR for pushed-but-unopened work, resolve merge conflicts, drive the
- // review loop, auto-merge when green) AFTER a deterministic pass that removes
- // fully-merged orphaned branches + their worktrees. PERPETUAL (drain-until-done):
+ // branch-reconcile first removes fully-merged, clean orphaned worktrees and
+ // branches, then finishes THIS machine's remaining in-flight LOCAL branches
+ // per app (open a PR for pushed-but-unopened work, resolve merge conflicts,
+ // drive the review loop, auto-merge when green). PERPETUAL (drain-until-done):
// the generator runs the deterministic reconcile every dispatch, and dispatches
// the coordinator agent only while actionable in-flight branches remain — then
// PARKS on the daily recheckCron. The action toggles (cleanupMerged / openPr /
// resolveConflicts / autoMerge / finishAbandoned) are per-app taskMetadata
// booleans (each ON unless explicitly false); `finishAbandoned` covers the work
// a dead agent left UNCOMMITTED in its worktree — commit + ship it, or report it
- // as unfinished. useWorktree/openPR are LOCKED off (MANAGED_AGENT_OPTIONS):
+ // as unfinished. `branchesPerAgent` bounds each coordinator prompt to a
+ // prioritized batch so a large backlog drains across several agents. It is
+ // independently overridable per app. useWorktree/openPR are LOCKED off
+ // (MANAGED_AGENT_OPTIONS):
// the coordinator runs in the app's live checkout so it can see + operate on the
// sibling worktrees; a CoS-managed worktree would hide the branches and could
// trigger cleanupAgentWorktree's auto-merge. Its edits likewise land in those
// SIBLING worktrees, never in its own cwd — hence the shared non-committing
// -coordinator posture above. Off by default — enabling it is the user's
// explicit consent to let it drive PRs on a schedule.
- 'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true } },
+ 'branch-reconcile': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
// issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with
// their PR already MERGED and no live claim anywhere — a partial ship left the
// claim marker on, so the queue (which skips `in-progress`) never re-picks the
@@ -393,7 +400,7 @@ export const DEFAULT_TASK_INTERVALS = {
'jira-status-report': { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, readOnly: true } },
// do-replan audits PLAN.md after open PRs and stale branches have been cleaned up,
// so the plan reflects what actually merged.
- 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['pr-reviewer', 'branch-cleanup'], taskMetadata: { useWorktree: true, openPR: true } },
+ 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['pr-reviewer', 'branch-reconcile'], taskMetadata: { useWorktree: true, openPR: true } },
// Writable — the v2 reference-watch prompt (PROMPT_VERSIONS['reference-watch'] = 2)
// instructs the agent to APPEND slug-tagged `[ref-watch-…]` checklist items to
// PLAN.md and commit them. `readOnly: true` would inject the "do not modify or
@@ -453,11 +460,10 @@ export const MANAGED_AGENT_OPTIONS = {
// run in the app's LIVE checkout and ship no code, so a CoS-managed worktree is at
// best unused and at worst harmful — branch-reconcile needs to see the sibling
// worktrees of the in-flight branches (a managed worktree hides them from the scan
- // AND could trip cleanupAgentWorktree's auto-merge), and branch-cleanup's worktree
- // would hold refs it is trying to delete. Locking both off also keeps the
+ // AND could trip cleanupAgentWorktree's auto-merge). Locking both off also keeps the
// finalize-time PR-claim check from scoring a completed run `pr-missing`.
//
- // `worktreeChangesExpected` is managed for these four as well — the one type-keyed
+ // `worktreeChangesExpected` is managed for these coordinators as well — the one type-keyed
// exception to it being a free per-app override. A clean tree is definitionally the
// success shape for a branch deletion or a posted report, so setting it back to
// `true` can only make successful runs fail; it is exactly as non-negotiable here as
@@ -497,12 +503,14 @@ export function stripManagedAgentOptionsFromOverride(taskType, taskMetadata) {
function enforceManagedAgentOptions(taskType, config) {
const managed = MANAGED_AGENT_OPTIONS[taskType];
if (!managed || !config) return false;
- const defaults = DEFAULT_TASK_INTERVALS[taskType]?.taskMetadata || {};
+ const defaults = DEFAULT_TASK_INTERVALS[taskType]?.taskMetadata
+ || LEGACY_MANAGED_TASK_METADATA[taskType]
+ || {};
let changed = false;
// If the stored config explicitly cleared taskMetadata (or never had it),
// we still need the managed fields present — otherwise upstream resolvers
// (e.g., cos.js applyAppWorktreeDefault) can flip them on via app defaults.
- if (!config.taskMetadata || typeof config.taskMetadata !== 'object') {
+ if (!config.taskMetadata || typeof config.taskMetadata !== 'object' || Array.isArray(config.taskMetadata)) {
config.taskMetadata = {};
changed = true;
}
@@ -515,6 +523,23 @@ function enforceManagedAgentOptions(taskType, config) {
return changed;
}
+// The batch size is user-configurable, but an old schedule or an explicit
+// metadata clear must not silently restore the pre-batch all-at-once behavior.
+// Keep the persisted global task on the same safe default as a fresh install;
+// per-app overrides still layer on top of it at dispatch time.
+function enforceBranchReconcileBatch(taskType, config) {
+ if (taskType !== 'branch-reconcile' || !config) return false;
+ if (!config.taskMetadata || typeof config.taskMetadata !== 'object' || Array.isArray(config.taskMetadata)) {
+ config.taskMetadata = {};
+ }
+ const value = config.taskMetadata.branchesPerAgent;
+ if (!Number.isInteger(value) || value < BRANCHES_PER_AGENT_MIN || value > BRANCHES_PER_AGENT_MAX) {
+ config.taskMetadata.branchesPerAgent = DEFAULT_BRANCHES_PER_AGENT;
+ return true;
+ }
+ return false;
+}
+
/**
* Default schedule data structure (v2 - unified)
*/
@@ -691,6 +716,7 @@ export async function loadSchedule() {
let needsSave = false;
for (const [taskType, config] of Object.entries(schedule.tasks)) {
if (enforceManagedAgentOptions(taskType, config)) needsSave = true;
+ if (enforceBranchReconcileBatch(taskType, config)) needsSave = true;
// Stamp a creation timestamp the first time we see a task so the cron
// catch-up bound (shouldRunTask) never replays a slot that predates the
// task. Backfilling to "now" is conservative: it only suppresses catch-up
@@ -799,6 +825,7 @@ export async function updateTaskInterval(taskType, settings) {
// tries to flip them (UI bypass, hand-edited TASKS.md, direct API call)
// gets the locked value back in its response.
enforceManagedAgentOptions(taskType, schedule.tasks[taskType]);
+ enforceBranchReconcileBatch(taskType, schedule.tasks[taskType]);
// Config change unparks a failure-parked type (#2616): editing a type's
// settings is an explicit "I've addressed the cause" signal, so clear the
@@ -2187,7 +2214,6 @@ export const TASK_TYPE_DESCRIPTIONS = {
'claim-issue': 'Claim and ship the next open GitHub issue (owner-filed or any author), PR closes it',
'claim-work': "Ship the next work item from the app's configured tracker (PLAN.md, GitHub/GitLab issues, or JIRA), routed automatically",
'accessibility': 'Accessibility audit',
- 'branch-cleanup': 'Clean up merged branches',
'branch-reconcile': "Finish this machine's in-flight local branches: clean up merged ones, open PRs, resolve conflicts, drive review, auto-merge when green",
'issue-reconcile': "Heal zombie issues: open + in-progress but their PR already merged with no live claim — close + file a scoped follow-up when work remains, or release the claim so the queue re-picks it",
'dependency-updates': 'Land or resolve open Dependabot/Renovate PRs, then update the dependencies they missed',
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 1b158050d5..a38d5ec883 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -1163,7 +1163,9 @@ describe('taskSchedule', () => {
// posture. That drift is exactly how `branch-cleanup` shipped with no
// taskMetadata at all, letting an app-level `defaultOpenPR: true` attach a
// worktree + PR expectation to a task that only runs `git branch -d`.
- it.each([...NON_COMMITTING_COORDINATOR_TASK_TYPES])(
+ // branch-cleanup remains in the coordinator exemption only for archived
+ // tasks from before migration 274; it is no longer a shipped schedule type.
+ it.each([...NON_COMMITTING_COORDINATOR_TASK_TYPES].filter((type) => DEFAULT_TASK_INTERVALS[type]))(
'%s declares no worktree/PR, expects a clean tree, and locks both flags',
(taskType) => {
const meta = DEFAULT_TASK_INTERVALS[taskType].taskMetadata
@@ -1184,7 +1186,7 @@ describe('taskSchedule', () => {
// is the only thing that rebuilds the bag — and it rebuilds MANAGED fields only.
// Before worktreeChangesExpected was managed, it went absent here and a successful
// clean-tree run was scored `idle-no-changes` all over again.
- it.each([...NON_COMMITTING_COORDINATOR_TASK_TYPES])(
+ it.each([...NON_COMMITTING_COORDINATOR_TASK_TYPES].filter((type) => DEFAULT_TASK_INTERVALS[type]))(
'%s keeps the full posture when stored taskMetadata was cleared to null',
async (taskType) => {
mockSchedule({
@@ -1197,13 +1199,14 @@ describe('taskSchedule', () => {
expect(meta.useWorktree).toBe(false)
expect(meta.openPR).toBe(false)
expect(meta.worktreeChangesExpected).toBe(false)
+ if (taskType === 'branch-reconcile') expect(meta.branchesPerAgent).toBe(3)
}
)
- it('forces branch-cleanup useWorktree/openPR back off when stored true (loadSchedule)', async () => {
+ it('forces branch-reconcile useWorktree/openPR back off when stored true (loadSchedule)', async () => {
mockSchedule({
tasks: {
- 'branch-cleanup': {
+ 'branch-reconcile': {
type: 'cron',
enabled: true,
providerId: null,
@@ -1215,14 +1218,35 @@ describe('taskSchedule', () => {
})
const schedule = await loadSchedule()
- expect(schedule.tasks['branch-cleanup'].taskMetadata.useWorktree).toBe(false)
- expect(schedule.tasks['branch-cleanup'].taskMetadata.openPR).toBe(false)
+ expect(schedule.tasks['branch-reconcile'].taskMetadata.useWorktree).toBe(false)
+ expect(schedule.tasks['branch-reconcile'].taskMetadata.openPR).toBe(false)
// Backfilled from the defaults for installs whose stored config predates it.
- expect(schedule.tasks['branch-cleanup'].taskMetadata.worktreeChangesExpected).toBe(false)
+ expect(schedule.tasks['branch-reconcile'].taskMetadata.worktreeChangesExpected).toBe(false)
+ expect(schedule.tasks['branch-reconcile'].taskMetadata.branchesPerAgent).toBe(3)
})
- it('strips a per-app branch-cleanup worktree/PR override', () => {
- expect(stripManagedAgentOptionsFromOverride('branch-cleanup', { useWorktree: true, openPR: true })).toBeNull()
+ it('keeps the legacy branch-cleanup safety posture until migration 274 runs', async () => {
+ mockSchedule({
+ tasks: {
+ 'branch-cleanup': {
+ type: 'weekly',
+ enabled: true,
+ providerId: null,
+ model: null,
+ prompt: null,
+ taskMetadata: { useWorktree: true, openPR: true, worktreeChangesExpected: true }
+ }
+ }
+ })
+
+ const meta = (await loadSchedule()).tasks['branch-cleanup'].taskMetadata
+ expect(meta.useWorktree).toBe(false)
+ expect(meta.openPR).toBe(false)
+ expect(meta.worktreeChangesExpected).toBe(false)
+ })
+
+ it('strips a per-app branch-reconcile worktree/PR override', () => {
+ expect(stripManagedAgentOptionsFromOverride('branch-reconcile', { useWorktree: true, openPR: true })).toBeNull()
})
})
@@ -1245,6 +1269,15 @@ describe('taskSchedule', () => {
})
})
+ describe('branch-reconcile defaults', () => {
+ it('is the single hygiene task and defaults to a three-branch coordinator batch', () => {
+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('branch-reconcile')
+ expect(SELF_IMPROVEMENT_TASK_TYPES).not.toContain('branch-cleanup')
+ expect(DEFAULT_TASK_INTERVALS['branch-reconcile'].taskMetadata.branchesPerAgent).toBe(3)
+ expect(DEFAULT_TASK_INTERVALS['do-replan'].runAfter).toContain('branch-reconcile')
+ })
+ })
+
describe('refresh-local-llm-catalog defaults', () => {
it('is registered as a self-improvement task type', () => {
expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('refresh-local-llm-catalog')
diff --git a/server/services/workflow.js b/server/services/workflow.js
index 58570ebe4e..ada5805792 100644
--- a/server/services/workflow.js
+++ b/server/services/workflow.js
@@ -41,7 +41,7 @@ export const WORKFLOW_STAGES = [
id: 'hygiene',
label: 'Hygiene',
description: 'Reset state: clean up merged branches and stale agent data so downstream stages start clean.',
- taskTypes: ['branch-cleanup'],
+ taskTypes: ['branch-reconcile'],
jobIds: ['job-agent-data-cleanup']
},
{
diff --git a/server/services/workflow.test.js b/server/services/workflow.test.js
index e3e93fdeaa..04708248f7 100644
--- a/server/services/workflow.test.js
+++ b/server/services/workflow.test.js
@@ -39,10 +39,10 @@ describe('WORKFLOW_STAGES contract', () => {
expect(buildStage.taskTypes).toContain('feature-ideas');
});
- it('places branch-cleanup in the hygiene stage and pr-reviewer in review', () => {
+ it('places branch-reconcile in the hygiene stage and pr-reviewer in review', () => {
const hygiene = WORKFLOW_STAGES.find(s => s.id === 'hygiene');
const review = WORKFLOW_STAGES.find(s => s.id === 'review');
- expect(hygiene.taskTypes).toContain('branch-cleanup');
+ expect(hygiene.taskTypes).toContain('branch-reconcile');
expect(review.taskTypes).toContain('pr-reviewer');
});