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: hold a continuation while a possible swarm owner is live instead of probing for absence (#10015)
Adam Eivyeb4c7e11b19e
diff --git a/server/lib/README.md b/server/lib/README.mdindex a7db3431dc..4dbd7ea32c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -508,7 +508,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. || `taskStatusTransition.js` | The CoS task STATUS TRANSITION vocabulary (#6620) — `resolveTaskStatusTransition(previousStatus, nextStatus)` classifies one update's status pair ONCE and returns `{ action, isRevive, isRequeue, entersInProgress, leavesInProgress, leavesBlocked, isTerminal }`, so `writeTaskUpdate`'s blocked/pause clear, resume-pointer drop, retry-hold retire, claim release, requeue stamp and emitted `tasks:changed` action all read one answer instead of re-deriving seven. A falsy `nextStatus` means "this patch carries no status" (a lease-renewal heartbeat) and releases nothing. `isTerminalTaskStatus(status)` is the shared `completed`/`blocked` predicate `cosTaskStore` and `cosTaskMerge` both read. Pure — metadata predicates (is this block a pause?) stay at the application site. || `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. |-| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator) a claim run registers on its agent record, and `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner clears only when the continued run itself registered the branch). |+| `claimContinuation.js` | Claim-flow relaunch pointer. `claimContinuationBranch(claimTarget)` is the `claim/issue-<n>` or `claim/<key>` branch a pinned target checks out. `claimContinuationPointer(...)` names the `claim-*` worktree already holding that branch when a relaunch should finish it in place (locked, prunable, unmanaged, or occupied by another running/paused agent → null). `claimContinuationWorkspace(...)` turns a still-on-disk pointer into the cwd the next agent uses without moving the directory. `claimOwnershipBinding(task)` is the branch (or "picks its own", for a swarm orchestrator) a claim run registers on its agent record, and `claimContinuationAdmission(...)` is the launch-time ownership check that re-reads holder, branch and live owners before a cached pointer may be entered (anything unreadable or changed → refuse, the caller defers; a possible swarm owner holds the launch until that run ends). || `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing; plus the retired-name map (`TASK_TYPE_RENAMES`, `currentTaskTypeName`, `taskExecutionKey`) for tasks and records written before a task rename. || `scheduleExecutionFieldsValidation.js` | `scheduleExecutionFieldsSchema` validates optional prompt and provider/model selections before schedule writes, preserving null/empty clears. || `scheduleRunOrder.js` | Storage rules for a task's advisory `suggestedAfter` list — which OTHER scheduled tasks to run first. `normalizeSuggestedAfter` drops blanks, duplicates and self-references and caps at `SUGGESTED_AFTER_MAX`; the shipped order it defaults to is `auditCatalog.AUDIT_SUGGESTED_AFTER`, layered at read time in `getScheduleStatus`. Advisory only — the ENFORCED dependency field is `runAfter`. Pure — no I/O. |diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.jsindex ba082c7dd8..12b1448c3e 100644--- a/server/lib/claimContinuation.js+++ b/server/lib/claimContinuation.js@@ -187,11 +187,10 @@ 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, 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.+ * children cut trees PortOS never sees) might own this tree. Nothing observable+ * proves it does not — git activity, the continued run's own registration, and+ * the absence of a process inside the tree can all be true of a live owner — so+ * the launch stays deferred until that run ends, which is its explicit release.** @param {{* metadata?: object,@@ -199,11 +198,10 @@ 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, holderOccupied = null }) {+export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace, worktrees, agents }) {if (!Array.isArray(worktrees) || !Array.isArray(agents)) return { admit: false, reason: 'ownership-unreadable' };const branchName = metadata?.existingBranch;const worktreePath = metadata?.resumeWorktreePath;@@ -219,6 +217,6 @@ export function claimContinuationAdmission({ metadata, agentId, sourceWorkspace,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' && holderOccupied !== false) return { admit: false, reason: 'owner-ambiguous' };+ if (occupancy === 'ambiguous') return { admit: false, reason: 'owner-ambiguous' };return { admit: true };}diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.jsindex 330213d3ad..43a59f35c2 100644--- a/server/lib/claimContinuation.test.js+++ b/server/lib/claimContinuation.test.js@@ -190,21 +190,18 @@ describe('claimContinuationAdmission', () => {id: 'agent-swarm', status: 'running', metadata: { claimPicksOwnBranch: true, sourceWorkspace: SOURCE },};- it('refuses unless a process listing ran and found nothing in the checkout', () => {+ it('refuses however the checkout looks, because a live owner can be quiet in every observable way', () => {expect(admit({ agents: [orchestrator] })).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('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' } }],- 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('admits once the picker run has ended', () => {+ expect(admit({ agents: [{ ...orchestrator, status: 'completed' }] })).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 2579121c73..c1e68b478c 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -44,7 +44,6 @@ 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;@@ -296,14 +295,7 @@ async function admitClaimContinuation({ task, agentId, sourceWorkspace, claimWorgetAgents().catch(() => null),listWorktrees(sourceWorkspace).catch(() => null),]);- 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 });+ return claimContinuationAdmission({ metadata: task.metadata, agentId, sourceWorkspace, worktrees, agents });}/**diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex d66a656ba1..e093333c5e 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -50,7 +50,6 @@ 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),@@ -74,7 +73,6 @@ 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';@@ -542,30 +540,17 @@ 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() });+ it('defers while a live picker run in the repository might own the tree, and continues once it ends', async () => {+ getAgents.mockResolvedValue([{ id: 'agent-picker', status: 'running', metadata: { claimPicksOwnBranch: true } }]);+ const deferred = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });+ expect(deferred.outcome).toBe('blocked');+ expect(createWorktree).not.toHaveBeenCalled();- expect(r.outcome).toBe('ready');- expect(r.workspacePath).toBe(CLAIM_DIR);- expect(worktreeHasLiveProcess).toHaveBeenCalledWith(CLAIM_DIR);- });+ getAgents.mockResolvedValue([{ id: 'agent-picker', status: 'completed', metadata: { claimPicksOwnBranch: true } }]);+ claimContinuationWorkspace.mockReturnValueOnce(pointerWorkspace());+ const resumed = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });+ expect(resumed.outcome).toBe('ready');+ expect(resumed.workspacePath).toBe(CLAIM_DIR);});it('fails closed when the agent registry cannot be read', async () => {diff --git a/server/services/worktreeOccupancy.js b/server/services/worktreeOccupancy.jsdeleted file mode 100644index deaa20e31b..0000000000--- a/server/services/worktreeOccupancy.js+++ /dev/null@@ -1,43 +0,0 @@-/**- * 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.jsdeleted file mode 100644index 57f276fbdb..0000000000--- a/server/services/worktreeOccupancy.test.js+++ /dev/null@@ -1,33 +0,0 @@-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();- });-});