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: relaunch a claim inside the worktree it already started

[._.]/ Adam Eivy7866590b5f3e
diff --git a/server/lib/README.md b/server/lib/README.md
index 4083bc7431..a72b19680c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -475,6 +475,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. |
| `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing. |
| `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. |
| `taskTargetScope.js` | Target scope for a scheduled task type: `INSTALL_WIDE_TASK_TYPES`, `MANAGED_APP_TARGET_TASK_TYPES`, `PROGRAMMATIC_SCHEDULED_TASK_TYPES`, `isProgrammaticScheduledTaskType`, `requiresManagedAppTarget`, `requiresInstallWideTarget`. Declared here (not in `services/taskScheduleRegistry.js`, which re-exports it) so `quotaBurnValidation.js` can reject a burn reference with the wrong target scope without importing upward into services. |
diff --git a/server/lib/claimContinuation.js b/server/lib/claimContinuation.js
new file mode 100644
index 0000000000..9e033a760c
--- /dev/null
+++ b/server/lib/claimContinuation.js
@@ -0,0 +1,110 @@
+/**
+ * Claim-flow relaunch — continue the worktree the previous run of this task
+ * already created, instead of treating that claim as someone else's.
+ *
+ * A claim agent cuts `claim/issue-<n>` (or `claim/<key>`) itself, under
+ * `data/cos/worktrees/claim-*`, and stamps `in-progress`. PortOS does not own
+ * that directory as an `agent-*` worktree, so a provider relaunch used to
+ * requeue onto a clean checkout. The replacement then followed the claim
+ * prompt's "already in progress / already on this branch → exit" rule and
+ * abandoned the work the user asked it to finish.
+ *
+ * The pointer stays on the claim directory. Moving it to `agent-<id>` would
+ * break the claim prompt's own path and the claim-shaped reaper. Pure: the
+ * git listing and the agent list stay with the caller.
+ */
+
+import { resolve } from 'path';
+import { isPathInsideDir } from './pathSafety.js';
+import { isHumanClaimWorktree, worktreeAgentId } from './worktreeOwnership.js';
+
+const CASE_FOLD = process.platform === 'win32';
+
+/** 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();
+ if (!ref || ref.length > 80) return null;
+ if (/^\d+$/.test(ref)) return `claim/issue-${ref}`;
+ if (/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(ref)) return `claim/${ref}`;
+ if (/^[a-z0-9][a-z0-9-]*$/i.test(ref)) return `claim/${ref}`;
+ return null;
+}
+
+function samePath(a, b) {
+ if (typeof a !== 'string' || typeof b !== 'string' || !a || !b) return false;
+ const left = resolve(a);
+ const right = resolve(b);
+ return CASE_FOLD ? left.toLowerCase() === right.toLowerCase() : left === right;
+}
+
+/**
+ * The claim worktree this task's previous run left on its own branch, when
+ * PortOS may hand it to the relaunch. Null when there is nothing to continue:
+ * not a claim task, no pinned target, no holder, a lock, a tree outside the
+ * claim root, or another live or paused agent already working in that directory.
+ *
+ * @param {{
+ * task: object,
+ * agentId: string,
+ * worktrees?: Array<{path?: string, branch?: string, locked?: boolean, prunable?: boolean}>,
+ * agents?: Array<{id?: string, status?: string, workspacePath?: string, metadata?: {workspacePath?: string}}>,
+ * worktreesRoot: string,
+ * }} input
+ * @returns {{ existingBranch: string, resumedFromAgentId: string, resumeWorktreePath: string, claimResumeInPlace: true }|null}
+ */
+export function claimContinuationPointer({ task, agentId, worktrees = [], agents = [], worktreesRoot }) {
+ if (task?.metadata?.claimFlow !== true && task?.metadata?.claimFlow !== 'true') return null;
+ const branchName = claimContinuationBranch(task?.metadata?.claimTarget);
+ if (!branchName || !agentId || !worktreesRoot) return null;
+ if (!Array.isArray(agents)) return null;
+
+ const holder = worktrees.find((wt) => {
+ const branch = String(wt?.branch || '').replace(/^refs\/heads\//, '');
+ return branch === branchName && wt?.path && !wt.locked && !wt.prunable;
+ });
+ if (!holder) return null;
+ if (!isHumanClaimWorktree(worktreeAgentId(holder.path))) return null;
+ if (!isPathInsideDir(worktreesRoot, holder.path)) return null;
+
+ const occupied = agents.some((agent) => {
+ if (!agent || agent.id === agentId) return false;
+ if (agent.status !== 'running' && agent.status !== 'paused') return false;
+ const workspace = agent.workspacePath || agent.metadata?.workspacePath;
+ return samePath(workspace, holder.path);
+ });
+ if (occupied) return null;
+
+ return {
+ existingBranch: branchName,
+ resumedFromAgentId: agentId,
+ resumeWorktreePath: holder.path,
+ claimResumeInPlace: true,
+ };
+}
+
+/**
+ * Workspace a relaunch should use when the claim pointer is still valid on
+ * disk. Null sends the caller down the ordinary prep path.
+ *
+ * @param {{ metadata?: object, pathExists?: (path: string) => boolean, worktreesRoot: string }} input
+ */
+export function claimContinuationWorkspace({ metadata, pathExists = () => false, worktreesRoot }) {
+ if (metadata?.claimResumeInPlace !== true && metadata?.claimResumeInPlace !== 'true') return null;
+ const worktreePath = metadata?.resumeWorktreePath;
+ const branchName = metadata?.existingBranch;
+ if (!worktreePath || !branchName || !worktreesRoot) return null;
+ if (!isHumanClaimWorktree(worktreeAgentId(worktreePath))) return null;
+ if (!isPathInsideDir(worktreesRoot, worktreePath)) return null;
+ if (!pathExists(worktreePath)) return null;
+ return {
+ workspacePath: worktreePath,
+ worktreeInfo: {
+ worktreePath,
+ branchName,
+ baseBranch: null,
+ existingBranch: true,
+ adopted: true,
+ claimResumeInPlace: true,
+ },
+ };
+}
diff --git a/server/lib/claimContinuation.test.js b/server/lib/claimContinuation.test.js
new file mode 100644
index 0000000000..05a15311cd
--- /dev/null
+++ b/server/lib/claimContinuation.test.js
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+import { claimContinuationBranch, claimContinuationPointer, claimContinuationWorkspace } from './claimContinuation.js';
+
+const ROOT = '/data/cos/worktrees';
+const CLAIM = `${ROOT}/claim-portos-issue-42`;
+
+describe('claimContinuationBranch', () => {
+ it('names a GitHub or GitLab issue branch and a JIRA or plan branch', () => {
+ expect(claimContinuationBranch('42')).toBe('claim/issue-42');
+ expect(claimContinuationBranch('ACME-9')).toBe('claim/ACME-9');
+ expect(claimContinuationBranch('fix-the-thing')).toBe('claim/fix-the-thing');
+ });
+
+ it('rejects a ref that is not a claim branch name', () => {
+ expect(claimContinuationBranch('')).toBeNull();
+ expect(claimContinuationBranch('12; rm')).toBeNull();
+ expect(claimContinuationBranch(null)).toBeNull();
+ });
+});
+
+describe('claimContinuationPointer', () => {
+ const task = { id: 'task-1', metadata: { claimFlow: true, claimTarget: '42' } };
+ const holder = { path: CLAIM, branch: 'refs/heads/claim/issue-42' };
+
+ it('hands a relaunch the claim worktree the previous run left behind', () => {
+ expect(claimContinuationPointer({
+ task, agentId: 'agent-old', worktrees: [holder], agents: [], worktreesRoot: ROOT,
+ })).toEqual({
+ existingBranch: 'claim/issue-42',
+ resumedFromAgentId: 'agent-old',
+ resumeWorktreePath: CLAIM,
+ claimResumeInPlace: true,
+ });
+ });
+
+ it('leaves the relaunch clean when another live agent is in that worktree', () => {
+ expect(claimContinuationPointer({
+ task,
+ agentId: 'agent-old',
+ worktrees: [holder],
+ agents: [{ id: 'agent-other', status: 'running', metadata: { workspacePath: CLAIM } }],
+ worktreesRoot: ROOT,
+ })).toBeNull();
+ });
+
+ it('ignores the predecessor itself, a lock, and a tree outside the claim root', () => {
+ expect(claimContinuationPointer({
+ task,
+ agentId: 'agent-old',
+ worktrees: [holder],
+ agents: [{ id: 'agent-old', status: 'paused', workspacePath: CLAIM }],
+ worktreesRoot: ROOT,
+ })?.claimResumeInPlace).toBe(true);
+
+ expect(claimContinuationPointer({
+ task, agentId: 'agent-old', worktrees: [{ ...holder, locked: true }], agents: [], worktreesRoot: ROOT,
+ })).toBeNull();
+
+ expect(claimContinuationPointer({
+ task,
+ agentId: 'agent-old',
+ worktrees: [{ path: '/elsewhere/claim-portos-issue-42', branch: 'refs/heads/claim/issue-42' }],
+ agents: [],
+ worktreesRoot: ROOT,
+ })).toBeNull();
+ });
+
+ it('does nothing for a task that is not a pinned claim', () => {
+ expect(claimContinuationPointer({
+ task: { metadata: { claimFlow: true } },
+ agentId: 'agent-old',
+ worktrees: [holder],
+ agents: [],
+ worktreesRoot: ROOT,
+ })).toBeNull();
+ });
+});
+
+describe('claimContinuationWorkspace', () => {
+ it('uses the claim directory in place when it is still on disk', () => {
+ const workspace = claimContinuationWorkspace({
+ metadata: {
+ claimResumeInPlace: true,
+ existingBranch: 'claim/issue-42',
+ resumeWorktreePath: CLAIM,
+ },
+ pathExists: (path) => path === CLAIM,
+ worktreesRoot: ROOT,
+ });
+ expect(workspace.workspacePath).toBe(CLAIM);
+ expect(workspace.worktreeInfo.claimResumeInPlace).toBe(true);
+ expect(workspace.worktreeInfo.branchName).toBe('claim/issue-42');
+ });
+
+ it('stays off the path when the directory is gone', () => {
+ expect(claimContinuationWorkspace({
+ metadata: { claimResumeInPlace: 'true', existingBranch: 'claim/issue-42', resumeWorktreePath: CLAIM },
+ pathExists: () => false,
+ worktreesRoot: ROOT,
+ })).toBeNull();
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 158840ea26..dcaad16141 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -442,6 +442,7 @@ export * from './taskRequeue.js';
export * from './taskRetryHold.js';
export * from './taskStatusTransition.js';
export * from './taskTargetBranch.js';
+export * from './claimContinuation.js';
export * from './scheduledTaskTypes.js';
export * from './scheduleRunOrder.js';
export * from './taskTargetScope.js';
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 32623b6fea..7fc64c27dd 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -634,7 +634,7 @@ const REPLACEMENT_RUNTIME_METADATA_KEYS = new Set([
'lastErrorCategory', 'lastFailureAt', 'cooldownUntil', 'totalSpawnCount',
'orphanRetryCount', 'lastOrphanedAt', 'lastOrphanedAgentId', 'worktreeBusyAttempts',
LAST_SPAWNED_AT_KEY, 'interruptedByRestart', 'lastInterruptedAt', 'lastInterruptedAgentId',
- 'outputHookDispatchedAt', 'existingBranch', 'resumedFromAgentId', 'resumeWorktreePath',
+ 'outputHookDispatchedAt', 'existingBranch', 'resumedFromAgentId', 'resumeWorktreePath', 'claimResumeInPlace',
'autoRetryCount', 'autoRetriedByInvestigation', 'autoRetriedAt', 'autoRetryExhaustedAt',
'resolution', 'autoExpiredReason', 'autoExpiredAt',
REQUEUED_AT_KEY, RETRY_HOLD_KEY, RETRY_HOLD_SINCE_KEY,
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 2b5d075be5..99e041adb1 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -38,6 +38,8 @@ import {
buildActionOutputCompletionSection,
buildAuditOutputCompletionSection,
buildClaimFlowCompletionSection,
+ buildClaimResumeOverride,
+ claimResumeContext,
buildReleaseFlowCompletionSection,
buildAuditFlowCompletionSection,
buildCliCompletionSection,
@@ -600,6 +602,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
isTui, sentinelPath, reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers),
leavePrOpen: resolvePrCompletion(task.metadata) === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task),
prCompletion: task.metadata?.prCompletion || null,
+ claimResume: claimResumeContext(task, worktreeInfo),
}),
[COMPLETION_MODES.AUDIT_FLOW]: () => buildAuditFlowCompletionSection({ isTui, sentinelPath }),
[COMPLETION_MODES.RELEASE_FLOW]: () => buildReleaseFlowCompletionSection({ isTui, sentinelPath }),
@@ -1074,6 +1077,11 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// suppressed in buildTaskBlock since cwd already reveals it. Shared with the
// full path via buildTaskBlock.
const taskBlock = buildTaskBlock(task, { screenshotsAsList: true });
+ // Ahead of the stored claim prompt, which still says to exit when the issue
+ // is already in progress. That sentence is right for a fresh claim and wrong
+ // for the relaunch that is here to finish the previous run's worktree.
+ const claimResume = claimResumeContext(task, worktreeInfo);
+ if (claimResume) taskSections.push(buildClaimResumeOverride(claimResume));
taskSections.push(taskBlock.description);
if (taskBlock.targetApp) taskSections.push(taskBlock.targetApp);
@@ -1145,6 +1153,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
isTui, sentinelPath: lightSentinelPath(), reviewersCsv: claimReviewersCsv(task, codeReviewDefaults, defaultReviewers),
leavePrOpen: resolvePrCompletion(task.metadata) === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task),
prCompletion: task.metadata?.prCompletion || null,
+ claimResume: claimResumeContext(task, worktreeInfo),
})),
[COMPLETION_MODES.READ_ONLY]: () => contractSections.push(buildReadOnlyCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),
[COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => {
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 391eef55c3..fef9c14e48 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -453,6 +453,42 @@ describe('claim-flow completion handoff', () => {
expect(prompt).toContain('do not wait for a human or require MERGED status');
});
+ it('tells a relaunched claim to finish the worktree the previous run already started', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({
+ description: 'Claim issue 42',
+ metadata: {
+ claimFlow: true,
+ useWorktree: false,
+ openPR: false,
+ claimResumeInPlace: true,
+ existingBranch: 'claim/issue-42',
+ resumeWorktreePath: '/data/cos/worktrees/claim-portos-issue-42',
+ resumedFromAgentId: 'agent-previous',
+ prompt: 'if the issue is already in progress, exit cleanly',
+ },
+ }),
+ '/repo',
+ {
+ worktreePath: '/data/cos/worktrees/claim-portos-issue-42',
+ branchName: 'claim/issue-42',
+ existingBranch: true,
+ claimResumeInPlace: true,
+ },
+ isTruthyMeta,
+ { isTui: true, providerId: 'grok-tui', providerCommand: 'grok' },
+ );
+
+ const overrideAt = prompt.indexOf('## Relaunch — finish the claim already started');
+ const exitAt = prompt.indexOf('if the issue is already in progress, exit cleanly');
+ expect(overrideAt).toBeGreaterThan(-1);
+ expect(exitAt).toBeGreaterThan(overrideAt);
+ expect(prompt).toContain('`/data/cos/worktrees/claim-portos-issue-42`');
+ expect(prompt).toContain('`claim/issue-42`');
+ expect(prompt).toContain('`agent-previous`');
+ expect(prompt).toContain('finish this task\'s existing claim');
+ });
+
it('keeps self-managed claim work out of the generic false/false handoff', () => {
const prompt = buildLightContextPrompt(
makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, simplify: true } }),
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index fce77159ab..32b451abf0 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 } from './taskTypeHooks.js';
+import { claimContinuationWorkspace } from '../lib/claimContinuation.js';
const ROOT_DIR = PATHS.root;
@@ -368,6 +369,23 @@ export async function prepareAgentWorkspace({ agentId, task }) {
let jiraTicket = null;
let jiraBranchName = null;
let worktreeInfo = null;
+ // A relaunched claim keeps the `claim-*` directory the previous run cut.
+ // Moving it (the ordinary adopt path) would rename it to `agent-<id>` and
+ // break the claim prompt's own cleanup path. Use it where it sits, and skip
+ // every later provisioner so a checked-out claim branch cannot fall through
+ // to the shared checkout.
+ const claimWorkspace = claimContinuationWorkspace({
+ metadata: task.metadata,
+ pathExists: existsSync,
+ worktreesRoot: PATHS.worktrees,
+ });
+ if (claimWorkspace) {
+ workspacePath = claimWorkspace.workspacePath;
+ worktreeInfo = claimWorkspace.worktreeInfo;
+ emitLog('info', `🌳 Agent ${agentId} is continuing the claim worktree ${worktreeInfo.branchName}`, {
+ agentId, taskId: task.id, worktreePath: workspacePath, branchName: worktreeInfo.branchName,
+ });
+ }
const explicitOpenPR = isTruthyMeta(task.metadata?.openPR);
const explicitWorktree = isTruthyMeta(task.metadata?.useWorktree) || explicitOpenPR;
// A task pointed at an existing branch must run in a worktree whatever isolated
@@ -384,7 +402,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {
const forkHead = resolveTaskForkHead(task.metadata);
const wantsWorktree = explicitWorktree || !!existingBranch;
- if (!isReadOnly) {
+ if (!isReadOnly && !claimWorkspace) {
// Isolated tasks fetch their base in createWorktree; never rebase the
// shared checkout as a side effect of preparing a separate workspace.
const pullResult = wantsWorktree ? { skipped: 'isolated-task' } : await git.ensureLatest(workspacePath).catch(err => {
@@ -513,7 +531,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {
// run repository commands and the action stage's provider-specific sandbox
// needs it for tests/patch inspection. Never let `readOnly` turn an explicit
// isolation request into the live application checkout.
- if (wantsWorktree && !jiraBranchName) {
+ if (wantsWorktree && !jiraBranchName && !claimWorkspace) {
const worktreeOutcome = await prepareRequestedWorktree({
agentId,
workspacePath,
@@ -525,7 +543,7 @@ export async function prepareAgentWorkspace({ agentId, task }) {
if (worktreeOutcome.outcome !== 'ready') return worktreeOutcome;
workspacePath = worktreeOutcome.workspacePath;
worktreeInfo = worktreeOutcome.worktreeInfo;
- } else if (!isReadOnly && !jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {
+ } else if (!claimWorkspace && !isReadOnly && !jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {
const { getAgents } = await import('./cos.js');
const allAgents = await getAgents();
const runningAgents = allAgents.filter(a => a.status === 'running');
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index e2ee920f25..d49d72e2b4 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -33,6 +33,13 @@ vi.mock('./taskConflict.js', () => ({ detectConflicts: vi.fn().mockResolvedValue
// pure predicate over git's own wording, and re-stating that regex in the mock
// would make every branch-busy assertion below agree with a copy of the code
// instead of with the code.
+vi.mock('../lib/claimContinuation.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ claimContinuationWorkspace: vi.fn((...args) => actual.claimContinuationWorkspace(...args)),
+ };
+});
vi.mock('./worktreeManager.js', async (importOriginal) => ({
...(await importOriginal()),
createWorktree: vi.fn(),
@@ -56,6 +63,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
});
import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';
+import { claimContinuationWorkspace } from '../lib/claimContinuation.js';
import { updateTask, getAgents } from './cos.js';
import { ensureLatest } from './git.js';
import { execGit } from '../lib/execGit.js';
@@ -422,6 +430,40 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {
expect(r.outcome).toBe('blocked');
});
+ it('continues a relaunched claim inside the existing claim worktree', async () => {
+ claimContinuationWorkspace.mockReturnValueOnce({
+ workspacePath: '/mock/worktrees/claim-portos-issue-42',
+ worktreeInfo: {
+ worktreePath: '/mock/worktrees/claim-portos-issue-42',
+ branchName: 'claim/issue-42',
+ baseBranch: null,
+ existingBranch: true,
+ adopted: true,
+ claimResumeInPlace: true,
+ },
+ });
+ const task = {
+ id: 't-claim', taskType: 'user',
+ metadata: {
+ claimFlow: true,
+ claimTarget: '42',
+ claimResumeInPlace: true,
+ existingBranch: 'claim/issue-42',
+ resumeWorktreePath: '/mock/worktrees/claim-portos-issue-42',
+ useWorktree: false,
+ },
+ };
+
+ const r = await prepareAgentWorkspace({ agentId: 'agent-new', task });
+
+ expect(r.outcome).toBe('ready');
+ expect(r.workspacePath).toBe('/mock/worktrees/claim-portos-issue-42');
+ expect(r.worktreeInfo.claimResumeInPlace).toBe(true);
+ expect(createWorktree).not.toHaveBeenCalled();
+ expect(adoptWorktree).not.toHaveBeenCalled();
+ expect(ensureLatest).not.toHaveBeenCalled();
+ });
+
it('ignores a stale worktree pointer with no branch to resume', async () => {
createWorktree.mockResolvedValue({
worktreePath: '/mock/worktrees/agent-new', branchName: 'cos/t-resume/agent-new', baseBranch: 'main'
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 7c40231f6c..754a010868 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -14,9 +14,10 @@
import { existsSync } from 'fs';
import { join } from 'path';
import { emitLog } from './cosEvents.js';
-import { addTask, forceSpawnTask, updateTask } from './cos.js';
+import { addTask, forceSpawnTask, getAgents, updateTask } from './cos.js';
import * as git from './git.js';
-import { removeWorktree, classifyWorktreeDirt } from './worktreeManager.js';
+import { removeWorktree, classifyWorktreeDirt, listWorktrees } from './worktreeManager.js';
+import { claimContinuationPointer } from '../lib/claimContinuation.js';
import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { execGit } from '../lib/execGit.js';
@@ -685,8 +686,37 @@ export async function resolveResumePointer(sourceWorkspace, branchName, worktree
* @param {{task: object, agentId: string, agentMetadata: object}} params
* @returns {Promise<object>} metadata patch to merge into an `updateTask` call
*/
+/**
+ * A claim-flow relaunch continues the `claim-*` worktree the paused run already
+ * cut for its pinned target. Resolved before the CoS-worktree bail: claim agents
+ * record `isWorktree: false` because PortOS did not provision the directory, and
+ * that bail is what used to requeue the relaunch onto a clean checkout.
+ *
+ * Fails closed (null → the caller keeps the ordinary "start clean" answer) when
+ * the agent list cannot be read. An empty list would look like "nobody is in
+ * that tree."
+ */
+async function resolveClaimContinuationPatch({ task, agentId, agentMetadata }) {
+ const source = agentMetadata?.sourceWorkspace || agentMetadata?.workspacePath;
+ if (!source) return null;
+ const agents = await getAgents().catch(() => null);
+ if (!agents) return null;
+ const worktrees = await listWorktrees(source).catch(() => []);
+ const pointer = claimContinuationPointer({
+ task, agentId, worktrees, agents, worktreesRoot: PATHS.worktrees,
+ });
+ if (!pointer) return null;
+ emitLog('info', `🔁 Task ${task.id} will resume in the claim worktree ${pointer.resumeWorktreePath} (${pointer.existingBranch}) instead of starting clean`, {
+ taskId: task.id, agentId, branchName: pointer.existingBranch, worktreePath: pointer.resumeWorktreePath,
+ });
+ return pointer;
+}
+
export async function resolveTaskResumePatch({ task, agentId, agentMetadata }) {
if (!task?.id || !agentId) return {};
+ if (isTruthyMeta(task.metadata?.discardWorktree)) return {};
+ const claimContinuation = await resolveClaimContinuationPatch({ task, agentId, agentMetadata });
+ if (claimContinuation) return claimContinuation;
// Persistent feature-agent worktrees are never torn down, and throwaway
// reasoning worktrees are deliberately discarded — neither leaves work to resume.
// These runs are NOT evaluated at all, which is why they return the empty patch
@@ -694,7 +724,6 @@ export async function resolveTaskResumePatch({ task, agentId, agentMetadata }) {
// worktree (see agentWorkspacePrep's degrade path) must KEEP its pointer, since
// the tree it names is still sitting there for the attempt after this one.
if (!agentMetadata?.isWorktree || agentMetadata?.isPersistentWorktree) return {};
- if (isTruthyMeta(task.metadata?.discardWorktree)) return {};
// The agent's own recorded path is authoritative; the `<worktrees>/<agentId>`
// convention is the fallback for a record written before it was stamped (same
@@ -749,7 +778,12 @@ export function resumePointerMetadata(pointer, agentId, task) {
// literal string `"null"` — which reads back as a truthy `existingBranch` and
// sends the next attempt looking for a branch named "null". The keys are still
// present on the returned patch, so callers can tell a clear from a no-op.
- return { existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined };
+ return {
+ existingBranch: undefined,
+ resumedFromAgentId: undefined,
+ resumeWorktreePath: undefined,
+ claimResumeInPlace: undefined,
+ };
}
/**
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 14f1972005..003d37e2c6 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -47,7 +47,8 @@ vi.mock('./cos.js', () => ({
getTaskById: vi.fn().mockResolvedValue(null),
forceSpawnTask: vi.fn().mockResolvedValue({ success: true }),
getAgent: vi.fn().mockResolvedValue(null),
- getAgentRecord: vi.fn().mockResolvedValue(null)
+ getAgentRecord: vi.fn().mockResolvedValue(null),
+ getAgents: vi.fn().mockResolvedValue([])
}));
vi.mock('./appActivity.js', () => ({
@@ -163,7 +164,8 @@ vi.mock('./worktreeManager.js', async (importOriginal) => ({
cleanupOrphanedWorktrees: vi.fn(),
// Real: the resume path's "is this dirt real work?" answer must be the SAME
// classifier removeWorktree preserves a tree on, and it's a pure function.
- classifyWorktreeDirt: (await importOriginal()).classifyWorktreeDirt
+ classifyWorktreeDirt: (await importOriginal()).classifyWorktreeDirt,
+ listWorktrees: vi.fn().mockResolvedValue([])
}));
vi.mock('./jira.js', () => ({
@@ -242,8 +244,8 @@ import { existsSync as existsSyncMock } from 'fs';
// They used to be pulled through the `subAgentSpawner.js` barrel, which was
// retired in #3450.
import { cleanupAgentWorktree, resolveWorktreeDisposition, spawnMergeRecoveryTask, spawnReviewLoopFollowUp, resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, releaseRetryHold, resumePointerMetadata } from './agentWorktreeCleanup.js';
-import { getAgent, getAgentRecord, getTaskById, addTask, forceSpawnTask, updateTask } from './cos.js';
-import { removeWorktree } from './worktreeManager.js';
+import { getAgent, getAgentRecord, getAgents, getTaskById, addTask, forceSpawnTask, updateTask } from './cos.js';
+import { listWorktrees, removeWorktree } from './worktreeManager.js';
import { PATHS } from '../lib/fileUtils.js';
import * as git from './git.js';
import { resolveReviewerConfig } from '../lib/reviewerConfig.js';
@@ -1407,7 +1409,7 @@ describe('resolveTaskResumePatch / recordTaskResumePointer', () => {
await recordTaskResumePointer({ task, agentId: 'agent-x', agentMetadata });
expect(updateTask).toHaveBeenCalledWith('task-1', {
- metadata: { existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined }
+ metadata: { existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined, claimResumeInPlace: undefined }
}, 'user');
});
@@ -1433,6 +1435,46 @@ describe('resolveTaskResumePatch / recordTaskResumePointer', () => {
// Reasoning agents run in a worktree whose edits are deliberately thrown away —
// resuming one would resurrect code the discard guarantee exists to drop.
+ it('points a relaunched claim at the claim worktree the previous run already cut', async () => {
+ const claimPath = '/mock/root/data/cos/worktrees/claim-portos-issue-42';
+ listWorktrees.mockResolvedValue([
+ { path: claimPath, branch: 'refs/heads/claim/issue-42' },
+ ]);
+ getAgents.mockResolvedValue([{ id: 'agent-old', status: 'paused', metadata: { workspacePath: '/repo' } }]);
+ const task = {
+ id: 'task-1', taskType: 'user',
+ metadata: { claimFlow: true, claimTarget: '42' },
+ };
+
+ await recordTaskResumePointer({
+ task, agentId: 'agent-old',
+ agentMetadata: { isWorktree: false, workspacePath: '/repo' },
+ });
+
+ expect(updateTask).toHaveBeenCalledWith('task-1', {
+ metadata: {
+ existingBranch: 'claim/issue-42',
+ resumedFromAgentId: 'agent-old',
+ resumeWorktreePath: claimPath,
+ claimResumeInPlace: true,
+ },
+ }, 'user');
+ });
+
+ it('leaves a claim relaunch clean when another paused agent is already in that worktree', async () => {
+ const claimPath = '/mock/root/data/cos/worktrees/claim-portos-issue-42';
+ listWorktrees.mockResolvedValue([{ path: claimPath, branch: 'refs/heads/claim/issue-42' }]);
+ getAgents.mockResolvedValue([{ id: 'agent-other', status: 'paused', metadata: { workspacePath: claimPath } }]);
+
+ await recordTaskResumePointer({
+ task: { id: 'task-1', metadata: { claimFlow: true, claimTarget: '42' } },
+ agentId: 'agent-old',
+ agentMetadata: { isWorktree: false, workspacePath: '/repo' },
+ });
+
+ expect(updateTask).not.toHaveBeenCalled();
+ });
+
it('skips throwaway (discardWorktree) tasks', async () => {
const task = { id: 'task-1', metadata: { discardWorktree: true } };
@@ -1642,7 +1684,7 @@ describe('resumePointerMetadata', () => {
// pointer would attach attempt 3 to already-merged work.
it('clears a pointer this mechanism wrote once there is nothing left to resume', () => {
expect(resumePointerMetadata(null, 'agent-y', { metadata: { resumedFromAgentId: 'agent-x' } })).toEqual({
- existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined
+ existingBranch: undefined, resumedFromAgentId: undefined, resumeWorktreePath: undefined, claimResumeInPlace: undefined
});
});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 37ef3b794d..17fbac878e 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -670,6 +670,7 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue
if (shouldStripTaskTargetBranch(updatedMetadata)) delete updatedMetadata.existingBranch;
delete updatedMetadata.resumedFromAgentId;
delete updatedMetadata.resumeWorktreePath;
+ delete updatedMetadata.claimResumeInPlace;
}
// Stamp the moment a RUNNING task is requeued (#3376). `in_progress → pending`
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 2c29deb99a..769c991542 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -495,10 +495,44 @@ export function claimReviewersCsv(task, codeReviewDefaults, defaultReviewers) {
* (`PR_COMPLETIONS`): `MERGE_ON_GREEN` suppresses the reviewer pin and emits
* the merge-on-green handoff instead; any other value keeps the pin.
*/
-export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '', leavePrOpen = false, prCompletion = null } = {}) {
+/**
+ * Relaunch of a claim whose previous run already cut the worktree. Null unless
+ * the resume pointer says to stay in that directory.
+ */
+export function claimResumeContext(task, worktreeInfo = null) {
+ const meta = task?.metadata;
+ if (meta?.claimResumeInPlace !== true && meta?.claimResumeInPlace !== 'true') return null;
+ const worktreePath = worktreeInfo?.worktreePath || meta.resumeWorktreePath;
+ const branchName = worktreeInfo?.branchName || meta.existingBranch;
+ const priorAgentId = meta.resumedFromAgentId;
+ if (!worktreePath || !branchName || !priorAgentId) return null;
+ return { priorAgentId, branchName, worktreePath };
+}
+
+/**
+ * Overrides the claim prompt's "already in progress / already on this branch →
+ * exit" rule for the markers THIS task's previous run left behind.
+ */
+export function buildClaimResumeOverride({ priorAgentId, branchName, worktreePath } = {}) {
+ if (!priorAgentId || !branchName || !worktreePath) return '';
+ return [
+ '## Relaunch — finish the claim already started',
+ `This run continues \`${priorAgentId}\` on the same task. That run already claimed this work and left it in \`${worktreePath}\` on branch \`${branchName}\`.`,
+ '',
+ 'Those markers belong to this task. The `in-progress` label, an assignee that is this account, and the existing branch and worktree are the claim you are finishing. The Target Issue Constraint and Phase 1 rule that say to exit when the issue is already in progress or already checked out on that branch do not apply to them. Finish the work in this worktree.',
+ '',
+ `Stay in \`${worktreePath}\` on \`${branchName}\`. Skip creating another worktree. Continue at the first phase that is not already done and ship it.`,
+ '',
+ 'Stop without taking the work when a different human left a clear active claim comment, or the issue is closed or parked for a human (`needs-input`, `blocked`). A contributor\'s claim is not this relaunch.',
+ ].join('\n');
+}
+
+export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '', leavePrOpen = false, prCompletion = null, claimResume = null } = {}) {
const isMergeOnGreen = prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN;
const pin = isMergeOnGreen ? '' : buildReviewerPinNote(reviewersCsv);
+ const resumeOverride = buildClaimResumeOverride(claimResume || {});
const lines = [
+ ...(resumeOverride ? [resumeOverride, ''] : []),
...(pin ? [pin, ''] : []),
'## Claim Workflow Handoff',
...(leavePrOpen ? [
@@ -510,6 +544,7 @@ export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath =
'',
] : []),
'This is a self-managed claim flow. The claim prompt above owns its claim worktree, branch, PR/MR, review, merge or human-handoff, and cleanup. Follow its phase-specific exit conditions — do NOT stop after a code commit or hand the lifecycle back to PortOS.',
+ ...(resumeOverride ? ['When the relaunch section above applies, finish this task\'s existing claim in the worktree named there.'] : []),
'',
...(!isMergeOnGreen ? [
`Required-review publication rule: if a required local reviewer cannot return a verdict because of a missing CLI, quota/provider or transport failure, timeout, malformed/empty response, or no-verdict result, record the local phase as \`review-blocked\` rather than substituting a self-review. Still push and open the PR/MR, leave it open, preserve the claim markers and branch, and stop before merge. ${REVIEW_UNAVAILABLE_REPORTING_NOTE} A substantive rejection, failed build/test, unpushed fix, or state/publication failure still blocks publication.`,