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(cos): retire merged manual claim checkouts with no exact-head PR (#12920)

[._.]/25ecd58ed070
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 0656641ad9..de6e328510 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -163,7 +163,11 @@ merge without a checkout. Cleanup reports locked, dirty, active, unmanaged,
unverified manual claim, changed-head and archive-failure holds explicitly.
An absent live registry entry alone cannot waive a manual claim hold; a
successful completion receipt bound to the current checkout path, head and
-filesystem incarnation is required. Older records cannot release a reused claim. Initialized submodules currently retain
+filesystem incarnation is required, or for a manual session the forge's merged
+PR at the exact head. A merged manual claim with no PR at its exact head (a
+reused branch, or a checkout left behind while the branch shipped from
+elsewhere) retires once a GitHub read finds no open PR for the branch and the
+checkout's directory, index and HEAD log have been untouched for an hour. Older records cannot release a reused claim. Initialized submodules currently retain
the checkout because their complete content is not supported by the archive.
A held merged receipt names a recovery task when policy and source ownership
permit it; intentional human handoffs stay with their existing owner. The recovery
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index acb138b5db..bb4da787f5 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1119,7 +1119,9 @@ async function retainedClaimMarkers(repoPath, branch, { origin } = {}) {
* 4. fresh ownership and completion policy permit retirement under the claim
* binding lock; a claim checkout has an exact successful run receipt, or
* the forge reports its exact head merged and it has idled past
- * SHIPPED_CLAIM_IDLE_MS (see manualClaimShippedHold).
+ * SHIPPED_CLAIM_IDLE_MS, or (no PR at that head) the forge reports no open
+ * PR for the branch and the checkout has been untouched that long (see
+ * manualClaimShippedHold).
* 5. recovery archives verify before removal and exact-head ref deletion.
* A failed gate skips the branch with a reason. Age, an absent upstream, and
* a cached merged flag never substitute for successful completion evidence.
@@ -1408,7 +1410,8 @@ async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(),
const records = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);
// Registry absence cannot prove a manual CLI or external task finished.
// Waive the claim hold only on a recorded completed owner or, for a
- // manual session that records none, the forge's merged exact head.
+ // manual session that records none, the forge's merged exact head (or,
+ // with no PR at that head, a forge-confirmed idle checkout).
const { hasCompletedCheckoutEvidence } = await import('./completedCheckoutEvidence.js');
if (!records) return stop({ ok: false, reason: 'claim-ownership-unreadable' });
if (await hasCompletedCheckoutEvidence(records, {
@@ -1417,6 +1420,8 @@ async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(),
else {
const hold = await manualClaimShippedHold(repoPath, b, expectedHead, forgeAccount);
if (hold) return stop(hold);
+ // Removal re-proves merge evidence, and the archive's byte check
+ // refuses a checkout that changed after this admission.
claimCompletion = 'forge-merged';
}
}
@@ -1442,8 +1447,28 @@ async function manualClaimShippedHold(repoPath, b, head, forgeAccount) {
if (!Number.isFinite(b.worktreeAgeMs) || b.worktreeAgeMs < SHIPPED_CLAIM_IDLE_MS) return unverified;
const { readMergedClaimEvidence } = await import('./completedCheckoutEvidence.js');
const merged = await readMergedClaimEvidence({ repoPath, branch: b.branch, head, forgeAccount }).catch(() => null);
- if (!merged || Date.now() - Date.parse(merged.mergedAt) < SHIPPED_CLAIM_IDLE_MS) return unverified;
- return null;
+ if (merged) return Date.now() - Date.parse(merged.mergedAt) < SHIPPED_CLAIM_IDLE_MS ? unverified : null;
+ // A reused claim branch, or a checkout left behind while the branch shipped
+ // from elsewhere, has no PR at its exact head. Its head is already on the
+ // default branch (re-proven by the caller), so the remaining question is
+ // whether a session is still live: no open PR for the branch on a forge read
+ // this cycle, and no checkout activity (directory, index, HEAD log) for the
+ // idle window. A session tearing down or waiting on CI fails one of those.
+ // Only a GitHub origin's PR read is evidence: elsewhere "no open PR" is the default, not an answer.
+ if (b.openPr !== null || b.prStateUnavailable !== false) return unverified;
+ if (!githubRepoSpec(await getOriginInfo(repoPath).catch(() => null))) return unverified;
+ const idle = await checkoutIdleMs(b.worktreePath);
+ return Number.isFinite(idle) && idle >= SHIPPED_CLAIM_IDLE_MS ? null : unverified;
+}
+
+/** Time since the checkout last changed: its directory, index or HEAD log. Null when unreadable. */
+async function checkoutIdleMs(worktreePath) {
+ const gitDir = (await execGit(['rev-parse', '--absolute-git-dir'], worktreePath).catch(() => null))?.stdout?.trim();
+ if (!gitDir) return null;
+ const stamps = await Promise.all([worktreePath, join(gitDir, 'index'), join(gitDir, 'logs', 'HEAD')]
+ .map(path => stat(path).then(st => st.mtimeMs, error => (error.code === 'ENOENT' ? 0 : null))));
+ if (stamps.some(stamp => stamp === null)) return null;
+ return Math.max(0, Date.now() - Math.max(...stamps));
}
/**
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 8b62f4c7b0..61cf2cef40 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -1245,6 +1245,42 @@ describe('reconcile', () => {
expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/data/cos/worktrees/claim-issue-4348', expect.any(Object));
});
+ // A reused claim branch, or a checkout left behind while the branch shipped
+ // from another checkout, has no merged PR at its exact head. Merge evidence
+ // plus a forge read with no open PR and an idle checkout proves it finished.
+ it.each([
+ ['idle with no open PR', {}, true],
+ ['an open PR', { openPr: true }, false],
+ ['recent checkout activity', { mtime: Date.now() - 60 * 1000 }, false],
+ ['an unreadable checkout', { gitDir: '' }, false],
+ ])('retires a merged manual claim with no exact-head PR only when idle: %s', async (_label, { openPr = false, mtime = Date.now() - 4 * 60 * 60 * 1000, gitDir = '/repo/.git/worktrees/claim-issue-4348' }, cleaned) => {
+ hasCompletedCheckoutEvidence.mockResolvedValue(false);
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-4348', isDefault: false, current: false, tracking: '', merged: true }
+ ]);
+ wt.listWorktrees.mockResolvedValue([
+ { head: RETIRE_HEAD, path: '/repo/data/cos/worktrees/claim-issue-4348', branch: 'refs/heads/claim/issue-4348' }
+ ]);
+ execGh.mockResolvedValue(openPr
+ ? JSON.stringify([{ number: 7, headRefName: 'claim/issue-4348', mergeable: 'MERGEABLE', isDraft: false, url: 'u' }])
+ : '[]');
+ execGit.mockImplementation(async (args) => pinnedRef(args) ? { stdout: RETIRE_HEAD, exitCode: 0 }
+ : args[0] === 'rev-parse' && args[1] === '--absolute-git-dir' ? { stdout: gitDir, exitCode: 0 }
+ : args[0] === 'ls-remote' ? { stdout: 'abc123\trefs/heads/main\n', exitCode: 0 }
+ : { stdout: '', exitCode: 0 });
+ worktreeMtimeMs = mtime;
+ git.hasBranchMergeEvidence.mockResolvedValue(true);
+
+ const res = await reconcile('/repo');
+ if (cleaned) {
+ expect(res.cleaned).toEqual(['claim/issue-4348']);
+ expect(wt.forceRemoveWorktreeDir).toHaveBeenCalledWith('/repo', '/repo/data/cos/worktrees/claim-issue-4348', expect.any(Object));
+ } else {
+ expect(res.cleaned).toEqual([]);
+ expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ }
+ });
+
// 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.
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 940c5cea6b..81e37689bd 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -703,9 +703,13 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
const release = { ...c.release, locked: false, lockReason: null };
await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...release, reason: 'pr-completion-review-required' }] });
const retire = (more = {}) => retireInventoriedCheckout({ appId: 'app-1', release }, { ...c.opts, ...more });
- injected.policies[0].metadata.prCompletionPolicy = 'leave-open';
+ // A reused branch: the obligation names an earlier PR, not this head.
+ injected.policies[0].metadata.branchCompletionPolicy = {
+ branch: release.branch, completion: 'review-then-merge', prUrl: 'https://github.com/example/repo/pull/41', tip: null,
+ };
+ injected.policies[0].metadata.branchCompletionPolicy.completion = 'leave-open';
expect(await retire({ settleMergedReviewObligation: true })).toMatchObject({ ok: false, reason: 'pr-completion-human-handoff' });
- injected.policies[0].metadata.prCompletionPolicy = 'review-then-merge';
+ injected.policies[0].metadata.branchCompletionPolicy.completion = 'review-then-merge';
expect(await retire()).toMatchObject({ ok: false, reason: 'pr-completion-review-required' });
expect(await registered(release.path)).toBe(true);
const result = await retire({ settleMergedReviewObligation: true });