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
fix: give worktree teardown one liveness sentinel (#12990) (#13076)
[._.]/b814c1538baa
diff --git a/server/lib/README.md b/server/lib/README.mdindex a0c8529add..26fd9d310f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -585,7 +585,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. || `appPromptPlaceholders.js` | `applyAppPlaceholders(text, app)` — expand `{appName}` / `{repoPath}` / `{appId}` / `{appSlug}` in a CoS prompt template. The ONE owner of that chain: four renderers (`cosTaskGenerator.js`'s claim-work router and JIRA per-ticket builder, `cosTaskPreStepBlocks.js`'s scheduled builder, `referenceRepos.js`) each used to spell it themselves and drifted. Function-form replacers throughout, since a name/path/id is free text a `$` can appear in. Callers expand their own injected blocks (`{trackerInstructions}`, `{modeInstructions}`) FIRST — those blocks carry app placeholders of their own. Pure. || `worktreeNodeModules.js` | Workspace-aware `node_modules` provisioning for a worktree (#12633). `provisionWorkspaceNodeModules(sourceRoot, worktreeRoot)` builds a real `node_modules` directory when the source's holds workspace links (`@scope/pkg -> ../../packages/pkg`): every entry is symlinked back to the source except those links, which are recreated so they resolve INSIDE the worktree (a plain directory symlink resolves them against the source checkout, so a worktree ahead of the source's branch silently tests stale workspace code). Returns `false` and creates nothing when there are no workspace links. Every recreated link is checked to resolve inside the worktree, else provisioning fails; `removeProvisionedNodeModules` undoes the farm and only touches a directory carrying `WORKTREE_NODE_MODULES_MARKER`, so a real `npm install` is never mistaken for it. Consumed by `services/worktreeManager.js#linkWorktreeDependencies`. |-| `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. `appWorktreeSlug(app)` is the per-app segment (`<name-slug>-<8 id chars>`) that claim prompts render INSIDE the `claim-` prefix — `data/cos/worktrees/` is one directory shared by every managed app, so a work-item-only name collides whenever two apps carry the same issue number or PLAN slug. |+| `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). `knownAgentIds()` is the one live-agent sentinel: a Set (even empty) is authoritative, anything else is unknown liveness and must never be coerced to an empty Set. `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. `appWorktreeSlug(app)` is the per-app segment (`<name-slug>-<8 id chars>`) that claim prompts render INSIDE the `claim-` prefix — `data/cos/worktrees/` is one directory shared by every managed app, so a work-item-only name collides whenever two apps carry the same issue number or PLAN slug. || `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 b5f0bce87e..351a336bc4 100644--- a/server/lib/worktreeOwnership.js+++ b/server/lib/worktreeOwnership.js@@ -64,6 +64,21 @@ export function isAgentWorktreeId(agentId) {return typeof agentId === 'string' && agentId.startsWith('agent-');}+/**+ * The live-agent sentinel every destructive caller reads the same way: a `Set`+ * (INCLUDING an empty one — "nobody is running") is an authoritative answer and+ * passes through; anything else, `null` and `undefined` included, is UNKNOWN+ * liveness and comes back as `null`. Never coerce unknown to `new Set()` — an+ * empty Set lets `agent-*` trees be removed, which is how a checkout in its+ * dispatch-registration window was exposed (#12990).+ *+ * @param {*} value+ * @returns {Set<string>|null}+ */+export function knownAgentIds(value) {+ return value instanceof Set ? value : null;+}+function normalizedRoots(roots) {return (Array.isArray(roots) ? roots : []).filter((root) => typeof root?.path === 'string' && root.path);@@ -139,8 +154,9 @@ export function worktreeOwnershipReason({return 'worktree-missing-agent-id';}if (locked) return 'worktree-locked';- if (activeAgentIds instanceof Set && activeAgentIds.has(agentId)) return 'worktree-active-agent';- if (requireKnownLiveness && isAgentWorktreeId(agentId) && !(activeAgentIds instanceof Set)) {+ const liveIds = knownAgentIds(activeAgentIds);+ if (liveIds?.has(agentId)) return 'worktree-active-agent';+ if (requireKnownLiveness && isAgentWorktreeId(agentId) && !liveIds) {return 'worktree-agent-liveness-unknown';}diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.jsindex 9a6260244f..1d7b474889 100644--- a/server/services/branchReconcile.js+++ b/server/services/branchReconcile.js@@ -28,7 +28,7 @@ import { isHostShuttingDown } from '../lib/hostShutdown.js';import { getBranches, getDefaultBranch, hasBranchMergeEvidence, deleteMergedRemoteBranches } from './git.js';import { execGit } from '../lib/execGit.js';import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees, readWorktreeStatus } from './worktreeManager.js';-import { isAgentWorktreeId, isHumanClaimWorktree, worktreeAgentId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';+import { isAgentWorktreeId, isHumanClaimWorktree, knownAgentIds, worktreeAgentId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';import { execGh, ensureForgeReachable, getIssueDispatchHint } from './github.js';import { resolveForgeExecOptions } from './forgeExecOptions.js';import { isForgeNoAccessError, logForgeNoAccessOnce } from '../lib/forgeAccessErrors.js';@@ -351,12 +351,21 @@ async function getOpenPrsByHead(repoPath, providedOrigin, { forgeExec = null, fo* worktree outside them is `worktree-unmanaged-location` before any of the above:* a directory PortOS never created carries no ownership signal at all.*- * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number, staleClaimIdleMs?:number, roots?:Array<{path:string, requireAgentId?:boolean}> }} input+ * `activeAgentIds` is read through `knownAgentIds`: a Set (even an empty one) is+ * authoritative, anything else is UNKNOWN liveness and holds every `agent-*` tree+ * (`worktree-agent-liveness-unknown`). A missing `path` is+ * `worktree-missing-path`, never null — null means only "this caller may remove it".+ *+ * @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string>|null, ageMs?:number, staleClaimIdleMs?:number, roots?:Array<{path:string, requireAgentId?:boolean}> }} input* @returns {string|null}*/-export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, roots = [], unmanagedIdleMs }) {- if (!path) return null;- return worktreeOwnershipReason({+export function worktreeProtectionReason(input) {+ return worktreeOwnershipReason(teardownGate(input));+}++/** The teardown posture both protection helpers share: stale claims reclaimable, unknown liveness held. */+function teardownGate({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, roots = [], unmanagedIdleMs }) {+ return {path,locked,activeAgentIds,@@ -366,7 +375,8 @@ export function worktreeProtectionReason({ path, locked, activeAgentIds, ageMs,ageMs,staleClaimIdleMs,unmanagedIdleMs,- });+ requireKnownLiveness: true,+ };}/**@@ -408,19 +418,8 @@ function reconcileWorktreeRoots(repoPath) {* @param {{ path:string|null, locked?:boolean, activeAgentIds?:Set<string>, ageMs?:number|null, staleClaimIdleMs?:number, allowLiveClaim?:boolean }} input* @returns {string|null} ISO timestamp*/-export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageMs, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, roots = [], unmanagedIdleMs }) {- if (!path) return null;- return worktreeHoldExpiresAt({- path,- locked,- activeAgentIds,- roots,- allowStaleClaim: true,- allowLiveClaim,- unmanagedIdleMs,- ageMs,- staleClaimIdleMs,- });+export function worktreeProtectionExpiresAt(input) {+ return worktreeHoldExpiresAt(teardownGate(input));}/**@@ -428,12 +427,18 @@ export function worktreeProtectionExpiresAt({ path, locked, activeAgentIds, ageM* plus every running or paused record's id and its workspace basename (a claim* tree uses a branch-shaped directory name, not the run's `agent-*` id). Pure.*- * @param {Iterable<string>} runtimeIds - `getActiveAgentIds()`- * @param {object[]} liveAgents - the agent registry- * @returns {Set<string>}+ * Unknown stays unknown: a `runtimeIds` that is not a Set (see `knownAgentIds`)+ * or an unreadable registry returns null, never an empty Set — `new Set(null)`+ * would read as "nobody is running" and release every `agent-*` tree.+ *+ * @param {Set<string>|null|undefined} runtimeIds - `new Set(getActiveAgentIds())`+ * @param {object[]|null} liveAgents - the agent registry+ * @returns {Set<string>|null}*/export function buildActiveOwnerIds(runtimeIds, liveAgents) {- const ids = new Set(runtimeIds);+ const known = knownAgentIds(runtimeIds);+ if (!known || !Array.isArray(liveAgents)) return null;+ const ids = new Set(known);for (const agent of liveAgents) {if (agent?.status !== 'running' && agent?.status !== 'paused') continue;if (agent.id) ids.add(agent.id);@@ -504,8 +509,8 @@ function pendingMergeReason(pendingMergeBranches, branch) {* `activeAgentIds` is a sentinel, not a plain collection: a Set (INCLUDING an* empty one — "no agents running", the common case) is an authoritative liveness* answer, while a missing/non-Set value means liveness is UNKNOWN and every agent- * worktree stays protected. Same fail-safe posture as `worktreeProtectionReason`'s- * unknown-age branch — never infer abandonment from an answer we didn't get.+ * worktree stays protected (`knownAgentIds`). `worktreeProtectionReason` holds+ * the same way — never infer abandonment from an answer we didn't get.** @param {{ path:string, locked?:boolean, activeAgentIds?:Set<string> }} input* @returns {boolean}@@ -539,7 +544,7 @@ export function isAbandonedAgentWorktree({ path, locked, activeAgentIds }) {* @returns {boolean}*/export function isAbandonedClaimWorktree({ path, locked, worktreeDirty = false, activeAgentIds }) {- if (!worktreeDirty || !(activeAgentIds instanceof Set) || !isHumanClaimWorktree(worktreeAgentId(path))) return false;+ if (!worktreeDirty || !knownAgentIds(activeAgentIds) || !isHumanClaimWorktree(worktreeAgentId(path))) return false;return worktreeOwnershipReason({path,locked,@@ -552,12 +557,10 @@ export function isAbandonedClaimWorktree({ path, locked, worktreeDirty = false,* Why this branch must be left ALONE this cycle — the dispatch-side counterpart to* `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- * an empty one), so a missing Set reads there as "no agents running" and returns- * null. For a DISPATCH decision that default is backwards: an `agent-*` worktree- * whose owner's liveness is UNKNOWN must be presumed live, exactly as- * `isAbandonedAgentWorktree` presumes it. Fail safe toward not-touching.+ * 1. **Liveness we could not determine.** An `agent-*` worktree whose owner's+ * liveness is UNKNOWN (`knownAgentIds` returned null) is presumed live —+ * the same posture `worktreeProtectionReason` and `isAbandonedAgentWorktree`+ * take. Fail safe toward not-touching.* 2. **A live agent whose worktree is already GONE.** Ownership is in the branch* NAME, not the worktree: CoS branches are `cos/<taskId>/<agentId>` and the* worktree basename is that same `<agentId>`. An agent that removed its worktree@@ -589,7 +592,7 @@ 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() || '';- if (isAgentWorktreeId(owner) && activeAgentIds instanceof Set && activeAgentIds.has(owner)) {+ if (isAgentWorktreeId(owner) && knownAgentIds(activeAgentIds)?.has(owner)) {return 'branch-active-agent';}if (!path) return null;@@ -1154,12 +1157,15 @@ async function claimIssueUnreserved(target, issue, forgeExec) {* @param {string} repoPath* @param {string} defaultBranch* @param {object[]} merged - gathered inputs whose state === 'MERGED'- * @param {{ activeAgentIds?: Set<string> }} [opts] - CoS agents currently running;+ * @param {{ activeAgentIds?: Set<string>|null }} [opts] - CoS agents currently running;* their worktrees are never torn down even when the branch is merged + clean.+ * Omitted or null is unknown liveness and holds every `agent-*` worktree.+ * A `claim-*` checkout keeps its claim hold; only exact completion evidence+ * (see `admitBranchRetirement`) waives it.* @returns {Promise<{cleaned:string[], skipped:{branch:string,reason:string,retryAt?:string}[]}>}* A skip carries `retryAt` when its hold is known to lift at a specific time.*/-export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds = new Set(), claimOwners, origin, forgeExec, forgeAccount = null } = {}) {+export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds, claimOwners, origin, forgeExec, forgeAccount = null } = {}) {const cleaned = [];const skipped = [];const claimMarkersHeld = [];@@ -1225,7 +1231,7 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge* @returns {Promise<{reaped:string[], held:object[], skipped:{branch:string,reason:string,retryAt?:string}[]}>}* `held` is the live entries the reap could not take, for the caller to report.*/-export async function reapSupersededBranches(repoPath, defaultBranch, superseded, { activeAgentIds = new Set(), claimOwners, cosDir } = {}) {+export async function reapSupersededBranches(repoPath, defaultBranch, superseded, { activeAgentIds, claimOwners, cosDir } = {}) {const reaped = [];const held = [];const skipped = [];@@ -1351,13 +1357,12 @@ async function retireBranch(repoPath, b, opts) {branchName: b.branch, holderPath: b.worktreePath, sourceWorkspace: repoPath, agents,});if (reason) return { result: { ok: false, reason } };- // A fresh registry read under the binding lock supersedes the directory-age- // proxy. A claim name alone is not a live owner. Keep all other retirement- // gates, and refresh workspace owners too (not only explicit claim bindings).+ // Refresh workspace owners from the registry read under the binding lock+ // (not only explicit claim bindings). The caller's `allowLiveClaim` stands:+ // a merged claim's hold is waived only by completion evidence, below.const gated = await admitBranchRetirement(repoPath, b, {...opts,activeAgentIds: buildActiveOwnerIds(opts.activeAgentIds, agents),- allowLiveClaim: true,});if (gated.result) return gated;if (!gated.archiveTree && !gated.prepare) return { result: await finishBranchRetirement(repoPath, gated) };@@ -1377,7 +1382,7 @@ async function retireBranch(repoPath, b, opts) {}/** Every gate before the archive. Returns `{ result }` to stop, else the context removal needs. */-async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false, mergeTarget, forgeAccount = null }) {+async function admitBranchRetirement(repoPath, b, { activeAgentIds, staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false, mergeTarget, forgeAccount = null }) {const stop = result => ({ result });if (PROTECTED_BRANCHES.includes(b.branch)) return stop({ ok: false, reason: 'protected-branch' });const defaultBranch = await getDefaultBranch(repoPath, { strict: true }).catch(() => null);@@ -1417,7 +1422,12 @@ async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(),roots: reconcileWorktreeRoots(repoPath),unmanagedIdleMs,};- const protectedReason = worktreeProtectionReason(gate);+ let protectedReason = worktreeProtectionReason(gate);+ // The claim gate runs LAST, so `worktree-human-claim` means every other hold+ // already cleared. For a merged claim that one hold is waivable, but only by+ // the exact completion evidence required below — never by the claim name or+ // the registry's silence (#12990).+ if (protectedReason === 'worktree-human-claim' && mergedRetirement) protectedReason = null;if (protectedReason) {// Carry WHEN the hold lifts when it lifts on a clock (a claim worktree// still inside its grace window). Without it the caller can only park on@@ -1639,7 +1649,7 @@ const isStillDetachedOnMerged = async (repoPath, treePath, defaultBranch) => {* @param {{ activeAgentIds?: Set<string>, claimOwners?: { agents: object[]|null } }} [opts]* @returns {Promise<{cleaned:string[], skipped:object[], held:{path:string, head:string|null, reason:string, managed:boolean, retryAt?:string}[]}>}*/-async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { activeAgentIds = new Set(), claimOwners } = {}) {+async function reapDetachedWorktrees(repoPath, defaultBranch, detached, { activeAgentIds, claimOwners } = {}) {const cleaned = [];const skipped = [];const held = [];diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.jsindex ede3bca439..a66eb46b30 100644--- a/server/services/branchReconcile.ownership.test.js+++ b/server/services/branchReconcile.ownership.test.js@@ -311,6 +311,25 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (reexpect(existsSync(tree)).toBe(false);});+ // #12990: omitted ids used to become `new Set(null)` — "nobody running" — so an+ // agent tree in its dispatch-registration window was retired by the default call.+ it('holds an agent tree when the operator cleanup is not given live-agent ids', async () => {+ const tree = await addTree(join(repo, '.claude', 'worktrees', 'agent-registering'), 'agent/registering');+ await addOrigin();+ markAgentDispatching('agent-registering');+ try {+ const unknown = await deleteMergedBranches(repo);+ expect(unknown.deleted).toEqual([]);+ expect(unknown.skipped).toContain('agent/registering (local: agent liveness unknown)');+ expect(existsSync(tree)).toBe(true);+ } finally {+ clearAgentDispatching('agent-registering');+ }+ const known = await deleteMergedBranches(repo, { activeAgentIds: new Set() });+ expect(known.deleted.map((row) => row.name)).toEqual(['agent/registering']);+ expect(existsSync(tree)).toBe(false);+ });+it('keeps an unmanaged checkout held at the operator merged-branch cleanup boundary', async () => {const loose = await addTree(join(external, 'loose'), 'loose-br', { ageMs: 30 * DAY });diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.jsindex 122e17bfcf..66c3091239 100644--- a/server/services/branchReconcile.test.js+++ b/server/services/branchReconcile.test.js@@ -132,7 +132,7 @@ import {SHIPPED_CLAIM_IDLE_MS, STALE_CLAIM_IDLE_MS, SUPERSEDED_UNMANAGED_IDLE_MS,isMalformedClaimBranch,listRemoteHeads, upstreamBranchName, parseRemoteHeads, partitionRemoteOrphans, reapOrphanedRemotes,- reapSupersededBranches+ reapSupersededBranches, buildActiveOwnerIds} from './branchReconcile.js';import * as git from './git.js';import * as wt from './worktreeManager.js';@@ -717,6 +717,28 @@ describe('worktreeProtectionReason', () => {expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', allowLiveClaim: true, locked: true })).toBe('worktree-locked');expect(worktreeProtectionReason({ head: RETIRE_HEAD, path: '/x/claim-foo', allowLiveClaim: true, activeAgentIds: new Set(['claim-foo']) })).toBe('worktree-active-agent');});++ // #12990: unknown liveness is a hold, an empty Set is "nobody running", and a+ // missing path is never the null that means "safe to remove".+ it('holds agent trees on unknown liveness and never answers null for a missing path', () => {+ for (const activeAgentIds of [undefined, null]) {+ expect(worktreeProtectionReason({ path: '/x/agent-1', activeAgentIds })).toBe('worktree-agent-liveness-unknown');+ }+ expect(worktreeProtectionReason({ path: '/x/agent-1', activeAgentIds: new Set() })).toBeNull();+ expect(worktreeProtectionReason({ path: '' })).toBe('worktree-missing-path');+ expect(worktreeProtectionReason({ path: null, activeAgentIds: new Set() })).toBe('worktree-missing-path');+ });+});++describe('buildActiveOwnerIds', () => {+ it('keeps unknown runtime liveness unknown instead of coercing it to an empty Set', () => {+ const live = [{ id: 'agent-live', status: 'running', workspacePath: '/wt/claim-x' }];+ expect(buildActiveOwnerIds(null, live)).toBeNull();+ expect(buildActiveOwnerIds(undefined, live)).toBeNull();+ expect(buildActiveOwnerIds(new Set(), null)).toBeNull();+ expect([...buildActiveOwnerIds(new Set(['agent-rt']), live)].sort()).toEqual(['agent-live', 'agent-rt', 'claim-x']);+ expect(buildActiveOwnerIds(new Set(), [])).toEqual(new Set());+ });});describe('gatherBranchState', () => {diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.jsindex 836891bb67..5ad0832882 100644--- a/server/services/branchReconcileCompletion.js+++ b/server/services/branchReconcileCompletion.js@@ -33,7 +33,7 @@ export async function settleBranchReconcileRun(agent) {cleanup: true,reapSuperseded: task.metadata.reapSuperseded !== false,pendingMergeBranches,- activeAgentIds: buildActiveOwnerIds(getActiveAgentIds(), agents),+ activeAgentIds: buildActiveOwnerIds(new Set(getActiveAgentIds()), agents),claimOwners: { agents, readAgents: readClaimOwnershipAgents },forgeAccount: app.forgeAccount || null});diff --git a/server/services/cosClaimOwnership.js b/server/services/cosClaimOwnership.jsindex ac837d998e..4eafc04e99 100644--- a/server/services/cosClaimOwnership.js+++ b/server/services/cosClaimOwnership.js@@ -171,7 +171,7 @@ export async function checkReconcileOwnership(input, deps = {}) {const others = agentId ? agents.filter((a) => a?.id !== agentId) : agents;const reason = resolveLiveOwnerReason({branch, path: holder?.path || null, locked: Boolean(holder?.locked),- activeAgentIds: buildActiveOwnerIds(getActiveAgentIds().filter((id) => id !== agentId), others),+ activeAgentIds: buildActiveOwnerIds(new Set(getActiveAgentIds().filter((id) => id !== agentId)), others),}) || claimCheckoutOwnerReason({ branchName: branch, holderPath: holder?.path || null, sourceWorkspace: repoPath, agents: others });return reason ? { admitted: false, reason } : { admitted: true };};diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex 91491eb3ed..98ccf6080d 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -454,7 +454,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS// stored on the run, so the live records' workspace basenames join the// ownership set — and a run that cut its own claim tree keeps the source repo// as its workspace, so its registered branch bindings are passed as well.- const activeAgentIds = buildActiveOwnerIds(getActiveAgentIds(), liveAgents);+ const activeAgentIds = buildActiveOwnerIds(new Set(getActiveAgentIds()), liveAgents);// Action toggles were merged (global → per-app override) + value-constrained// by sanitizeTaskMetadata into `metadata`; each is ON unless explicitly false.const actions = {diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.jsindex 9f54f7758e..53962d7910 100644--- a/server/services/heldCheckoutRecovery.js+++ b/server/services/heldCheckoutRecovery.js@@ -422,7 +422,7 @@ async function ownerReason({ repoPath, tree, branch, readAgents, reviewed = fals]);// The released lock is excluded here on purpose: it was matched against the// release above, and a NEW lock is caught by the registration recheck.- const live = resolveLiveOwnerReason({ branch, path: tree.path, locked: false, activeAgentIds: buildActiveOwnerIds(getActiveAgentIds(), agents) });+ const live = resolveLiveOwnerReason({ branch, path: tree.path, locked: false, activeAgentIds: buildActiveOwnerIds(new Set(getActiveAgentIds()), agents) });if (live) return live;if (!branch || reviewed) return null;const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');