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: preserve claim-owned delivery lifecycle

[._.]/ Adam Eivyba0d6bbc0488
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 5a5d807646..f8e2db696e 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1395,7 +1395,7 @@ export const MAX_TOTAL_SPAWNS = 5;
// override can disable an individual rectification behavior and survive
// sanitizeTaskMetadata.
const ALLOWED_TASK_METADATA_KEYS = [
- ...PIPELINE_BEHAVIOR_FLAGS, 'readOnly',
+ ...PIPELINE_BEHAVIOR_FLAGS, 'readOnly', 'claimFlow',
'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge', 'finishAbandoned', 'autoClose',
// Throwaway-worktree posture for programmatic-I/O reasoning tasks (layered-
// intelligence): the worktree is discarded without a merge or PR so a reasoning
@@ -1486,7 +1486,8 @@ export const resumeCosAgentSchema = createCosTaskSchema
/**
* Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags
- * (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`reviewerApplies`)
+ * (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`claimFlow`/
+ * `reviewerApplies`)
* are kept only when actually boolean; constrained values include `prCompletion`,
* reviewers, reviewer usernames, and `reviewStopMode` — plus a validated pipeline
* object. Prevents prototype pollution and reserved-field overrides.
diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.js
index a83e52ae5e..3a1b3cae9e 100644
--- a/server/lib/cosValidation.test.js
+++ b/server/lib/cosValidation.test.js
@@ -106,6 +106,14 @@ describe('cosValidation job taskMetadata.worktreeChangesExpected (#3102)', () =>
});
});
+describe('cosValidation task metadata claimFlow marker', () => {
+ it('sanitizes the claim lifecycle marker as a boolean', () => {
+ expect(sanitizeTaskMetadata({ claimFlow: true })).toEqual({ claimFlow: true });
+ expect(sanitizeTaskMetadata({ claimFlow: false })).toEqual({ claimFlow: false });
+ expect(sanitizeTaskMetadata({ claimFlow: 'true' })).toBeNull();
+ });
+});
+
describe('cosValidation quick-template deliverable posture (#3651)', () => {
it('taskTemplateSettingsSchema accepts worktreeChangesExpected (the block is .strict())', () => {
// taskTemplates.js copies the slashdo catalog posture onto each built-in
diff --git a/server/routes/cos.test.js b/server/routes/cos.test.js
index 387b210503..c269dc700d 100644
--- a/server/routes/cos.test.js
+++ b/server/routes/cos.test.js
@@ -1091,6 +1091,7 @@ describe('CoS Routes', () => {
// prompt builder append the whole /do:next body on top of the claim prompt).
expect(taskData.slashdoCommand).toBeUndefined();
expect(taskData.description).not.toContain('/do:');
+ expect(taskData.claimFlow).toBe(true);
});
// `next` is commit-shaped in the catalog, but the claim flow resolves the
@@ -1299,6 +1300,7 @@ describe('CoS Routes', () => {
// claim-issue-jira self-manages its worktree + PR.
expect(taskData.useWorktree).toBe(false);
expect(taskData.openPR).toBe(false);
+ expect(taskData.claimFlow).toBe(true);
});
it('uppercases the ticket key', async () => {
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 4b1dafc9f3..b453d60670 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -204,8 +204,10 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
// claim.taskMetadata overrides the catalog posture only where it carries a
// key. All current claim flows (plan-task / claim-issue / claim-issue-gitlab
// / claim-issue-jira) self-manage their worktree + MR/PR, so false/false
- // stands; the spread stays for a future delegated type that needs
- // CoS-managed isolation. `worktreeChangesExpected` is one such key: the
+ // remains the CoS provisioning posture. `claimFlow` is a separate
+ // lifecycle marker so the prompt builder cannot mistake false/false for a
+ // commit-only handoff. The spread stays for a future delegated type that
+ // needs CoS-managed isolation. `worktreeChangesExpected` is one such key: the
// claim flow derives it from the app's RESOLVED work tracker (a file
// tracker commits its checklist, a forge tracker doesn't), which is more
// specific than the catalog's commit-shaped default, so the spread wins.
@@ -214,7 +216,8 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {
openPR,
worktreeChangesExpected,
...(claim.target ? { claimTarget: claim.target } : {}),
- ...claim.taskMetadata
+ ...claim.taskMetadata,
+ claimFlow: true
},
};
} else {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 5f7c4e5657..487ccadf9d 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -52,7 +52,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { createAgentRun } from './agentRunTracking.js';
import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';
import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';
-import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection } from './agentPromptBuilder.js';
+import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection, isClaimFlowTask } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
import { prClaimWasVerified } from '../lib/prDisposition.js';
@@ -563,6 +563,12 @@ async function runAgentSpawn(task) {
jiraInstanceId: task.metadata?.jiraInstanceId || null,
jiraCreatePR: task.metadata?.jiraCreatePR ?? null,
configOpenPR: isTruthyMeta(task.metadata?.openPR),
+ // Claim prompts own their external claim/<item> worktree and forge
+ // lifecycle even though CoS must keep configOpenPR/configUseWorktree off
+ // to avoid provisioning a nested worktree. Preserve that distinction in
+ // the run record so completion diagnostics cannot mistake the claim path
+ // for the generic commit-only handoff.
+ configClaimFlow: isClaimFlowTask(task, isTruthyMeta),
configSimplify: isTruthyMeta(task.metadata?.simplify),
configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),
configReviewers: normalizeReviewers(task.metadata),
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 54eb1e2e92..3c9155648f 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -668,6 +668,14 @@ describe('runAgentSpawn source — instance provenance + claim ordering (#1563)'
expect(metaSlice).toMatch(/\binstanceId,/);
expect(metaSlice.indexOf('instanceId,')).toBeLessThan(metaSlice.indexOf('workspacePath'));
});
+
+ it('records claimFlow separately from CoS-managed PR/worktree flags', () => {
+ const registerIdx = AGENT_LIFECYCLE_SRC.indexOf('registerAgent(agentId, task.id, {');
+ const metaSlice = AGENT_LIFECYCLE_SRC.slice(registerIdx, registerIdx + 8_000);
+ expect(metaSlice).toContain('configOpenPR: isTruthyMeta(task.metadata?.openPR)');
+ expect(metaSlice).toContain('configClaimFlow: isClaimFlowTask(task, isTruthyMeta)');
+ expect(metaSlice.indexOf('configClaimFlow')).toBeGreaterThan(metaSlice.indexOf('configOpenPR'));
+ });
});
// These used to be three source-regex assertions pinning a hand-spread env
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 04a3b6bf2a..08e6ac26fc 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -35,6 +35,18 @@ const ROOT_DIR = PATHS.root;
const AGENTS_DIR = PATHS.cosAgents;
const SKILLS_DIR = join(ROOT_DIR, 'data/prompts/skills');
+// Scheduled claim tasks created before the explicit marker was introduced still
+// carry their task kind in analysisType. Keep those persisted queue records on
+// the claim-owned lifecycle while new/manual tasks use the explicit marker.
+const CLAIM_FLOW_TASK_TYPES = new Set([
+ 'plan-task', 'claim-issue', 'claim-issue-gitlab', 'claim-issue-jira', 'claim-work'
+]);
+
+export function isClaimFlowTask(task, isTruthyMetaFn = (value) => value === true || value === 'true') {
+ return isTruthyMetaFn(task?.metadata?.claimFlow)
+ || CLAIM_FLOW_TASK_TYPES.has(task?.metadata?.analysisType);
+}
+
/**
* Absolute path of the completion sentinel this run must write. The spawners'
* pollers resolve the same per-instance filename from the same helper (see
@@ -1257,7 +1269,7 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '
export function buildCompletionGuidelineBullet({
isReadOnly, isTui, tuiCompletionCommand, slashdoFree = false,
worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, discardWorktree = false, noCodeOutput = false,
- leavePrOpen = false, isPrFollowUp = false,
+ leavePrOpen = false, isPrFollowUp = false, claimFlow = false,
}) {
// A PR follow-up (review-loop or merge-only) already carries its own PRIMARY
// OBJECTIVE section with the full procedure, and its cleanup runs with
@@ -1281,6 +1293,9 @@ export function buildCompletionGuidelineBullet({
if (discardWorktree) {
return '**This is a reasoning-only task.** The worktree is discarded on exit — do NOT commit, push, merge, or open a PR. Write your result to the completion sentinel (see the Completion section) and stop.';
}
+ if (claimFlow) {
+ return '**This is a self-managed claim flow.** Follow the claim prompt above through its phase-specific worktree, PR/MR, review, merge or human-handoff, and cleanup steps. Do NOT stop after committing or hand the lifecycle back to PortOS.';
+ }
if (isReadOnly) {
return '**This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.';
}
@@ -1457,6 +1472,27 @@ export function buildActionOutputCompletionSection({ isTui = false, sentinelPath
].join('\n');
}
+/**
+ * Completion handoff for claim prompts that create their own worktree and own
+ * the forge lifecycle. `openPR: false` must remain the CoS provisioning posture,
+ * so claimFlow is the explicit signal that keeps these prompts out of the
+ * generic commit-only handoff.
+ */
+function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null } = {}) {
+ const lines = [
+ '## Claim Workflow Handoff',
+ '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.',
+ '',
+ 'For a successful claim, signal completion only after the prompt\'s prescribed PR/MR and cleanup steps are complete. For a clean no-work, blocked, or review-stuck exit, follow the prompt\'s prescribed leave-open/cleanup path first.'
+ ];
+ if (isTui && sentinelPath) {
+ lines.push('', 'When that path is complete, write the completion sentinel and stop:', '', ...buildSentinelWriteSteps(1, sentinelPath, ' ## PR/MR\n <PR or MR URL, or explain the clean exit>'));
+ } else {
+ lines.push('', 'After the prompt\'s prescribed final step, exit so PortOS can record the completed claim.');
+ }
+ return lines.join('\n');
+}
+
/**
* Build the agent prompt.
*
@@ -1606,6 +1642,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// Build worktree context section if applicable
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
+ const claimFlow = isClaimFlowTask(task, isTruthyMetaFn);
const prCompletion = resolvePrCompletion(task.metadata);
// A discard (reasoning-only) worktree: the agent reasons in it but it's thrown
// away on exit with no commit/merge/PR (see agentWorktreeCleanup.js). Suppresses
@@ -1627,6 +1664,8 @@ ${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (lat
**Important**: ${discardWorktree
? DISCARD_WORKTREE_NOTE
+ : claimFlow
+ ? 'The claim workflow in the Completion section owns its claim branch, push, PR/MR, review, merge or human-handoff, and cleanup — do not hand those steps back to PortOS.'
: isTui
? 'Commit your changes to this branch — see the **Completion Workflow** section below for the full push/PR/exit sequence.'
: isWorktreeOnExistingBranch
@@ -1668,7 +1707,7 @@ Use the findings from the previous stage to inform your work. If the previous st
? 'run `/simplify` to review the changed code for reuse, quality, and efficiency'
: SIMPLIFY_INLINE_REVIEW;
// Discard tasks don't commit, so the simplify-before-commit step is moot.
- const simplifySection = simplifyEnabled && !isTui && !discardWorktree ? `
+ const simplifySection = simplifyEnabled && !isTui && !discardWorktree && !claimFlow ? `
## Simplify Step
After completing your work and before committing, ${simplifyInstruction}. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.
` : '';
@@ -1719,6 +1758,8 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
? buildActionOutputCompletionSection({ isTui, sentinelPath })
: discardWorktree
? buildProgrammaticOutputCompletionSection(sentinelPath)
+ : claimFlow
+ ? buildClaimFlowCompletionSection({ isTui, sentinelPath })
: isTui
? buildTuiCompletionSection({
willOpenPR, prCompletion, simplifyEnabled,
@@ -1911,6 +1952,8 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too
? 'Deliver your result the way the task describes (the API call or command it names) — do NOT commit, push, or open a PR; this task changes no code'
: discardWorktree
? 'Write your result to the completion sentinel (see the Completion section above) — do NOT commit, push, or open a PR; this worktree is discarded on exit'
+ : claimFlow
+ ? 'Follow the claim workflow prompt above; it owns its worktree, PR/MR, review, merge or human-handoff, and cleanup. Do not stop after committing.'
: isReviewLoopFollowUp
? 'Follow the follow-up section above — push any fixes you make to the PR branch; a run that needed no fix makes no commit and that is a success, not a miss'
: isTui
@@ -1933,7 +1976,7 @@ ${(() => {
isTui, tuiCompletionCommand, slashdoFree: isTui && !canRunSlashCommands,
worktreeInfo, willOpenPR, prCompletion, discardWorktree, noCodeOutput,
leavePrOpen: leavesPrForHuman(task),
- isPrFollowUp: isReviewLoopFollowUp,
+ isPrFollowUp: isReviewLoopFollowUp, claimFlow,
});
return bullet ? `- ${bullet}` : '';
})()}
@@ -1946,6 +1989,8 @@ ${noCodeOutput
? `- **Do NOT commit, push, or open a PR.** This task changes no code — its result is delivered by the API call or command described above. Without this, a no-worktree task of this shape was told to \`/do:push\` **directly to the branch it is standing on**, which for a task running in the app's live checkout is its default branch.`
: discardWorktree
? `- **Do NOT commit, push, or open a PR.** This worktree is discarded on exit — your only output is the completion sentinel (see the Completion section above).`
+ : claimFlow
+ ? `- **Follow the claim workflow prompt above.** It owns the claim worktree and the full PR/MR lifecycle; do not stop after committing or hand push/PR/merge/cleanup back to PortOS.`
: isReviewLoopFollowUp
? `- **Push fixes straight to the PR branch you are on** (the follow-up section above is the procedure). Stage specific files, use a \`fix:\` prefix, no Co-Authored-By annotations. Do NOT open a new PR.`
: isTui && tuiSlashdoFree
@@ -1955,7 +2000,7 @@ ${noCodeOutput
: worktreeInfo && willOpenPR
? `- **Commit only — do NOT push.** Stage specific files, use \`feat:\`/\`fix:\`/\`breaking:\` prefix in the commit message, no Co-Authored-By annotations. The system will push your branch and open the PR after you exit, so do NOT run \`git push\` or \`/do:push\` yourself.`
: `- **Commit and push using \`/do:push\`** — this handles changelog updates, staging specific files, writing a conventional commit message, and pushing safely. If \`/do:push\` is unavailable, follow its conventions manually: stage specific files, use \`feat:\`/\`fix:\`/\`breaking:\` prefix, no Co-Authored-By annotations, and push with \`git pull --rebase && git push\`.`}
-${discardWorktree || noCodeOutput ? '' : worktreeInfo ? `- **Your PR should contain only your task's commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents' work.` : `- **Commit directly to the current branch.** Do NOT create feature branches or PRs unless explicitly instructed.`}
+${discardWorktree || noCodeOutput || claimFlow ? '' : worktreeInfo ? `- **Your PR should contain only your task's commits.** If you see unrelated commits in your branch history, something is wrong — do not open a PR with other agents' work.` : `- **Commit directly to the current branch.** Do NOT create feature branches or PRs unless explicitly instructed.`}
## Working Directory
${task.metadata?.app ? `You are working in the target app directory: \`${workspaceDir}\`. All code changes, research, plans, and docs for this task belong in this directory — NOT in the PortOS repo.` : 'You are working in the project directory.'} Use the available tools to explore, modify, and test code.
@@ -2013,6 +2058,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// directly-exported buildLightContextPrompt/Parts entry points.
task = reconcileSplitContext(task);
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
+ const claimFlow = isClaimFlowTask(task, isTruthyMetaFn);
const prCompletion = resolvePrCompletion(task.metadata);
const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);
const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);
@@ -2072,7 +2118,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// a JIRA run be told to open a PR whose merge section was suppressed — and
// PortOS opened that PR too. `inlineSection` also names WHICH section follows,
// so the completion step's cross-reference can't name the wrong one.
- const inlineSection = inlinePrLifecycleSection(task, {
+ const inlineSection = claimFlow ? null : inlinePrLifecycleSection(task, {
providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,
providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,
});
@@ -2126,7 +2172,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
`- **Path**: \`${worktreeInfo.worktreePath}\``,
worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,
'',
- worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }),
+ worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow }),
'Do NOT manually switch branches or modify the worktree configuration.',
// Resuming a previous failed agent's branch: establish what's already done
// before writing code (see buildResumeSection). '' when not a resume.
@@ -2176,6 +2222,11 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// output hook) is the sole output; the worktree is discarded on exit. Wins
// over the isTui / CLI push-and-PR completion workflows below.
sections.push(buildProgrammaticOutputCompletionSection(resolveSentinelPath(worktreeInfo, workspaceDir, agentId)));
+ } else if (claimFlow) {
+ sections.push(buildClaimFlowCompletionSection({
+ isTui,
+ sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),
+ }));
} else if (isReadOnly) {
sections.push(buildReadOnlyCompletionSection({
isTui,
@@ -2244,8 +2295,9 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
* push workflow (TUI or Claude Code CLI with slashdo), reuse an existing PR
* branch (review fixes), or hand off to PortOS's post-exit push.
*/
-function worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }) {
+function worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false }) {
if (discardWorktree) return DISCARD_WORKTREE_NOTE;
+ if (claimFlow) return 'The claim workflow in the Completion section owns the push, PR/MR, review, merge or human-handoff, and cleanup steps.';
if (isTui) return 'Commit your changes to this branch — see **Completion Workflow** below.';
if (isWorktreeOnExistingBranch) {
return 'Commit and **push** any review-fix commits to this branch (the PR points at it). Use `git pull --rebase` before pushing if needed.';
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index c0a108bfe7..b1a140fb99 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -243,6 +243,45 @@ describe('no-code / API-action task completion (CD agents must NOT be told to /d
});
});
+describe('claim-flow completion handoff', () => {
+ 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 } }),
+ '/repo', null, isTruthyMeta,
+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },
+ );
+
+ expect(prompt).toMatch(/## Claim Workflow Handoff/);
+ expect(prompt).toMatch(/owns its claim worktree, branch, PR\/MR, review, merge or human-handoff, and cleanup/);
+ expect(prompt).toMatch(/\.agent-done/);
+ expect(prompt).not.toMatch(/PortOS will merge it back after completion/);
+ expect(prompt).not.toMatch(/Do NOT push this worktree branch yourself/);
+ expect(prompt).not.toMatch(/Commit and push using `\/do:push`/);
+ });
+
+ it('uses the claim handoff on the full API prompt path too', async () => {
+ const prompt = await buildAgentPrompt(
+ makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, simplify: true } }),
+ {}, '/repo', null, isTruthyMeta, { providerType: 'api' },
+ );
+
+ expect(prompt).toMatch(/## Claim Workflow Handoff/);
+ expect(prompt).toMatch(/follow the claim workflow prompt above/i);
+ expect(prompt).not.toMatch(/PortOS will merge it back after completion/);
+ });
+
+ it('recognizes a queued legacy claim task by analysisType', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { analysisType: 'claim-issue', useWorktree: false, openPR: false } }),
+ '/repo', null, isTruthyMeta,
+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },
+ );
+
+ expect(prompt).toMatch(/## Claim Workflow Handoff/);
+ expect(prompt).not.toMatch(/PortOS will merge it back after completion/);
+ });
+});
+
describe('buildLightContextPrompt', () => {
describe('what it omits', () => {
it('does NOT include the obsolete "# Chief of Staff Agent Briefing" header', () => {
@@ -1930,6 +1969,16 @@ describe('buildCompletionGuidelineBullet', () => {
expect(bullet).not.toMatch(/`\/do:pr`/);
});
+ it('claimFlow short-circuits to the claim-owned lifecycle bullet', () => {
+ const bullet = buildCompletionGuidelineBullet({
+ isReadOnly: false, isTui: true, tuiCompletionCommand: '/do:push',
+ worktreeInfo: null, willOpenPR: false, claimFlow: true,
+ });
+ expect(bullet).toMatch(/self-managed claim flow/i);
+ expect(bullet).toMatch(/Do NOT stop after committing/);
+ expect(bullet).not.toMatch(/PortOS will merge/);
+ });
+
it('noCodeOutput wins over discardWorktree — the deliverable is the action, not the sentinel', () => {
// The two flags answer different questions: discardWorktree decides what
// happens to the checkout, noCodeOutput decides where the deliverable goes.
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index a54967e7a8..3d1c4c8e59 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -47,6 +47,14 @@ import { TIMED_COOLDOWN_BLOCKED_CATEGORIES } from '../lib/taskBlockCategories.js
import { PATHS } from '../lib/fileUtils.js';
import { shellQuote } from '../lib/shellQuote.js';
+// Claim prompts create and manage their own claim/<item> worktree and
+// push/PR/MR/review lifecycle. This marker is separate from `openPR: false`,
+// which is the CoS provisioning posture that prevents a nested worktree. Keep
+// the type list here as a backstop for old schedules that predate claimFlow.
+const CLAIM_FLOW_TASK_TYPES = new Set([
+ 'plan-task', 'claim-issue', 'claim-issue-gitlab', 'claim-issue-jira', 'claim-work'
+]);
+
/**
* Block a task that has exceeded the max spawn limit. Returns true if blocked.
*/
@@ -397,8 +405,10 @@ export function resolveClaimAuthorFilter(explicit, metadata) {
* the scheduled `claim-work` router below. Resolves the tracker, delegates to the
* matching claim prompt body (plan-task / claim-issue / claim-issue-gitlab /
* claim-issue-jira), substitutes the standard placeholders, and surfaces the
- * delegated flow's worktree/PR posture (all four claim prompts self-manage their
- * own worktree + MR/PR, so the self-managed false/false posture is correct).
+ * delegated flow's worktree/PR posture. `claimFlow` separately marks that the
+ * prompt owns its worktree + MR/PR lifecycle; false/false remains the correct
+ * CoS provisioning posture because a nested CoS worktree would conflict with
+ * the claim branch.
*
* `issueAuthorFilter` and the reviewer options default to the app's *configured*
* `claim-work` behavior (global schedule metadata → per-app override → Code
@@ -504,7 +514,7 @@ export async function buildClaimWorkTask(app, {
// Mirror the scheduler: inherit the delegated flow's isolation posture so the
// JIRA route runs in a CoS-managed worktree rather than the live checkout.
const delegatedMeta = taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata || {};
- const taskMetadata = {};
+ const taskMetadata = { claimFlow: true };
if ('useWorktree' in delegatedMeta) taskMetadata.useWorktree = delegatedMeta.useWorktree;
if ('openPR' in delegatedMeta) taskMetadata.openPR = delegatedMeta.openPR;
@@ -736,10 +746,11 @@ const appendLocalReviewerInstructions = (promptTaskType, reviewers, reviewerMode
* a target-ticket constraint that pins the agent to `ticketKey` while keeping
* every claim safety check. `ticketKey` is normalized to upper-case (`PROJ-1234`).
*
- * claim-issue-jira self-manages its worktree + MR/PR, so `taskMetadata` stays
- * `false/false` (matching the `/do:next` slashdo default for the JIRA tracker).
+ * claim-issue-jira self-manages its worktree + MR/PR. `claimFlow` records that
+ * lifecycle ownership while `useWorktree/openPR` stay `false/false` so CoS does
+ * not provision a nested worktree.
*
- * @returns {Promise<{ ticketKey: string, prompt: string, taskMetadata: { useWorktree: boolean, openPR: boolean } }>}
+ * @returns {Promise<{ ticketKey: string, prompt: string, taskMetadata: { useWorktree: boolean, openPR: boolean, claimFlow: boolean } }>}
*/
export async function buildJiraTicketTask(app, ticketKey) {
const { getTaskPrompt } = await import('./taskPromptService.js');
@@ -764,7 +775,7 @@ export async function buildJiraTicketTask(app, ticketKey) {
+ effortBlock
+ localReviewerBlock;
- return { ticketKey: key, prompt, taskMetadata: { useWorktree: false, openPR: false } };
+ return { ticketKey: key, prompt, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true } };
}
/**
@@ -2235,6 +2246,14 @@ async function buildImprovementTaskMetadata(taskType, app, interval, taskSchedul
if (sanitizedAppMeta) {
Object.assign(metadata, sanitizedAppMeta);
}
+
+ // Derive the marker from the task type as well as the shipped schedule
+ // metadata. This keeps pre-migration/custom schedule records from losing the
+ // claim-owned lifecycle when they still carry the legacy false/false flags.
+ // Do this after schedule and app overrides so the claim contract cannot be
+ // disabled by stale or malformed metadata.
+ if (CLAIM_FLOW_TASK_TYPES.has(taskType)) metadata.claimFlow = true;
+
return metadata;
}
@@ -2281,6 +2300,7 @@ export async function resolveTaskInputHook(app, taskType, taskSchedule, { ignore
*/
async function resolveClaimWorkRouting(app, taskType, metadata, taskSchedule) {
if (taskType !== 'claim-work') return taskType;
+ metadata.claimFlow = true;
const { resolveAppWorkTracker, trackerToClaimTaskType } = await import('../lib/workTracker.js');
const wt = await resolveAppWorkTracker(app);
const promptTaskType = trackerToClaimTaskType(wt.resolved) || 'plan-task';
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 3678689004..ec511435d0 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -328,12 +328,16 @@ describe('claim-work single-source routing', () => {
it('pulls the delegated flow isolation posture from DEFAULT_TASK_INTERVALS metadata', () => {
// claim-work forces useWorktree/openPR=false, correct for all four
- // self-managing claim prompts (plan/github/gitlab/jira). The hook stays so a
- // future delegated type that DOES need CoS-managed isolation would have its
+ // self-managing claim prompts (plan/github/gitlab/jira). `claimFlow` is the
+ // separate lifecycle marker that prevents those false/false flags from
+ // selecting the generic commit-only handoff. The hook stays so a future
+ // delegated type that DOES need CoS-managed isolation would have its
// DEFAULT_TASK_INTERVALS metadata applied here.
expect(GEN_SRC).toContain('taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata');
expect(GEN_SRC).toContain("'useWorktree' in delegatedMeta");
expect(GEN_SRC).toContain("'openPR' in delegatedMeta");
+ expect(GEN_SRC).toContain('const taskMetadata = { claimFlow: true }');
+ expect(GEN_SRC).toContain('metadata.claimFlow = true');
});
it('exposes buildClaimWorkTask so the manual /do:next button reuses the same router', () => {
@@ -504,8 +508,9 @@ describe('buildJiraTicketTask', () => {
expect(prompt).toContain('PROJ-1234');
// Ticket key normalized to upper-case.
expect(ticketKey).toBe('PROJ-1234');
- // claim-issue-jira self-manages worktree + PR.
- expect(taskMetadata).toEqual({ useWorktree: false, openPR: false });
+ // claim-issue-jira self-manages worktree + PR; claimFlow keeps that
+ // lifecycle from falling into CoS's generic false/false handoff.
+ expect(taskMetadata).toEqual({ useWorktree: false, openPR: false, claimFlow: true });
});
it('is exported so the /tasks/jira-ticket route reuses the shared assembly', () => {
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index ccdde105c7..82e17ccbf3 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -369,6 +369,10 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
// their existing auto-merge behavior so automation isn't silently gated on a
// human merging a PR.
else if (taskData.useWorktree === true && taskType === 'user') metadata.openPR = true;
+ // Claim prompts own their forge lifecycle in a separately-created
+ // claim/<item> worktree. Keep this marker independent from openPR: false is
+ // still required to stop CoS from provisioning a second worktree.
+ if (taskData.claimFlow === true) metadata.claimFlow = true;
if (PR_COMPLETION_VALUES.includes(taskData.prCompletion)) {
metadata.prCompletion = taskData.prCompletion;
} else if (metadata.openPR === true && taskType === 'user') {
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index d77035c8ed..313ebf56dc 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -686,9 +686,10 @@ describe('cosTaskStore.addTask', () => {
});
it('persists boolean override flags (true and false) into metadata', async () => {
- const task = await addTask({ description: 'flagged', useWorktree: false, openPR: true }, 'user');
+ const task = await addTask({ description: 'flagged', useWorktree: false, openPR: true, claimFlow: true }, 'user');
expect(task.metadata.useWorktree).toBe(false);
expect(task.metadata.openPR).toBe(true);
+ expect(task.metadata.claimFlow).toBe(true);
expect(task.metadata.prCompletion).toBe('review-then-merge');
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 2c84d921ad..91f5d98a95 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -356,8 +356,13 @@ export const DEFAULT_TASK_INTERVALS = {
// `cleanupAgentWorktree`'s auto-merge into whatever the source repo's HEAD is on (clobbering a TUI user's in-flight claim branch).
// * `openPR: false` — keeps the cos.js "openPR implies useWorktree" invariant from forcing useWorktree back on. The agent opens its own PR via `gh pr create`
// and merges via `gh pr merge`, so CoS doesn't need to.
+ // `claimFlow: true` is the lifecycle marker. It is deliberately separate from
+ // `openPR`: the former tells prompt/completion handling that the claim prompt
+ // owns push → PR/MR → review → merge/cleanup, while the latter tells CoS whether
+ // it should provision and publish a managed worktree. Conflating them sent
+ // claim agents into the generic commit-only handoff (#4153).
// The agent runs in the source repo's working directory; `git worktree add` doesn't touch that working tree, so it's safe even with uncommitted user changes.
- 'plan-task': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, simplify: true } },
+ 'plan-task': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true } },
// claim-issue drives the /claim --issues flow — the agent creates its OWN
// claim/issue-<num> worktree, opens the PR (Closes #<num>), merges via
// `gh pr merge`, and cleans up. Both `useWorktree` and `openPR` are OFF on the
@@ -370,7 +375,7 @@ export const DEFAULT_TASK_INTERVALS = {
// access (GitHub collaborators / GitLab project members); 'owner' only claims
// issues the repo owner filed; 'any' claims any open issue. Per-app override
// supported via taskTypeOverrides.
- 'claim-issue': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, simplify: true, issueAuthorFilter: 'self' } },
+ 'claim-issue': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true, issueAuthorFilter: 'self' } },
// claim-work is the SINGLE-SOURCE router: one toggle per app that ships the
// next work item from whatever tracker the app is configured for
// (app.workTracker, default 'auto' → resolved from the git origin host). At
@@ -384,7 +389,7 @@ export const DEFAULT_TASK_INTERVALS = {
// hide the claim slug and trigger cleanupAgentWorktree's auto-merge).
// `issueAuthorFilter` applies only when the resolved tracker is a forge
// (github/gitlab); it's inert for plan/jira.
- 'claim-work': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, simplify: true, issueAuthorFilter: 'self' } },
+ 'claim-work': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: false, openPR: false, claimFlow: true, simplify: true, issueAuthorFilter: 'self' } },
'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },
'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },
'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },
@@ -455,7 +460,7 @@ export const DEFAULT_TASK_INTERVALS = {
// (e.g., plan-task's prompt creates its own claim/<slug> worktree, so a
// CoS-managed worktree would clobber it).
export const MANAGED_AGENT_OPTIONS = {
- 'plan-task': ['useWorktree', 'openPR'],
+ 'plan-task': ['useWorktree', 'openPR', 'claimFlow'],
// The non-committing coordinators (NON_COMMITTING_COORDINATOR_METADATA above) all
// run in the app's LIVE checkout and ship no code, so a CoS-managed worktree is at
// best unused and at worst harmful — branch-reconcile needs to see the sibling
@@ -478,10 +483,10 @@ export const MANAGED_AGENT_OPTIONS = {
),
// claim-issue's prompt creates its own claim/issue-<num> worktree (same
// rationale as plan-task), so CoS must not pre-create one or open the PR.
- 'claim-issue': ['useWorktree', 'openPR'],
+ 'claim-issue': ['useWorktree', 'openPR', 'claimFlow'],
// claim-work delegates to one of the above prompt bodies, each of which
// creates its own worktree + PR — so the same lock applies to the router.
- 'claim-work': ['useWorktree', 'openPR'],
+ 'claim-work': ['useWorktree', 'openPR', 'claimFlow'],
// ux's deliverable is tracker issues, not code — it never edits source, so a
// worktree/PR would only produce an empty branch. Lock both off.
'ux': ['useWorktree', 'openPR']
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index a38d5ec883..5b85594025 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -567,6 +567,7 @@ describe('taskSchedule', () => {
const schedule = await loadSchedule()
expect(schedule.tasks['plan-task'].taskMetadata.useWorktree).toBe(false)
expect(schedule.tasks['plan-task'].taskMetadata.openPR).toBe(false)
+ expect(schedule.tasks['plan-task'].taskMetadata.claimFlow).toBe(true)
// Non-managed flags pass through untouched
expect(schedule.tasks['plan-task'].taskMetadata.simplify).toBe(true)
})
@@ -574,7 +575,7 @@ describe('taskSchedule', () => {
it('exposes managedAgentOptions in getScheduleStatus for plan-task', async () => {
mockSchedule()
const status = await getScheduleStatus()
- expect(status.tasks['plan-task'].managedAgentOptions).toEqual(['useWorktree', 'openPR'])
+ expect(status.tasks['plan-task'].managedAgentOptions).toEqual(['useWorktree', 'openPR', 'claimFlow'])
// Other tasks should not carry the field
expect(status.tasks['security'].managedAgentOptions).toBeUndefined()
})
@@ -586,6 +587,7 @@ describe('taskSchedule', () => {
})
expect(result.taskMetadata.useWorktree).toBe(false)
expect(result.taskMetadata.openPR).toBe(false)
+ expect(result.taskMetadata.claimFlow).toBe(true)
expect(result.taskMetadata.simplify).toBe(true)
})
@@ -606,6 +608,7 @@ describe('taskSchedule', () => {
const schedule = await loadSchedule()
expect(schedule.tasks['plan-task'].taskMetadata.useWorktree).toBe(false)
expect(schedule.tasks['plan-task'].taskMetadata.openPR).toBe(false)
+ expect(schedule.tasks['plan-task'].taskMetadata.claimFlow).toBe(true)
})
})
@@ -1265,7 +1268,8 @@ describe('taskSchedule', () => {
// so CoS must keep both off (and lock them).
expect(cfg.taskMetadata.useWorktree).toBe(false)
expect(cfg.taskMetadata.openPR).toBe(false)
- expect(MANAGED_AGENT_OPTIONS['claim-issue']).toEqual(['useWorktree', 'openPR'])
+ expect(cfg.taskMetadata.claimFlow).toBe(true)
+ expect(MANAGED_AGENT_OPTIONS['claim-issue']).toEqual(['useWorktree', 'openPR', 'claimFlow'])
})
})