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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: order the worktree-ownership gate so a lock structurally outranks a claim (#4668)
[._.]/ Adam Eivydcd29dae03ee
diff --git a/server/lib/README.md b/server/lib/README.mdindex 538c47e094..941c1dfc66 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -277,7 +277,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `taskRetryHold.js` | The failed-task RETRY HOLD state (#3373) — pure metadata helpers shared by the failure verdict, the post-cleanup release, the spawn guard, and the orphan sweep. `retryHoldMetadata(agentId, now)` arms it (task stays `in_progress`, so no dequeue tier can claim the retry before its resume pointer is resolved); `clearedRetryHoldMetadata()` releases it in the same write that flips the task to `pending`; `isRetryHeld(metadata)` / `isRetryHoldOwner(metadata, agentId)` gate the spawn and the owner-scoped release; `isStaleRetryHold(metadata, now, graceMs)` + `RETRY_HOLD_GRACE_MS` let the orphan sweep finish a transition whose process died. || `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. || `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. |-| `worktreeOwnership.js` | Pure ownership gate for destructive worktree operations. `worktreeOwnershipReason()` applies explicit root, agent-id, claim, lock, and active-agent policies; `worktreeAgentId()` is separator-safe; `isHumanClaimWorktree()` and `isAgentWorktreeId()` make the protected namespaces explicit; `worktreeHoldExpiresAt()` names when a hold lapses on its own (the stale-claim window) so callers can wait exactly that long. |+| `worktreeOwnership.js` | Pure ownership gate for destructive worktree operations. `worktreeOwnershipReason()` applies root, agent-id, lock, active-agent, liveness and claim policies IN THAT ORDER, so an unconditional hold always outranks a claim and callers never re-derive the precedence from the slug; the claim hold has two opt-outs (`allowStaleClaim` for reapers, `allowLiveClaim` for the dispatch side). `worktreeAgentId()` is separator-safe; `isHumanClaimWorktree()` and `isAgentWorktreeId()` make the protected namespaces explicit; `worktreeHoldExpiresAt()` names when a hold lapses on its own (the stale-claim window) so callers can wait exactly that long. || `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |## Curated static datadiff --git a/server/lib/worktreeOwnership.js b/server/lib/worktreeOwnership.jsindex b379e21e5b..21263a5524 100644--- a/server/lib/worktreeOwnership.js+++ b/server/lib/worktreeOwnership.js@@ -42,6 +42,14 @@ function normalizedRoots(roots) {* `requireKnownLiveness` fails closed for `agent-*` trees when an authoritative* `Set` of live agents is unavailable.*+ * ORDER IS THE POLICY. The checks run cheapest-and-most-absolute first, and the+ * human-claim test runs LAST on purpose: a claim hold is the one hold with+ * caller-specific exceptions (`allowStaleClaim`, `allowLiveClaim`), so anything+ * that outranks it — an explicit `git worktree lock`, a running agent, liveness+ * we could not determine — must already have returned by the time those+ * exceptions are consulted. That way "a lock outranks a claim" is a fact of this+ * function rather than something each caller re-derives from the returned slug.+ ** @param {{* path?: string,* locked?: boolean,@@ -49,6 +57,7 @@ function normalizedRoots(roots) {* roots?: Array<{path:string, requireAgentId?:boolean}>,* requireAgentId?: boolean,* allowStaleClaim?: boolean,+ * allowLiveClaim?: boolean,* ageMs?: number|null,* staleClaimIdleMs?: number,* requireKnownLiveness?: boolean,@@ -62,6 +71,7 @@ export function worktreeOwnershipReason({roots = [],requireAgentId = false,allowStaleClaim = false,+ allowLiveClaim = false,ageMs = null,staleClaimIdleMs,requireKnownLiveness = false,@@ -73,14 +83,6 @@ export function worktreeOwnershipReason({if (configuredRoots.length > 0 && !root) return 'worktree-unmanaged-location';const agentId = worktreeAgentId(path);- if (isHumanClaimWorktree(agentId)) {- const stale = allowStaleClaim- && typeof ageMs === 'number'- && typeof staleClaimIdleMs === 'number'- && ageMs >= staleClaimIdleMs;- if (!stale) return 'worktree-human-claim';- }-const mustBeAgentWorktree = root?.requireAgentId ?? requireAgentId;if (mustBeAgentWorktree && !isAgentWorktreeId(agentId)) return 'worktree-missing-agent-id';if (locked) return 'worktree-locked';@@ -88,6 +90,19 @@ export function worktreeOwnershipReason({if (requireKnownLiveness && isAgentWorktreeId(agentId) && !(activeAgentIds instanceof Set)) {return 'worktree-agent-liveness-unknown';}++ // Last, so every unconditional hold above already had its say. Two callers+ // opt out of the claim hold: reapers that may reclaim an ABANDONED claim once+ // its window lapses (`allowStaleClaim` + `ageMs`), and the dispatch side,+ // which treats a `claim-*` directory as a marker rather than a live process+ // (`allowLiveClaim`) once the classifier has proven the tree clean.+ if (isHumanClaimWorktree(agentId) && !allowLiveClaim) {+ const stale = allowStaleClaim+ && typeof ageMs === 'number'+ && typeof staleClaimIdleMs === 'number'+ && ageMs >= staleClaimIdleMs;+ if (!stale) return 'worktree-human-claim';+ }return null;}@@ -96,27 +111,26 @@ export function worktreeOwnershipReason({* instant — or null when only an outside change can clear it.** Lives here, next to the gate, because the expiry is the same policy as the- * hold: the stale-claim window (`ageMs >= staleClaimIdleMs`) is the one gate keyed- * to a clock, so this is the only module that can name the deadline without- * re-deriving it from a returned slug. A lock, a live agent, and unknown- * liveness all end at times nothing here can predict.+ * hold: the stale-claim window (`ageMs >= staleClaimIdleMs`) is the one gate+ * keyed to a clock, so this is the only module that can name the deadline+ * without re-deriving it from a returned slug. A lock, a live agent, and+ * unknown liveness all end at times nothing here can predict.*- * The slug alone is not enough to answer this, which is the other reason it- * belongs here: a claim worktree that is ALSO locked reports- * `worktree-human-claim` (first match wins), and its hold does NOT lift when the- * 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.+ * Because the gate tests the claim LAST, `worktree-human-claim` now means every+ * other hold already cleared — so the deadline needs no hypothetical re-ask:+ * with `allowStaleClaim` and a finite age, that slug is returned only while+ * `ageMs < staleClaimIdleMs`, and the window is the whole remaining wait.** Pure. Takes the same options object as `worktreeOwnershipReason`.* @param {object} [options] - plus `nowMs` for the clock* @returns {string|null} ISO timestamp*/export function worktreeHoldExpiresAt({ nowMs = Date.now(), ...options } = {}) {- const { ageMs, staleClaimIdleMs } = options;- if (worktreeOwnershipReason(options) !== 'worktree-human-claim') return null;+ const { ageMs, staleClaimIdleMs, allowStaleClaim = false } = options;+ // Without this caller's opt-in the window never lapses, so there is no date to+ // report even though the tree does read `worktree-human-claim`.+ if (!allowStaleClaim) return null;if (!Number.isFinite(ageMs) || !Number.isFinite(staleClaimIdleMs)) return null;- const remaining = staleClaimIdleMs - ageMs;- if (remaining <= 0) return null;- if (worktreeOwnershipReason({ ...options, ageMs: staleClaimIdleMs }) !== null) return null;- return new Date(nowMs + remaining).toISOString();+ if (worktreeOwnershipReason(options) !== 'worktree-human-claim') return null;+ return new Date(nowMs + (staleClaimIdleMs - ageMs)).toISOString();}diff --git a/server/lib/worktreeOwnership.test.js b/server/lib/worktreeOwnership.test.jsindex 0654ed3ee0..3a660dd92d 100644--- a/server/lib/worktreeOwnership.test.js+++ b/server/lib/worktreeOwnership.test.js@@ -18,10 +18,31 @@ describe('worktree ownership', () => {expect(worktreeOwnershipReason({ ...options, path: `${COS_ROOT}/agent-locked`, locked: true })).toBe('worktree-locked');});- it('keeps human claims unless the stale-claim caller explicitly permits reclamation', () => {+ it('keeps human claims unless the caller explicitly permits reclamation', () => {const input = { path: `${COS_ROOT}/claim-issue-42`, ageMs: 8_000, staleClaimIdleMs: 7_000 };expect(worktreeOwnershipReason(input)).toBe('worktree-human-claim');+ // A reaper may take an ABANDONED claim once its window lapses…expect(worktreeOwnershipReason({ ...input, allowStaleClaim: true })).toBeNull();+ // …and the dispatch side never treats the directory as an owner at all,+ // regardless of age (it reads the tree as a claim MARKER, not a process).+ expect(worktreeOwnershipReason({ ...input, ageMs: 1, allowLiveClaim: true })).toBeNull();+ });++ it('tests the claim LAST, so every unconditional hold outranks it', () => {+ // The ordering IS the precedence: a claim tree that is also locked / also+ // running an agent reports that hold, not 'worktree-human-claim'. Callers+ // therefore never have to re-derive "a lock beats a claim" from the slug.+ const claim = `${COS_ROOT}/claim-issue-42`;+ expect(worktreeOwnershipReason({ path: claim, locked: true })).toBe('worktree-locked');+ expect(worktreeOwnershipReason({ path: claim, activeAgentIds: new Set(['claim-issue-42']) }))+ .toBe('worktree-active-agent');+ // …and the exceptions cannot reach past them either.+ expect(worktreeOwnershipReason({+ path: claim, locked: true, allowLiveClaim: true, allowStaleClaim: true, ageMs: 8_000, staleClaimIdleMs: 7_000+ })).toBe('worktree-locked');+ // A root that demands an agent id refuses the claim basename on that ground.+ expect(worktreeOwnershipReason({ path: claim, roots: [{ path: COS_ROOT, requireAgentId: true }] }))+ .toBe('worktree-missing-agent-id');});it('fails closed when agent liveness is unknown and permits an explicitly non-agent root', () => {@@ -59,9 +80,9 @@ describe('worktreeHoldExpiresAt', () => {});it('gives no expiry to a claim tree that is ALSO locked', () => {- // The slug still reads 'worktree-human-claim' (first match wins), but the- // lock outlives the window — deriving a date from the slug alone would- // promise a lift that never happens.+ // The lock outlives the window, and the gate now says so structurally: a+ // locked claim tree reports 'worktree-locked', never the claim slug, so+ // there is no window here to date.expect(claim({ locked: true })).toBeNull();});diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 8ab8b1daa4..6759608e3f 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -234,12 +234,13 @@ async function getOpenPrsByHead(repoPath) {* Reason a worktree must NOT be torn down, or null if it's safe to remove.* Pure — the dangerous-to-remove cases the deterministic cleanup must respect* (mirrors the guards the existing worktree reaper honors):+ * In gate order, so a tree held by more than one of these reports the FIRST:* - locked → the user explicitly `git worktree lock`ed it+ * - active CoS agent → an agent (`agent-<id>`) is currently running in 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,* 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.*@@ -316,7 +317,7 @@ export function isAbandonedAgentWorktree({ path, locked, activeAgentIds }) {/*** Why this branch must be left ALONE this cycle — the dispatch-side counterpart to- * `worktreeProtectionReason`'s teardown gate. Two cases that gate doesn't cover:+ * `worktreeProtectionReason`'s teardown gate. Three cases that gate doesn't cover:** 1. **Liveness we could not determine.** `worktreeProtectionReason` is only ever* called with an authoritative `activeAgentIds` Set (cleanupMerged defaults it to@@ -332,12 +333,20 @@ export function isAbandonedAgentWorktree({ path, locked, activeAgentIds }) {* otherwise classifies IN_REVIEW and gets handed to the coordinator while its own* agent is still working. That is the bug this whole guard exists to prevent,* surviving in a narrower window. So the branch name is checked too.+ * 3. **A claim directory, which is a claim MARKER and not a live process.** The+ * claim flow has no durable local agent id for its 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. So this side passes `allowLiveClaim`, while cleanup keeps the hold+ * through `worktreeProtectionReason` until the claim is stale or provably+ * shipped. A lock still outranks it: the gate tests the lock BEFORE the+ * claim, so a locked claim tree reports `worktree-locked` on its own.* A branch with no worktree at all and no live owner is simply free (null).*- * @param {{ branch?:string|null, path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null }} input+ * @param {{ branch?:string|null, path:string|null, locked?:boolean, activeAgentIds?:Set<string> }} input* @returns {string|null} a stable reason slug, or null when nobody owns it*/-export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds, ageMs }) {+export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds }) {// The branch's own trailing segment is an agent id for CoS branches — checked// FIRST because it holds even after the worktree is gone.const owner = (branch || '').split('/').pop() || '';@@ -345,27 +354,13 @@ export function resolveLiveOwnerReason({ branch, path, locked, activeAgentIds, areturn 'branch-active-agent';}if (!path) return null;- const reason = worktreeOwnershipReason({+ return worktreeOwnershipReason({path,locked,activeAgentIds,- allowStaleClaim: true,- ageMs,- staleClaimIdleMs: STALE_CLAIM_IDLE_MS,+ allowLiveClaim: true,requireKnownLiveness: true,});-- // A `claim-*` directory is a claim marker, not a live-process marker. The- // 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 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;}/**@@ -726,7 +721,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId// the two must agree, or the reconciler protects a worktree from deletion and// then hands its branch to an agent that rebases underneath the live session.liveOwnerReason: resolveLiveOwnerReason({- branch: b.name, path: worktreePath, locked: worktreeLocked, activeAgentIds, ageMs: worktreeAge+ branch: b.name, path: worktreePath, locked: worktreeLocked, activeAgentIds}),behind: divergence.behind,ahead: divergence.ahead,diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 0795fe2461..6a6bc743a8 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -450,8 +450,10 @@ describe('resolveLiveOwnerReason', () => {it('reports dispatch-side ownership while cleanup keeps claim worktrees protected', () => {expect(resolveLiveOwnerReason({ path: '/wt/agent-aaaaaaaa', activeAgentIds: live })).toBe('worktree-active-agent');expect(resolveLiveOwnerReason({ path: '/wt/agent-bbbbbbbb', locked: true, activeAgentIds: live })).toBe('worktree-locked');- // A claim directory identifies the claim, but not a live process. The- // cleanup-side protection remains covered by worktreeProtectionReason.+ // A claim directory identifies the claim, but not a live process — this side+ // passes allowLiveClaim. The cleanup-side protection remains covered by+ // worktreeProtectionReason. A lock still wins, structurally: the gate tests+ // it before the claim, so no slug rewriting happens here.expect(resolveLiveOwnerReason({ path: '/wt/claim-fix-thing', activeAgentIds: live })).toBeNull();expect(resolveLiveOwnerReason({ path: '/wt/claim-fix-thing', locked: true, activeAgentIds: live })).toBe('worktree-locked');});@@ -1600,9 +1602,9 @@ describe('worktreeProtectionExpiresAt', () => {});it('gives no expiry to a claim worktree that is ALSO locked', () => {- // The reason slug says 'worktree-human-claim' (first match wins), but the- // lock outlives the grace window — deriving the date from the slug alone- // would promise a lift that never happens.+ // The lock outlives the grace window, and the gate reports it as such: it+ // tests the lock BEFORE the claim, so a locked claim tree reads+ // 'worktree-locked' and there is no window here to date.expect(worktreeProtectionExpiresAt({ path: CLAIM, ageMs: 2 * DAY, locked: true })).toBeNull();});diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 75f450e140..c70e3bd59c 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -1053,8 +1053,20 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)* `.claude/worktrees/` trees created by `/work`, `/claim`, and the superpowers* git-worktree skill (these share the PortOS repo, so they appear in* `git worktree list`). Active CoS agents and locked worktrees are never touched.- * Human `/claim` worktrees (`claim-*`) are skipped by default (they self-clean in- * the claim flow's Phase 7).+ *+ * Human `/claim` worktrees (`claim-*`) are ALWAYS skipped here, and deliberately+ * so — this reaper passes neither `allowStaleClaim` nor an age, which is not an+ * oversight to be fixed by handing it the same discriminator branch-reconcile+ * uses. Reclaiming a claim tree turns on how long it has been idle and on+ * whether its branch was provably SHIPPED (its upstream ref gone from origin),+ * and `branchReconcile` is the module that computes both, per branch, with the+ * remote-head listing to back it. This reaper knows only "merged + clean", which+ * is also true of a claim a human paused ten minutes ago. So the claim window+ * stays in ONE place: branch-reconcile reaps a shipped or abandoned claim on its+ * own pass, and the claim flow's Phase 7 self-cleans the ordinary case. (Under+ * `WORKTREES_DIR` the skip is doubly enforced: that root sets+ * `requireAgentId: true`, so a `claim-*` basename is refused as+ * `worktree-missing-agent-id` before the claim test is even reached.)** @param {string} sourceWorkspace - repo root* @param {object} [options]diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 150e971a73..81dd281824 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -488,6 +488,37 @@ describe('Orphaned Worktree Detection', () => {});});+// reapMergedWorktrees knows only "merged + clean", which is ALSO true of a claim+// a human paused ten minutes ago. Reclaiming one turns on idle time and on+// whether the branch was provably shipped, both of which only branchReconcile+// computes — so this reaper deliberately passes neither `allowStaleClaim` nor an+// age, and a claim tree is refused under BOTH of its managed roots. This mirrors+// the gate call it makes so the skip cannot be lost to a future reordering.+describe('reapMergedWorktrees claim policy', () => {+ const COS_ROOT = '/repo/data/cos/worktrees';+ const CLAUDE_ROOT = '/repo/.claude/worktrees';+ const managedRoots = [+ { path: COS_ROOT, requireAgentId: true },+ { path: CLAUDE_ROOT, requireAgentId: false },+ ];+ const reason = (path) => worktreeOwnershipReason({+ path, locked: false, activeAgentIds: new Set(), roots: managedRoots, requireKnownLiveness: true,+ });++ it('refuses a claim worktree under either managed root', () => {+ // Under the CoS root the agent-id policy refuses it first; under the+ // `.claude/worktrees/` root, which admits arbitrary names, the claim hold+ // itself does. Either way the reaper skips it with a reported reason.+ expect(reason(`${COS_ROOT}/claim-issue-42`)).toBe('worktree-missing-agent-id');+ expect(reason(`${CLAUDE_ROOT}/claim-issue-42`)).toBe('worktree-human-claim');+ });++ it('still reaps the non-claim trees it exists to clean', () => {+ expect(reason(`${COS_ROOT}/agent-abc12345`)).toBeNull();+ expect(reason(`${CLAUDE_ROOT}/review-fix`)).toBeNull();+ });+});+describe('isHumanClaimWorktree', () => {it('is true for /claim worktree dir names', () => {expect(isHumanClaimWorktree('claim-extract-compare-helpers')).toBe(true);