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 classifier + deterministic cleanup

Adam Eivy68efb397da7f
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
new file mode 100644
index 0000000000..8f8e0c1f39
--- /dev/null
+++ b/server/services/branchReconcile.js
@@ -0,0 +1,215 @@
+/**
+ * Branch & PR Reconciler — deterministic core (Tier 1).
+ *
+ * Enumerates THIS machine's local branches (`refs/heads/`), classifies each by
+ * its merge / PR state, and deterministically cleans up the fully-merged,
+ * orphaned ones (remove the lingering worktree + delete the local branch).
+ * Everything that needs judgment (open a PR, resolve conflicts, drive a review
+ * loop, merge) is returned in `inFlight` for the scheduler to hand to a
+ * coordinator CoS agent — this module never spawns an agent, so it stays pure
+ * enough to unit-test.
+ *
+ * PEER SAFETY: only `refs/heads/` (local) branches are ever considered. A branch
+ * created on a federated peer exists here only as a remote-tracking ref
+ * (`origin/*`), never as a local branch, so it is structurally invisible. We
+ * never author-filter — every machine shares one GitHub login, so authorship
+ * can't distinguish machines; local-branch existence can.
+ */
+
+import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } from './git.js';
+import { execGit } from '../lib/execGit.js';
+import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt } from './worktreeManager.js';
+import { execGh } from './github.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
+import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
+
+// Never reconciled — these are long-lived shared branches, not disposable work.
+// The resolved default branch is added on top at runtime.
+export const PROTECTED_BRANCHES = ['main', 'master', 'release'];
+
+// Bound the gh query (single-user repos never realistically truncate at 200).
+const PR_LIST_LIMIT = 200;
+
+/**
+ * Pure classifier: map one branch's git/PR facts to a reconcile state.
+ * First match wins.
+ * MERGED — work is fully in the default branch → deterministic cleanup
+ * CONFLICTED — open PR with merge conflicts → agent resolves
+ * IN_REVIEW — open PR, otherwise → agent drives to merge
+ * NEEDS_PR — pushed, not merged, no PR, clean → agent verifies + opens PR
+ * WIP — local-only or dirty worktree → skip + report (never touch)
+ *
+ * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, openPr:({mergeable?:string}|null) }} input
+ * @returns {'MERGED'|'CONFLICTED'|'IN_REVIEW'|'NEEDS_PR'|'WIP'}
+ */
+export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, openPr }) {
+ if (isMerged) return 'MERGED';
+ if (openPr) return openPr.mergeable === 'CONFLICTING' ? 'CONFLICTED' : 'IN_REVIEW';
+ if (hasUpstream && !worktreeDirty) return 'NEEDS_PR';
+ return 'WIP';
+}
+
+/**
+ * Classify a list of gathered branch inputs. Pure.
+ * @param {object[]} inputs - each from `gatherBranchState`
+ * @returns {object[]} inputs with a `state` field added
+ */
+export function classifyBranches(inputs) {
+ return inputs.map((input) => ({ ...input, state: classifyBranch(input) }));
+}
+
+/**
+ * Resolve the open PRs for a repo, keyed by head branch name.
+ * Returns an empty Map on any gh failure (degrade: treat as "no PR").
+ * @param {string} repoPath
+ * @returns {Promise<Map<string, {number:number, mergeable:string, isDraft:boolean, url:string}>>}
+ */
+async function getOpenPrsByHead(repoPath) {
+ const origin = await getOriginInfo(repoPath).catch(() => null);
+ if (!origin?.isGithub || !origin.fullName) return new Map();
+ const raw = await execGh([
+ 'pr', 'list', '--repo', origin.fullName, '--state', 'open',
+ '--limit', String(PR_LIST_LIMIT),
+ '--json', 'number,headRefName,mergeable,isDraft,url'
+ ]).catch(() => null);
+ const parsed = safeJSONParse(raw, null);
+ if (!Array.isArray(parsed)) return new Map();
+ const byHead = new Map();
+ for (const pr of parsed) {
+ if (pr?.headRefName) {
+ byHead.set(pr.headRefName, {
+ number: pr.number,
+ mergeable: pr.mergeable || 'UNKNOWN',
+ isDraft: pr.isDraft === true,
+ url: pr.url || ''
+ });
+ }
+ }
+ return byHead;
+}
+
+/**
+ * Is a worktree's working tree carrying real (non-lockfile) uncommitted changes?
+ * @param {string} worktreePath
+ * @returns {Promise<boolean>}
+ */
+async function isWorktreeDirty(worktreePath) {
+ const { stdout } = await execGit(['status', '--porcelain'], worktreePath, { ignoreExitCode: true })
+ .catch(() => ({ stdout: '' }));
+ return classifyWorktreeDirt(stdout).hasRealChanges;
+}
+
+/**
+ * Gather the raw git/PR facts for every local feature branch in `repoPath`.
+ * Excludes the default branch, the currently-checked-out branch, and the
+ * always-protected set. Effectful (git + gh).
+ *
+ * @param {string} repoPath
+ * @param {{ defaultBranch:string }} ctx
+ * @returns {Promise<object[]>} one entry per candidate branch:
+ * { branch, hasUpstream, isMerged, hasWorktree, worktreePath, worktreeDirty, openPr }
+ */
+export async function gatherBranchState(repoPath, { defaultBranch }) {
+ const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);
+
+ const [branches, worktrees, prsByHead] = await Promise.all([
+ getBranches(repoPath),
+ listWorktrees(repoPath).catch(() => []),
+ getOpenPrsByHead(repoPath)
+ ]);
+
+ // Map local branch name -> worktree path (strip the refs/heads/ prefix).
+ const worktreeByBranch = new Map();
+ for (const wt of worktrees) {
+ const name = wt.branch?.replace(/^refs\/heads\//, '');
+ if (name) worktreeByBranch.set(name, wt.path);
+ }
+
+ const candidates = branches.filter(
+ (b) => !b.isDefault && !b.current && !protectedSet.has(b.name)
+ );
+
+ const inputs = [];
+ for (const b of candidates) {
+ const worktreePath = worktreeByBranch.get(b.name) || null;
+ const worktreeDirty = worktreePath ? await isWorktreeDirty(worktreePath) : false;
+ // getBranches' `merged` is ancestor-based (misses squash/rebase); confirm
+ // the harder cases via isBranchMergedInto (covers squash + rebase). Short
+ // -circuit when the cheap check already proved it merged.
+ const isMerged = b.merged || await isBranchMergedInto(repoPath, b.name, defaultBranch);
+ inputs.push({
+ branch: b.name,
+ hasUpstream: Boolean(b.tracking),
+ isMerged,
+ hasWorktree: Boolean(worktreePath),
+ worktreePath,
+ worktreeDirty,
+ openPr: prsByHead.get(b.name) || null
+ });
+ }
+ return inputs;
+}
+
+/**
+ * Deterministically clean up fully-merged branches: remove the lingering
+ * worktree, then delete the local branch. Safety gates (ALL must hold):
+ * 1. `isBranchMergedInto(default)` re-verified true (fail closed).
+ * 2. the branch's worktree (if any) has no real uncommitted changes.
+ * A failed gate skips the branch (with a reason) — never a force-delete of
+ * unmerged or dirty work.
+ *
+ * @param {string} repoPath
+ * @param {string} defaultBranch
+ * @param {object[]} merged - gathered inputs whose state === 'MERGED'
+ * @returns {Promise<{cleaned:string[], skipped:{branch:string,reason:string}[]}>}
+ */
+export async function cleanupMerged(repoPath, defaultBranch, merged) {
+ const cleaned = [];
+ const skipped = [];
+ for (const b of merged) {
+ // Re-verify at action time — state may have shifted since the gather.
+ const stillMerged = await isBranchMergedInto(repoPath, b.branch, defaultBranch);
+ if (!stillMerged) {
+ skipped.push({ branch: b.branch, reason: 'not-merged-on-recheck' });
+ continue;
+ }
+ if (b.worktreePath) {
+ const dirty = await isWorktreeDirty(b.worktreePath);
+ if (dirty) {
+ skipped.push({ branch: b.branch, reason: 'worktree-dirty' });
+ continue;
+ }
+ await forceRemoveWorktreeDir(repoPath, b.worktreePath, {
+ label: `🔀 branch-reconcile: remove worktree for ${b.branch}`, log: 'all'
+ });
+ }
+ const result = await deleteBranch(repoPath, b.branch, { local: true }).catch((err) => ({ error: err.message }));
+ if (result?.error || result?.results?.local?.startsWith?.('failed')) {
+ skipped.push({ branch: b.branch, reason: `delete-failed: ${result.error || result.results.local}` });
+ continue;
+ }
+ cleaned.push(b.branch);
+ }
+ return { cleaned, skipped };
+}
+
+/**
+ * Full Tier-1 reconcile: gather → classify → clean up merged. Returns the
+ * 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}[] }>}
+ */
+export async function reconcile(repoPath = PATHS.root) {
+ const defaultBranch = await getDefaultBranch(repoPath).catch(() => 'main') || 'main';
+ const inputs = await gatherBranchState(repoPath, { defaultBranch });
+ const classified = classifyBranches(inputs);
+
+ const merged = classified.filter((c) => c.state === 'MERGED');
+ 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);
+
+ return { defaultBranch, cleaned, inFlight, wip, skipped };
+}
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
new file mode 100644
index 0000000000..76cf4b150d
--- /dev/null
+++ b/server/services/branchReconcile.test.js
@@ -0,0 +1,169 @@
+/**
+ * Unit tests for the Branch & PR Reconciler deterministic core.
+ *
+ * - classifyBranch / classifyBranches — the pure state machine (no mocks).
+ * - cleanupMerged — the safety gates: only delete a branch when it re-verifies
+ * merged AND its worktree is clean; a failed gate skips with a reason.
+ * - reconcile — end-to-end wiring over a mocked gather (partitions cleaned /
+ * inFlight / wip correctly).
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./git.js', () => ({
+ getBranches: vi.fn(),
+ getDefaultBranch: vi.fn(async () => 'main'),
+ isBranchMergedInto: vi.fn(),
+ deleteBranch: vi.fn(async () => ({ branch: 'x', results: { local: 'deleted' } }))
+}));
+vi.mock('../lib/execGit.js', () => ({
+ execGit: vi.fn(async () => ({ stdout: '', exitCode: 0 }))
+}));
+vi.mock('./worktreeManager.js', () => ({
+ listWorktrees: vi.fn(async () => []),
+ forceRemoveWorktreeDir: vi.fn(async () => {}),
+ // Real pure classifier semantics: empty porcelain = clean.
+ classifyWorktreeDirt: vi.fn((p) => ({ hasRealChanges: Boolean((p || '').trim()) }))
+}));
+vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));
+vi.mock('../lib/gitRemote.js', () => ({
+ getOriginInfo: vi.fn(async () => ({ isGithub: true, fullName: 'atomantic/PortOS' }))
+}));
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { root: '/repo' },
+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } }
+}));
+
+import {
+ classifyBranch, classifyBranches, cleanupMerged, reconcile, gatherBranchState
+} from './branchReconcile.js';
+import * as git from './git.js';
+import * as wt from './worktreeManager.js';
+import { execGit } from '../lib/execGit.js';
+import { execGh } from './github.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ git.getDefaultBranch.mockResolvedValue('main');
+ git.deleteBranch.mockResolvedValue({ branch: 'x', results: { local: 'deleted' } });
+ wt.forceRemoveWorktreeDir.mockResolvedValue(undefined);
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 });
+});
+
+describe('classifyBranch', () => {
+ it('merged wins even over an open PR', () => {
+ expect(classifyBranch({ isMerged: true, openPr: { mergeable: 'MERGEABLE' }, hasUpstream: true })).toBe('MERGED');
+ });
+ it('open conflicting PR → CONFLICTED', () => {
+ expect(classifyBranch({ isMerged: false, openPr: { mergeable: 'CONFLICTING' }, hasUpstream: true })).toBe('CONFLICTED');
+ });
+ it('open mergeable PR → IN_REVIEW', () => {
+ expect(classifyBranch({ isMerged: false, openPr: { mergeable: 'MERGEABLE' }, hasUpstream: true })).toBe('IN_REVIEW');
+ });
+ it('pushed, no PR, clean → NEEDS_PR', () => {
+ expect(classifyBranch({ isMerged: false, openPr: null, hasUpstream: true, worktreeDirty: false })).toBe('NEEDS_PR');
+ });
+ it('pushed but dirty worktree → WIP', () => {
+ expect(classifyBranch({ isMerged: false, openPr: null, hasUpstream: true, worktreeDirty: true })).toBe('WIP');
+ });
+ it('local-only (no upstream), no PR → WIP', () => {
+ expect(classifyBranch({ isMerged: false, openPr: null, hasUpstream: false, worktreeDirty: false })).toBe('WIP');
+ });
+});
+
+describe('classifyBranches', () => {
+ it('annotates each input with its state', () => {
+ const out = classifyBranches([
+ { branch: 'a', isMerged: true, hasUpstream: true },
+ { branch: 'b', isMerged: false, openPr: null, hasUpstream: false }
+ ]);
+ expect(out.map((o) => o.state)).toEqual(['MERGED', 'WIP']);
+ });
+});
+
+describe('cleanupMerged', () => {
+ it('removes worktree + deletes branch when merged and clean', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktree
+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);
+ expect(res.cleaned).toEqual(['next/issue-2190']);
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/wt/2190', expect.any(Object));
+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'next/issue-2190', { local: true });
+ });
+
+ it('skips when re-check says not merged (fail closed)', async () => {
+ git.isBranchMergedInto.mockResolvedValue(false);
+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);
+ expect(res.cleaned).toEqual([]);
+ expect(res.skipped).toEqual([{ branch: 'next/issue-2190', reason: 'not-merged-on-recheck' }]);
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+
+ it('skips when the worktree has real uncommitted changes', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: ' M server/index.js', exitCode: 0 }); // dirty
+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2196', worktreePath: '/wt/2196' }]);
+ expect(res.cleaned).toEqual([]);
+ expect(res.skipped).toEqual([{ branch: 'next/issue-2196', reason: 'worktree-dirty' }]);
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+
+ it('deletes a merged branch with no worktree', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'orphan', worktreePath: null }]);
+ expect(res.cleaned).toEqual(['orphan']);
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ });
+});
+
+describe('gatherBranchState', () => {
+ it('excludes default/current/protected and folds in worktree + PR facts', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'main', isDefault: true, current: true, tracking: 'origin/main', merged: false },
+ { name: 'release', isDefault: false, current: false, tracking: 'origin/release', merged: false },
+ { name: 'next/issue-2199', isDefault: false, current: false, tracking: 'origin/next/issue-2199', merged: false },
+ { name: 'next/issue-2190', isDefault: false, current: false, tracking: 'origin/next/issue-2190', merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([
+ { path: '/wt/2199', branch: 'refs/heads/next/issue-2199' }
+ ]);
+ execGh.mockResolvedValue(JSON.stringify([
+ { number: 2206, headRefName: 'next/issue-2199', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }
+ ]));
+ git.isBranchMergedInto.mockResolvedValue(false);
+
+ const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });
+ const names = inputs.map((i) => i.branch);
+ expect(names).toEqual(['next/issue-2199', 'next/issue-2190']); // main + release excluded
+
+ const i2199 = inputs.find((i) => i.branch === 'next/issue-2199');
+ expect(i2199.hasWorktree).toBe(true);
+ expect(i2199.openPr.number).toBe(2206);
+ expect(inputs.find((i) => i.branch === 'next/issue-2190').isMerged).toBe(true);
+ });
+});
+
+describe('reconcile', () => {
+ it('cleans merged, returns in-flight + wip partitions', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'next/issue-2190', isDefault: false, current: false, tracking: 'origin/x', merged: true },
+ { name: 'next/issue-2199', isDefault: false, current: false, tracking: 'origin/y', merged: false },
+ { name: 'wip-local', isDefault: false, current: false, tracking: '', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ execGh.mockResolvedValue(JSON.stringify([
+ { number: 2206, headRefName: 'next/issue-2199', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }
+ ]));
+ // Branch-aware: only 2190 is merged (gather short-circuits it via merged:true;
+ // this also satisfies the cleanup re-check). 2199 must stay un-merged so it
+ // classifies IN_REVIEW rather than being swept into cleanup.
+ git.isBranchMergedInto.mockImplementation(async (_dir, branch) => branch === 'next/issue-2190');
+
+ const res = await reconcile('/repo');
+ expect(res.cleaned).toEqual(['next/issue-2190']);
+ expect(res.inFlight.map((i) => i.branch)).toEqual(['next/issue-2199']);
+ expect(res.inFlight[0].state).toBe('IN_REVIEW');
+ expect(res.wip.map((i) => i.branch)).toEqual(['wip-local']);
+ });
+});