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

fix: reap superseded worktrees without claim idle hold and align instructions

[._.]/ Adam Eivy4ba7920b9427
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 9c023477ae..05495f2642 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -321,13 +321,14 @@ async function getOpenPrsByHead(repoPath, providedOrigin, { forgeExec = null, fo
* @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number, staleClaimIdleMs?:number }} input
* @returns {string|null}
*/
-export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS }) {
+export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false }) {
if (!path) return null;
return worktreeOwnershipReason({
path,
locked,
activeAgentIds,
allowStaleClaim: true,
+ allowLiveClaim,
ageMs,
staleClaimIdleMs,
});
@@ -335,23 +336,23 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,
/**
* When `worktreeProtectionReason`'s hold on this worktree lapses by itself, as an
- * ISO instant — or null when it takes an outside change (a lock released, an
- * agent exiting) that we cannot schedule.
+ * ISO instant — or null when only an outside change can clear it.
*
* The exact mirror of the gate above, so cleanup can report not just THAT a
* merged branch was held back but WHEN it stops being held. Policy lives in
* worktreeOwnership.js; this only supplies this caller's defaults.
*
- * @param {{ path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null, staleClaimIdleMs?:number }} input
+ * @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 }) {
+export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false }) {
if (!path) return null;
return worktreeHoldExpiresAt({
path,
locked,
activeAgentIds,
allowStaleClaim: true,
+ allowLiveClaim,
ageMs,
staleClaimIdleMs,
});
@@ -1008,6 +1009,7 @@ export async function reapSupersededBranches(repoPath, defaultBranch, superseded
}
const retired = await retireBranch(repoPath, b, {
activeAgentIds,
+ allowLiveClaim: true,
label: `🔀 branch-reconcile: remove superseded worktree for ${b.branch}`,
// The dirty tree IS this branch's deliverable — an abandoned agent worktree
// has no commits of its own — so refusing on it would make the reap a no-op
@@ -1054,7 +1056,7 @@ export async function reapSupersededBranches(repoPath, defaultBranch, superseded
*
* @param {string} repoPath
* @param {object} b - a gathered branch entry
- * @param {{ activeAgentIds?: Set<string>, staleClaimIdleMs?: number, label: string, requireCleanWorktree?: boolean, prepare?: () => Promise<any> }} opts
+ * @param {{ activeAgentIds?: Set<string>, staleClaimIdleMs?: number, allowLiveClaim?: boolean, label: string, requireCleanWorktree?: boolean, prepare?: () => Promise<any> }} opts
* `prepare` runs after every gate has passed and before the first irreversible
* step, and aborts the retirement by resolving to `{ error }`. That is the only
* place work like "write a recoverable backup" belongs: earlier it is paid for
@@ -1069,7 +1071,7 @@ export async function reapSupersededBranches(repoPath, defaultBranch, superseded
* copies them out before anything is removed. Never set it false without both.
* @returns {Promise<{ ok: true, prepared?: any } | { ok: false, reason: string, retryAt?: string }>}
*/
-async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, label, requireCleanWorktree = true, prepare }) {
+async function retireBranch(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
@@ -1081,6 +1083,7 @@ async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClai
activeAgentIds,
ageMs: b.worktreeAgeMs,
staleClaimIdleMs,
+ allowLiveClaim,
};
const protectedReason = worktreeProtectionReason(gate);
if (protectedReason) {
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index bf3a751825..09b8e6d6f0 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -106,7 +106,8 @@ import {
branchPriorityRank, prioritizeBranches, worktreeProtectionExpiresAt, describeIdleReconcilePark,
SHIPPED_CLAIM_IDLE_MS, STALE_CLAIM_IDLE_MS,
isMalformedClaimBranch,
- listRemoteHeads, upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes
+ listRemoteHeads, upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes,
+ reapSupersededBranches
} from './branchReconcile.js';
import * as git from './git.js';
import * as wt from './worktreeManager.js';
@@ -461,6 +462,12 @@ describe('worktreeProtectionReason', () => {
expect(at(null, SHIPPED_CLAIM_IDLE_MS)).toBe('worktree-human-claim');
expect(SHIPPED_CLAIM_IDLE_MS).toBeLessThan(STALE_CLAIM_IDLE_MS);
});
+
+ it('allows live claims through when allowLiveClaim is true, but locked and active-agent still hold', () => {
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', allowLiveClaim: true })).toBeNull();
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', allowLiveClaim: true, locked: true })).toBe('worktree-locked');
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', allowLiveClaim: true, activeAgentIds: new Set(['claim-foo']) })).toBe('worktree-active-agent');
+ });
});
describe('gatherBranchState', () => {
@@ -1250,11 +1257,10 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {
expect(res.skipped).toContainEqual({ branch: BRANCH, reason: 'backup-failed: disk full' });
});
- // "Superseded" must never become a way around the worktree protection gate —
- // it is the same gate cleanupMerged applies. A recent /claim tree is the case
- // that reaches it: the branch is clean and un-pushed (NEEDS_PR), so nothing
- // upstream of the reaper holds it back.
- it('holds the reap while a claim worktree is still inside its idle window', async () => {
+ // Verified-superseded branches are backed up before removal and their work
+ // has already been replaced on the default branch. They must not be held back
+ // by the human claim idle window, but explicit locks and active agents still hold.
+ it('reaps a verified-superseded claim worktree even when inside the claim idle window', async () => {
const CLAIM = 'claim/issue-5769';
const CLAIM_TREE = '/repo/data/cos/worktrees/claim-issue-5769';
git.getBranches.mockResolvedValue([
@@ -1281,12 +1287,55 @@ describe('reconcile — cached SUPERSEDED verdicts (#3842)', () => {
}));
const res = await reconcile('/repo', { activeAgentIds: new Set() });
+ expect(backupSupersededBranchMock).toHaveBeenCalledTimes(1);
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', CLAIM_TREE, expect.anything());
+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', CLAIM, { local: true });
+ expect(res.reapedSuperseded).toEqual([CLAIM]);
+ expect(res.superseded).toEqual([]);
+ });
+
+ it('holds the reap of a superseded branch when the worktree is locked', async () => {
+ const CLAIM = 'claim/issue-5769';
+ const CLAIM_TREE = '/repo/data/cos/worktrees/claim-issue-5769';
+ const superseded = [{
+ branch: CLAIM,
+ tip: 'aaaaaaa',
+ worktreePath: CLAIM_TREE,
+ worktreeLocked: true,
+ dirtyPaths: [],
+ verdict: {
+ branch: CLAIM, repoPath: '/repo', verdict: 'SUPERSEDED', tip: 'aaaaaaa',
+ dirtyPaths: [], collisionPaths: ['server/services/thing.js'], replacedBy: ['ffffff1']
+ }
+ }];
+
+ const res = await reapSupersededBranches('/repo', 'main', superseded, { activeAgentIds: new Set() });
expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
expect(git.deleteBranch).not.toHaveBeenCalled();
expect(backupSupersededBranchMock).not.toHaveBeenCalled();
- // Still reported, so a held-back reap is visible rather than silent.
- expect(res.superseded.map((b) => b.branch)).toEqual([CLAIM]);
- expect(res.skipped.find((sk) => sk.branch === CLAIM)?.reason).toBeTruthy();
+ expect(res.held.map((b) => b.branch)).toEqual([CLAIM]);
+ expect(res.skipped.find((sk) => sk.branch === CLAIM)?.reason).toBe('worktree-locked');
+ });
+
+ it('holds the reap of a superseded branch when an active CoS agent is running in it', async () => {
+ const superseded = [{
+ branch: BRANCH,
+ tip: 'aaaaaaa',
+ worktreePath: WORKTREE,
+ worktreeLocked: false,
+ dirtyPaths: ['server/services/thing.js'],
+ verdict: {
+ branch: BRANCH, repoPath: '/repo', verdict: 'SUPERSEDED', tip: 'aaaaaaa',
+ dirtyPaths: ['server/services/thing.js'], collisionPaths: ['server/services/thing.js'], replacedBy: ['ffffff1']
+ }
+ }];
+
+ const res = await reapSupersededBranches('/repo', 'main', superseded, { activeAgentIds: new Set(['agent-deadbeef']) });
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ expect(backupSupersededBranchMock).not.toHaveBeenCalled();
+ expect(res.held.map((b) => b.branch)).toEqual([BRANCH]);
+ expect(res.skipped.find((sk) => sk.branch === BRANCH)?.reason).toBe('worktree-active-agent');
});
// `cleanupMerged` means "delete branches whose work is already on main". This
@@ -2126,6 +2175,10 @@ describe('worktreeProtectionExpiresAt', () => {
it('gives no expiry to a non-claim worktree that is not held at all', () => {
expect(worktreeProtectionExpiresAt({ path: '/repo/data/cos/worktrees/agent-abc12345', ageMs: 2 * DAY, activeAgentIds: new Set() })).toBeNull();
});
+
+ it('returns null when allowLiveClaim is true', () => {
+ expect(worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, allowLiveClaim: true })).toBeNull();
+ });
});
describe('describeIdleReconcilePark', () => {
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index ca76ec689d..ed58b9c9e4 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -435,7 +435,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
}
// Verified-superseded branches are reaped by the reconciler itself and counted
// in `cleaned`. What is left in `superseded` is the reap's leftovers — held by a
- // lock, a live agent, or a claim window — so name them rather than letting them
+ // lock or a live agent — so name them rather than letting them
// vanish into a quiet park; the invisibility is the same failure mode as a
// lingering worktree reported as "cleaned 0".
const supersededSuffix = countSuffix(result.superseded, 'branch(es) verified superseded, reap held back');
diff --git a/server/services/supersededLedger.js b/server/services/supersededLedger.js
index 1e1a8b21ae..47792b7c1f 100644
--- a/server/services/supersededLedger.js
+++ b/server/services/supersededLedger.js
@@ -190,7 +190,7 @@ export function formatSupersededForPrompt(superseded) {
const lines = [
`## Already verified SUPERSEDED — reap held back (${superseded.length}) — DO NOT ANALYZE`,
'',
- 'Each branch below was analyzed by an earlier run and confirmed superseded: the default branch already solves its problem, so merging it would REGRESS shipped work. The verdict is cached and still valid (branch tip, uncommitted change set, and collision paths all unchanged; the replacing commits are still on the default branch). PortOS reaps a verified-superseded branch itself, after backing it up — these are the ones this cycle could NOT take, because something still holds them: a locked worktree, a live CoS agent, a claim tree inside its idle window, or a tip that moved after the verdict was recorded. Do not read these worktrees, do not re-derive the verdict, do not commit, rebase, resolve, or merge anything on them. Report them; the next cycle reaps whatever has since been released.',
+ 'Each branch below was analyzed by an earlier run and confirmed superseded: the default branch already solves its problem, so merging it would REGRESS shipped work. The verdict is cached and still valid (branch tip, uncommitted change set, and collision paths all unchanged; the replacing commits are still on the default branch). PortOS reaps a verified-superseded branch itself, after backing it up — these are the ones this cycle could NOT take, because something still holds them: a locked worktree, a live CoS agent, or a tip that moved after the verdict was recorded. Do not read these worktrees, do not re-derive the verdict, do not commit, rebase, resolve, or merge anything on them. Report them; the next cycle reaps whatever has since been released.',
''
];
for (const b of superseded) {
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index cbc3a5fdc2..a08a68890e 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -658,9 +658,9 @@ describe('taskPromptDefaults integrity snapshot', () => {
// issue labels — the same per-issue routing DISPATCH_HINT_FANOUT_GUIDANCE
// already gives the claim swarm's Phase B, imported verbatim rather than
// retyped so the two consumers can't drift on vocabulary.
- it('branch-reconcile v5 routes each fan-out sub-agent by its own branch\'s dispatch labels', () => {
+ it('branch-reconcile v7 routes each fan-out sub-agent by its own branch\'s dispatch labels and aligns superseded instructions', () => {
const current = DEFAULT_TASK_PROMPTS['branch-reconcile'];
- expect(PROMPT_VERSIONS['branch-reconcile']).toBe(6);
+ expect(PROMPT_VERSIONS['branch-reconcile']).toBe(7);
expect(current).toContain(DISPATCH_HINT_FANOUT_GUIDANCE);
expect(current).toContain('Dispatch each sub-agent at ITS OWN branch\'s recommended model and effort');
// Still carries every v3 behavior — v4 only adds the routing guidance.
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 7de8fad884..20debf4375 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -9,7 +9,7 @@
"better-structural-drift": "941389a1f1c8983eef4f87af1241fbf9",
"better-test-quality": "ab53a477cd194a5c4fbda09d901a3775",
"branch-cleanup": "8fdeb4acc2749816a47ca318b6602721",
- "branch-reconcile": "45feea1d5ccd456bb0bec5d12c373a64",
+ "branch-reconcile": "ae6e8164698faebc2a5fd4fecb3d41e8",
"claim-issue": "f6f3c5865744d46da2edde702beecf27",
"claim-issue-gitlab": "542e10eb02e850fb40d11fab6497deee",
"claim-issue-jira": "64ccd403371ea2b55c53b665b789dd38",
@@ -63,7 +63,7 @@
"better-runtime-safety": 2,
"better-structural-drift": 1,
"better-test-quality": 1,
- "branch-reconcile": 6,
+ "branch-reconcile": 7,
"claim-issue": 34,
"claim-issue-gitlab": 31,
"claim-issue-jira": 20,
@@ -122,7 +122,8 @@
"ecb0621588a751b1383ecd89cf514382",
"16479f4b64395103fd222dc9608830b1",
"7c296ced3f0dec6e764d123f24009ccc",
- "44281269863b3133696fdebe9b558256"
+ "44281269863b3133696fdebe9b558256",
+ "45feea1d5ccd456bb0bec5d12c373a64"
],
"claim-issue": [
"37949d1b1fa8d461a15658f8f4192d97",
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index e0672b5e92..2f60daddfb 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -3230,7 +3230,7 @@ ${DISPATCH_HINT_FANOUT_GUIDANCE}
- **A branch whose "Do:" line ends in a merge is not finished until it IS merged.** Its sub-agent stays alive through CI — waiting out the check run, fixing what goes red, then merging — and reports back only when the PR is merged or a specific check/review is blocking it. "PR opened, left open for review" is a completed STEP, not a completed branch: the PR just sits green until the next run re-drives it. Do not end your own run while a sub-agent is still waiting on CI.
- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.
- If a sub-agent reports a branch is incomplete, superseded, or blocked, leave it as-is and note it in your summary.
-- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / superseded / left incomplete). For a SUPERSEDED branch, name the file(s) and what on the default branch replaced it, so the user can delete the branch with confidence. When a PR is left open, name the check or review that blocked it.`,
+- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / superseded / left incomplete). For a SUPERSEDED branch, record the verdict per the instructions above so PortOS's deterministic pass backs it up, removes its worktree, and deletes the branch. Name the file(s) and what on the default branch replaced it in your summary. When a PR is left open, name the check or review that blocked it.`,
'issue-reconcile': `[Improvement: {appName}] Trusted Issue Reconciliation
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index f165310d21..94006664b5 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -21,7 +21,7 @@ export const PROMPT_VERSIONS = {
'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)
'reference-watch': 3, // v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)
'pr-watcher': 2, // v1: review-and-comment default for newly-opened PRs on the app's default branch
- 'branch-reconcile': 6, // v6: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. v5: explicit Ultra capability dispatch alongside the existing three tiers.
+ 'branch-reconcile': 7, // v7: align SUPERSEDED summary instruction with deterministic cleanup pass; superseded branches with worktrees are reaped rather than held by the claim idle window. v6: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. v5: explicit Ultra capability dispatch alongside the existing three tiers.
// v4: the prompt now interpolates DISPATCH_HINT_FANOUT_GUIDANCE next to the "spawn one sub-agent per branch" instruction and tells the coordinator to dispatch each sub-agent at ITS OWN branch's recommended model/effort — the same per-issue routing the claim swarm's Phase B already does, applied here because branch-reconcile fans out over issue-derived branches too (#6373). v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.
'issue-reconcile': 7, // v7: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. Shared mandatory issue-label contract and restricted contributor invitations. v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.
'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)