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

branch-reconcile: reap abandoned /claim worktrees (age-gated) instead of parking forever

Adam Eivydd0c848ae40d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ab9393089b..0b3a7ee544 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## CoS Agents
+- **branch-reconcile now reaps ABANDONED `/claim` worktrees instead of parking on them forever.** When a `/claim` (or `/do:next`) agent finishes WITHOUT committing, it leaves a `claim/issue-N` branch that's just a bare pointer at an already-merged commit plus a lingering worktree. branch-reconcile classified these as `MERGED` but its cleanup unconditionally protected any `claim-*` worktree as a live human session (`worktree-human-claim`) — so it skipped them every run and parked with the misleading *"nothing in-flight (cleaned 0)"*, and the stale branches/worktrees accumulated indefinitely (this is exactly what left `claim/issue-1933` + `claim/issue-1938` stuck locally). The protection is now age-gated: a claim worktree is reaped only when it's **merged AND clean AND older than `STALE_CLAIM_IDLE_MS` (24h)** — a trio that's only ever true for an abandoned claim, since a claim with real work in progress is never merged+clean (uncommitted edits → dirty → WIP; committed work → not an ancestor of default → not MERGED). Recent claim worktrees stay fully protected so the `/claim` Phase-7 self-clean window and any live human session are untouched, and unknown-age worktrees fail safe toward not-deleting. The park log also now names any merged branches held back by a protection guard (`, N merged branch(es) held back (worktree-human-claim, …)`) so a lingering worktree is a visible breadcrumb instead of an invisible "cleaned 0". Worktree age is read from the worktree root's mtime (set at `git worktree add`, unmoved by deep-file edits) in `gatherBranchState` and threaded into the pure `worktreeProtectionReason` gate. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`)
+
- **An explicit "Run" of a perpetual claim/reconcile task that finds no work now tells you so — instead of silently doing nothing.** Triggering an on-demand `claim-issue` (or any perpetual task) that had nothing actionable produced zero UI feedback: the task parked with a log line buried in pm2, so the user was left wondering why "40 open issues" didn't spawn an agent. The on-demand path now (1) resets any existing park **and the branch/issue-reconcile convergence signature** before re-running the detector, so a manual trigger always re-checks live state and never honors a stale/cached verdict — previously an explicit "Run" of `branch-reconcile`/`issue-reconcile` could re-park `no-progress` against an unchanged-since-last-run set even though the user asked to re-drive; and (2) when the fresh check still finds no work, emits a `cos:schedule:on-demand-empty` event that surfaces a toast — e.g. *"claim-issue: re-checked now — no claimable issues (0 of 40 claimable — 2 in-flight, 38 filtered). Next auto-recheck in 33 hours."* The GitHub/GitLab work-detector now returns a breakdown (`open`, `inFlight` held by open claim branches/PRs, `filtered` skipped by label/assignee/epic), plumbed through the park record and event, so the message explains WHY a non-empty queue yields zero claimable work — the common case being issues already shipped whose stale `claim/issue-N` branches still count as in-flight. The event carries an `outcome` so the message fits the case: `parked` (perpetual detector found no work), `transient` (a `gh`/`glab` probe failure — *"couldn't complete the check just now — try again"*, never a false "nothing to do"), or `idle` (a non-perpetual task like `pr-watcher` genuinely had nothing — a calm neutral note, not an error). Both on-demand drain engines — `cos.dequeueNextTask` and `cosTaskGenerator.spawnPriority0OnDemand` — share the reset-and-emit path (via `emitOnDemandEmpty`), so a user Run gets feedback no matter which engine picks it up. The event fires ONLY for user-initiated on-demand runs (never background parks), so there's no toast spam. (`server/services/cos.js`, `server/services/cosTaskGenerator.js`, `server/services/perpetualWork.js`, `server/services/taskSchedule.js`, `server/services/socket.js`, `client/src/hooks/useOnDemandTaskToast.js`)
- **The proactive voice agent now announces a task's topic, not the raw prompt block.** When a voice-dispatched CoS task became ready or finished, the spoken line read the first ~240 characters of the task's `description` — which for a scheduled swarm/claim run is the `# ⚡ SWARM MODE — claim and ship up to 3 independent issues in parallel. This run operates in slashdo /do:next --swarm=3 mode. …` prompt scaffolding, so the assistant recited the orchestration preamble instead of naming the work. Both the "new task is ready" and "task is done" lines now derive a short topical label via a shared `deriveTaskSpeechLabel` helper that prefers an explicit title or the post-run agent summary and otherwise strips the first meaningful description line down to its topic (leading markdown heading, emoji, `[Claim Issue: App]` tag, `**bold**` markers, and the `SWARM MODE —` label), clipped to one phrase — so the swarm task speaks "claim and ship up to 3 independent issues in parallel" and a plain claim task speaks "Claim and ship the next open GitHub issue". (`server/services/voice/proactiveTriggers.js`)
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index d7d6d600cc..4fc2e2af30 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -16,6 +16,7 @@
* can't distinguish machines; local-branch existence can.
*/
+import { stat } from 'node:fs/promises';
import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } from './git.js';
import { execGit } from '../lib/execGit.js';
import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, isHumanClaimWorktree } from './worktreeManager.js';
@@ -27,6 +28,19 @@ import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
// The resolved default branch is added on top at runtime.
export const PROTECTED_BRANCHES = ['main', 'master', 'release'];
+// A `claim-*` worktree is normally protected as a human `/claim` session that
+// self-cleans in the /claim Phase-7 flow. But when that flow never runs (the
+// agent finished WITHOUT committing), the branch is left as a bare pointer at an
+// already-merged commit and the worktree lingers forever — making branch-reconcile
+// park with "cleaned 0" every run (the exact confusion behind this guard). Reap
+// such a claim worktree once it is older than this AND its branch is merged AND
+// its worktree is clean. That trio is only ever true for an ABANDONED claim: a
+// claim with real work in progress is never merged+clean (uncommitted edits →
+// dirty → WIP; committed work → not an ancestor of default → not MERGED), so the
+// age gate exists purely to spare the narrow "just created, about to start"
+// window a live human session occupies.
+export const STALE_CLAIM_IDLE_MS = 24 * 60 * 60 * 1000; // 24h
+
// Bound the gh query (single-user repos never realistically truncate at 200).
const PR_LIST_LIMIT = 200;
@@ -99,18 +113,26 @@ async function getOpenPrsByHead(repoPath) {
* Pure — the dangerous-to-remove cases the deterministic cleanup must respect
* (mirrors the guards the existing worktree reaper honors):
* - locked → the user explicitly `git worktree lock`ed it
- * - human `/claim` → a `claim-<slug>` worktree self-cleaned by the /claim flow
+ * - human `/claim` → a `claim-<slug>` worktree self-cleaned by the /claim flow,
+ * UNLESS it is an abandoned one older than `staleClaimIdleMs`
+ * (`ageMs` supplied) — those are reaped (see STALE_CLAIM_IDLE_MS)
* - active CoS agent → an agent (`agent-<id>`) is currently running in it
* Sibling worktrees (`next-issue-*`, etc.) whose basename is none of these fall
* through to null and are cleaned normally.
*
- * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string> }} input
+ * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number, staleClaimIdleMs?:number }} input
* @returns {string|null}
*/
-export function worktreeProtectionReason({ path, locked, activeAgentIds }) {
+export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS }) {
if (locked) return 'worktree-locked';
const basename = (path || '').split('/').pop() || '';
- if (isHumanClaimWorktree(basename)) return 'worktree-human-claim';
+ if (isHumanClaimWorktree(basename)) {
+ // Reap an abandoned claim (age known AND past the idle window); keep protecting
+ // a recent one so a live human /claim session — or its Phase-7 self-clean — wins.
+ // Unknown age (ageMs omitted) stays protected: fail safe toward not-deleting.
+ if (typeof ageMs === 'number' && ageMs >= staleClaimIdleMs) return null;
+ return 'worktree-human-claim';
+ }
if (activeAgentIds?.has(basename)) return 'worktree-active-agent';
return null;
}
@@ -126,6 +148,20 @@ async function isWorktreeDirty(worktreePath) {
return classifyWorktreeDirt(stdout).hasRealChanges;
}
+/**
+ * Age of a worktree directory (ms since its last structural mtime), or null when
+ * it can't be stat'd. The worktree root's mtime is set when `git worktree add`
+ * lays down its top-level entries and doesn't move for deep-file edits, so for an
+ * abandoned claim (no top-level churn after creation) it tracks "time since the
+ * worktree was created" — exactly the staleness signal STALE_CLAIM_IDLE_MS needs.
+ * @param {string} worktreePath
+ * @returns {Promise<number|null>}
+ */
+async function worktreeAgeMs(worktreePath) {
+ const st = await stat(worktreePath).catch(() => null);
+ return st ? Math.max(0, Date.now() - st.mtimeMs) : null;
+}
+
/**
* Gather the raw git/PR facts for every local feature branch in `repoPath`.
* Excludes the default branch, the currently-checked-out branch, and the
@@ -161,6 +197,7 @@ export async function gatherBranchState(repoPath, { defaultBranch }) {
const wt = worktreeByBranch.get(b.name) || null;
const worktreePath = wt?.path || null;
const worktreeLocked = Boolean(wt?.locked);
+ const worktreeAge = worktreePath ? await worktreeAgeMs(worktreePath) : 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
@@ -173,6 +210,7 @@ export async function gatherBranchState(repoPath, { defaultBranch }) {
hasWorktree: Boolean(worktreePath),
worktreePath,
worktreeLocked,
+ worktreeAgeMs: worktreeAge,
worktreeDirty,
openPr: prsByHead.get(b.name) || null
});
@@ -206,10 +244,12 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
continue;
}
if (b.worktreePath) {
- // Never tear down a worktree that's locked, a human /claim session, or an
- // active CoS agent workspace — even if its branch is merged and clean.
+ // Never tear down a worktree that's locked, a RECENT human /claim session, or
+ // an active CoS agent workspace — even if its branch is merged and clean. An
+ // abandoned claim worktree (merged + clean + older than STALE_CLAIM_IDLE_MS)
+ // falls through and IS reaped; that's the "cleaned 0 forever" leak this fixes.
const protectedReason = worktreeProtectionReason({
- path: b.worktreePath, locked: b.worktreeLocked, activeAgentIds
+ path: b.worktreePath, locked: b.worktreeLocked, activeAgentIds, ageMs: b.worktreeAgeMs
});
if (protectedReason) {
skipped.push({ branch: b.branch, reason: protectedReason });
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 829f4629a6..01a0cd1b73 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -139,6 +139,29 @@ describe('cleanupMerged', () => {
expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
expect(git.deleteBranch).not.toHaveBeenCalled();
});
+
+ it('reaps an ABANDONED claim worktree (merged + clean + stale age)', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean
+ const res = await cleanupMerged('/repo', 'main', [
+ { branch: 'claim/issue-1933', worktreePath: '/repo/data/cos/worktrees/claim-issue-1933', worktreeAgeMs: 3 * 24 * 60 * 60 * 1000 }
+ ]);
+ expect(res.cleaned).toEqual(['claim/issue-1933']);
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/data/cos/worktrees/claim-issue-1933', expect.any(Object));
+ expect(git.deleteBranch).toHaveBeenCalledWith('/repo', 'claim/issue-1933', { local: true });
+ });
+
+ it('still protects a RECENT claim worktree even when merged + clean', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean
+ const res = await cleanupMerged('/repo', 'main', [
+ { branch: 'claim/issue-9999', worktreePath: '/repo/data/cos/worktrees/claim-issue-9999', worktreeAgeMs: 60 * 1000 } // 1 min old
+ ]);
+ expect(res.cleaned).toEqual([]);
+ expect(res.skipped).toEqual([{ branch: 'claim/issue-9999', reason: 'worktree-human-claim' }]);
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
});
describe('worktreeProtectionReason', () => {
@@ -148,6 +171,18 @@ describe('worktreeProtectionReason', () => {
expect(worktreeProtectionReason({ path: '/x/agent-1', activeAgentIds: new Set(['agent-1']) })).toBe('worktree-active-agent');
expect(worktreeProtectionReason({ path: '/repo/next-issue-2199', activeAgentIds: new Set(['agent-1']) })).toBeNull();
});
+
+ it('reaps an abandoned claim (stale age) but protects a recent one and unknown age', () => {
+ const staleClaimIdleMs = 24 * 60 * 60 * 1000;
+ // recent human /claim session (2h old) — still protected
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', ageMs: 2 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-human-claim');
+ // abandoned claim (3d old, merged+clean) — reaped
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBeNull();
+ // unknown age → fail safe toward protecting
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', ageMs: null, staleClaimIdleMs })).toBe('worktree-human-claim');
+ // locked always wins even when stale
+ expect(worktreeProtectionReason({ path: '/x/claim-foo', locked: true, ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-locked');
+ });
});
describe('gatherBranchState', () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 3366f47a11..f5c4483742 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1698,7 +1698,14 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// Definitive idle: nothing in-flight to drive. Park on the recheck cadence
// and clear the progress signature so a fresh set later dispatches.
await taskSchedule.parkPerpetual(taskType, app.id, { reason: 'no-in-flight-branches', actionableCount: 0, signature: null });
- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing in-flight (cleaned ${result.cleaned.length})`, { appId: app.id });
+ // Surface merged branches held back by a protection guard (locked / recent
+ // human-claim / active-agent / dirty) so a lingering worktree isn't an
+ // invisible "cleaned 0" — the exact confusion behind the stale-claim reaper.
+ const heldBack = (result.skipped || []).filter((s) => s.reason?.startsWith('worktree-'));
+ const heldSuffix = heldBack.length
+ ? `, ${heldBack.length} merged branch(es) held back (${[...new Set(heldBack.map((s) => s.reason))].join(', ')})`
+ : '';
+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: nothing in-flight (cleaned ${result.cleaned.length}${heldSuffix})`, { appId: app.id });
return null;
}
// Convergence guard — kills the back-to-back re-dispatch loop WITHOUT stalling