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
Release ownerless foreign worktrees holding a task's branch (#12845) (#12847)
[._.]/51c018b6a61c
diff --git a/server/lib/README.md b/server/lib/README.mdindex e42194b95d..c77c580144 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -689,6 +689,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ports.js` | Canonical `PORTS` object (mirroring `ecosystem.config.cjs`, pinned by `ports.test.js`), `DEFAULT_PEER_PORT`, and `resolvePostgresPort(pgMode)`. A pure leaf: `client/src/lib/ports.js` re-exports it, so nothing here may read `process.env` at module scope — the env-derived origins live in `portosUrls.js`. || `portosUrls.js` | `PORTOS_UI_URL` / `PORTOS_API_URL` — the origins PortOS interpolates into prompts and links, resolved from `PORTOS_*` / `PORT` at module load. `PORTOS_API_URL_TOKEN` is the `{portosApiUrl}` placeholder agent prompts embed instead of `PORTOS_API_URL`; `buildAgentPrompt` expands it at spawn time to `localApiBaseUrl()` (the loopback mirror on HTTPS installs). Split out of `ports.js` so that module stays free of module-scope `process.env` reads and can be re-exported to the client. || `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). |+| `processCwdProbe.js` | `hasProcessCwdInside(dir)` — true when any process (via `lsof -d cwd`) has its working directory inside `dir`. Fails CLOSED: no `lsof`, an unsupported platform or an empty/unreadable listing reads as occupied. Backs the ownerless-foreign-worktree release in `worktreeManager.js`. || `signalCrypto.js` | Pure, dependency-free crypto for Signal Desktop (#2154, #11149): SQLCipher-4 page decryption (`decryptSqlcipherDatabase`, `deriveSqlcipherKeys`, `sqlcipherPageHmac`) and Chromium/Electron `safeStorage` unwrap (`decryptSafeStorageValue`, `deriveSafeStorageKey`). Live sync does not decrypt a raw main-file copy — that misses committed WAL frames — and instead uses `services/signalSnapshot.js`. `isRawHexKey` still gates the key. All functions return `{ ok, ... }` reports (never throw). || `timezone.js` | Timezone utilities for scheduling. `getLocalParts(utcDate, timezone)` / `getUtcOffsetMs(utcDate, timezone)` are the primitives; `nextLocalTime(afterMs, hours, minutes, timezone)` finds the next UTC instant matching a local HH:MM. `anchorLocalMidnightUtc(dayStr, tz)` resolves the first UTC instant belonging to a local date, including zones whose DST transition skips 00:00; `localDayWindowUtc(timezone, atDate?)` exposes an inclusive ISO-string window, while `localDayRangeUtc(dateStr, timezone)` returns a validated half-open `{ start, end }` `Date` pair ending at the next local-date boundary so 23h/25h transition days remain exact. Also owns `HHMM_RE`/`HHMM_STRICT_RE`, `parseHHMM`, `dailyCronFromHHMM(time)` (the one strict "HH:MM" → `"M H * * *"` conversion every daily-reminder scheduler registers through, null on malformed input so the caller cancels rather than firing in some other slot), and `isWithinTimeWindow` (mirrored client-side in `client/src/utils/timeWindow.js`). || `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 2d7ad7429f..1416bc2e28 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -657,6 +657,7 @@ export * from './db.js';export * from './pgTimestamp.js';export * from './pgTools.js';export * from './platform.js';+export * from './processCwdProbe.js';export * from './systemCapabilities.js';export * from './ports.js';export * from './portosUrls.js';diff --git a/server/lib/processCwdProbe.js b/server/lib/processCwdProbe.jsnew file mode 100644index 0000000000..438cffd78f--- /dev/null+++ b/server/lib/processCwdProbe.js@@ -0,0 +1,44 @@+/**+ * Is any process running with its working directory inside a directory?+ *+ * Used to tell an abandoned foreign worktree (its terminal session exited) from+ * one a person or tool is still sitting in. The answer is tri-state collapsed+ * to a boolean that fails CLOSED: anything the probe cannot establish (no+ * `lsof`, a platform without it, an unreadable or implausible listing) reads as+ * "occupied", never as "nobody is there".+ */++import { realpathSync } from 'node:fs';+import { posix } from 'node:path';+import { promisify } from 'node:util';+import { execFile } from './childProcess.js';++const LSOF_TIMEOUT_MS = 10_000;+const LSOF_MAX_BUFFER = 16 * 1024 * 1024;++// lsof only runs on darwin/linux and prints POSIX paths, so compare with posix semantics on every host.+const realOrResolved = (p) => { try { return realpathSync(p); } catch { return posix.resolve(p); } };++/** Working directories from `lsof -Fn` field output (`p<pid>` then `n<path>` per process). */+function parseLsofCwds(stdout) {+ return String(stdout || '').split('\n').filter(l => l.startsWith('n')).map(l => l.slice(1));+}++/**+ * @param {string} dir+ * @param {{ platform?: string, run?: (file: string, args: string[], opts: object) => Promise<{ stdout: string }> }} [options] test seams+ * @returns {Promise<boolean>} true when a process has its cwd in `dir`, or when that cannot be ruled out+ */+export async function hasProcessCwdInside(dir, { platform = process.platform, run = promisify(execFile) } = {}) {+ if (!dir) return true;+ if (platform !== 'darwin' && platform !== 'linux') return true;+ // lsof exits non-zero when it merely could not read some other user's process,+ // while still printing what it saw; the listing is judged on content below.+ const out = await run('lsof', ['-a', '-d', 'cwd', '-Fn'], { timeout: LSOF_TIMEOUT_MS, maxBuffer: LSOF_MAX_BUFFER })+ .then(r => r.stdout, err => err?.stdout ?? null);+ const cwds = out == null ? [] : parseLsofCwds(out);+ // This very process always has a cwd, so an empty listing means lsof failed.+ if (cwds.length === 0) return true;+ const targets = new Set([posix.resolve(dir), realOrResolved(dir)]);+ return cwds.some(cwd => [...targets].some(t => cwd === t || cwd.startsWith(t.endsWith(posix.sep) ? t : t + posix.sep)));+}diff --git a/server/lib/processCwdProbe.test.js b/server/lib/processCwdProbe.test.jsnew file mode 100644index 0000000000..13ac5ac98e--- /dev/null+++ b/server/lib/processCwdProbe.test.js@@ -0,0 +1,28 @@+import { describe, it, expect } from 'vitest';+import { hasProcessCwdInside } from './processCwdProbe.js';++const listing = (...cwds) => async () => ({ stdout: cwds.map((c, i) => `p${i + 1}\nn${c}\n`).join('') });++describe('hasProcessCwdInside', () => {+ const opts = (run, platform = 'linux') => ({ platform, run });++ it('finds a process in the directory or below it, not in a prefix-sharing sibling', async () => {+ expect(await hasProcessCwdInside('/work/wt', opts(listing('/', '/work/wt')))).toBe(true);+ expect(await hasProcessCwdInside('/work/wt', opts(listing('/', '/work/wt/sub/dir')))).toBe(true);+ expect(await hasProcessCwdInside('/work/wt', opts(listing('/', '/work/wt-other')))).toBe(false);+ });++ it('fails closed when the probe cannot answer', async () => {+ const rejects = async () => { throw new Error('spawn lsof ENOENT'); };+ expect(await hasProcessCwdInside('/work/wt', opts(rejects))).toBe(true);+ expect(await hasProcessCwdInside('/work/wt', opts(listing()))).toBe(true);+ expect(await hasProcessCwdInside('/work/wt', opts(listing('/'), 'win32'))).toBe(true);+ expect(await hasProcessCwdInside('', opts(listing('/')))).toBe(true);+ });++ it('reads only name fields and judges the listing lsof printed before a non-zero exit', async () => {+ const partial = async () => { throw Object.assign(new Error('exit 1'), { stdout: 'p1\nfcwd\nn/\np2\nfcwd\nn/work/wt\n' }); };+ expect(await hasProcessCwdInside('/work/wt', opts(partial))).toBe(true);+ expect(await hasProcessCwdInside('/work/other', opts(partial))).toBe(false);+ });+});diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 35dbea83bd..7a855769dc 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -36,7 +36,7 @@ import { isTruthyMeta, isFalsyMeta, protectedAgentIds } from './agentState.js';import { PATHS, ensureDir } from '../lib/fileUtils.js';import * as git from './git.js';import { detectConflicts } from './taskConflict.js';-import { PINNED_HEAD_MOVED, createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';+import { PINNED_HEAD_MOVED, createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, listWorktrees, releaseIdleSiblingNextHolder, releaseOwnerlessForeignHolder, unlinkWorktreeDependencies } from './worktreeManager.js';import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';import { resolveTaskTargetBranch, resolveTaskRemoteBranch } from '../lib/taskTargetBranch.js';@@ -161,6 +161,28 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,return worktreeInfo ? { worktreeInfo, adoptedFrom: holder.agentId } : null;}+/**+ * Free the branch from an ownerless foreign worktree so `createWorktree` can+ * attach. Fails closed: an unreadable agent list is "somebody may own it".+ * @returns {Promise<boolean>} true when the holder was released+ */+async function releaseOwnerlessForeignHolderForTask({ workspacePath, branchName, agentId, taskId }) {+ const { getAgents } = await import('./cos.js');+ const agents = await getAgents().catch(() => null);+ if (!Array.isArray(agents)) return false;+ const activeIds = protectedAgentIds(agents);+ const released = await releaseOwnerlessForeignHolder(workspacePath, branchName, {+ agents,+ requestingAgentId: agentId,+ activeWorkspacePaths: agents.filter(a => activeIds.has(a.id)).map(a => a.workspacePath || a.metadata?.workspacePath),+ }).catch(err => {+ emitLog('warn', `🌳 Could not release ${branchName} from its foreign worktree for task ${taskId}: ${err.message}`, { taskId });+ return null;+ });+ if (released) emitLog('info', `🌳 Released ${branchName} from ownerless worktree ${released.path} for task ${taskId}`, { taskId, branch: branchName });+ return Boolean(released);+}+/*** The commit a task's branch attach is pinned to, '' when the task needs a pin* but carries none, null when it is unpinned. A PR remediation agent runs the@@ -277,7 +299,7 @@ async function prepareRequestedWorktree({// The failure reason decides whether the task is unrunnable or merely early.let worktreeError = null;- const worktreeInfo = takeover?.worktreeInfo || await createWorktree(agentId, workspacePath, task.id, {+ const create = () => createWorktree(agentId, workspacePath, task.id, {baseBranch: detectedBase || undefined,...(baseCommit ? { baseCommit } : {}),existingBranch: resolveTaskRemoteBranch(task.metadata) || undefined,@@ -287,11 +309,25 @@ async function prepareRequestedWorktree({expectedHeadSha: pinnedHead || reviewTarget?.headSha || undefined,planId: task.metadata?.planId || undefined,linkDependencies: !isolateDependencies,- }).catch(err => {+ });+ let worktreeInfo = takeover?.worktreeInfo || await create().catch(err => {worktreeError = err;- emitLog('warn', `🌳 Worktree creation failed for task ${task.id}: ${err.message}`, { taskId: task.id });return null;});+ // A foreign checkout (a terminal session's own worktree) that holds the branch+ // is never reaped by anything, so waiting out the cooldown cannot free it. If it+ // is ownerless, clean and fully pushed, detach it in place and retry at once.+ if (!worktreeInfo && existingBranch && isBranchCheckedOutElsewhereError(worktreeError?.message)+ && await releaseOwnerlessForeignHolderForTask({ workspacePath, branchName: existingBranch, agentId, taskId: task.id })) {+ worktreeError = null;+ worktreeInfo = await create().catch(err => {+ worktreeError = err;+ return null;+ });+ }+ if (worktreeError) {+ emitLog('warn', `🌳 Worktree creation failed for task ${task.id}: ${worktreeError.message}`, { taskId: task.id });+ }if (worktreeInfo) {const nextWorkspacePath = worktreeInfo.worktreePath;diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 08586ac603..9f99108429 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -57,6 +57,7 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({unlinkWorktreeDependencies: vi.fn().mockResolvedValue(undefined),findAdoptableWorktreeForBranch: vi.fn().mockResolvedValue(null),releaseIdleSiblingNextHolder: vi.fn().mockResolvedValue(null),+ releaseOwnerlessForeignHolder: vi.fn().mockResolvedValue(null),listWorktrees: vi.fn().mockResolvedValue([]),mergeBaseIntoFeatureWorktree: vi.fn(),}));@@ -87,7 +88,7 @@ import { ensureLatest, isRepo, fetchOrigin } from './git.js';import { execGit } from '../lib/execGit.js';import { detectConflicts } from './taskConflict.js';import { getAppWorkspace } from './agentAppWorkspace.js';-import { PINNED_HEAD_MOVED, createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';+import { PINNED_HEAD_MOVED, createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, listWorktrees, releaseIdleSiblingNextHolder, releaseOwnerlessForeignHolder, unlinkWorktreeDependencies } from './worktreeManager.js';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';@@ -1015,6 +1016,57 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktreexpect(patch.metadata.blockedReason).toContain('already used by worktree');});+ // A terminal session's own worktree holds the branch for good: nothing PortOS+ // runs ever reaps it, so the cooldown can only burn the retry budget (#12845).+ describe('an ownerless foreign holder', () => {+ const READY = { worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/task-x/agent-y', baseBranch: null, existingBranch: true };++ it('is released and the branch attached within the same attempt', async () => {+ createWorktree.mockRejectedValueOnce(BUSY).mockResolvedValueOnce(READY);+ releaseOwnerlessForeignHolder.mockResolvedValue({ path: '/scratch/wt-portos' });+ getAgents.mockResolvedValue([+ { id: 'agent-live', status: 'running', workspacePath: '/mock/worktrees/agent-live' },+ { id: 'agent-done', status: 'completed', workspacePath: '/mock/worktrees/agent-done' },+ ]);++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });++ expect(r.outcome).toBe('ready');+ expect(createWorktree).toHaveBeenCalledTimes(2);+ expect(releaseOwnerlessForeignHolder).toHaveBeenCalledWith(expect.any(String), 'cos/task-x/agent-y', expect.objectContaining({+ requestingAgentId: 'agent-new',+ activeWorkspacePaths: ['/mock/worktrees/agent-live'],+ }));+ expect(updateTask).not.toHaveBeenCalled();+ });++ it.each([+ ['refuses to release', () => releaseOwnerlessForeignHolder.mockResolvedValue(null)],+ ['throws while releasing', () => releaseOwnerlessForeignHolder.mockRejectedValue(new Error('git exploded'))],+ ['finds the agent list unreadable at release time', () => getAgents.mockResolvedValueOnce([]).mockRejectedValue(new Error('state unreadable'))],+ ])('keeps the timed worktree-busy pause when the holder %s', async (_label, arrange) => {+ arrange();+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });+ expect(r.outcome).toBe('blocked');+ expect(createWorktree).toHaveBeenCalledTimes(1);+ expect(updateTask.mock.calls.at(-1)[1].metadata.blockedCategory).toBe('worktree-busy');+ });++ it('pauses when the branch is still busy after a release', async () => {+ releaseOwnerlessForeignHolder.mockResolvedValue({ path: '/scratch/wt-portos' });+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });+ expect(r.outcome).toBe('blocked');+ expect(createWorktree).toHaveBeenCalledTimes(2);+ expect(updateTask.mock.calls.at(-1)[1].metadata.blockedCategory).toBe('worktree-busy');+ });++ it('is not sought for a failure that is not a busy branch', async () => {+ createWorktree.mockRejectedValue(new Error("fatal: '/mock/worktrees/agent-new' already exists"));+ await prepareAgentWorkspace({ agentId: 'agent-new', task: followUpTask() });+ expect(releaseOwnerlessForeignHolder).not.toHaveBeenCalled();+ });+ });+it('does NOT pause for a permanent worktree failure', async () => {createWorktree.mockRejectedValue(new Error("fatal: '/mock/worktrees/agent-new' already exists"));diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 025dca747e..b2d91a3f86 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -17,6 +17,7 @@ import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fiimport { DONE_SENTINEL_NAME, doneSentinelCandidateNames } from '../lib/agentSentinel.js';import { AGENT_SCRATCH_PATHS, matchesScratchRoot } from '../lib/agentScratchPaths.js';import { execGit } from '../lib/execGit.js';+import { hasProcessCwdInside } from '../lib/processCwdProbe.js';import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';import { clearStaleGitLock } from '../lib/gitStaleLock.js';import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';@@ -1113,25 +1114,86 @@ async function releaseIdleSiblingNextHolderAdmitted(sourceWorkspace, branchName,.map(f => stat(join(gitDir, f)).then(s => s.mtimeMs, () => 0)));if (nowMs - Math.max(...mtimes) < idleMs) return null;+ if (!await detachCleanPushedHolder(holder.path, branchName, { allowUntracked })) return null;+ console.log(`🌳 Released ${branchName} from idle /do:next worktree ${holder.path} (HEAD detached in place)`);+ return { path: holder.path };+}++/**+ * Detach `holderPath`'s HEAD in place iff the tree holds nothing the branch ref+ * does not: tracked/staged state clean (untracked files too unless+ * `allowUntracked`; git-ignored caches never count) and HEAD already on the+ * remote. A detached HEAD keeps every file where it is and `git switch <branch>`+ * restores it. Any unreadable check refuses (false).+ */+async function detachCleanPushedHolder(holderPath, branchName, { allowUntracked = false } = {}) {+ const git = (args) => execGit(args, holderPath).then(r => r.stdout.trim());// Stricter than `classifyWorktreeDirt` on purpose: this tree isn't PortOS's,// so no path counts as disposable scratch.const porcelain = await git(['--no-optional-locks', 'status', '--porcelain', '--untracked-files=all']).catch(() => null);- if (porcelain === null) return null;- if (allowUntracked ? porcelain.split('\n').some(l => l && !l.startsWith('?? ')) : porcelain !== '') return null;+ if (porcelain === null) return false;+ if (allowUntracked ? porcelain.split('\n').some(l => l && !l.startsWith('?? ')) : porcelain !== '') return false;const remoteRef = await git(['rev-parse', '--verify', '--quiet', `${branchName}@{upstream}`]).catch(() => git(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branchName}`])).catch(() => null);- if (!remoteRef) return null;- const pushed = await execGit(['merge-base', '--is-ancestor', 'HEAD', remoteRef], holder.path)+ if (!remoteRef) return false;+ const pushed = await execGit(['merge-base', '--is-ancestor', 'HEAD', remoteRef], holderPath).then(() => true, () => false);- if (!pushed) return null;+ if (!pushed) return false;- const detached = await execGit(['switch', '--detach', '--quiet'], holder.path).then(() => true, (err) => {- console.warn(`⚠️ Could not detach ${holder.path} to release ${branchName}: ${err.message}`);+ const detached = await execGit(['switch', '--detach', '--quiet'], holderPath).then(() => true, (err) => {+ console.warn(`⚠️ Could not detach ${holderPath} to release ${branchName}: ${err.message}`);return false;});- if (!detached) return null;- console.log(`🌳 Released ${branchName} from idle /do:next worktree ${holder.path} (HEAD detached in place)`);+ return detached;+}++/**+ * Free `branchName` from a worktree PortOS did not create and nothing owns+ * anymore — typically one a terminal agent session cut under its own scratchpad+ * and left behind after pushing its PR (#12845). Detaches the holder in place+ * (never moves or deletes it), so no content can be lost; the caller then+ * retries `git worktree add`.+ *+ * Refuses (null) unless ALL hold, each failing closed when unreadable: the+ * holder is a linked worktree (never the primary checkout) OUTSIDE the managed+ * `data/cos/worktrees/` root, unlocked, with no branch/repository owner or+ * running/paused agent registered in or on it; no process has its cwd inside it+ * (`hasProcessInside`); it is clean (git-ignored caches excepted) and its HEAD+ * is already on the remote.+ *+ * @param {string} sourceWorkspace+ * @param {string} branchName+ * @param {{ activeWorkspacePaths?: string[], agents?: object[]|null, requestingAgentId?: string, hasProcessInside?: (dir: string) => Promise<boolean> }} [options]+ * @returns {Promise<{ path: string }|null>} the released holder, or null+ */+export async function releaseOwnerlessForeignHolder(sourceWorkspace, branchName, options = {}) {+ if (!sourceWorkspace || !branchName || PROTECTED_BRANCHES.includes(branchName)) return null;+ const { withCheckoutPublication } = await import('../lib/checkoutRetirementAdmission.js');+ return withCheckoutPublication(sourceWorkspace, () => releaseOwnerlessForeignHolderAdmitted(sourceWorkspace, branchName, options));+}++async function releaseOwnerlessForeignHolderAdmitted(sourceWorkspace, branchName, {+ activeWorkspacePaths = [],+ agents = null,+ requestingAgentId = null,+ hasProcessInside = hasProcessCwdInside,+} = {}) {+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);+ if (!claimBranchAdmission({+ branchName, agentId: requestingAgentId, sourceWorkspace, worktrees, agents,+ }).admit) return null;+ const holderIndex = worktrees.findIndex(wt => wt.branch?.replace('refs/heads/', '') === branchName);+ // Index 0 is the main worktree — the user's own checkout is never released.+ if (holderIndex <= 0) return null;+ const holder = worktrees[holderIndex];+ if (holder.locked || holder.prunable || !existsSync(holder.path)) return null;+ // Managed trees have their own owners and reapers (adoption, claim cleanup).+ if (isPathInsideDir(WORKTREES_DIR, holder.path)) return null;+ if (activeWorkspacePaths.some(p => p && (pathsEqual(p, holder.path) || isPathInsideDir(holder.path, p)))) return null;+ if (await hasProcessInside(holder.path).catch(() => true)) return null;+ if (!await detachCleanPushedHolder(holder.path, branchName)) return null;+ console.log(`🌳 Released ${branchName} from ownerless foreign worktree ${holder.path} (HEAD detached in place)`);return { path: holder.path };}diff --git a/server/services/worktreeManager.releaseOwnerlessHolder.test.js b/server/services/worktreeManager.releaseOwnerlessHolder.test.jsnew file mode 100644index 0000000000..5c962be95d--- /dev/null+++ b/server/services/worktreeManager.releaseOwnerlessHolder.test.js@@ -0,0 +1,93 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdir, mkdtemp, rm, writeFile, realpath } from 'fs/promises';+import { existsSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';+import { execGit } from '../lib/execGit.js';+import { releaseOwnerlessForeignHolder } from './worktreeManager.js';++// Real git: the guard's whole job is reading real repo state before it detaches+// a tree PortOS did not create.+const BRANCH = 'chore/leftover';+const free = async () => false;++let root, repo, holder;+const git = (args, cwd = repo) => execGit(args, cwd).then(r => r.stdout.trim());+const holderBranch = () => git(['branch', '--show-current'], holder);+const release = (extra = {}) => releaseOwnerlessForeignHolder(repo, BRANCH, { agents: [], hasProcessInside: free, ...extra });++beforeEach(async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ root = await realpath(await mkdtemp(join(tmpdir(), 'release-ownerless-')));+ const remote = join(root, 'remote.git');+ repo = join(root, 'repo');+ holder = join(root, 'wt-leftover');+ await git(['init', '--bare', '-b', 'main', remote], root);+ await git(['init', '-b', 'main', repo], root);+ for (const [k, v] of [['user.email', '[email protected]'], ['user.name', 'Test'], ['commit.gpgsign', 'false']]) await git(['config', k, v]);+ await git(['remote', 'add', 'origin', remote]);+ await git(['commit', '--allow-empty', '-m', 'init']);+ await git(['push', '-q', '-u', 'origin', 'main']);+ await git(['worktree', 'add', '-q', '-b', BRANCH, holder, 'main']);+ await git(['commit', '--allow-empty', '-m', 'work'], holder);+ await git(['push', '-q', '-u', 'origin', BRANCH], holder);+});++afterEach(async () => {+ vi.restoreAllMocks();+ await rm(root, { recursive: true, force: true });+});++describe('releaseOwnerlessForeignHolder', () => {+ it('detaches a clean, pushed, ownerless foreign tree in place so the branch can be attached at once', async () => {+ const released = await release();+ expect(resolve(released.path)).toBe(resolve(holder));+ expect(existsSync(holder)).toBe(true);+ expect(await holderBranch()).toBe('');+ await git(['worktree', 'add', '-q', join(root, 'follow-up'), BRANCH]);+ });++ it('ignores git-ignored caches', async () => {+ await writeFile(join(holder, '.gitignore'), 'cache/\n');+ await git(['add', '.gitignore'], holder);+ await git(['commit', '-q', '-m', 'ignore'], holder);+ await git(['push', '-q'], holder);+ await mkdir(join(holder, 'cache'));+ await writeFile(join(holder, 'cache', 'x'), '1');+ expect(await release()).not.toBeNull();+ expect(existsSync(join(holder, 'cache', 'x'))).toBe(true);+ });++ it.each([+ ['an untracked file', async () => writeFile(join(holder, 'notes.txt'), 'draft')],+ ['a staged change', async () => { await writeFile(join(holder, 't.txt'), 'v'); await git(['add', 't.txt'], holder); }],+ ['an unpushed commit', async () => git(['commit', '--allow-empty', '-m', 'local'], holder)],+ ])('refuses a holder with %s', async (_label, dirty) => {+ await dirty();+ await expect(release()).resolves.toBeNull();+ expect(await holderBranch()).toBe(BRANCH);+ });++ it('refuses when a process may be inside the tree, including a probe that throws', async () => {+ await expect(release({ hasProcessInside: async () => true })).resolves.toBeNull();+ await expect(release({ hasProcessInside: async () => { throw new Error('lsof missing'); } })).resolves.toBeNull();+ expect(await holderBranch()).toBe(BRANCH);+ });++ it('refuses when the agent registry is unreadable or a live agent workspace is in the tree', async () => {+ await expect(release({ agents: null })).resolves.toBeNull();+ await expect(release({ activeWorkspacePaths: [join(holder, 'sub')] })).resolves.toBeNull();+ expect(await holderBranch()).toBe(BRANCH);+ });++ it('refuses a locked holder, the primary checkout and a protected branch', async () => {+ await git(['worktree', 'lock', holder]);+ await expect(release()).resolves.toBeNull();+ await git(['worktree', 'unlock', holder]);+ await expect(releaseOwnerlessForeignHolder(repo, 'main', { agents: [], hasProcessInside: free })).resolves.toBeNull();+ await git(['checkout', '-q', '-b', 'feature/primary']);+ await expect(releaseOwnerlessForeignHolder(repo, 'feature/primary', { agents: [], hasProcessInside: free })).resolves.toBeNull();+ expect(await git(['branch', '--show-current'])).toBe('feature/primary');+ });+});