Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep branch reconcile from deleting fresh worktrees it does not own (#10270)
Adam Eivy7b931c1380c0
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex b3d3120ea5..76171e7cc2 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -23,6 +23,7 @@*/import { stat } from 'node:fs/promises';+import { join } from 'node:path';import { isHostShuttingDown } from '../lib/hostShutdown.js';import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteBranch } from './git.js';import { execGit } from '../lib/execGit.js';@@ -325,18 +326,20 @@ async function getOpenPrsByHead(repoPath, providedOrigin, { forgeExec = null, fo* UNLESS it is an abandoned one older than `staleClaimIdleMs`* (`ageMs` supplied) — those are reaped (see STALE_CLAIM_IDLE_MS,* and SHIPPED_CLAIM_IDLE_MS for a claim proven shipped)- * Sibling worktrees (`next-issue-*`, etc.) whose basename is none of these fall- * through to null and are cleaned normally.+ * With `roots` (what every retirement passes — see `reconcileWorktreeRoots`), a+ * worktree outside them is `worktree-unmanaged-location` before any of the above:+ * a directory PortOS never created carries no ownership signal at all.*- * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number, staleClaimIdleMs?:number }} input+ * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number, staleClaimIdleMs?:number, roots?:Array<{path:string, requireAgentId?:boolean}> }} input* @returns {string|null}*/-export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false }) {+export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, roots = [] }) {if (!path) return null;return worktreeOwnershipReason({path,locked,activeAgentIds,+ roots,allowStaleClaim: true,allowLiveClaim,ageMs,@@ -344,6 +347,33 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,});}+/**+ * The only places unattended branch reconciliation may retire a worktree from:+ * PortOS's own CoS worktree root (agent and claim checkouts, PortOS's and every+ * managed app's) and the repository's `.claude/worktrees/` — the same two roots+ * `reapMergedWorktrees` confines its unattended pass to.+ *+ * Anywhere else is a directory some other process made, and nothing about it+ * proves that process is gone: a checkout freshly cut from the default branch is+ * clean and an ancestor of it, which is all `cleanupMerged` otherwise asks for,+ * and its mtime says when it was created, not whether its owner is finished.+ * Reconcile once deleted a release worktree a minute after a still-running+ * release run created it (#10270). So such a tree holds, at any age, with its+ * branch; the operator's explicit merged-branch cleanup (`deleteMergedBranches`,+ * `includeUnmanagedTrees`) keeps its wider reach.+ *+ * Arbitrary names are accepted INSIDE these roots on purpose: claim trees are+ * `claim-*`, not `agent-*`, and still need their stale/shipped retirement.+ *+ * @param {string} repoPath+ * @returns {Array<{path:string, requireAgentId:boolean}>}+ */+function reconcileWorktreeRoots(repoPath) {+ return [PATHS.worktrees, repoPath && join(repoPath, '.claude', 'worktrees')]+ .filter(Boolean)+ .map((path) => ({ path, requireAgentId: false }));+}+/*** When `worktreeProtectionReason`'s hold on this worktree lapses by itself, as an* ISO instant — or null when only an outside change can clear it.@@ -355,12 +385,13 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,* @param {{ path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null, staleClaimIdleMs?:number, allowLiveClaim?:boolean }} input* @returns {string|null} ISO timestamp*/-export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false }) {+export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, roots = [] }) {if (!path) return null;return worktreeHoldExpiresAt({path,locked,activeAgentIds,+ roots,allowStaleClaim: true,allowLiveClaim,ageMs,@@ -1021,6 +1052,8 @@ async function releaseRetiredClaim(repoPath, branch, { origin, forgeExec, forgeA* worktree, then delete the local branch. Safety gates (ALL must hold):* 1. `hasBranchMergeEvidence(default)` re-verified true (fail closed).* 2. the branch's worktree (if any) has no real uncommitted changes.+ * 3. that worktree (if any) lives in a managed root (`reconcileWorktreeRoots`)+ * and no lock, live owner, or claim window holds it.* A failed gate skips the branch (with a reason) — never a force-delete of* unmerged or dirty work.*@@ -1220,8 +1253,9 @@ async function retireBranch(repoPath, b, opts) {async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, prepare }) {if (b.worktreePath) {- // Never tear down a worktree that's locked, a RECENT human /claim session, or- // an active CoS agent workspace. An abandoned claim worktree (clean and older+ // Never tear down a worktree outside the managed roots (see+ // reconcileWorktreeRoots), one that's locked, a RECENT human /claim session,+ // or an active CoS agent workspace. An abandoned claim worktree (clean and older// than the window) falls through and IS retired; that's the "cleaned 0// forever" leak this exists to close.const gate = {@@ -1231,6 +1265,7 @@ async function retireBranchNow(repoPath, b, { activeAgentIds = new Set(), staleCageMs: b.worktreeAgeMs,staleClaimIdleMs,allowLiveClaim,+ roots: reconcileWorktreeRoots(repoPath),};const protectedReason = worktreeProtectionReason(gate);if (protectedReason) {diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.jsnew file mode 100644index 0000000000..fe67f73236--- /dev/null+++ b/server/services/branchReconcile.ownership.test.js@@ -0,0 +1,107 @@+/**+ * Worktree ownership through branch-reconcile's real cleanup boundary (#10270).+ *+ * A checkout freshly cut from the default branch is clean and an ancestor of+ * it, so the merged-branch cleanup used to retire it — and its branch — while+ * the process that created it was still running. These tests drive `reconcile`+ * against a real throwaway repository (no origin, so no forge is consulted) to+ * pin that only PortOS-managed roots are retired unattended, while the+ * operator's explicit merged-branch cleanup keeps its wider reach.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtemp, mkdir, rm, utimes, writeFile } from 'fs/promises';+import { existsSync, realpathSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { execGit } from '../lib/execGit.js';+import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';++// Keep the run hermetic: the verdict ledger otherwise reads this install's+// real CoS data directory.+vi.mock('./supersededLedger.js', async (importOriginal) => ({+ ...await importOriginal(),+ readVerdictLedger: async () => [],+}));++const { reconcile } = await import('./branchReconcile.js');+const { deleteMergedBranches } = await import('./git.js');++const DAY = 24 * 60 * 60 * 1000;++describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (real git)', () => {+ let scratch;+ let repo;+ let external;++ beforeEach(async () => {+ scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reconcile-own-')));+ const safeRepo = join(scratch, 'repo');+ await mkdir(safeRepo);+ await materializeGitRepo(safeRepo, { identity: { email: '[email protected]', name: 'Test' } });+ repo = (await execGit(['rev-parse', '--show-toplevel'], safeRepo)).stdout.trim() || safeRepo;+ external = join(scratch, 'elsewhere');+ await mkdir(external);+ });+ afterEach(async () => {+ await rm(scratch, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ });++ /** A clean checkout of a new branch at main — "merged" by ancestry alone. */+ async function addTree(path, branch, { ageMs = 0 } = {}) {+ await execGit(['worktree', 'add', '-b', branch, path, 'main'], repo);+ if (ageMs) {+ const then = new Date(Date.now() - ageMs);+ await utimes(path, then, then);+ }+ return path;+ }++ const branches = async () => (await execGit(['branch', '--format=%(refname:short)'], repo)).stdout.trim().split('\n');++ it('retires inactive managed trees but never a fresh or old unmanaged one', async () => {+ const claudeRoot = join(repo, '.claude', 'worktrees');+ await mkdir(claudeRoot, { recursive: true });+ const fresh = await addTree(join(external, 'release-preparation'), 'release-prep/v9.9.9');+ const old = await addTree(join(external, 'old-workspace'), 'old-workspace', { ageMs: 30 * DAY });+ const staleClaim = await addTree(join(claudeRoot, 'claim-issue-5'), 'claim/issue-5', { ageMs: 30 * DAY });+ const lockedClaim = await addTree(join(claudeRoot, 'claim-issue-6'), 'claim/issue-6', { ageMs: 30 * DAY });+ await execGit(['worktree', 'lock', lockedClaim], repo);+ const dirtyClaim = await addTree(join(claudeRoot, 'claim-issue-7'), 'claim/issue-7');+ await writeFile(join(dirtyClaim, 'wip.txt'), 'unsaved\n');+ await utimes(dirtyClaim, new Date(Date.now() - 30 * DAY), new Date(Date.now() - 30 * DAY));++ const result = await reconcile(repo, { activeAgentIds: new Set() });+ const reasonFor = (branch) => result.skipped.find((s) => s.branch === branch)?.reason;+ const context = JSON.stringify({ cleaned: result.cleaned, skipped: result.skipped });++ // Unmanaged: held at any age, checkout AND branch intact.+ expect(reasonFor('release-prep/v9.9.9'), context).toBe('worktree-unmanaged-location');+ expect(reasonFor('old-workspace'), context).toBe('worktree-unmanaged-location');+ expect(existsSync(fresh)).toBe(true);+ expect(existsSync(old)).toBe(true);++ // Managed: an abandoned claim is still retired; a lock or real work holds.+ expect(result.cleaned, context).toContain('claim/issue-5');+ expect(existsSync(staleClaim)).toBe(false);+ expect(reasonFor('claim/issue-6'), context).toBe('worktree-locked');+ expect(existsSync(lockedClaim)).toBe(true);+ expect(result.cleaned, context).not.toContain('claim/issue-7');+ expect(existsSync(dirtyClaim)).toBe(true);++ const left = await branches();+ expect(left).toEqual(expect.arrayContaining(['release-prep/v9.9.9', 'old-workspace', 'claim/issue-6', 'claim/issue-7']));+ expect(left).not.toContain('claim/issue-5');+ });++ it('leaves the operator-initiated merged-branch cleanup able to remove an unmanaged tree', async () => {+ const loose = await addTree(join(external, 'loose'), 'loose-br', { ageMs: 30 * DAY });++ const held = await reconcile(repo, { activeAgentIds: new Set() });+ expect(held.skipped.find((s) => s.branch === 'loose-br')?.reason).toBe('worktree-unmanaged-location');++ const operator = await deleteMergedBranches(repo, { activeAgentIds: new Set() });+ expect(operator.deleted.map((d) => d.name), JSON.stringify(operator)).toContain('loose-br');+ expect(existsSync(loose)).toBe(false);+ expect(await branches()).not.toContain('loose-br');+ });+});diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex ceec5da013..b95f0d6dd4 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -81,7 +81,7 @@ vi.mock('../lib/fileUtils.js', () => ({// `issueReconcile.js`, whose module graph (via jira.js) reads `PATHS.data`// at import time — an incomplete PATHS here crashed with a raw TypeError// rather than a test failure.- PATHS: { root: '/repo', cos: '/repo/data/cos', data: '/repo/data' },+ PATHS: { root: '/repo', cos: '/repo/data/cos', data: '/repo/data', worktrees: '/repo/data/cos/worktrees' },safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } },isPathInsideDir: (dir, candidate) => typeof dir === 'string' && typeof candidate === 'string'&& candidate.startsWith(`${dir}/`),@@ -341,9 +341,9 @@ describe('cleanupMerged', () => {it('removes worktree + deletes branch when merged and clean', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktree- const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/repo/.claude/worktrees/next-2190' }]);expect(res.cleaned).toEqual(['next/issue-2190']);- expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/wt/2190', expect.any(Object));+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/.claude/worktrees/next-2190', expect.any(Object));expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'next/issue-2190', { local: true });});@@ -351,14 +351,14 @@ describe('cleanupMerged', () => {git.hasBranchMergeEvidence.mockResolvedValue(true);execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean worktreewt.forceRemoveWorktreeDir.mockResolvedValue({ removed: false, warning: 'Worktree cleanup incomplete — retryable' });- const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/repo/.claude/worktrees/next-2190' }]);expect(res.cleaned).toEqual([]);expect(git.deleteBranch).not.toHaveBeenCalled();});it('skips when re-check says not merged (fail closed)', async () => {git.hasBranchMergeEvidence.mockResolvedValue(false);- const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/wt/2190' }]);+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2190', worktreePath: '/repo/.claude/worktrees/next-2190' }]);expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'next/issue-2190', reason: 'not-merged-on-recheck' }]);expect(git.deleteBranch).not.toHaveBeenCalled();@@ -367,7 +367,7 @@ describe('cleanupMerged', () => {it('skips when the worktree has real uncommitted changes', async () => {git.hasBranchMergeEvidence.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' }]);+ const res = await cleanupMerged('/repo', 'main', [{ branch: 'next/issue-2196', worktreePath: '/repo/.claude/worktrees/next-2196' }]);expect(res.cleaned).toEqual([]);expect(res.skipped).toEqual([{ branch: 'next/issue-2196', reason: 'worktree-dirty' }]);expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();@@ -385,7 +385,7 @@ describe('cleanupMerged', () => {git.hasBranchMergeEvidence.mockResolvedValue(true);const activeAgentIds = new Set(['agent-abc12345']);const res = await cleanupMerged('/repo', 'main', [- { branch: 'locked-b', worktreePath: '/wt/locked', worktreeLocked: true },+ { branch: 'locked-b', worktreePath: '/repo/data/cos/worktrees/locked', worktreeLocked: true },{ branch: 'claim-b', worktreePath: '/repo/data/cos/worktrees/claim-foo' },{ branch: 'active-b', worktreePath: '/repo/data/cos/worktrees/agent-abc12345' }], { activeAgentIds });@@ -414,7 +414,7 @@ describe('cleanupMerged', () => {it('releases a retired issue claim with the repository credential after deletion', async () => {mockOwnedClaim();git.hasBranchMergeEvidence.mockResolvedValue(true);- await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-42', worktreePath: '/wt/retired' }]);+ await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-42', worktreePath: '/repo/.claude/worktrees/retired' }]);expect(execGh).toHaveBeenCalledWith(['issue', 'edit', '42', '--repo', 'github.com/atomantic/PortOS','--remove-assignee', '@me', '--remove-label', 'in-progress'@@ -438,7 +438,7 @@ describe('cleanupMerged', () => {it('leaves markers intact for a live owner or a failed branch deletion', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);- const branch = { branch: 'claim/issue-42', worktreePath: '/wt/claim-issue-42', worktreeAgeMs: 10 * 24 * 60 * 60 * 1000 };+ const branch = { branch: 'claim/issue-42', worktreePath: '/repo/data/cos/worktrees/claim-issue-42', worktreeAgeMs: 10 * 24 * 60 * 60 * 1000 };const held = await cleanupMerged('/repo', 'main', [branch], { activeAgentIds: new Set(['claim-issue-42']) });expect(held.skipped[0].reason).toBe('worktree-active-agent');expect(execGh).not.toHaveBeenCalled();@@ -522,7 +522,7 @@ describe('cleanupMerged', () => {it('omits retryAt for holds that do NOT lift on a clock', async () => {git.hasBranchMergeEvidence.mockResolvedValue(true);const res = await cleanupMerged('/repo', 'main', [- { branch: 'locked-b', worktreePath: '/wt/locked', worktreeLocked: true, worktreeAgeMs: 60 * 1000 },+ { branch: 'locked-b', worktreePath: '/repo/data/cos/worktrees/locked', worktreeLocked: true, worktreeAgeMs: 60 * 1000 },{ branch: 'active-b', worktreePath: '/repo/data/cos/worktrees/agent-abc12345', worktreeAgeMs: 60 * 1000 }], { activeAgentIds: new Set(['agent-abc12345']) });// A lock and a running agent both end at a time nothing here can predict —