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

shorten the shipped-claim window instead of bypassing it

[._.]/ Adam Eivy84e1fee5d638
diff --git a/server/lib/worktreeOwnership.js b/server/lib/worktreeOwnership.js
index 2a93bee70e..b379e21e5b 100644
--- a/server/lib/worktreeOwnership.js
+++ b/server/lib/worktreeOwnership.js
@@ -42,13 +42,6 @@ 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,
@@ -58,7 +51,6 @@ function normalizedRoots(roots) {
* allowStaleClaim?: boolean,
* ageMs?: number|null,
* staleClaimIdleMs?: number,
- * claimComplete?: boolean,
* requireKnownLiveness?: boolean,
* }} options
* @returns {string|null}
@@ -72,7 +64,6 @@ export function worktreeOwnershipReason({
allowStaleClaim = false,
ageMs = null,
staleClaimIdleMs,
- claimComplete = false,
requireKnownLiveness = false,
} = {}) {
if (!path) return 'worktree-missing-path';
@@ -83,14 +74,11 @@ export function worktreeOwnershipReason({
const agentId = worktreeAgentId(path);
if (isHumanClaimWorktree(agentId)) {
- // 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 stale = allowStaleClaim
+ && typeof ageMs === 'number'
+ && typeof staleClaimIdleMs === 'number'
+ && ageMs >= staleClaimIdleMs;
+ if (!stale) return 'worktree-human-claim';
}
const mustBeAgentWorktree = root?.requireAgentId ?? requireAgentId;
@@ -119,9 +107,6 @@ 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 615d8b09a2..0654ed3ee0 100644
--- a/server/lib/worktreeOwnership.test.js
+++ b/server/lib/worktreeOwnership.test.js
@@ -24,23 +24,6 @@ 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 9525c68ba7..8ab8b1daa4 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -99,6 +99,18 @@ export function prioritizeBranches(branches) {
// reaped on the daily recheck once it crosses the threshold.
export const STALE_CLAIM_IDLE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
+// The same window, for a claim that has demonstrably SHIPPED (see SHIPPED_CLAIM
+// on cleanupMerged). Proof of completion collapses the wait but does not remove
+// it: the one thing "merged + clean + remote branch gone" does NOT prove is that
+// the local /claim PROCESS has exited. A session that just merged its own PR —
+// or whose PR was merged from a peer machine, which PortOS users routinely run —
+// sits in exactly that state for the seconds-to-minutes it spends on teardown,
+// and reaping there deletes a directory a live process is still standing in.
+// mtime is the only liveness proxy available (a claim has no durable local agent
+// id), so keep a short idle floor over it. An hour is far longer than any
+// teardown and still turns a week-long park into a single recheck.
+export const SHIPPED_CLAIM_IDLE_MS = 60 * 60 * 1000; // 1 hour
+
// Bound the gh query (single-user repos never realistically truncate at 200).
const PR_LIST_LIMIT = 200;
@@ -225,17 +237,16 @@ 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) —
- * or a `claimComplete` one, which is reaped at any age
+ * (`ageMs` supplied) — those are reaped (see STALE_CLAIM_IDLE_MS,
+ * and SHIPPED_CLAIM_IDLE_MS for a claim proven shipped)
* - 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, claimComplete?:boolean }} input
- * `claimComplete` — see the SHIPPED_CLAIM note on `cleanupMerged`.
+ * @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, claimComplete = false }) {
+export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS }) {
if (!path) return null;
return worktreeOwnershipReason({
path,
@@ -244,7 +255,6 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,
allowStaleClaim: true,
ageMs,
staleClaimIdleMs,
- claimComplete,
});
}
@@ -257,10 +267,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, claimComplete?:boolean }} input
+ * @param {{ path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null, staleClaimIdleMs?:number }} input
* @returns {string|null} ISO timestamp
*/
-export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, claimComplete = false }) {
+export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS }) {
if (!path) return null;
return worktreeHoldExpiresAt({
path,
@@ -269,7 +279,6 @@ export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageM
allowStaleClaim: true,
ageMs,
staleClaimIdleMs,
- claimComplete,
});
}
@@ -773,21 +782,26 @@ export function describeIdleReconcilePark(skipped = [], heldLive = []) {
* 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.
+ * a claim session is still using it. Waiting out a full week is pointless once
+ * the claim has demonstrably SHIPPED, and doing it anyway is what left four
+ * finished claims parked 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:
+ * A shipped claim is one where all three hold, established here 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.
+ * 3. clean worktree — the dirty gate below, which this never overrides.
+ * Together they say the /claim flow finished everything except its own teardown.
+ * `upstreamGone` is the discriminator the long window was standing in for: a
+ * claim still being WORKED either has no upstream yet or has one that still
+ * exists.
+ *
+ * What it does NOT prove is that the claim PROCESS has exited — so this
+ * SHORTENS the idle window to SHIPPED_CLAIM_IDLE_MS rather than removing it,
+ * leaving one mechanism (the age window) with two durations instead of a second
+ * way past the gate. Everything the window already guarantees still holds: an
+ * unreadable mtime fails safe to protected, and an explicit lock still wins.
*
* @param {string} repoPath
* @param {string} defaultBranch
@@ -812,14 +826,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.
- // A SHIPPED claim (see SHIPPED_CLAIM above) skips the wait entirely —
- // `stillMerged` is proven above, the dirty gate below is still ahead of it.
+ // A SHIPPED claim (see SHIPPED_CLAIM above) waits out the short window
+ // instead of the week-long one — `stillMerged` is proven above, and the
+ // dirty gate below is still ahead of it.
const gate = {
path: b.worktreePath,
locked: b.worktreeLocked,
activeAgentIds,
ageMs: b.worktreeAgeMs,
- claimComplete: b.upstreamGone,
+ staleClaimIdleMs: b.upstreamGone ? SHIPPED_CLAIM_IDLE_MS : STALE_CLAIM_IDLE_MS,
};
const protectedReason = worktreeProtectionReason(gate);
if (protectedReason) {
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index ae784ff882..0795fe2461 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -35,6 +35,13 @@ vi.mock('./worktreeManager.js', () => ({
};
}),
}));
+// Worktree age drives the claim windows (STALE_CLAIM_IDLE_MS / SHIPPED_CLAIM_IDLE_MS),
+// and gatherBranchState reads it via stat(). Default to "ancient" so tests that
+// don't care about age behave as before; set worktreeMtimeMs to pin a specific age.
+let worktreeMtimeMs = 0;
+vi.mock('node:fs/promises', () => ({
+ stat: vi.fn(async () => ({ mtimeMs: worktreeMtimeMs })),
+}));
const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
vi.mock('./github.js', () => ({
execGh: vi.fn(async () => '[]'),
@@ -64,6 +71,7 @@ import {
actionOn, filterActionable, desiredEndState, formatInFlightForPrompt, actionableSignature,
limitBranchesForAgent,
branchPriorityRank, prioritizeBranches, worktreeProtectionExpiresAt, describeIdleReconcilePark,
+ SHIPPED_CLAIM_IDLE_MS, STALE_CLAIM_IDLE_MS,
upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes
} from './branchReconcile.js';
import * as git from './git.js';
@@ -74,6 +82,9 @@ import { getOriginInfo } from '../lib/gitRemote.js';
beforeEach(() => {
vi.clearAllMocks();
+ // Ancient by default, so age-indifferent tests keep their pre-window behavior;
+ // a test that pins a specific age must not leak it into the next one.
+ worktreeMtimeMs = 0;
// clearAllMocks keeps implementations, so restore the default GitHub origin —
// a case that swaps in a GitLab/origin-less remote would otherwise leak into
// every test after it.
@@ -249,26 +260,41 @@ 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 () => {
+ it('reaps a SHIPPED claim once idle, but not while dirty, un-shipped, or still busy', async () => {
+ const HOUR = 60 * 60 * 1000;
+ const shipped = (over) => ({
+ worktreePath: '/repo/data/cos/worktrees/claim-x', worktreeAgeMs: 2 * HOUR, upstreamGone: true, ...over
+ });
git.isBranchMergedInto.mockResolvedValue(true);
+
+ execGit.mockResolvedValue({ stdout: '', exitCode: 0 }); // clean
+ const reaped = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-0', ...shipped() }]);
+ expect(reaped.cleaned).toEqual(['claim/issue-0']);
+
+ // The dirty gate is independent — a shorter window never overrides it.
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.
+ const dirty = await cleanupMerged('/repo', 'main', [{ branch: 'claim/issue-1', ...shipped() }]);
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 }
+ // No completion proof — never pushed, remote ref still on origin, or the
+ // remote could not be read. The week-long window still applies.
+ const unshipped = await cleanupMerged('/repo', 'main', [
+ { branch: 'claim/issue-2', ...shipped({ upstreamGone: false }) }
]);
- expect(live.cleaned).toEqual([]);
- expect(live.skipped[0]).toMatchObject({ branch: 'claim/issue-2', reason: 'worktree-human-claim' });
- expect(wt.forceRemoveWorktreeDir).not.toHaveBeenCalled();
+ expect(unshipped.cleaned).toEqual([]);
+ expect(unshipped.skipped[0]).toMatchObject({ branch: 'claim/issue-2', reason: 'worktree-human-claim' });
+
+ // Shipped but touched a minute ago — a claim process mid-teardown, or a peer
+ // machine merged the PR while this session is still running. Held, and the
+ // caller is told when the short window lapses.
+ const busy = await cleanupMerged('/repo', 'main', [
+ { branch: 'claim/issue-3', ...shipped({ worktreeAgeMs: 60 * 1000 }) }
+ ]);
+ expect(busy.cleaned).toEqual([]);
+ expect(busy.skipped[0]).toMatchObject({ branch: 'claim/issue-3', reason: 'worktree-human-claim' });
+ expect(Date.parse(busy.skipped[0].retryAt)).toBeLessThanOrEqual(Date.now() + SHIPPED_CLAIM_IDLE_MS);
});
it('omits retryAt for holds that do NOT lift on a clock', async () => {
@@ -306,16 +332,21 @@ describe('worktreeProtectionReason', () => {
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();
+ // A shipped claim gets a SHORTER window, not a bypass — so a worktree a live
+ // claim process is still standing in (it just merged, or a peer machine merged
+ // for it) is protected until it has been idle, and an unreadable mtime still
+ // fails safe. Both properties come free from reusing the window; a bypass had
+ // neither.
+ it('honors the short shipped-claim window without abandoning the window itself', () => {
+ const at = (ageMs, staleClaimIdleMs) => worktreeProtectionReason({ path: '/x/claim-foo', ageMs, staleClaimIdleMs });
+ // Just-merged and still busy: inside the short window, still protected.
+ expect(at(60 * 1000, SHIPPED_CLAIM_IDLE_MS)).toBe('worktree-human-claim');
+ // Idle past it: reaped, without waiting out the week-long window.
+ expect(at(2 * 60 * 60 * 1000, SHIPPED_CLAIM_IDLE_MS)).toBeNull();
+ expect(at(2 * 60 * 60 * 1000, STALE_CLAIM_IDLE_MS)).toBe('worktree-human-claim');
+ // Unreadable mtime fails safe even for a shipped claim.
+ expect(at(null, SHIPPED_CLAIM_IDLE_MS)).toBe('worktree-human-claim');
+ expect(SHIPPED_CLAIM_IDLE_MS).toBeLessThan(STALE_CLAIM_IDLE_MS);
});
});
@@ -716,6 +747,8 @@ describe('reconcile', () => {
execGit.mockImplementation(async (args) => args[0] === 'ls-remote'
? { stdout: 'abc123\trefs/heads/main\n', exitCode: 0 }
: { stdout: '', exitCode: 0 });
+ // Idle for hours — past SHIPPED_CLAIM_IDLE_MS, so no live session is implied.
+ worktreeMtimeMs = Date.now() - 4 * 60 * 60 * 1000;
git.isBranchMergedInto.mockResolvedValue(true);
const res = await reconcile('/repo');
@@ -741,6 +774,9 @@ describe('reconcile', () => {
execGit.mockImplementation(async (args) => args[0] === 'ls-remote'
? { stdout: '', exitCode: 1 } // ls-remote failed → listRemoteHeads returns null
: { stdout: '', exitCode: 0 });
+ // Idle long enough that the SHORT window would have released it — so the only
+ // thing holding it back is the unreadable remote, which is what this pins.
+ worktreeMtimeMs = Date.now() - 4 * 60 * 60 * 1000;
git.isBranchMergedInto.mockResolvedValue(true);
const res = await reconcile('/repo');