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: clear a possible swarm owner only on a process listing that found nothing in the checkout (#10015)
Adam Eivy51180bd8945a
diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.jsindex c84fda442b..ba082c7dd8 100644--- a/server/lib/claimContinuation.js+++ b/server/lib/claimContinuation.js@@ -187,10 +187,11 @@ export function claimContinuationWorkspace({ metadata, pathExists = () => false,* defers the launch and touches neither ref nor tree.** A live claim run that picks its own branch (a swarm orchestrator whose- * children cut trees PortOS never sees) might own this tree. Git activity is not- * proof it stopped, so that doubt clears only on a registration: the run being- * continued must itself have registered this exact branch, which only the run- * that cut the tree could have done.+ * children cut trees PortOS never sees) might own this tree, and neither git+ * activity nor the predecessor's own registration proves it does not. That doubt+ * clears only on checkout-specific evidence: `holderOccupied === false`, a+ * process listing that ran and found nothing inside the tree. `true` and `null`+ * (could not be established) both keep the launch deferred.** @param {{* metadata?: object,@@ -198,10 +199,11 @@ export function claimContinuationWorkspace({ metadata, pathExists = () => false,* sourceWorkspace?: string,* worktrees: Array<object>|null,* agents: Array<object>|null,+ * holderOccupied?: boolean|null,* }} input* @returns {{ admit: true }|{ admit: false, reason: string }}*/-export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace, worktrees, agents }) {+export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace, worktrees, agents, holderOccupied = null }) {if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admit: false, reason: 'ownership-unreadable' };const branchName = metadata?.existingBranch;const worktreePath = metadata?.resumeWorktreePath;@@ -214,15 +216,9 @@ export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace,}if (holder.locked || holder.prunable) return { admit: false, reason: 'holder-locked' };- const predecessorId = metadata?.resumedFromAgentId;- const ignoreIds = new Set([agentId, predecessorId].filter(Boolean));+ const ignoreIds = new Set([agentId, metadata?.resumedFromAgentId].filter(Boolean));const occupancy = claimHolderOccupancy({ agents, holderPath: holder.path, branchName, sourceWorkspace, ignoreIds });if (occupancy === 'active') return { admit: false, reason: 'owner-active' };- if (occupancy === 'ambiguous') {- const predecessor = agents.find((agent) => agent?.id === predecessorId);- if (!predecessor || registeredClaimBranch(predecessor) !== branchName) {- return { admit: false, reason: 'owner-ambiguous' };- }- }+ if (occupancy === 'ambiguous' && holderOccupied !== false) return { admit: false, reason: 'owner-ambiguous' };return { admit: true };}diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.jsindex 4ed6ade0a0..330213d3ad 100644--- a/server/lib/claimContinuation.test.js+++ b/server/lib/claimContinuation.test.js@@ -190,17 +190,21 @@ describe('claimContinuationAdmission', () => {id: 'agent-swarm', status: 'running', metadata: { claimPicksOwnBranch: true, sourceWorkspace: SOURCE },};- it('refuses when the run being continued never registered this branch, however long the checkout has been quiet', () => {+ it('refuses unless a process listing ran and found nothing in the checkout', () => {expect(admit({ agents: [orchestrator] })).toEqual({ admit: false, reason: 'owner-ambiguous' });- expect(admit({- agents: [orchestrator, { id: 'agent-dead', status: 'completed', metadata: { claimPicksOwnBranch: true } }],- })).toEqual({ admit: false, reason: 'owner-ambiguous' });+ expect(admit({ agents: [orchestrator], holderOccupied: null })).toEqual({ admit: false, reason: 'owner-ambiguous' });+ expect(admit({ agents: [orchestrator], holderOccupied: true })).toEqual({ admit: false, reason: 'owner-ambiguous' });});- it('admits when the run being continued registered this exact branch, since it cut the tree', () => {+ it('is not cleared by the continued run having registered the branch, since that does not prove it cut the tree', () => {expect(admit({agents: [orchestrator, { id: 'agent-dead', status: 'completed', metadata: { claimBranch: 'claim/issue-42' } }],- })).toEqual({ admit: true });+ holderOccupied: null,+ })).toEqual({ admit: false, reason: 'owner-ambiguous' });+ });++ it('admits when nothing is inside the checkout', () => {+ expect(admit({ agents: [orchestrator], holderOccupied: false })).toEqual({ admit: true });});it('does not suspect an orchestrator working in a different repository', () => {diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 8d9b66675c..2579121c73 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -44,6 +44,7 @@ import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';import { createJiraTicketForTask } from './promptSections/appContext.js';import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';import { isNonCommittingCoordinatorTask, resolveTaskHookType } from './taskTypeHooks.js';+import { worktreeHasLiveProcess } from './worktreeOccupancy.js';import { claimContinuationAdmission, claimContinuationWorkspace } from '../lib/claimContinuation.js';const ROOT_DIR = PATHS.root;@@ -295,9 +296,14 @@ async function admitClaimContinuation({ task, agentId, sourceWorkspace, claimWorgetAgents().catch(() => null),listWorktrees(sourceWorkspace).catch(() => null),]);- return claimContinuationAdmission({- metadata: task.metadata, agentId, sourceWorkspace, worktrees, agents,- });+ const input = { metadata: task.metadata, agentId, sourceWorkspace, worktrees, agents };+ const admission = claimContinuationAdmission(input);+ if (admission.reason !== 'owner-ambiguous') return admission;+ // A live picker run in this repository may own the tree. Ask the OS whether+ // anything is actually inside it; only a listing that ran and found nothing+ // clears the doubt.+ const holderOccupied = await worktreeHasLiveProcess(claimWorkspace.workspacePath).catch(() => null);+ return claimContinuationAdmission({ ...input, holderOccupied });}/**diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 79f35ac6f9..d66a656ba1 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -50,6 +50,7 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({listWorktrees: vi.fn().mockResolvedValue([]),mergeBaseIntoFeatureWorktree: vi.fn(),}));+vi.mock('./worktreeOccupancy.js', () => ({ worktreeHasLiveProcess: vi.fn().mockResolvedValue(null) }));vi.mock('./agentAppWorkspace.js', () => ({getAppWorkspace: vi.fn().mockResolvedValue('/repos/app-x'),getAppDataForTask: vi.fn().mockResolvedValue(null),@@ -73,6 +74,7 @@ import { execGit } from '../lib/execGit.js';import { detectConflicts } from './taskConflict.js';import { getAppWorkspace } from './agentAppWorkspace.js';import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';+import { worktreeHasLiveProcess } from './worktreeOccupancy.js';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';@@ -540,6 +542,32 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {expect(adoptWorktree).not.toHaveBeenCalled();});+ describe('while a live picker run in the repository might own the tree', () => {+ const picker = { id: 'agent-picker', status: 'running', metadata: { claimPicksOwnBranch: true } };++ it('defers unless the OS confirms nothing is inside the checkout', async () => {+ getAgents.mockResolvedValue([picker]);+ for (const [i, answer] of [true, null].entries()) {+ if (i > 0) claimContinuationWorkspace.mockReturnValueOnce(pointerWorkspace()); // beforeEach queued the first+ worktreeHasLiveProcess.mockResolvedValueOnce(answer);+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });+ expect(r.outcome).toBe('blocked');+ }+ expect(createWorktree).not.toHaveBeenCalled();+ });++ it('continues in place once a process listing found nothing inside the checkout', async () => {+ getAgents.mockResolvedValue([picker]);+ worktreeHasLiveProcess.mockResolvedValueOnce(false);++ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });++ expect(r.outcome).toBe('ready');+ expect(r.workspacePath).toBe(CLAIM_DIR);+ expect(worktreeHasLiveProcess).toHaveBeenCalledWith(CLAIM_DIR);+ });+ });+it('fails closed when the agent registry cannot be read', async () => {getAgents.mockRejectedValue(new Error('state unreadable'));diff --git a/server/services/worktreeOccupancy.js b/server/services/worktreeOccupancy.jsnew file mode 100644index 0000000000..deaa20e31b--- /dev/null+++ b/server/services/worktreeOccupancy.js@@ -0,0 +1,43 @@+/**+ * Whether any process is sitting inside a worktree right now.+ *+ * The agent registry cannot see every owner of a `claim-*` tree: a swarm child or+ * a hand-run claim session cuts and works in a directory PortOS never provisioned.+ * A process whose current directory is inside the tree is checkout-specific+ * evidence of a live occupant, which the registry alone can never give.+ *+ * Read-only (`lsof` listing). Three answers, and the difference matters:+ * `true` — a process is inside; `false` — the listing ran and none is;+ * `null` — it could not be established (no `lsof`, Windows, timeout), which a+ * caller must treat as "unknown", never as "empty".+ */++import { realpath } from 'fs/promises';+import { resolve } from 'path';+import { commandOutput } from '../lib/commandExists.js';+import { isPathInsideDir } from '../lib/pathSafety.js';++/** Directories named by an `lsof -d cwd -Fn` listing (the `n` field lines). Pure. */+export function parseLsofCwdListing(output) {+ return String(output ?? '').split(/\r?\n/)+ .filter((line) => line.startsWith('n') && line.length > 1)+ .map((line) => line.slice(1));+}++export async function worktreeHasLiveProcess(worktreePath, { listCwds = defaultListCwds } = {}) {+ if (!worktreePath) return null;+ const cwds = await listCwds().catch(() => null);+ if (!cwds) return null;+ // lsof reports resolved paths, so compare against the resolved directory too.+ const roots = new Set([worktreePath]);+ const resolved = await realpath(worktreePath).catch(() => null);+ if (resolved) roots.add(resolved);+ return cwds.some((cwd) => [...roots].some((root) => resolve(cwd) === resolve(root) || isPathInsideDir(root, cwd)));+}++async function defaultListCwds() {+ if (process.platform === 'win32') return null;+ const output = await commandOutput('lsof', ['-d', 'cwd', '-Fn'], { timeoutMs: 10_000, maxBuffer: 16 * 1024 * 1024 });+ // `null` (could not run / non-zero exit) stays unknown; `''` means it ran and listed nothing.+ return output === null ? null : parseLsofCwdListing(output);+}diff --git a/server/services/worktreeOccupancy.test.js b/server/services/worktreeOccupancy.test.jsnew file mode 100644index 0000000000..57f276fbdb--- /dev/null+++ b/server/services/worktreeOccupancy.test.js@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';+import { parseLsofCwdListing, worktreeHasLiveProcess } from './worktreeOccupancy.js';++const TREE = '/data/cos/worktrees/claim-portos-issue-42';++describe('parseLsofCwdListing', () => {+ it('reads the directory of every n field and ignores process and fd fields', () => {+ expect(parseLsofCwdListing(`p101\nfcwd\nn/home/alice\np102\nfcwd\nn${TREE}/server\n`))+ .toEqual(['/home/alice', `${TREE}/server`]);+ expect(parseLsofCwdListing('')).toEqual([]);+ expect(parseLsofCwdListing(null)).toEqual([]);+ });+});++describe('worktreeHasLiveProcess', () => {+ const probe = (cwds) => worktreeHasLiveProcess(TREE, { listCwds: async () => cwds });++ it('reports a process sitting in the checkout root or below it', async () => {+ expect(await probe(['/elsewhere', TREE])).toBe(true);+ expect(await probe([`${TREE}/server/lib`])).toBe(true);+ });++ it('reports none when the listing ran and nothing is inside, including a sibling with the same prefix', async () => {+ expect(await probe(['/elsewhere', `${TREE}-other`])).toBe(false);+ expect(await probe([])).toBe(false);+ });++ it('reports unknown, never empty, when the listing could not be taken', async () => {+ expect(await probe(null)).toBeNull();+ expect(await worktreeHasLiveProcess(TREE, { listCwds: async () => { throw new Error('no lsof'); } })).toBeNull();+ expect(await worktreeHasLiveProcess('', { listCwds: async () => [] })).toBeNull();+ });+});