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

reap a shipped claim worktree instead of parking it for a week

[._.]/ Adam Eivydb8e326c816d
diff --git a/server/lib/worktreeOwnership.js b/server/lib/worktreeOwnership.js
index b379e21e5b..2a93bee70e 100644
--- a/server/lib/worktreeOwnership.js
+++ b/server/lib/worktreeOwnership.js
@@ -42,6 +42,13 @@ function normalizedRoots(roots) {
* `requireKnownLiveness` fails closed for `agent-*` trees when an authoritative
* `Set` of live agents is unavailable.
*
+ * `claimComplete` is the other way past the claim hold, for a caller that has
+ * PROVEN the claim already finished rather than merely waited out
+ * `staleClaimIdleMs`. Both are the same opt-in — it is only honored under
+ * `allowStaleClaim`, so claim reclamation stays a thing a caller declares. What
+ * counts as proof is deliberately NOT decided here; branch reconciliation is the
+ * only caller that supplies it (see its SHIPPED_CLAIM note).
+ *
* @param {{
* path?: string,
* locked?: boolean,
@@ -51,6 +58,7 @@ function normalizedRoots(roots) {
* allowStaleClaim?: boolean,
* ageMs?: number|null,
* staleClaimIdleMs?: number,
+ * claimComplete?: boolean,
* requireKnownLiveness?: boolean,
* }} options
* @returns {string|null}
@@ -64,6 +72,7 @@ export function worktreeOwnershipReason({
allowStaleClaim = false,
ageMs = null,
staleClaimIdleMs,
+ claimComplete = false,
requireKnownLiveness = false,
} = {}) {
if (!path) return 'worktree-missing-path';
@@ -74,11 +83,14 @@ export function worktreeOwnershipReason({
const agentId = worktreeAgentId(path);
if (isHumanClaimWorktree(agentId)) {
- const stale = allowStaleClaim
- && typeof ageMs === 'number'
- && typeof staleClaimIdleMs === 'number'
- && ageMs >= staleClaimIdleMs;
- if (!stale) return 'worktree-human-claim';
+ // Both escapes ride the SAME `allowStaleClaim` opt-in: one proves the claim
+ // is finished, the other waits out the window. A caller that has not declared
+ // itself a claim reclaimer gets neither.
+ const released = allowStaleClaim && (
+ claimComplete
+ || (typeof ageMs === 'number' && typeof staleClaimIdleMs === 'number' && ageMs >= staleClaimIdleMs)
+ );
+ if (!released) return 'worktree-human-claim';
}
const mustBeAgentWorktree = root?.requireAgentId ?? requireAgentId;
@@ -107,6 +119,9 @@ export function worktreeOwnershipReason({
* claim window lapses. So the window is re-asked with the deadline already
* crossed, and only a tree that comes back free gets an expiry.
*
+ * A released hold (`claimComplete`) reports no reason at all, so it correctly
+ * yields no expiry — nothing is pending for a caller to wait on.
+ *
* Pure. Takes the same options object as `worktreeOwnershipReason`.
* @param {object} [options] - plus `nowMs` for the clock
* @returns {string|null} ISO timestamp
diff --git a/server/lib/worktreeOwnership.test.js b/server/lib/worktreeOwnership.test.js
index 0654ed3ee0..615d8b09a2 100644
--- a/server/lib/worktreeOwnership.test.js
+++ b/server/lib/worktreeOwnership.test.js
@@ -24,6 +24,23 @@ describe('worktree ownership', () => {
expect(worktreeOwnershipReason({ ...input, allowStaleClaim: true })).toBeNull();
});
+ it('releases a completed claim at any age, but keeps an explicit lock', () => {
+ // The grace window guards a claim session that may still be working. A claim
+ // the caller has proven complete has no such session, so it must not wait it
+ // out — that wait is what parked finished claims for a week.
+ const fresh = { path: `${COS_ROOT}/claim-issue-42`, ageMs: 60_000, staleClaimIdleMs: 7 * 24 * 60 * 60 * 1000, allowStaleClaim: true };
+ expect(worktreeOwnershipReason(fresh)).toBe('worktree-human-claim');
+ expect(worktreeOwnershipReason({ ...fresh, claimComplete: true })).toBeNull();
+ // Unknown age no longer blocks it either — completion is proof, age is a proxy.
+ expect(worktreeOwnershipReason({ ...fresh, ageMs: null, claimComplete: true })).toBeNull();
+ // A lock is a deliberate human hold and still outranks completion.
+ expect(worktreeOwnershipReason({ ...fresh, claimComplete: true, locked: true })).toBe('worktree-locked');
+ // Completion says nothing about agent trees — they keep their own gates.
+ expect(worktreeOwnershipReason({
+ path: `${COS_ROOT}/agent-live`, claimComplete: true, activeAgentIds: new Set(['agent-live'])
+ })).toBe('worktree-active-agent');
+ });
+
it('fails closed when agent liveness is unknown and permits an explicitly non-agent root', () => {
expect(worktreeOwnershipReason({
path: `${COS_ROOT}/agent-unknown`,
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 1ffc3de15e..67c0b4e63a 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -225,15 +225,17 @@ async function getOpenPrsByHead(repoPath) {
* - locked → the user explicitly `git worktree lock`ed it
* - 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)
+ * (`ageMs` supplied) — those are reaped (see STALE_CLAIM_IDLE_MS) —
+ * or a `claimComplete` one, which is reaped at any age
* - 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>, ageMs?:number, staleClaimIdleMs?:number }} input
+ * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number, staleClaimIdleMs?:number, claimComplete?:boolean }} input
+ * `claimComplete` — see the SHIPPED_CLAIM note on `cleanupMerged`.
* @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, claimComplete = false }) {
if (!path) return null;
return worktreeOwnershipReason({
path,
@@ -242,6 +244,7 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,
allowStaleClaim: true,
ageMs,
staleClaimIdleMs,
+ claimComplete,
});
}
@@ -254,10 +257,10 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,
* 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, claimComplete?: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, claimComplete = false }) {
if (!path) return null;
return worktreeHoldExpiresAt({
path,
@@ -266,6 +269,7 @@ export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageM
allowStaleClaim: true,
ageMs,
staleClaimIdleMs,
+ claimComplete,
});
}
@@ -346,10 +350,11 @@ export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds, a
// claim flow has no durable local agent id for this branch, so treating the
// directory's existence as liveness hides clean, open-PR claims after the
// claim agent has exited — exactly the branches branch-reconcile exists to
- // finish. Cleanup still uses worktreeProtectionReason and keeps every claim
- // worktree protected; this dispatch-side exception only applies after the
- // classifier has established that the tree is clean. A lock remains an
- // explicit hold even for a claim worktree.
+ // finish. Cleanup makes the same call through worktreeProtectionReason, which
+ // holds a claim worktree until it is stale or provably shipped; this
+ // dispatch-side exception only applies after the classifier has established
+ // that the tree is clean. A lock remains an explicit hold even for a claim
+ // worktree.
if (reason === 'worktree-human-claim') return locked ? 'worktree-locked' : null;
return reason;
}
@@ -629,20 +634,24 @@ async function worktreeAgeMs(worktreePath) {
* always-protected set. Effectful (git + gh).
*
* @param {string} repoPath
- * @param {{ defaultBranch:string, activeAgentIds?:Set<string> }} ctx - `activeAgentIds`
- * distinguishes a live agent's worktree from an abandoned one (see
+ * @param {{ defaultBranch:string, activeAgentIds?:Set<string>, remoteHeads?:Map<string,string>|null }} ctx
+ * `activeAgentIds` distinguishes a live agent's worktree from an abandoned one (see
* `isAbandonedAgentWorktree`); omitting it leaves every agent worktree protected.
+ * `remoteHeads` is `listRemoteHeads`' answer when the caller already has it;
+ * omitted, this reads it itself, and `null` (unreadable remote) is carried
+ * through as "we could not ask" rather than "the remote is empty".
* @returns {Promise<object[]>} one entry per candidate branch:
- * { branch, tip, hasUpstream, tracking, isMerged, hasWorktree, worktreePath, worktreeDirty,
- * dirtyPaths, behind, ahead, collisionPaths, abandonedAgentWorktree, openPr }
+ * { branch, tip, hasUpstream, tracking, upstreamGone, isMerged, hasWorktree, worktreePath,
+ * worktreeDirty, dirtyPaths, behind, ahead, collisionPaths, abandonedAgentWorktree, openPr }
*/
-export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null }) {
+export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, remoteHeads: providedRemoteHeads } = {}) {
const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);
- const [branches, worktrees, prsByHeadOrNull] = await Promise.all([
+ const [branches, worktrees, prsByHeadOrNull, remoteHeads] = await Promise.all([
getBranches(repoPath),
listWorktrees(repoPath).catch(() => []),
- getOpenPrsByHead(repoPath)
+ getOpenPrsByHead(repoPath),
+ providedRemoteHeads === undefined ? listRemoteHeads(repoPath) : providedRemoteHeads
]);
// null = the forge could not be read (see getOpenPrsByHead). Carried onto every
// input so the classifier can refuse to conclude "no PR" from an unread forge.
@@ -662,6 +671,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
const inputs = [];
for (const b of candidates) {
+ const upstreamName = upstreamBranchName(b.tracking);
const wt = worktreeByBranch.get(b.name) || null;
const worktreePath = wt?.path || null;
const worktreeLocked = Boolean(wt?.locked);
@@ -686,6 +696,14 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
// fact: a branch may track a remote branch called something else, and the
// remote-side delete has to name the right ref.
tracking: b.tracking || null,
+ // This branch was pushed, and the ref it tracks is no longer on origin —
+ // the tell that its PR merged with `--delete-branch`. Read from
+ // `listRemoteHeads`, not `%(upstream:track)`'s `[gone]`: that marker is
+ // computed against `refs/remotes/origin/*`, which this module already
+ // documents as too stale to act on (see listRemoteHeads). An unreadable
+ // remote (`null`) yields false — "we could not ask" must not read as
+ // "the remote branch is gone". See the SHIPPED_CLAIM note on cleanupMerged.
+ upstreamGone: Boolean(remoteHeads) && upstreamName !== null && !remoteHeads.has(upstreamName),
isMerged,
hasWorktree: Boolean(worktreePath),
worktreePath,
@@ -754,6 +772,23 @@ export function describeIdleReconcilePark(skipped = [], heldLive = []) {
* A failed gate skips the branch (with a reason) — never a force-delete of
* unmerged or dirty work.
*
+ * SHIPPED_CLAIM: a `claim-*` worktree holds for STALE_CLAIM_IDLE_MS on the chance
+ * a claim session is still using it. That grace is pointless once the claim has
+ * demonstrably SHIPPED, and holding anyway is what left four finished claims
+ * parked for a week while every run reported "cleaned 0" and parked on "merged
+ * branches held back" — the exact stall this reconcile exists to clear.
+ *
+ * The proof is a trio, and this function establishes all three in order:
+ * 1. `stillMerged` — re-verified against the default branch just above.
+ * 2. `upstreamGone` — the branch was pushed and its remote ref is no longer on
+ * origin, i.e. its PR merged with `--delete-branch`.
+ * 3. clean worktree — the dirty gate below, which `claimComplete` never
+ * overrides; completion releases the claim HOLD, never the dirty guard.
+ * Together they say the /claim flow finished everything except its own teardown,
+ * so nothing recoverable remains and the tree is reaped at any age. `upstreamGone`
+ * is the discriminator the age window was standing in for: a claim still being
+ * worked either has no upstream yet or has one that still exists.
+ *
* @param {string} repoPath
* @param {string} defaultBranch
* @param {object[]} merged - gathered inputs whose state === 'MERGED'
@@ -777,7 +812,15 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
// 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 gate = { path: b.worktreePath, locked: b.worktreeLocked, activeAgentIds, ageMs: b.worktreeAgeMs };
+ // A SHIPPED claim (see SHIPPED_CLAIM above) skips the wait entirely —
+ // `stillMerged` is proven above, the dirty gate below is still ahead of it.
+ const gate = {
+ path: b.worktreePath,
+ locked: b.worktreeLocked,
+ activeAgentIds,
+ ageMs: b.worktreeAgeMs,
+ claimComplete: b.upstreamGone,
+ };
const protectedReason = worktreeProtectionReason(gate);
if (protectedReason) {
// Carry WHEN the hold lifts when it lifts on a clock (a claim worktree
@@ -857,7 +900,11 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapRem
}
const defaultBranch = await getDefaultBranch(repoPath).catch(() => 'main') || 'main';
- const inputs = await gatherBranchState(repoPath, { defaultBranch, activeAgentIds });
+ // Read origin's branch list once for the whole cycle: the gather needs it to
+ // tell a shipped claim from a live one, and a repo with no origin has no
+ // remote to ask (null → nothing reads as gone, which is the safe direction).
+ const remoteHeads = origin?.hasOrigin ? await listRemoteHeads(repoPath) : null;
+ const inputs = await gatherBranchState(repoPath, { defaultBranch, activeAgentIds, remoteHeads });
// A gh failure AFTER a passing probe (a blip mid-cycle, or an unparseable
// page) is still "we could not ask" — surface it so the caller retries next
// tick instead of parking on an in-flight set built from unknown PR state.
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 412d0021c4..ae784ff882 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -249,6 +249,28 @@ describe('cleanupMerged', () => {
expect(git.deleteBranch).not.toHaveBeenCalled();
});
+ it('will not reap a shipped claim whose worktree is dirty, or one still tracking a live remote', async () => {
+ git.isBranchMergedInto.mockResolvedValue(true);
+ execGit.mockResolvedValue({ stdout: ' M server/index.js', exitCode: 0 }); // dirty
+ const dirty = await cleanupMerged('/repo', 'main', [
+ { branch: 'claim/issue-1', worktreePath: '/repo/data/cos/worktrees/claim-issue-1', worktreeAgeMs: 60 * 1000, upstreamGone: true }
+ ]);
+ // Completion releases the claim HOLD; it never overrides the dirty gate, which
+ // is the one that protects uncommitted work.
+ expect(dirty.cleaned).toEqual([]);
+ expect(dirty.skipped).toEqual([{ branch: 'claim/issue-1', reason: 'worktree-dirty' }]);
+
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean
+ const live = await cleanupMerged('/repo', 'main', [
+ // No completion proof — the branch was never pushed, its remote ref is still
+ // on origin, or the remote could not be read. The grace window still applies.
+ { branch: 'claim/issue-2', worktreePath: '/repo/data/cos/worktrees/claim-issue-2', worktreeAgeMs: 60 * 1000, upstreamGone: false }
+ ]);
+ expect(live.cleaned).toEqual([]);
+ expect(live.skipped[0]).toMatchObject({ branch: 'claim/issue-2', reason: 'worktree-human-claim' });
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ });
+
it('omits retryAt for holds that do NOT lift on a clock', async () => {
git.isBranchMergedInto.mockResolvedValue(true);
const res = await cleanupMerged('/repo', 'main', [
@@ -283,6 +305,18 @@ describe('worktreeProtectionReason', () => {
// locked always wins even when stale
expect(worktreeProtectionReason({ path: '/x/claim-foo', locked: true, ageMs: 3 * 24 * 60 * 60 * 1000, staleClaimIdleMs })).toBe('worktree-locked');
});
+
+ // The gate's own claimComplete semantics are covered in worktreeOwnership.test.js.
+ // What only THIS pair can get wrong is staying mirrored: the expiry helper must
+ // report no deadline for a hold the reason helper has already released, or a
+ // caller parks waiting out a window that is no longer running.
+ it('keeps the reason and expiry helpers mirrored for a released claim', () => {
+ const fresh = { path: '/x/claim-foo', ageMs: 60 * 1000, staleClaimIdleMs: 24 * 60 * 60 * 1000 };
+ expect(worktreeProtectionReason(fresh)).toBe('worktree-human-claim');
+ expect(worktreeProtectionExpiresAt(fresh)).toEqual(expect.any(String));
+ expect(worktreeProtectionReason({ ...fresh, claimComplete: true })).toBeNull();
+ expect(worktreeProtectionExpiresAt({ ...fresh, claimComplete: true })).toBeNull();
+ });
});
describe('gatherBranchState', () => {
@@ -665,6 +699,56 @@ describe('reconcile', () => {
expect(res.inFlight.every((i) => i.state === 'NEEDS_PR')).toBe(true);
});
+ // The regression this whole `upstreamGone` path exists for: four claims whose
+ // PRs had merged (deleting their remote branches) sat with their worktrees
+ // intact, and every run reported "cleaned 0 / merged branches held back" for a
+ // week because the claim grace window outranked the fact that they were done.
+ it('cleans a SHIPPED claim end to end instead of parking on the grace window', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-4348', isDefault: false, current: false, tracking: 'origin/claim/issue-4348', merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([
+ { path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }
+ ]);
+ execGh.mockResolvedValue('[]');
+ // ls-remote reports origin has only main — the claim's remote branch was
+ // deleted when its PR merged. Everything else (status, etc.) reads clean.
+ execGit.mockImplementation(async (args) => args[0] === 'ls-remote'
+ ? { stdout: 'abc123\trefs/heads/main\n', exitCode: 0 }
+ : { stdout: '', exitCode: 0 });
+ git.isBranchMergedInto.mockResolvedValue(true);
+
+ const res = await reconcile('/repo');
+ expect(res.cleaned).toEqual(['claim/issue-4348']);
+ expect(res.skipped).toEqual([]);
+ // Nothing left to report as held back — the park reason must be "quiet repo",
+ // not "waiting on a protected worktree".
+ expect(describeIdleReconcilePark(res.skipped, res.wip).reason).toBe('no-in-flight-branches');
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/data/cos/worktrees/claim-issue-4348', expect.any(Object));
+ });
+
+ // The fail-safe half of the same signal: "we could not read origin" must never
+ // read as "the remote branch is gone", or an unreachable network would start
+ // reaping claim worktrees that were never shipped.
+ it('does NOT treat an unreadable remote as proof a claim shipped', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-4348', isDefault: false, current: false, tracking: 'origin/claim/issue-4348', merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([
+ { path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }
+ ]);
+ execGh.mockResolvedValue('[]');
+ execGit.mockImplementation(async (args) => args[0] === 'ls-remote'
+ ? { stdout: '', exitCode: 1 } // ls-remote failed → listRemoteHeads returns null
+ : { stdout: '', exitCode: 0 });
+ git.isBranchMergedInto.mockResolvedValue(true);
+
+ const res = await reconcile('/repo');
+ expect(res.cleaned).toEqual([]);
+ expect(res.skipped[0]).toMatchObject({ branch: 'claim/issue-4348', reason: 'worktree-human-claim' });
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ });
+
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 },