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: add branch reconcile scheduler + coordinator dispatch

Adam Eivy6e9f58473ef6
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 8f8e0c1f39..37d2393e90 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -198,9 +198,11 @@ export async function cleanupMerged(repoPath, defaultBranch, merged) {
* in-flight set (branches needing an agent) for the scheduler to dispatch.
*
* @param {string} [repoPath=PATHS.root]
- * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[] }>}
+ * @param {{ cleanup?: boolean }} [opts] - when cleanup is false, merged branches
+ * are reported (as `merged`) but not deleted (honors the cleanupMerged toggle).
+ * @returns {Promise<{ defaultBranch:string, cleaned:string[], merged:object[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[] }>}
*/
-export async function reconcile(repoPath = PATHS.root) {
+export async function reconcile(repoPath = PATHS.root, { cleanup = true } = {}) {
const defaultBranch = await getDefaultBranch(repoPath).catch(() => 'main') || 'main';
const inputs = await gatherBranchState(repoPath, { defaultBranch });
const classified = classifyBranches(inputs);
@@ -209,7 +211,9 @@ export async function reconcile(repoPath = PATHS.root) {
const inFlight = classified.filter((c) => ['CONFLICTED', 'IN_REVIEW', 'NEEDS_PR'].includes(c.state));
const wip = classified.filter((c) => c.state === 'WIP');
- const { cleaned, skipped } = await cleanupMerged(repoPath, defaultBranch, merged);
+ const { cleaned, skipped } = cleanup
+ ? await cleanupMerged(repoPath, defaultBranch, merged)
+ : { cleaned: [], skipped: merged.map((m) => ({ branch: m.branch, reason: 'cleanup-disabled' })) };
- return { defaultBranch, cleaned, inFlight, wip, skipped };
+ return { defaultBranch, cleaned, merged, inFlight, wip, skipped };
}
diff --git a/server/services/branchReconcileScheduler.js b/server/services/branchReconcileScheduler.js
new file mode 100644
index 0000000000..3801fc27f2
--- /dev/null
+++ b/server/services/branchReconcileScheduler.js
@@ -0,0 +1,208 @@
+/**
+ * Branch & PR Reconciler — scheduler + coordinator dispatch (Tier 2).
+ *
+ * Registers a daily cron (via eventScheduler, the backupScheduler.js pattern)
+ * that runs the deterministic Tier-1 `reconcile()` and, when in-flight branches
+ * remain, enqueues ONE coordinator CoS task. The coordinator agent orchestrates
+ * one sub-agent per in-flight branch (each in that branch's existing worktree)
+ * to open PRs, resolve conflicts, drive review loops, and merge when fully green.
+ *
+ * The whole feature is opt-in: the cron handler no-ops unless
+ * `settings.branchReconcile.enabled` is true. The API "Run now" path passes
+ * `{ force: true }` — an explicit user action is its own consent, so it runs even
+ * while the schedule is off (letting the user test on demand).
+ */
+
+import { schedule, cancel } from './eventScheduler.js';
+import { getSettings } from './settings.js';
+import { getUserTimezone } from '../lib/timezone.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { PRIORITY_VALUES } from './cosTaskStore.js';
+import { addTask } from './cosTaskStore.js';
+import { reconcile } from './branchReconcile.js';
+
+const CRON_ID = 'branch-reconcile';
+
+// Stable first-line description → addTask dedups it against any pending/in_progress
+// coordinator, so a later daily run can't stack a second coordinator on top of one
+// still finishing (the re-entrancy guard, for free).
+const COORDINATOR_DESCRIPTION = 'Branch & PR reconcile: finish this machine\'s in-flight local branches';
+
+// Last run summary, surfaced by GET /api/branch-reconcile/status.
+let lastRun = null;
+export function getLastRun() { return lastRun; }
+
+/** An action is ON unless the settings explicitly set it to false (opt-out). */
+const actionOn = (actions, key) => actions?.[key] !== false;
+
+/**
+ * Which in-flight branches have an enabled action? Pure — drives both the
+ * dispatch gate and the prompt payload.
+ * @param {object[]} inFlight - reconcile()'s inFlight entries (with `state`)
+ * @param {object} actions - settings.branchReconcile.actions
+ */
+export function filterActionable(inFlight, actions) {
+ return inFlight.filter((b) => {
+ if (b.state === 'NEEDS_PR') return actionOn(actions, 'openPr');
+ if (b.state === 'CONFLICTED') return actionOn(actions, 'resolveConflicts');
+ if (b.state === 'IN_REVIEW') return actionOn(actions, 'resolveConflicts') || actionOn(actions, 'autoMerge');
+ return false;
+ });
+}
+
+/** Per-state one-line instruction to the coordinator/sub-agent. */
+function desiredEndState(state, actions) {
+ if (state === 'NEEDS_PR') {
+ return 'Verify the branch\'s work is complete and ready (tests pass, no stubs/TODO markers, changelog present). If ready, run `/do:pr`. If NOT ready, report it as incomplete and leave the branch untouched — do not open a half-baked PR.';
+ }
+ if (state === 'CONFLICTED') {
+ return 'Rebase the branch onto the default branch, resolve all conflicts, run the tests, and push.';
+ }
+ // IN_REVIEW
+ const canMerge = actionOn(actions, 'autoMerge');
+ return `Drive the open PR toward green: request/await the Copilot review and address feedback.${canMerge
+ ? ' Then MERGE it (`gh pr merge --merge --delete-branch`) ONLY when it is MERGEABLE, CI is fully green, and the LATEST Copilot review reports "0 comments" (pre-resolved threads do NOT count; a PR over 20k lines is exempt from the Copilot check and needs only CI-green + mergeable). After merging, delete the local branch and remove its worktree.'
+ : ' Do NOT merge (auto-merge is disabled) — stop once the PR is green and ready for the user to merge.'}`;
+}
+
+/**
+ * Render the in-flight branch set into the coordinator prompt body.
+ * @param {object[]} inFlight - actionable branches
+ * @param {{ defaultBranch:string, actions:object }} ctx
+ * @returns {string}
+ */
+export function formatInFlightForPrompt(inFlight, { defaultBranch, actions }) {
+ const lines = [`Default branch: \`${defaultBranch}\`. Branches to reconcile (${inFlight.length}):`, ''];
+ 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}`);
+ if (b.worktreePath) lines.push(`- Worktree: \`${b.worktreePath}\``);
+ lines.push(`- Do: ${desiredEndState(b.state, actions)}`);
+ lines.push('');
+ }
+ return lines.join('\n');
+}
+
+/**
+ * Build the coordinator CoS task (raw shape, ready for addTask({raw:true})).
+ * Multi-line instructions live in `metadata.context` (survives the TASKS.md
+ * round-trip); `description` is a stable single line for dedup.
+ *
+ * @param {object[]} inFlight - actionable in-flight branches
+ * @param {{ defaultBranch:string, actions:object, now?:number }} ctx
+ * @returns {object} task object
+ */
+export function buildCoordinatorTask(inFlight, { defaultBranch, actions, now = 0 }) {
+ const body = [
+ '# Branch & PR Reconciliation',
+ '',
+ 'You are the coordinator for finishing this machine\'s unfinished local git work. Each branch below is a LOCAL branch on this machine (peer branches are never included). Spawn ONE sub-agent per branch (they are independent — run them in parallel) to carry out the "Do:" instruction for that branch, each working in the branch\'s existing worktree when it has one. Never touch any branch not listed here.',
+ '',
+ formatInFlightForPrompt(inFlight, { defaultBranch, actions }),
+ '## Rules',
+ '- Work only on the branches listed above.',
+ '- Never force-push the default branch and never merge unreviewed work.',
+ '- If a sub-agent reports a branch is incomplete or blocked, leave it and note it in your summary.',
+ '- Summarize what each branch ended up doing (PR opened / conflicts resolved / merged / left incomplete).'
+ ].join('\n');
+
+ return {
+ id: `sys-branch-reconcile-${now.toString(36)}`,
+ status: 'pending',
+ priority: 'LOW',
+ priorityValue: PRIORITY_VALUES.LOW,
+ description: COORDINATOR_DESCRIPTION,
+ metadata: {
+ context: body,
+ // Runs on the PortOS checkout itself (it orchestrates across sibling
+ // worktrees), so no isolated worktree for the coordinator.
+ useWorktree: false,
+ source: 'branchReconcile',
+ updatedAt: new Date(now).toISOString()
+ },
+ approvalRequired: false,
+ autoApproved: true,
+ section: 'pending'
+ };
+}
+
+/**
+ * Run one reconcile pass. Wrapped in try/catch — it runs from a cron handler and
+ * the API route, both outside the Express request lifecycle.
+ *
+ * @param {{ force?: boolean, now?: number }} [opts]
+ * @returns {Promise<object>} summary
+ */
+export async function runBranchReconcile({ force = false, now = Date.now() } = {}) {
+ try {
+ const settings = await getSettings();
+ const cfg = settings.branchReconcile || {};
+ if (!force && !cfg.enabled) {
+ lastRun = { at: new Date(now).toISOString(), skipped: 'disabled' };
+ return lastRun;
+ }
+ const actions = cfg.actions || {};
+
+ const result = await reconcile(PATHS.root, { cleanup: actionOn(actions, 'cleanupMerged') });
+ const actionable = filterActionable(result.inFlight, actions);
+
+ let dispatched = false;
+ if (actionable.length > 0) {
+ const task = buildCoordinatorTask(actionable, {
+ defaultBranch: result.defaultBranch, actions, now
+ });
+ const added = await addTask(task, 'internal', { raw: true });
+ dispatched = !added?.duplicate;
+ if (added?.duplicate) {
+ console.log('🔀 branch-reconcile: a coordinator is already in flight — skipping dispatch');
+ }
+ }
+
+ const summary = {
+ at: new Date(now).toISOString(),
+ cleaned: result.cleaned,
+ inFlight: result.inFlight.map((b) => ({ branch: b.branch, state: b.state })),
+ actionable: actionable.map((b) => b.branch),
+ wip: result.wip.map((b) => b.branch),
+ skipped: result.skipped,
+ dispatched
+ };
+ lastRun = summary;
+ console.log(`🔀 branch-reconcile: cleaned ${result.cleaned.length}, ${actionable.length} in-flight actionable, dispatched=${dispatched}`);
+ return summary;
+ } catch (err) {
+ console.error(`❌ branch-reconcile run failed: ${err.message}`);
+ lastRun = { at: new Date(now).toISOString(), error: err.message };
+ return lastRun;
+ }
+}
+
+/**
+ * Register the daily cron. No-ops (leaves the job unregistered) when disabled;
+ * the handler re-reads settings each run so action toggles take effect live, but
+ * changing the cron expression itself needs a restart (matches backupScheduler).
+ */
+export async function startBranchReconcileScheduler() {
+ const settings = await getSettings();
+ const cfg = settings.branchReconcile || {};
+ if (!cfg.enabled) {
+ console.log('🔀 branch-reconcile scheduler: disabled in settings — skipping');
+ return;
+ }
+ const cron = cfg.cron || '0 3 * * *';
+ const timezone = await getUserTimezone();
+ schedule({
+ id: CRON_ID,
+ type: 'cron',
+ cron,
+ timezone,
+ handler: () => runBranchReconcile(),
+ metadata: { source: 'branchReconcileScheduler' }
+ });
+ console.log(`🔀 branch-reconcile scheduler: registered at cron "${cron}"`);
+}
+
+export function stopBranchReconcileScheduler() {
+ cancel(CRON_ID);
+ console.log('🔀 branch-reconcile scheduler: stopped');
+}
diff --git a/server/services/branchReconcileScheduler.test.js b/server/services/branchReconcileScheduler.test.js
new file mode 100644
index 0000000000..c133c35fab
--- /dev/null
+++ b/server/services/branchReconcileScheduler.test.js
@@ -0,0 +1,137 @@
+/**
+ * Unit tests for the Branch & PR Reconciler scheduler + coordinator dispatch.
+ *
+ * - filterActionable — action toggles gate which in-flight branches dispatch.
+ * - buildCoordinatorTask — stable dedup description, multi-line body in
+ * metadata.context, auto-approved, no worktree.
+ * - runBranchReconcile — disabled short-circuit, force bypass, cleanup toggle,
+ * dispatch only when actionable, duplicate handling.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./eventScheduler.js', () => ({ schedule: vi.fn(), cancel: vi.fn() }));
+vi.mock('./settings.js', () => ({ getSettings: vi.fn() }));
+vi.mock('../lib/timezone.js', () => ({ getUserTimezone: vi.fn(async () => 'UTC') }));
+vi.mock('../lib/fileUtils.js', () => ({ PATHS: { root: '/repo' } }));
+vi.mock('./cosTaskStore.js', () => ({
+ PRIORITY_VALUES: { LOW: 1, MEDIUM: 2, HIGH: 3 },
+ addTask: vi.fn(async () => ({ id: 'sys-branch-reconcile-x' }))
+}));
+vi.mock('./branchReconcile.js', () => ({ reconcile: vi.fn() }));
+
+import {
+ filterActionable, formatInFlightForPrompt, buildCoordinatorTask, runBranchReconcile, getLastRun
+} from './branchReconcileScheduler.js';
+import { getSettings } from './settings.js';
+import { addTask } from './cosTaskStore.js';
+import { reconcile } from './branchReconcile.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ addTask.mockResolvedValue({ id: 'sys-branch-reconcile-x' });
+});
+
+const IN_FLIGHT = [
+ { branch: 'needspr', state: 'NEEDS_PR', openPr: null },
+ { branch: 'conflicted', state: 'CONFLICTED', openPr: { number: 1, mergeable: 'CONFLICTING' } },
+ { branch: 'inreview', state: 'IN_REVIEW', openPr: { number: 2, mergeable: 'MERGEABLE', url: 'u' } }
+];
+
+describe('filterActionable', () => {
+ it('all states pass when all actions default on', () => {
+ expect(filterActionable(IN_FLIGHT, {}).map((b) => b.branch))
+ .toEqual(['needspr', 'conflicted', 'inreview']);
+ });
+ it('drops NEEDS_PR when openPr disabled', () => {
+ expect(filterActionable(IN_FLIGHT, { openPr: false }).map((b) => b.branch))
+ .toEqual(['conflicted', 'inreview']);
+ });
+ it('drops CONFLICTED when resolveConflicts disabled', () => {
+ expect(filterActionable(IN_FLIGHT, { resolveConflicts: false }).map((b) => b.branch))
+ .toEqual(['needspr', 'inreview']); // IN_REVIEW still kept via autoMerge
+ });
+ it('drops IN_REVIEW only when both resolveConflicts and autoMerge disabled', () => {
+ expect(filterActionable(IN_FLIGHT, { resolveConflicts: false, autoMerge: false }).map((b) => b.branch))
+ .toEqual(['needspr']);
+ });
+});
+
+describe('formatInFlightForPrompt', () => {
+ it('renders a section per branch with state, PR, and a Do line', () => {
+ const out = formatInFlightForPrompt(IN_FLIGHT, { defaultBranch: 'main', actions: {} });
+ expect(out).toContain('`needspr` [NEEDS_PR]');
+ expect(out).toContain('PR #2 (MERGEABLE)');
+ expect(out).toContain('Do:');
+ });
+ it('IN_REVIEW omits merge instruction when autoMerge is off', () => {
+ const out = formatInFlightForPrompt([IN_FLIGHT[2]], { defaultBranch: 'main', actions: { autoMerge: false } });
+ expect(out).toContain('Do NOT merge');
+ });
+});
+
+describe('buildCoordinatorTask', () => {
+ it('produces a raw, auto-approved task with body in metadata.context', () => {
+ const task = buildCoordinatorTask(IN_FLIGHT, { defaultBranch: 'main', actions: {}, now: 0 });
+ expect(task.autoApproved).toBe(true);
+ expect(task.status).toBe('pending');
+ expect(task.metadata.useWorktree).toBe(false);
+ expect(task.metadata.context).toContain('Branch & PR Reconciliation');
+ expect(task.metadata.context).toContain('`conflicted`');
+ // Stable description = dedup key across daily runs.
+ expect(task.description).toBe("Branch & PR reconcile: finish this machine's in-flight local branches");
+ });
+});
+
+describe('runBranchReconcile', () => {
+ it('short-circuits when disabled (no reconcile)', async () => {
+ getSettings.mockResolvedValue({ branchReconcile: { enabled: false } });
+ const res = await runBranchReconcile({ now: 0 });
+ expect(res.skipped).toBe('disabled');
+ expect(reconcile).not.toHaveBeenCalled();
+ });
+
+ it('force bypasses the disabled gate', async () => {
+ getSettings.mockResolvedValue({ branchReconcile: { enabled: false } });
+ reconcile.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [] });
+ const res = await runBranchReconcile({ force: true, now: 0 });
+ expect(res.skipped).not.toBe('disabled'); // ran, not short-circuited
+ expect(reconcile).toHaveBeenCalledWith('/repo', { cleanup: true });
+ });
+
+ it('passes cleanup:false when cleanupMerged disabled', async () => {
+ getSettings.mockResolvedValue({ branchReconcile: { enabled: true, actions: { cleanupMerged: false } } });
+ reconcile.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [] });
+ await runBranchReconcile({ now: 0 });
+ expect(reconcile).toHaveBeenCalledWith('/repo', { cleanup: false });
+ });
+
+ it('dispatches a coordinator when actionable branches exist', async () => {
+ getSettings.mockResolvedValue({ branchReconcile: { enabled: true, actions: {} } });
+ reconcile.mockResolvedValue({
+ defaultBranch: 'main', cleaned: ['old'], inFlight: IN_FLIGHT, wip: [], skipped: []
+ });
+ const res = await runBranchReconcile({ now: 0 });
+ expect(addTask).toHaveBeenCalledTimes(1);
+ expect(addTask.mock.calls[0][1]).toBe('internal');
+ expect(res.dispatched).toBe(true);
+ expect(res.actionable).toEqual(['needspr', 'conflicted', 'inreview']);
+ });
+
+ it('does not dispatch when nothing is actionable', async () => {
+ getSettings.mockResolvedValue({ branchReconcile: { enabled: true, actions: {} } });
+ reconcile.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: ['x'], skipped: [] });
+ const res = await runBranchReconcile({ now: 0 });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(res.dispatched).toBe(false);
+ });
+
+ it('reports dispatched=false when addTask says duplicate', async () => {
+ getSettings.mockResolvedValue({ branchReconcile: { enabled: true, actions: {} } });
+ reconcile.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: IN_FLIGHT, wip: [], skipped: [] });
+ addTask.mockResolvedValue({ id: 'existing', duplicate: true });
+ const res = await runBranchReconcile({ now: 0 });
+ expect(res.dispatched).toBe(false);
+ expect(getLastRun()).toBe(res);
+ });
+});