Skip to content

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

fix: require registered ownership, not git activity age, to clear a possible swarm owner (#10015)

Adam Eivy59d86b69bfec
diff --git a/server/lib/README.md b/server/lib/README.md
index cd8d1e8adf..a7db3431dc 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). |
+| `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). |
| `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.js
index 140a24f63f..c84fda442b 100644
--- a/server/lib/claimContinuation.js
+++ b/server/lib/claimContinuation.js
@@ -21,15 +21,6 @@ import { isTruthyMeta } from './metadataFlags.js';
const CASE_FOLD = process.platform === 'win32';
-/**
- * How long a claim checkout must sit untouched before a claim-flow agent that
- * has NOT named its branch (an unpinned or swarm orchestrator run, whose
- * children cut `claim/issue-<n>` trees PortOS never sees) stops counting as the
- * possible owner. Matches `SIBLING_NEXT_HOLDER_IDLE_MS`: a live session touches
- * its index constantly, a finished one waiting on CI goes quiet for longer.
- */
-export const CLAIM_AMBIGUOUS_OWNER_IDLE_MS = 10 * 60 * 1000;
-
/** Branch a pinned claim target checks out, or null when the ref is not a claim name. */
export function claimContinuationBranch(claimTarget) {
const ref = String(claimTarget ?? '').trim();
@@ -77,10 +68,22 @@ function agentRepository(agent) {
return agent.sourceWorkspace || agent.metadata?.sourceWorkspace || agentWorkspace(agent);
}
+// Conservative: an agent whose repository cannot be read is treated as being in
+// this one, because the alternative is to wave a possible owner through.
+function inRepository(agent, sourceWorkspace) {
+ const repository = agentRepository(agent);
+ return !repository || !sourceWorkspace || samePath(repository, sourceWorkspace);
+}
+
+function registeredClaimBranch(agent) {
+ return agent?.claimBranch ?? agent?.metadata?.claimBranch;
+}
+
/**
* Whether a running or paused agent other than `ignoreIds` holds, or may hold,
* the claim checkout:
- * - `active`: it works inside the directory, or registered this exact branch;
+ * - `active`: it works inside the directory, or registered this exact branch
+ * in this repository;
* - `ambiguous`: it is a claim run that picks its own branch, in this same
* repository, so it might be the one that cut this tree — unprovable from
* the registry alone.
@@ -94,10 +97,9 @@ function claimHolderOccupancy({ agents, holderPath, branchName, sourceWorkspace,
if (!agent || ignoreIds.has(agent.id) || !isLiveAgent(agent)) continue;
const workspace = agentWorkspace(agent);
if (samePath(workspace, holderPath) || (workspace && isPathInsideDir(holderPath, workspace))) return 'active';
- const registeredBranch = agent.claimBranch ?? agent.metadata?.claimBranch;
- if (registeredBranch === branchName) return 'active';
- const picksOwn = agent.claimPicksOwnBranch ?? agent.metadata?.claimPicksOwnBranch;
- if (isTruthyMeta(picksOwn) && samePath(agentRepository(agent), sourceWorkspace)) ambiguous = true;
+ if (!inRepository(agent, sourceWorkspace)) continue;
+ if (registeredClaimBranch(agent) === branchName) return 'active';
+ if (isTruthyMeta(agent.claimPicksOwnBranch ?? agent.metadata?.claimPicksOwnBranch)) ambiguous = true;
}
return ambiguous ? 'ambiguous' : null;
}
@@ -184,9 +186,11 @@ export function claimContinuationWorkspace({ metadata, pathExists = () => false,
* live owner holds it. Anything unreadable or changed refuses — the caller
* defers the launch and touches neither ref nor tree.
*
- * `holderIdleMs` is how long the checkout has been untouched (null when it
- * cannot be read). It only matters for a possible owner that picks its own
- * branch; a registered owner refuses at any idleness.
+ * 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.
*
* @param {{
* metadata?: object,
@@ -194,14 +198,10 @@ export function claimContinuationWorkspace({ metadata, pathExists = () => false,
* sourceWorkspace?: string,
* worktrees: Array<object>|null,
* agents: Array<object>|null,
- * holderIdleMs?: number|null,
- * idleMs?: number,
* }} input
* @returns {{ admit: true }|{ admit: false, reason: string }}
*/
-export function claimContinuationAdmission({
- metadata, agentId, sourceWorkspace, worktrees, agents, holderIdleMs = null, idleMs = CLAIM_AMBIGUOUS_OWNER_IDLE_MS,
-}) {
+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;
@@ -214,11 +214,15 @@ export function claimContinuationAdmission({
}
if (holder.locked || holder.prunable) return { admit: false, reason: 'holder-locked' };
- const ignoreIds = new Set([agentId, metadata?.resumedFromAgentId].filter(Boolean));
+ const predecessorId = metadata?.resumedFromAgentId;
+ const ignoreIds = new Set([agentId, predecessorId].filter(Boolean));
const occupancy = claimHolderOccupancy({ agents, holderPath: holder.path, branchName, sourceWorkspace, ignoreIds });
if (occupancy === 'active') return { admit: false, reason: 'owner-active' };
- if (occupancy === 'ambiguous' && !(Number.isFinite(holderIdleMs) && holderIdleMs >= idleMs)) {
- return { admit: false, reason: 'owner-ambiguous' };
+ if (occupancy === 'ambiguous') {
+ const predecessor = agents.find((agent) => agent?.id === predecessorId);
+ if (!predecessor || registeredClaimBranch(predecessor) !== branchName) {
+ return { admit: false, reason: 'owner-ambiguous' };
+ }
}
return { admit: true };
}
diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.js
index 180473e5ec..4ed6ade0a0 100644
--- a/server/lib/claimContinuation.test.js
+++ b/server/lib/claimContinuation.test.js
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
import {
- CLAIM_AMBIGUOUS_OWNER_IDLE_MS,
claimContinuationAdmission,
claimContinuationBranch,
claimContinuationPointer,
@@ -146,7 +145,7 @@ describe('claimContinuationAdmission', () => {
});
const metadata = { ...pointer, resumedFromAgentId: 'agent-dead' };
const admit = (overrides = {}) => claimContinuationAdmission({
- metadata, agentId: 'agent-new', sourceWorkspace: SOURCE, worktrees: [holder], agents: [], holderIdleMs: null, ...overrides,
+ metadata, agentId: 'agent-new', sourceWorkspace: SOURCE, worktrees: [holder], agents: [], ...overrides,
});
it('admits a surviving claim whose previous owner is gone', () => {
@@ -180,18 +179,28 @@ describe('claimContinuationAdmission', () => {
})).toEqual({ admit: true });
});
+ it('does not let a same-named claim in another repository block this one', () => {
+ expect(admit({
+ agents: [{ id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42', sourceWorkspace: '/repos/other' } }],
+ })).toEqual({ admit: true });
+ });
+
describe('a swarm orchestrator whose children cut their own trees', () => {
const orchestrator = {
id: 'agent-swarm', status: 'running', metadata: { claimPicksOwnBranch: true, sourceWorkspace: SOURCE },
};
- it('refuses while the checkout shows recent activity or its idleness is unknown', () => {
- expect(admit({ agents: [orchestrator], holderIdleMs: 30_000 })).toEqual({ admit: false, reason: 'owner-ambiguous' });
- expect(admit({ agents: [orchestrator], holderIdleMs: null })).toEqual({ admit: false, reason: 'owner-ambiguous' });
+ it('refuses when the run being continued never registered this branch, however long the checkout has been quiet', () => {
+ 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' });
});
- it('admits once the checkout has been quiet past the idle window', () => {
- expect(admit({ agents: [orchestrator], holderIdleMs: CLAIM_AMBIGUOUS_OWNER_IDLE_MS })).toEqual({ admit: true });
+ it('admits when the run being continued registered this exact branch, since it cut the tree', () => {
+ expect(admit({
+ agents: [orchestrator, { id: 'agent-dead', status: 'completed', metadata: { claimBranch: 'claim/issue-42' } }],
+ })).toEqual({ admit: true });
});
it('does not suspect an orchestrator working in a different repository', () => {
@@ -199,10 +208,13 @@ describe('claimContinuationAdmission', () => {
expect(admit({ agents: [elsewhere] })).toEqual({ admit: true });
});
- it('refuses a registered owner at any idleness', () => {
+ it('refuses a registered owner even when the predecessor registered the branch', () => {
expect(admit({
- agents: [orchestrator, { id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42' } }],
- holderIdleMs: Number.MAX_SAFE_INTEGER,
+ agents: [
+ orchestrator,
+ { id: 'agent-dead', status: 'completed', metadata: { claimBranch: 'claim/issue-42' } },
+ { id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42' } },
+ ],
})).toEqual({ admit: false, reason: 'owner-active' });
});
});
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 158ac9f882..8d9b66675c 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -35,7 +35,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 { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies, worktreeIdleMs } from './worktreeManager.js';
+import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError, listWorktrees, releaseIdleSiblingNextHolder, unlinkWorktreeDependencies } from './worktreeManager.js';
import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
@@ -295,9 +295,8 @@ async function admitClaimContinuation({ task, agentId, sourceWorkspace, claimWor
getAgents().catch(() => null),
listWorktrees(sourceWorkspace).catch(() => null),
]);
- const holderIdleMs = await worktreeIdleMs(claimWorkspace.workspacePath).catch(() => null);
return claimContinuationAdmission({
- metadata: task.metadata, agentId, sourceWorkspace, worktrees, agents, holderIdleMs,
+ metadata: task.metadata, agentId, sourceWorkspace, worktrees, agents,
});
}
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 340cbc6e7c..79f35ac6f9 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -48,7 +48,6 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({
findAdoptableWorktreeForBranch: vi.fn().mockResolvedValue(null),
releaseIdleSiblingNextHolder: vi.fn().mockResolvedValue(null),
listWorktrees: vi.fn().mockResolvedValue([]),
- worktreeIdleMs: vi.fn().mockResolvedValue(null),
mergeBaseIntoFeatureWorktree: vi.fn(),
}));
vi.mock('./agentAppWorkspace.js', () => ({
@@ -521,7 +520,7 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {
it('defers the launch when a live owner registered the branch after the pointer was made', async () => {
getAgents.mockResolvedValue([
- { id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42', sourceWorkspace: '/repos/app-x' } },
+ { id: 'agent-other', status: 'running', metadata: { claimBranch: 'claim/issue-42' } },
]);
const r = await prepareAgentWorkspace({ agentId: 'agent-new', task: claimTask() });
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index bbc8d341ac..9a3a65695c 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -792,22 +792,6 @@ export async function findAdoptableWorktreeForBranch(sourceWorkspace, branchName
return { path: holder.path, agentId };
}
-/**
- * How long a worktree's git state has sat untouched, in ms — the newest mtime of
- * its index, HEAD and HEAD reflog. A live session touches its index constantly;
- * a finished one goes quiet. Null when nothing could be read (no git dir, or no
- * file stat-able), which callers must treat as "unknown", never as "idle".
- * Read-only: it only stats files, so reading never resets the clock.
- */
-export async function worktreeIdleMs(worktreePath, nowMs = Date.now()) {
- const gitDir = await execGit(['rev-parse', '--absolute-git-dir'], worktreePath).then(r => r.stdout.trim(), () => null);
- if (!gitDir) return null;
- const mtimes = await Promise.all(['index', 'HEAD', join('logs', 'HEAD')]
- .map(f => stat(join(gitDir, f)).then(st => st.mtimeMs, () => 0)));
- const newest = Math.max(...mtimes);
- return newest > 0 ? nowMs - newest : null;
-}
-
// How long a sibling `/do:next` tree must sit untouched before a follow-up may
// release its branch. An agent that finished and kept its tree (waiting on CI,
// say) goes quiet for far longer; a live session touches its index constantly.
@@ -853,10 +837,13 @@ export async function releaseIdleSiblingNextHolder(sourceWorkspace, branchName,
if (activeWorkspacePaths.some(p => p && (pathsEqual(p, holder.path) || isPathInsideDir(holder.path, p)))) return null;
const git = (args) => execGit(args, holder.path).then(r => r.stdout.trim());
- // Idleness first; the `--no-optional-locks` status below keeps a refused attempt
- // from refreshing the index and so resetting the very clock this reads.
- const idle = await worktreeIdleMs(holder.path, nowMs);
- if (idle === null || idle < idleMs) return null;
+ // Idleness first; `--no-optional-locks` keeps `status` from refreshing the
+ // index and so resetting the very clock this reads on a refused attempt.
+ const gitDir = await git(['rev-parse', '--absolute-git-dir']).catch(() => null);
+ if (!gitDir) return null;
+ const mtimes = await Promise.all(['index', 'HEAD', join('logs', 'HEAD')]
+ .map(f => stat(join(gitDir, f)).then(s => s.mtimeMs, () => 0)));
+ if (nowMs - Math.max(...mtimes) < idleMs) return null;
// Stricter than `classifyWorktreeDirt` on purpose: this tree isn't PortOS's,
// so no path counts as disposable scratch.