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: publish PRs when required reviews are unavailable

[._.]/ Adam Eivy2247c7030e15
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 560303876c..6b5b495348 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -1000,6 +1000,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
reviewerApplies: lightReviewerApplies,
localPhaseReviewers: localReviewers,
localPhaseCanShortCircuit,
+ localPhaseReviewRequired: localReviewSection ? localReviewRequired : false,
reviewerPositions,
forgeCli: resolvedForgeCli,
workflowStep: localReviewSection ? 5 : 4,
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 5a81101df8..425e824fbe 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -877,6 +877,10 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toContain('PR_HEAD="$PUSH_OWNER:$BRANCH"');
expect(prompt).toContain('portos-local-review-baseline');
expect(prompt).toContain('refusing to overwrite them');
+ expect(prompt).toContain('LOCAL_OVERALL_STATUS=review-blocked');
+ expect(prompt).toContain('case "$LOCAL_OVERALL_STATUS" in clean|partial|review-blocked)');
+ expect(prompt).toContain('gh pr comment "$PR_URL" --body "$REVIEW_BLOCKED_COMMENT"');
+ expect(prompt).toContain('Required code review was not completed before publication. This PR/MR is intentionally left open and will not be merged until the required review completes.');
expect(prompt).toMatch(/PR_URL=\$\(gh pr create --base main --head "\$PR_HEAD"/);
expect(prompt).toMatch(/## Review Loop/);
expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --delete-branch/);
@@ -885,6 +889,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toContain('`all` always runs the PR-side reviewers.');
expect(prompt.indexOf('### Local Review Before Opening the PR/MR')).toBeLessThan(prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"'));
expect(prompt.indexOf('publish_reviewed_branch -u "$PUSH_REMOTE" "$BRANCH"')).toBeLessThan(prompt.indexOf('## Review Loop'));
+ expect(prompt.indexOf('Required local-review merge gate')).toBeLessThan(prompt.indexOf('gh pr merge "$PR_URL" --merge --delete-branch'));
// The post-PR section receives only Copilot, never the local codex reviewer.
expect(prompt.slice(prompt.indexOf('## Review Loop'))).not.toMatch(/CLI Reviewer Procedure/);
// PortOS no longer promises to do any of it.
@@ -1029,6 +1034,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/git diff origin\/main\.\.\.HEAD/);
expect(prompt).toMatch(/PR_URL=\$\(glab mr create --source-branch claim\/issue-4363 --target-branch main/);
expect(prompt).toMatch(/PR_NUMBER=\$\(glab mr view "\$PR_URL" --output json \| jq -r \.iid\)/);
+ expect(prompt).toContain('LOCAL_OVERALL_STATUS=review-blocked');
+ expect(prompt).toContain('glab mr note "$PR_NUMBER" --message "$REVIEW_BLOCKED_COMMENT"');
+ expect(prompt).toContain('Required code review was not completed before publication. This PR/MR is intentionally left open and will not be merged until the required review completes.');
expect(prompt).toMatch(/## Review Loop/);
expect(prompt).toMatch(/request `@alice` as MR reviewer/);
expect(prompt).toMatch(/glab mr merge "\$PR_NUMBER" --yes --remove-source-branch/);
@@ -1171,6 +1179,8 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/You are done — exit/);
expect(prompt).toContain('repeat the pre-PR local review phase');
expect(prompt).toContain('the pre-PR local review is the only configured review');
+ expect(prompt).toContain('Required local-review merge gate');
+ expect(prompt).toContain('review-blocked');
expect(prompt).not.toContain('No code review was requested for this task');
expect(prompt).not.toMatch(/write the completion sentinel — the run is not done/);
});
@@ -1211,7 +1221,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/READ THAT FILE/);
expect(prompt).toMatch(/\/data\/slashdo-resolved\/local-agent-review-loop\.md/);
expect(prompt).not.toMatch(/RECIPE HEADER/);
- expect(prompt.length).toBeLessThan(21_000);
+ // The fixed review-blocked publication/merge contract adds prose to the
+ // prompt, but the 40KB recipe itself must still stay in the staged file.
+ expect(prompt.length).toBeLessThan(25_000);
});
it('quotes a hostile branch ref inert in the PR-create command line', () => {
@@ -2810,6 +2822,22 @@ describe('buildReviewLoopFollowUpSection — CLI reviewer procedure inlining', (
expect(out).toMatch(/STATUS=no-verdict[^]*exit 1/);
});
+ it('keeps an inline merge gate closed when the pre-PR required review is unavailable', () => {
+ const out = buildReviewLoopFollowUpSection(
+ { ...baseMeta, reviewLoopReviewers: ['copilot'] },
+ {
+ verbose: false,
+ inlineExitStep: 'write the completion sentinel and stop',
+ localPhaseReviewers: ['codex'],
+ localPhaseReviewRequired: true,
+ }
+ );
+ expect(out).toContain('Required local-review merge gate');
+ expect(out).toContain('LOCAL_OVERALL_STATUS=review-blocked');
+ expect(out).toContain('leave it open');
+ expect(out.indexOf('Required local-review merge gate')).toBeLessThan(out.indexOf('gh pr merge'));
+ });
+
it('does NOT inline the procedure for a copilot-only loop', () => {
const out = buildReviewLoopFollowUpSection(
{ ...baseMeta, reviewLoopReviewers: ['copilot'] },
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 8bc3742891..6f4270dadb 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -131,6 +131,9 @@ describe('claim reviewer resolution', () => {
expect(pinned).toContain('run-local-code-review.mjs');
expect(pinned).not.toContain('localhost:5555');
expect(pinned).toContain('missing/empty findings is INCONCLUSIVE');
+ expect(pinned).toContain('REVIEW_STATUS=review-blocked');
+ expect(pinned).toContain('continue to publish the MR/PR');
+ expect(pinned).toContain('leave it open and do not merge until the required review completes');
const bare = buildLocalReviewerInstructions(['lmstudio']);
expect(bare).toContain('git diff "origin/$DEFAULT_BRANCH...HEAD"');
diff --git a/server/services/cosTaskPrompts.js b/server/services/cosTaskPrompts.js
index dfdec79752..9ca16e48b0 100644
--- a/server/services/cosTaskPrompts.js
+++ b/server/services/cosTaskPrompts.js
@@ -128,5 +128,5 @@ export function buildLocalReviewerInstructions(reviewers, reviewerModels = {}, r
return `### ${reviewer}\n\n\`\`\`bash\nREVIEW_DIFF=$(mktemp)\nREVIEW_RESPONSE=$(mktemp)\ntrap 'rm -f "$REVIEW_DIFF" "$REVIEW_RESPONSE" "\${REVIEW_RESPONSE}.findings"' EXIT\nif ! { ${diffCommand}; } > "$REVIEW_DIFF"; then\n echo "Unable to resolve the current branch's review diff" >&2\n exit 1\nfi\njq -Rs ${jqArgs} '{ ${jqObject}, diff: . }' < "$REVIEW_DIFF" | node ${reviewScript} > "$REVIEW_RESPONSE"\nif ! jq -er '.findings | select(type == "string" and length > 0)' "$REVIEW_RESPONSE" > "\${REVIEW_RESPONSE}.findings"; then\n echo "Local reviewer failed: $(jq -r '.error // "missing .findings in reviewer response"' "$REVIEW_RESPONSE")" >&2\n exit 1\nfi\ncat "\${REVIEW_RESPONSE}.findings"\n\`\`\``;
}).join('\n\n');
- return `\n\n## Local Reviewer Procedure\n\nRun each configured local reviewer in its listed order using the command below. Only a successfully extracted non-empty \`.findings\` string is a review result. Timeout, transport failure, malformed JSON, an error response, or missing/empty findings is INCONCLUSIVE: do not merge or substitute a self-review.\n\n${commands}`;
+ return `\n\n## Local Reviewer Procedure\n\nRun each configured local reviewer in its listed order using the command below. Only a successfully extracted non-empty \`.findings\` string is a review result. Timeout, transport failure, malformed JSON, an error response, or missing/empty findings is INCONCLUSIVE: do not substitute a self-review. For a required local reviewer, record \`REVIEW_STATUS=review-blocked\`, continue to publish the MR/PR, then leave it open and do not merge until the required review completes; an optional inconclusive result remains non-blocking. Substantive findings, failed tests/build, unpushed fixes, or publication failures still block.\n\n${commands}`;
}
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index c49b8e2056..e00dd42ff2 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -287,6 +287,8 @@ export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath =
'## 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.',
'',
+ '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, post a comment saying it is intentionally left open and will not be merged until the required review completes, preserve the claim markers and branch, and stop before merge. A substantive rejection, failed build/test, unpushed fix, or state/publication failure still blocks publication.',
+ '',
'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) {
@@ -368,7 +370,7 @@ function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW
? '`clean`, `partial` (a stop-mode short-circuit you opted into), or `too-large`'
: '`clean` (or `too-large`)';
const lines = [
- `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged; any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, or \`guardrail\`; leave the PR open for human follow-up.`,
+ `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged; any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, \`review-blocked\`, or \`guardrail\`; leave the PR open for human follow-up.`,
' ```bash',
' gh pr merge "<PR_URL>" --merge --delete-branch',
' ```',
@@ -432,7 +434,7 @@ function localReviewCompletionInstruction(localReviewRequired = true) {
if (!localReviewRequired) {
return 'Complete the **Local Review Before Opening the PR/MR** section below. All local reviewers are optional, so missing/inconclusive results (including skipped, timeout, malformed, or no-verdict) may continue. Set aggregate `LOCAL_OVERALL_STATUS=clean` for clean, configured capped, or optional inconclusive; use `partial` only for a qualifying stop, never raw statuses. Hard errors, failed build/test, rejection, or unpushed fixes block. Still run each reviewer and fix its findings.';
}
- return 'Complete the **Local Review Before Opening the PR/MR** section below. Commit its fixes. A missing/timed-out/malformed/inconclusive REQUIRED review blocks publication; an OPTIONAL inconclusive result may continue. Set aggregate `LOCAL_OVERALL_STATUS=clean` for clean, configured capped, or optional inconclusive; use `partial` only for a qualifying stop, never raw statuses. Hard errors, failed build/test, rejection, or unpushed fixes block.';
+ return 'Complete the **Local Review Before Opening the PR/MR** section below. Commit its fixes. A missing/timed-out/quota/provider/transport-failed/malformed/inconclusive REQUIRED review blocks merging, not publication: record aggregate `LOCAL_OVERALL_STATUS=review-blocked`, do not self-review, continue to publish the PR/MR, and leave it open with the required pending-review comment. An OPTIONAL inconclusive result may continue. Set aggregate `LOCAL_OVERALL_STATUS=clean` for clean, configured capped, or optional inconclusive; use `partial` only for a qualifying stop, never raw statuses. A substantive rejection, failed build/test, unpushed fix, or state/publication failure blocks publication.';
}
/**
@@ -468,6 +470,9 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE
const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + mergeArg;
const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0;
const reviewerListLabel = [...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ');
+ const requiredLocalReviewBlockedNote = willOpenPR && runsReviewLoop && localReviewRequired
+ ? ' If a required local reviewer cannot return a verdict because of a quota/provider or transport failure, timeout, malformed/empty response, or no-verdict result, treat the local phase as `review-blocked`: `/do:pr` must still open the PR, post the pending-review comment, and skip its merge.'
+ : '';
// Ordering matters to the agent: `/do:pr` partitions the list and runs every
// local reviewer BEFORE it creates the PR, so the PR opens against an
// already-review-clean branch and only the cloud-side reviewers (Copilot,
@@ -475,8 +480,8 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE
// agents expecting — and sometimes hand-rolling — a post-PR local pass.
const reviewSuffix = willOpenPR && runsReviewLoop
? (copilotOnly
- ? ' — `/do:pr` runs the Copilot review loop after the PR opens.'
- : ` — \`/do:pr\` runs the review loop for ${reviewerListLabel} in order: local reviewers before it opens the PR, then the PR-side reviewers (Copilot / \`@login\`) once it is open.`)
+ ? ` — \`/do:pr\` runs the Copilot review loop after the PR opens.${requiredLocalReviewBlockedNote}`
+ : ` — \`/do:pr\` runs the review loop for ${reviewerListLabel} in order: local reviewers before it opens the PR, then the PR-side reviewers (Copilot / \`@login\`) once it is open.${requiredLocalReviewBlockedNote}`)
: (willOpenPR ? ' — external review is disabled for this task.' : '');
// Reached only for a Claude TUI (a non-Claude one took the slashdoFree branch
// above), so `/simplify` — a Claude Code built-in — is invokable here.
@@ -541,6 +546,7 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'
const hasBaseBranch = typeof baseBranch === 'string' && baseBranch && baseBranch !== '<base-branch>';
const base = hasBaseBranch ? promptRef(baseBranch, '<base-branch>') : '"$BASE_BRANCH"';
const gitlab = forgeCli === 'glab';
+ const reviewBlockedComment = 'Required code review was not completed before publication. This PR/MR is intentionally left open and will not be merged until the required review completes.';
return [
`${step}. Publish the branch and open the pull request yourself, capturing its URL and number:`,
'',
@@ -562,7 +568,7 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'
' LOCAL_PRE_REBASE_REMOTE_SHA=$(grep -m1 "^LOCAL_PRE_REBASE_REMOTE_SHA=" "$LOCAL_REVIEW_BASELINE_FILE" | cut -d= -f2-)',
' if [ -z "$LOCAL_PRE_REBASE_REMOTE" ] || [ -z "$LOCAL_PRE_REBASE_HEAD_SHA" ]; then echo "Local review publication baseline is invalid; refusing to publish" >&2; exit 1; fi',
' CURRENT_HEAD_SHA=$(git rev-parse HEAD)',
- ' case "$LOCAL_OVERALL_STATUS" in clean|partial) ;; *) echo "Local review did not finish with an acceptable status; refusing to publish" >&2; exit 1 ;; esac',
+ ' case "$LOCAL_OVERALL_STATUS" in clean|partial|review-blocked) ;; *) echo "Local review did not finish with an acceptable status; refusing to publish" >&2; exit 1 ;; esac',
' if [ "$LOCAL_REVIEWED_HEAD_SHA" != "$CURRENT_HEAD_SHA" ]; then echo "Local review covered $LOCAL_REVIEWED_HEAD_SHA, but HEAD is $CURRENT_HEAD_SHA; refusing to publish an unreviewed branch" >&2; exit 1; fi',
] : []),
` BRANCH=${branch}`,
@@ -605,6 +611,14 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'
gitlab
? ' PR_NUMBER=$(glab mr view "$PR_URL" --output json | jq -r .iid)'
: ' PR_NUMBER=$(gh pr view "$PR_URL" --json number -q .number)',
+ ...(localReviewStateRequired ? [
+ ' if [ "$LOCAL_OVERALL_STATUS" = "review-blocked" ]; then',
+ ` REVIEW_BLOCKED_COMMENT="${reviewBlockedComment}"`,
+ gitlab
+ ? ' if ! glab mr note "$PR_NUMBER" --message "$REVIEW_BLOCKED_COMMENT"; then echo "Unable to post the required review-blocked MR note" >&2; exit 1; fi'
+ : ' if ! gh pr comment "$PR_URL" --body "$REVIEW_BLOCKED_COMMENT"; then echo "Unable to post the required review-blocked PR comment" >&2; exit 1; fi',
+ ' fi',
+ ] : []),
' ```',
// `--fill` on a one-line commit produces an empty description; PortOS used
// to generate the body server-side, so spell out what it must contain now
@@ -615,6 +629,9 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'
gitlab
? ' The GitLab MR URL and IID are captured in `$PR_URL` and `$PR_NUMBER`; use those variables for every review, merge, and verification command below.'
: ` On a GitLab remote use \`glab mr create --source-branch ${branch} --target-branch ${base} --title "…" --description "…"\` and read the MR URL/IID back with \`glab mr view\`.`,
+ ...(localReviewStateRequired ? [
+ ' If `LOCAL_OVERALL_STATUS=review-blocked`, the comment above is mandatory; the following Merge Gate must leave the PR/MR open and must not merge it.',
+ ] : []),
];
}
@@ -671,7 +688,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET
lines.push('', localReviewSection, '');
}
lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch, forgeCli, localReviewStateRequired: Boolean(localReviewSection) }));
- lines.push(`${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR. Come back here when it is done.`);
+ lines.push(`${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it merges the PR when eligible, but a review-blocked required review leaves it open. Come back here when it is done.`);
} else if (willOpenPR) {
const handoff = policyLeavesOpen
? 'PortOS will push the branch, create a pull request with your completion summary as its description, and leave it open for inspection.'
@@ -745,7 +762,7 @@ export function inlinePrLifecycleSection(task, { providerType, providerId, provi
*/
export function buildInlineReviewLoopSection({
taskId, branchName, runsReviewLoop, leaveOpen, localAgentLoopBody, localAgentLoopBodyPath = null, writesSentinel = false,
- reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, localPhaseReviewers = [], localPhaseCanShortCircuit = false, reviewerPositions = [], forgeCli = 'gh', workflowStep,
+ reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies, localPhaseReviewers = [], localPhaseCanShortCircuit = false, localPhaseReviewRequired = false, reviewerPositions = [], forgeCli = 'gh', workflowStep,
}) {
// Where control goes after the merge. A TUI run still owes PortOS its
// `.agent-done` sentinel — telling it to "exit" here is how a finished merge
@@ -770,7 +787,7 @@ export function buildInlineReviewLoopSection({
// exactly as the merge-only follow-up gets.
reviewLoopMergeOnly: !runsReviewLoop,
sourceTaskId: taskId || 'unknown',
- }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli, inlineWorkflowStep: workflowStep, localPhaseReviewers, localPhaseCanShortCircuit, reviewerPositions });
+ }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep, forgeCli, inlineWorkflowStep: workflowStep, localPhaseReviewers, localPhaseCanShortCircuit, localPhaseReviewRequired, reviewerPositions });
}
/**
@@ -801,7 +818,11 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti
? 'and drives the Copilot review loop until clean.'
: `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`)
: 'with external review disabled.';
+ const requiredLocalReviewBlockedNote = willOpenPR && runsReviewLoop && localReviewRequired
+ ? ' A required local reviewer that cannot return a verdict is `review-blocked`: still open the PR, post the pending-review comment, and do not merge it.'
+ : '';
lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);
+ if (requiredLocalReviewBlockedNote) lines.push(` ${requiredLocalReviewBlockedNote.trim()}`);
// Empty whenever the emitted `--review-with` already carries `~effort=<level>`
// (see buildReviewerEffortNote) — this speaks only for an unpinned invocation.
if (effortNote) lines.push(` ${effortNote}`);
@@ -847,7 +868,7 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti
forgeCli,
localReviewStateRequired: Boolean(localReviewSection),
}));
- lines.push(`${step}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR.`);
+ lines.push(`${step}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it merges the PR when eligible, but a review-blocked required review leaves it open.`);
return lines.join('\n');
}
let body;
diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.js
index 90441c9ee3..c235c19cd2 100644
--- a/server/services/promptSections/reviewLifecycle.js
+++ b/server/services/promptSections/reviewLifecycle.js
@@ -26,20 +26,21 @@ export function isMergeOnlyFollowUp(metadata = {}) {
* Adapt slashdo's local-agent recipe for the pre-PR half of a manual workflow.
* The normal recipe pushes after each reviewer pass so a later PR-side reviewer
* sees the fixes. A local-only section must keep every fix on the branch until
- * all local reviewers finish; the outer completion workflow performs the one
- * push after that gate.
+ * all local reviewers finish (or records an unavailable required review as
+ * `review-blocked`); the outer completion workflow performs the one push after
+ * that gate.
*/
export function prepareLocalReviewLoopBody(body) {
if (typeof body !== 'string' || !body) return body;
const withoutPushStep = body.replace(
/\r?\n[ \t]*5\. \*\*Push verified changes\*\*:[\s\S]*?(?=\r?\n[ \t]*6\. \*\*Re-loop or stop\*\*:)/,
- '\n5. **Keep verified changes local**:\n Skip the push step here. The outer Completion Workflow pushes the branch only after every local reviewer is clean.\n',
+ '\n5. **Keep verified changes local**:\n Skip the push step here. The outer Completion Workflow pushes the branch only after the local review phase completes.\n',
);
// Keep a future recipe revision fail-safe if it moves the push command out of
// the numbered step that the replacement above recognizes.
return withoutPushStep.replace(
/^[ \t]*(?:git pull --rebase --autostash && )?git push\b[^\r\n]*\r?$/gm,
- ' # Push is deferred until every local reviewer is clean.',
+ ' # Push is deferred until the local review phase completes.',
);
}
@@ -49,6 +50,10 @@ function remoteReviewBaseRef(baseBranch) {
return `origin/${baseBranch}`;
}
+function localReviewBlockedMergeGuard(handoff = 'follow the enclosing completion handoff without claiming a merge') {
+ return `**Required local-review merge gate:** Before any CI-fix or merge action, load the worktree-private local review state with \`LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"\`, fail closed if it is missing, and source it. If \`LOCAL_OVERALL_STATUS=review-blocked\`, do NOT run this merge path; the PR/MR was already published and the required comment was posted, so leave it open, report that the required review is pending, and ${handoff}. Accept only \`clean\` or \`partial\`; any other or missing status, or a \`LOCAL_REVIEWED_HEAD_SHA\` that does not equal \`$(git rev-parse HEAD)\`, fails closed.`;
+}
+
/**
* Build the **review-loop follow-up** section — the instructions for the
* agent spawned by `spawnReviewLoopFollowUp` to drive Copilot's review-and-fix
@@ -96,9 +101,12 @@ function remoteReviewBaseRef(baseBranch) {
* pre-PR local phase before this inline PR-side phase.
* @param {boolean} [opts.localPhaseCanShortCircuit=false] - Whether the local
* phase is allowed to satisfy the configured stop mode for this phase too.
+ * @param {boolean} [opts.localPhaseReviewRequired=false] - Whether the local
+ * phase contains a required reviewer whose unavailable result blocks merging
+ * but still permits publication.
* @returns {string}
*/
-export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null, localOnly = false, baseBranch = '<base-branch>', reviewerPositions = [], inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localPhaseReviewers = [], localPhaseCanShortCircuit = false } = {}) {
+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null, forgeCli = null, localOnly = false, baseBranch = '<base-branch>', reviewerPositions = [], inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localPhaseReviewers = [], localPhaseCanShortCircuit = false, localPhaseReviewRequired = false } = {}) {
// One parameter, not two: an `inline` boolean alongside it could disagree with
// it, and the disagreement renders silently — `inline` with a blank exit step
// emits a bare "6." and a truncated merge-gate hand-back.
@@ -129,7 +137,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
return buildMergeFollowUpSection({
prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,
prHost: metadata.reviewLoopPRHost ?? '',
- forgeCli: reviewForgeCli, inlineWorkflowStep, localReviewers: localPhaseReviewerList,
+ forgeCli: reviewForgeCli, inlineWorkflowStep, localReviewers: localPhaseReviewerList, localReviewRequired: localPhaseReviewRequired,
});
}
// Arbitrary GitHub reviewer usernames (gate-only PR reviewers), appended to
@@ -244,15 +252,20 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
const isOptionalReviewer = reviewer => optionalReviewers.some(optional => optional.toLowerCase() === reviewer.toLowerCase());
const requiredCliBinaries = cliBinaries.filter(reviewer => !isOptionalReviewer(reviewer.slug));
const optionalCliBinaries = cliBinaries.filter(reviewer => isOptionalReviewer(reviewer.slug));
- // A required reviewer that cannot run is NOT a clean review. Optional
- // reviewers have an explicit non-blocking contract for an inconclusive
- // precondition such as a missing binary, but that does not authorize a
- // self-review substitution.
+ // A required reviewer that cannot run is not a clean review. In a pre-PR
+ // phase it is recorded as review-blocked so publication can preserve the
+ // branch for the unavailable review while the merge gate remains fail-closed.
+ // Optional reviewers have an explicit non-blocking contract for an
+ // inconclusive precondition such as a missing binary, but that does not
+ // authorize a self-review substitution.
+ const requiredLocalReviewNote = localOnly && localPhaseReviewRequired
+ ? '**Required local-review availability:** if a required local reviewer cannot produce a verdict because its CLI/provider is unavailable, a quota or spend limit is exhausted, or the invocation times out, has a transport failure, returns malformed/empty output, or produces no verdict, record `LOCAL_OVERALL_STATUS=review-blocked`. Do NOT substitute a self-review. This permits the later publication step, but the PR/MR must remain open and unmerged until the required review completes. A substantive rejection, failed build/test, unpushed fix, or state/publication failure still blocks publication.'
+ : '';
const missingCliNote = hasCli
? [
`**Missing reviewer CLI:** verify each configured binary is on PATH (${cliBinaries.map(c => `\`command -v ${c.binary}\``).join(' / ')}) before concluding it is unavailable.`,
requiredCliBinaries.length
- ? `If a required reviewer binary is genuinely missing (${requiredCliBinaries.map(c => `\`${c.binary}\``).join(' / ')}), that reviewer is UNSATISFIED — do NOT substitute your own self-review and do NOT ${localOnly ? 'push or open a PR/MR' : 'merge'}. ${localOnly ? 'Exit without opening the PR/MR.' : 'Post a PR comment naming the missing command and exit.'}`
+ ? `If a required reviewer binary is genuinely missing (${requiredCliBinaries.map(c => `\`${c.binary}\``).join(' / ')}), that reviewer is UNSATISFIED — ${localOnly ? 'do NOT substitute your own self-review. Record `LOCAL_OVERALL_STATUS=review-blocked`, continue to the PR/MR publication step, and leave the PR/MR unmerged until the reviewer is available.' : 'do NOT substitute your own self-review and do NOT merge; post a PR comment naming the missing command and exit.'}`
: '',
optionalCliBinaries.length
? `A missing optional reviewer binary (${optionalCliBinaries.map(c => `\`${c.binary}\``).join(' / ')}) is an inconclusive optional result and does not block ${localOnly ? 'the push or PR/MR creation' : 'the merge'}; record it and continue without substituting a self-review.`
@@ -277,7 +290,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
...usernames.filter(username => isOptionalReviewer(`@${username}`)).map(username => `\`@${username}\``),
];
const optionalReviewNote = optionalConfiguredReviewers.length
- ? `**Optional reviewers (~opt):** ${optionalConfiguredReviewers.join(', ')} still run and their findings must still be fixed, but a timeout, skipped/incomplete pass, or missing/malformed/no-verdict result from one of them is non-blocking. A hard reviewer error, failed build/test, rejection, or push failure still blocks.`
+ ? `**Optional reviewers (~opt):** ${optionalConfiguredReviewers.join(', ')} still run and their findings must still be fixed, but a timeout, skipped/incomplete pass, or missing/malformed/no-verdict result from one of them is non-blocking; provider/transport failure from one of them is also non-blocking. A substantive rejection, failed build/test, or push failure still blocks.`
: '';
const equivArgs = buildReviewWithArgs(reviewers, { stopMode, reviewerApplies, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels: reviewerModelMap });
const equiv = equivArgs ? ` (equivalent to \`/do:pr ${equivArgs}\`)` : '';
@@ -422,7 +435,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
crossPhaseOrderingAllowsSkip
? '`on-findings` skips the PR-side reviewers only when the local phase actually satisfied that stop condition: `LOCAL_OVERALL_STATUS=partial` from a stop-mode short-circuit, or `LOCAL_OVERALL_STATUS=clean` with `LOCAL_STOP_REVIEW_COMMITS>0` and `LOCAL_STOP_TRIGGERED=true`.'
: '`on-findings` always runs every PR-side reviewer here because cross-phase skipping is disabled for this order.',
- 'An inconclusive or dirty local result does not satisfy a stop condition; a required local result still blocks the PR workflow, while an optional inconclusive result may continue but must never trigger this skip.',
+ 'An inconclusive or dirty local result does not satisfy a stop condition; a required unavailable local result is `review-blocked` (it permits publication but blocks merging), while an optional inconclusive result may continue but must never trigger this skip.',
crossPhaseOrderingAllowsSkip
? 'When the local phase satisfies the stop condition, skip the PR-side phase and record the configured stop-mode short-circuit as `partial`; otherwise run this PR-side list normally. If the stop index or triggering reviewer commit count is missing or invalid, run every PR-side reviewer.'
: 'Even when the local phase satisfies the stop condition, run every PR-side reviewer in this phase, then record the configured stop-mode result; do not skip reviewers across an interleaved phase boundary.',
@@ -492,9 +505,9 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
? '**Rebase conflict gate:** resolve routine conflicts and finish the rebase in this agent session. If a conflict genuinely cannot be resolved safely, run `git rebase --abort 2>/dev/null || true` and stop; never publish a conflicted or half-rebased worktree.'
: '';
const localStatePersistenceNote = localOnly
- ? '**State persistence:** shell calls do not share variables. Reload state before each reviewer, preserve it while persisting `LOCAL_REVIEWER_START_SHA`; reload before commit/stop calculations and the final aggregate. Any read/write failure blocks publication.'
+ ? '**State persistence:** shell calls do not share variables. Reload state before each reviewer, preserve it while persisting `LOCAL_REVIEWER_START_SHA`; reload before commit/stop calculations and the final aggregate. Any read/write failure blocks publication; only an explicitly recorded `review-blocked` reviewer-availability result may proceed to publication.'
: '';
- const extraNotes = [reviewScopeNote, crossPhaseStopModeNote, stopModeNote, applyNote, maxRoundsNote, missingCliNote, optionalReviewNote, localRebaseConflictNote, localStatePersistenceNote].filter(Boolean);
+ const extraNotes = [reviewScopeNote, crossPhaseStopModeNote, stopModeNote, applyNote, maxRoundsNote, missingCliNote, requiredLocalReviewNote, optionalReviewNote, localRebaseConflictNote, localStatePersistenceNote].filter(Boolean);
// Inline slashdo's local-agent review loop when a spawnable CLI reviewer is
// configured. This is the maintained, precise recipe — exact per-CLI headless
@@ -518,7 +531,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
// already carrying the real task, and pasting 40KB of reviewer recipe up front
// to be read at step 4 is the wrong place to spend that context.
const localOnlyProcedureNote = localOnly
- ? '**Pre-PR rule:** keep reviewer fixes committed locally. Do NOT push or open a PR/MR here; the outer workflow publishes after local review.\n\n'
+ ? '**Pre-PR rule:** keep reviewer fixes committed locally. Do NOT push or open a PR/MR here; the outer workflow publishes after the local review phase completes.\n\n'
: '';
const cliProcedureHeader = `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\n${localOnlyProcedureNote}Drive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop specifies — use its per-CLI invocation and review-only prompt contract verbatim; do NOT probe the CLI's \`--help\`, test it with throwaway prompts, or hand-roll flags. Run the reviewer once per round, capture its findings, and (unless reviewer-applies is set) apply the fixes yourself.\n\n`;
//
@@ -549,9 +562,12 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
const localStopIndexNote = reviewerPositionLabel
? ` The configured reviewer positions are zero-based: ${reviewerPositionLabel}. When a qualifying verdict triggers the configured stop condition, set \`LOCAL_STOP_TRIGGERED=true\` and \`LOCAL_STOP_INDEX\` to that triggering local reviewer's position; when the list exhausts without a qualifying stop or a result is inconclusive, set \`LOCAL_STOP_TRIGGERED=false\` and \`LOCAL_STOP_INDEX=-1\`.`
: ' Set `LOCAL_STOP_INDEX=-1` whenever no qualifying stop condition fired.';
+ const localReviewMergeGuard = !localOnly && inline && localPhaseReviewRequired && localPhaseReviewerList.length
+ ? localReviewBlockedMergeGuard('return to the enclosing completion handoff (write the sentinel for a TUI run or exit for a CLI run) without claiming a merge')
+ : '';
const closingSteps = localOnly
? [
- `4. When the local reviewer list is exhausted (or the stop mode triggers), record \`LOCAL_OVERALL_STATUS\`. Set \`LOCAL_STOP_TRIGGERED=true\` when the configured stop condition actually fired on a qualifying verdict, including when that verdict came from the final local reviewer; set it false only for list exhaustion without a qualifying stop or for an inconclusive result.${localStopIndexNote} Compute \`LOCAL_PHASE_COMMITS=$(git rev-list "$LOCAL_PHASE_START_SHA..HEAD" --count)\`; if a qualifying stop fired, retain the triggering reviewer's \`LOCAL_REVIEWER_COMMITS\` as \`LOCAL_STOP_REVIEW_COMMITS\`, otherwise set \`LOCAL_STOP_REVIEW_COMMITS=-1\`. Record \`LOCAL_REVIEWED_HEAD_SHA=$(git rev-parse HEAD)\`. Persist all phase state for later shell calls in the worktree-private Git state file: \`LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"\`; then run \`printf 'LOCAL_PHASE_START_SHA=%s\\nLOCAL_OVERALL_STATUS=%s\\nLOCAL_STOP_TRIGGERED=%s\\nLOCAL_STOP_INDEX=%s\\nLOCAL_STOP_REVIEW_COMMITS=%s\\nLOCAL_PHASE_COMMITS=%s\\nLOCAL_REVIEWED_HEAD_SHA=%s\\n' "$LOCAL_PHASE_START_SHA" "$LOCAL_OVERALL_STATUS" "$LOCAL_STOP_TRIGGERED" "$LOCAL_STOP_INDEX" "$LOCAL_STOP_REVIEW_COMMITS" "$LOCAL_PHASE_COMMITS" "$LOCAL_REVIEWED_HEAD_SHA" > "$LOCAL_REVIEW_STATE_FILE"\`. If that write fails, do NOT push or open the PR/MR. For a final-reviewer stop, follow the same phase-level gate below: \`on-clean\` requires \`LOCAL_OVERALL_STATUS=clean\` with \`LOCAL_STOP_REVIEW_COMMITS=0\`, while \`on-findings\` requires \`LOCAL_OVERALL_STATUS=clean\` with \`LOCAL_STOP_REVIEW_COMMITS>0\`; a \`partial\` status is already a qualifying stop. Return to the Completion Workflow and continue with the push and PR/MR creation step when all executed required reviewers are clean and optional reviewers are clean or inconclusive, or when \`LOCAL_OVERALL_STATUS=partial\` records a qualifying configured stop-mode short-circuit that intentionally skipped later reviewers. Do NOT push or open the PR/MR before this local phase is complete.`,
+ `4. When the local reviewer list is exhausted (or the stop mode triggers), record \`LOCAL_OVERALL_STATUS\`: use \`review-blocked\` only when a required reviewer could not produce a verdict because of an availability, quota/provider, timeout, transport, malformed, empty, or no-verdict failure; never use it for substantive findings, failed tests/build, unpushed fixes, or state/publication failures, and do not self-review. Set \`LOCAL_STOP_TRIGGERED=true\` when the configured stop condition actually fired on a qualifying verdict, including when that verdict came from the final local reviewer; set it false for list exhaustion, an inconclusive result, or \`review-blocked\`.${localStopIndexNote} Compute \`LOCAL_PHASE_COMMITS=$(git rev-list "$LOCAL_PHASE_START_SHA..HEAD" --count)\`; if a qualifying stop fired, retain the triggering reviewer's \`LOCAL_REVIEWER_COMMITS\` as \`LOCAL_STOP_REVIEW_COMMITS\`, otherwise set \`LOCAL_STOP_REVIEW_COMMITS=-1\`. Record \`LOCAL_REVIEWED_HEAD_SHA=$(git rev-parse HEAD)\`. Persist all phase state for later shell calls in the worktree-private Git state file: \`LOCAL_REVIEW_STATE_FILE="$(git rev-parse --git-path portos-local-review-state)"\`; then run \`printf 'LOCAL_PHASE_START_SHA=%s\\nLOCAL_OVERALL_STATUS=%s\\nLOCAL_STOP_TRIGGERED=%s\\nLOCAL_STOP_INDEX=%s\\nLOCAL_STOP_REVIEW_COMMITS=%s\\nLOCAL_PHASE_COMMITS=%s\\nLOCAL_REVIEWED_HEAD_SHA=%s\\n' "$LOCAL_PHASE_START_SHA" "$LOCAL_OVERALL_STATUS" "$LOCAL_STOP_TRIGGERED" "$LOCAL_STOP_INDEX" "$LOCAL_STOP_REVIEW_COMMITS" "$LOCAL_PHASE_COMMITS" "$LOCAL_REVIEWED_HEAD_SHA" > "$LOCAL_REVIEW_STATE_FILE"\`. A \`review-blocked\` state is a completed local phase that permits publication but blocks the merge gate; the publication step posts the required comment. If that write fails, do NOT push or open the PR/MR. For a final-reviewer stop, follow the same phase-level gate below: \`on-clean\` requires \`LOCAL_OVERALL_STATUS=clean\` with \`LOCAL_STOP_REVIEW_COMMITS=0\`, while \`on-findings\` requires \`LOCAL_OVERALL_STATUS=clean\` with \`LOCAL_STOP_REVIEW_COMMITS>0\`; a \`partial\` status is already a qualifying stop. Return to the Completion Workflow and continue with the push and PR/MR creation step when all executed required reviewers are clean and optional reviewers are clean or inconclusive, when \`LOCAL_OVERALL_STATUS=partial\` records a qualifying configured stop-mode short-circuit, or when \`LOCAL_OVERALL_STATUS=review-blocked\` records only reviewer unavailability. Do NOT push or open the PR/MR before this local phase is complete.`,
]
: leaveOpen
? [
@@ -561,6 +577,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l
exitStep,
]
: [
+ localReviewMergeGuard,
`4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):`,
' ```bash',
reviewForgeCli === 'glab'
@@ -624,9 +641,14 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
const loopCompletionText = optionalConfiguredReviewers.length
? 'all required reviewers are satisfied and optional reviewers are satisfied or explicitly inconclusive (or the stop mode triggers)'
: 'all configured reviewers are satisfied (or the stop mode triggers)';
+ const localHardStopText = localOnly && localPhaseReviewRequired
+ ? 'do NOT push or open a PR/MR when substantive findings remain or fixes leave the build/tests red; if the only failure is reviewer unavailability, record `review-blocked`, publish the PR/MR, and leave it unmerged'
+ : localOnly
+ ? 'do NOT push or open a PR/MR; report the unresolved blocker and exit'
+ : 'post a PR comment summarising blockers and exit';
const hardStopNote = optionalConfiguredReviewers.length
- ? `**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, ${localOnly ? 'do NOT push or open a PR/MR; report the unresolved blocker and exit.' : 'post a PR comment summarising blockers and exit.'} An optional reviewer may end with an inconclusive result without blocking, but a hard error, failed build/test, rejection, or push failure still blocks.`
- : `**Hard stop:** if a reviewer's loop is not converged after 10 rounds, ${localOnly ? 'do NOT push or open a PR/MR; report the unresolved blocker and exit.' : 'post a PR comment summarising blockers and exit.'}`;
+ ? `**Hard stop:** if a required reviewer's loop is not converged after 10 rounds, ${localHardStopText}. An optional reviewer may end with an inconclusive result without blocking, but a substantive rejection, failed build/test, or push failure still blocks.`
+ : `**Hard stop:** if a reviewer's loop is not converged after 10 rounds, ${localHardStopText}.`;
return [
heading,
compactOpening,
@@ -658,6 +680,9 @@ export function buildLocalReviewLoopSection({
}) {
const localReviewers = (reviewers || []).filter(reviewer => isCliReviewer(reviewer) || LOCAL_LLM_REVIEWERS.includes(reviewer));
if (!localReviewers.length) return '';
+ const localReviewRequired = localReviewers.some(reviewer =>
+ !(Array.isArray(optionalReviewers) && optionalReviewers.some(optional => optional.toLowerCase() === reviewer.toLowerCase()))
+ );
return buildReviewLoopFollowUpSection({
reviewLoopPRBranch: branchName || '<branch>',
reviewLoopReviewers: localReviewers,
@@ -668,7 +693,7 @@ export function buildLocalReviewLoopSection({
reviewLoopStopMode: reviewStopMode,
reviewLoopReviewerApplies: reviewerApplies,
sourceTaskId: taskId || 'unknown',
- }, { localAgentLoopBody, localAgentLoopBodyPath, localOnly: true, baseBranch, reviewerPositions });
+ }, { localAgentLoopBody, localAgentLoopBodyPath, localOnly: true, baseBranch, reviewerPositions, localPhaseReviewRequired: localReviewRequired });
}
/**
@@ -711,7 +736,7 @@ export const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Lea
* workflow, which runs before the PR exists) emits both, commented.
* @returns {{lines: string[], nextStep: number}}
*/
-export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)', localReviewers = [] }) {
+export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)', localReviewers = [], localReviewRequired = false }) {
const gh = forge !== 'gitlab';
const glab = forge !== 'github';
const both = gh && glab;
@@ -721,6 +746,9 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
const localReviewAfterCodeFix = localReviewNames
? ` If a CI fix changes code, repeat the pre-PR local review phase for ${localReviewNames} against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any reviewer fixes before pushing or merging.`
: '';
+ const localReviewMergeGuard = localReviewRequired && localReviewNames
+ ? localReviewBlockedMergeGuard()
+ : '';
const localReviewRecheck = localReviewNames
? ` After that rebase, repeat the pre-PR local review phase for ${localReviewNames} against the new HEAD, using its same required/optional and stop-mode rules; commit and verify any fixes before pushing or merging.`
: '';
@@ -734,6 +762,7 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
? `\`gh pr view ${prRef} --json state -q .state\` must return \`MERGED\`${glab ? ' (GitLab: `glab mr view ' + mrRef + '` must show it merged)' : ''}`
: `\`glab mr view ${mrRef}\` must show it merged`;
const lines = [
+ localReviewMergeGuard || null,
localReviewAfterCodeFix ? `**Code-changing CI fix gate:**${localReviewAfterCodeFix}` : null,
`${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,
`${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent,${localReviewRecheck} re-run the tests, \`git push --force-with-lease\`, and re-check.`,
@@ -760,11 +789,11 @@ export function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>',
* @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.
* @returns {string}
*/
-function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null, inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localReviewers = [] }) {
+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null, forgeCli = null, inlineWorkflowStep = INLINE_REVIEW_LOOP_STEP, localReviewers = [], localReviewRequired = false }) {
const inline = inlineExitStep !== null;
const hasLocalReview = Array.isArray(localReviewers) && localReviewers.length > 0;
const localReviewLabel = hasLocalReview
- ? `The pre-PR local review for ${localReviewers.map(reviewer => `\`${reviewer}\``).join(', ')} has completed; no PR-side code reviewer is configured. The merge gate still re-runs that local review after any conflict rebase.`
+ ? `The pre-PR local review for ${localReviewers.map(reviewer => `\`${reviewer}\``).join(', ')} has completed; no PR-side code reviewer is configured. The merge gate still re-runs that local review after any conflict rebase${localReviewRequired ? '; a `review-blocked` result leaves the PR/MR open until the required review completes' : ''}.`
: 'No code review was requested for this task, so nothing else will merge this PR';
// PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed
// `gh` commands (the host is persisted by spawnReviewLoopFollowUp). Classify
@@ -782,6 +811,7 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '
? (normalizeForgeCli(forgeCli) === 'glab' ? 'gitlab' : 'github')
: (detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github'),
localReviewers,
+ localReviewRequired,
// An inline run reached this gate through plain `git`/`gh` — it never ran
// `/do:pr`, so a saved slashdo merge default can't have landed the PR for it.
alreadyMergedHint: inline ? '' : undefined,
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index 03c7188599..d111b5298b 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -378,8 +378,8 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(current).toContain('`antigravity` (CLI binary: `agy`)');
// …and a reviewer whose binary is missing must not be replaced by the
// agent's own self-review, which is what actually merged the bad PR.
- expect(current).toContain('is UNSATISFIED, not clean');
- expect(current).toContain('Do NOT substitute your own self-review');
+ expect(current).toContain('is unavailable, not clean');
+ expect(current).toContain('do NOT substitute your own self-review');
// The pre-`agy` default named only the slug; preserved verbatim so installs
// holding it are recognized and auto-upgraded. Located by CONTENT, not array
@@ -715,6 +715,25 @@ describe('taskPromptDefaults integrity snapshot', () => {
expect(PREVIOUS_DEFAULT_PROMPTS['claim-issue-gitlab'].some((prompt) => prompt.includes('It has NO assignees'))).toBe(true);
});
+ it('publishes claim work when a required local review is unavailable, but leaves it unmerged', () => {
+ const cases = [
+ ['claim-issue', 23, 'gh pr comment "$PR_URL"'],
+ ['claim-issue-gitlab', 21, 'glab mr note "$MR_IID"'],
+ ['claim-issue-jira', 16, 'This MR/PR is intentionally left open and will not be merged'],
+ ];
+
+ for (const [key, version, publicationCommand] of cases) {
+ const current = DEFAULT_TASK_PROMPTS[key];
+ expect(PROMPT_VERSIONS[key]).toBe(version);
+ expect(current).toContain('review-blocked');
+ expect(current).toContain('continue to push and open the PR/MR');
+ expect(current).toContain('intentionally left open and will not be merged until the required review completes');
+ expect(current).toContain(publicationCommand);
+ expect(PREVIOUS_DEFAULT_PROMPTS[key]).toHaveLength(version - 1);
+ expect(PREVIOUS_DEFAULT_PROMPTS[key].at(-1)).not.toBe(current);
+ }
+ });
+
// Epic decomposition. Every claim flow used to skip an epic outright ("leave
// it for a human to split"), so a tracker whose remaining work was all epics
// ended each run with nothing done and reported an empty queue. Phase 1b makes
@@ -805,12 +824,18 @@ describe('taskPromptDefaults integrity snapshot', () => {
// instead of being flagged promptCustomized and pinned to the old flow.
const previous = PREVIOUS_DEFAULT_PROMPTS[key];
expect(previous).toHaveLength(PROMPT_VERSIONS[key] - 1);
- expect(previous.at(-1)).not.toBe(current);
- for (const command of releases[key]) expect(previous.at(-1)).not.toContain(command);
+ // A later review revision now follows this contributor-label revision, so
+ // locate the outgoing body by the property this revision introduced rather
+ // than assuming it remains the final historical entry.
+ const outgoing = previous.findLast((prompt) => prompt.includes('Phase 1b')
+ && releases[key].every((command) => !prompt.includes(command)));
+ expect(outgoing).toBeDefined();
+ expect(outgoing).not.toBe(current);
// …and it is the body that ONLY lacks the release: everything else the
// outgoing version shipped (Phase 1b) is still there, which is what makes it
// the immediately-previous body rather than some older one.
- expect(previous.at(-1)).toContain('Phase 1b');
+ expect(outgoing).toContain('Phase 1b');
+ for (const command of releases[key]) expect(outgoing).not.toContain(command);
}
});
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 6f3057c2c8..6f0fa696eb 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -20,9 +20,9 @@
"feature-ideas": "804f62f1dadadbfa8a0bcd4aff16b2e8",
"plan-feature": "87f71a894757f89354da4e2119e07118",
"plan-task": "b85fe92999aa4ee4a8910320457c4242",
- "claim-issue": "9bf278ab141120625cd6faf854622f91",
- "claim-issue-gitlab": "745672581d766edff0ec585dd5b1ef5d",
- "claim-issue-jira": "1407b5095c18524f02e6bf1ff45ad967",
+ "claim-issue": "688661e7e7b0b4b5af95288dd86a23e8",
+ "claim-issue-gitlab": "42fcfae41076d73b49050015fac0ae0e",
+ "claim-issue-jira": "b14a5dde5519fda59c2ba1ae7a3d8989",
"code-reviewer-review": "27ded42013f28e7d327d8f1cc624aac1",
"code-reviewer-implement": "2e10cac7c1e1cd021d06bfddb5c1eaf2",
"error-handling": "9afba2e99b90a8d5771c75e7f0615d96",
@@ -47,9 +47,9 @@
"do-replan": 2,
"feature-ideas": 11,
"plan-task": 18,
- "claim-issue": 22,
- "claim-issue-gitlab": 20,
- "claim-issue-jira": 15,
+ "claim-issue": 23,
+ "claim-issue-gitlab": 21,
+ "claim-issue-jira": 16,
"pr-reviewer": 3,
"code-reviewer-a": 1,
"code-reviewer-b": 1,
@@ -141,7 +141,8 @@
"52fd3506aad0b283be7234b608cf31ca",
"9d782972b20d6b721eb44d0673315cad",
"c66170bfcdee911f03e60261c4f503db",
- "d5e2b6cf39c2acfebef9ee8e826a7e42"
+ "d5e2b6cf39c2acfebef9ee8e826a7e42",
+ "1407b5095c18524f02e6bf1ff45ad967"
],
"claim-issue-gitlab": [
"fae92c45c89c65455930b4b06a1b88c4",
@@ -162,7 +163,8 @@
"ed2c2c9c8cd6297340b3a92666cb2c5a",
"348ed6348b90dcc6eead03e06df049e9",
"1f9ec476dce71d04e588d17e72cd46c9",
- "b5e24d2caefba4acc6fb09f6c09f2afd"
+ "b5e24d2caefba4acc6fb09f6c09f2afd",
+ "745672581d766edff0ec585dd5b1ef5d"
],
"claim-issue": [
"37949d1b1fa8d461a15658f8f4192d97",
@@ -185,7 +187,8 @@
"a91b3df45864cf1aeaea7b326a7717ae",
"a6f069d7276c9f31fdca3b50666324e2",
"6a9bebb3f31b7c1b0a0728def0fe5b3c",
- "af99e76b4881d1a18234eff0d58d49a4"
+ "af99e76b4881d1a18234eff0d58d49a4",
+ "9bf278ab141120625cd6faf854622f91"
],
"security": [
"b199739b21a8c45ed3778b2339ebf55f",
diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.js
index 9eb25d9390..cca94b70fa 100644
--- a/server/services/taskPromptDefaults/previousDefaults.js
+++ b/server/services/taskPromptDefaults/previousDefaults.js
@@ -12273,3 +12273,7 @@ The local reviewers already ran in Phase 5, so only the reviewers that need an o
## Phase 7 — Report
Generate a short summary: the ticket KEY + summary worked, the MR/PR URL, the ticket's FINAL JIRA status (confirm it is "In Review"), reviewers run, and any status transition that failed and why.`);
+PREVIOUS_DEFAULT_PROMPTS['claim-issue-jira'].push("[Claim Issue: {appName}] Claim and ship the next ready JIRA ticket\n\nPick the next ready JIRA ticket assigned to me in the current sprint, move it to **In Progress**, **create your own worktree at `claim/<KEY>`**, implement it, open a merge/pull request that references the ticket, move the ticket to **In Review**, and clean up. This is the `/claim --issues` flow for JIRA: same self-managed worktree and no-local-merge cleanup, but the work source is the app's **JIRA** project (via the PortOS JIRA API) and the ticket *status* — not an assignee/label — is the claim. **YOU pick the ticket in Phase 1.** Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.\n\nAll PortOS API calls below are relative to this base URL: http://localhost:5555\n\n**How claiming works.** A ticket is \"in flight\" when (a) a `claim/<KEY>` or `cos/<task>/<KEY>/<agent>` ref exists across local branches, remote branches, or open MR/PR source refs, OR (b) its JIRA status is anything other than a not-started status (so \"In Progress\", \"In Review\", \"Done\", etc. are already taken). Moving the ticket to **In Progress** + the `claim/<KEY>` branch ARE the claim, visible to every other agent and to the human looking at the sprint board.\n\n## Phase 1 — Pick the target ticket\n\nRun steps 1–5 in order.\n\n1. Resolve the app's JIRA config: GET http://localhost:5555/api/apps and find the app whose `id` is `{appId}`. Read `jira.enabled`, `jira.instanceId`, and `jira.projectKey`. If `jira.enabled` is not true or either id is missing, exit cleanly — this task only works against JIRA-configured apps.\n2. Fetch my current-sprint tickets: GET http://localhost:5555/api/jira/instances/<instanceId>/my-sprint-tickets/<projectKey>. This returns the tickets assigned to me in the active sprint.\n3. Build the in-flight set from git refs:\n ```bash\n cd {repoPath}\n git fetch --prune 2>/dev/null\n git branch -a --no-color --format='%(refname:short)'\n ```\n For each ref (after stripping any leading `origin/` / `upstream/` prefix), extract the ticket KEY **only when the ref matches** `claim/<KEY>` (the segment after `claim/`) or `cos/<task>/<KEY>/<agent>` (the `<KEY>` third segment). A KEY looks like `PROJ-1234`.\n4. **Pick the target ticket:** walk the sprint tickets in TWO passes (within each pass, prefer higher priority — Blocker/Highest/High — then oldest). First pass, consider only NON-epic tickets and take the first that satisfies every rule below — atomic work always outranks an epic, whatever their relative priority. Only if that pass finds nothing do you make a second pass for an undecomposed epic (same rules), and an epic you pick goes to **Phase 1b**, not Phase 2. A single pass would enter a decomposition the moment an epic happened to outrank claimable work, which is exactly backwards. The rules:\n - Its status is a not-started status (e.g. \"To Do\", \"Open\", \"Backlog\", \"Selected for Development\", \"Ready\"). Skip tickets already \"In Progress\", \"In Review\", \"Done\", or any closed/resolved status — those are claimed or finished.\n - Its KEY is NOT in the in-flight set from step 3.\n - It has enough of a summary/description to act on. A ticket that merely leaves a design choice unstated is still eligible — you'll decide the reading in Phase 3, not skip it here. Skip only a ticket with essentially no actionable content (bare title, no description or acceptance criteria).\n - It is NOT an ALREADY-DECOMPOSED tracking **Epic**. An epic is recognized by issue type \"Epic\" or a title ending in \"(epic)\"; it counts as decomposed once it ALSO carries the `decomposed` label (the sprint fetch returns each ticket's `labels`). Skip a decomposed epic — its child slices are ordinary claimable tickets, so claiming the parent would duplicate them. An UNdecomposed epic is eligible only in the second pass above, and goes to **Phase 1b**.\n5. **If no eligible ticket exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure. **But an open, undecomposed epic is NOT an empty queue**: never report \"no work available\" while one is unclaimed. Splitting it is the work — go to Phase 1b. If a ticket is in the sprint but too vague or blocked to start, create a Review Hub todo (POST http://localhost:5555/api/review/todo with title \"[<KEY>] Needs clarification\" or \"[<KEY>] Blocked\" and a description of what's missing) instead of claiming it.\n\nCapture the ticket KEY as `KEY`, its summary, and its full description — you'll reuse them in the branch, the MR/PR, and the commit trailer.\n\n## Phase 1b — Decompose an epic (only when Phase 1 landed on one)\n\nYou reach this phase two ways: Phase 1 found no eligible atomic ticket and fell through to an undecomposed epic, or the user pinned this run to an epic. **Never end a run reporting \"nothing to do\" while an undecomposed epic is open** — turning it into shippable slices IS this round's work, and it is what refills the sprint queue for every later run.\n\nCapture the epic's key as `EPIC`. This phase writes ONLY to JIRA — no worktree, no branch, no MR/PR, no edits in the source repo. A split leaves the epic's own STATUS untouched (it is a container, not work in progress); the single exception is step 3's all-children-done branch, which is what finally closes it.\n\n1. Read it in full: GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<EPIC> — the response carries `labels`, `description`, `status`, and `issueType`.\n2. **Find the children it already has** — an epic a human (or an earlier run) already split must never be re-split: GET http://localhost:5555/api/jira/instances/<instanceId>/epics/<EPIC>/children. Union that with every `<KEY>` the epic's own `description` checklist references. **A failed lookup is NOT an empty result**: if that request errors, stop and report — treating it as \"no children\" would re-split an epic that is already decomposed.\n3. **If children already exist, do NOT file more.**\n - **Some child still in a not-started status** → the epic is already decomposed. Make sure it carries the `decomposed` label and that its description checklist lists every child (steps 5–6), then set `KEY` to the FIRST such child that passes Phase 1 step 4's eligibility rules and continue at **Phase 2** with that child. If every child is in flight, in progress, or done, exit cleanly — that queue is busy, not empty.\n - **Every child Done/Closed** → the epic's work is finished. Comment naming the children that delivered it (POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<EPIC>/comments), transition the epic to **Done/Closed**, and return to Phase 1 to look for other work.\n - **Labeled `decomposed` but NO children exist** → an earlier split claimed the epic and died before filing anything. Treat it as undecomposed and continue at step 4; the marker is already in place, so nothing needs re-claiming.\n4. **Otherwise, plan the split.** Read the code the epic actually names before slicing — a split that never met the repo is worthless. Produce 2–8 slices, each independently shippable in ONE MR/PR, valuable on its own, and written with concrete scope + acceptance criteria + the files/areas involved. Slice by user-visible behavior or subsystem; never one-ticket-per-file, and never invent scope the epic doesn't ask for. Decide the boundaries yourself — an ambiguous epic is decided, not deferred (same rule as Phase 3). Only an epic so vague that no split survives contact with the code is a park case: create a Review Hub todo (\"[<EPIC>] Needs clarification\"), transition the epic to a Blocked/On Hold status if the workflow has one, and exit.\n5. **Claim the epic, THEN file the slices.** Stamp the marker before the first create — the label IS this phase's claim (Phase 1 skips a `decomposed` epic). Like every other marker in this flow it **narrows** the collision window without eliminating it, so re-run step 2's child query immediately before the first create and abandon the split if children now exist. Marking last instead of first would leave the epic actionable forever whenever that final write failed, and let a crashed run be re-split from scratch on the next tick:\n ```\n POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<EPIC>/labels\n {\"labels\": [\"decomposed\"]}\n ```\n Then comment on the epic saying how you sliced it, and resolve the sprint to file the slices INTO: GET http://localhost:5555/api/jira/instances/<instanceId>/boards/<boardId>/sprints (`jira.boardId` on the app config) and take the active sprint's `id`. **If `jira.boardId` is not configured, or that call returns no active sprint, do NOT abandon the split** — file the slices without `sprintId`, flag every one of them as **not sprinted** in step 6's checklist, and say so in your Phase 7 report, so a human can drop them into a sprint. File each slice, in the order you want them worked:\n ```\n POST http://localhost:5555/api/jira/instances/<instanceId>/tickets\n {\"projectKey\": \"<projectKey>\", \"summary\": \"<specific, human-readable>\",\n \"description\": \"<what + why + acceptance criteria + files/areas>\\n\\nPart of <EPIC>\",\n \"epicKey\": \"<EPIC>\", \"assignee\": \"currentUser\", \"sprintId\": <activeSprintId>}\n ```\n **The `assignee` + `sprintId` pair is what makes a slice claimable at all** — Phase 1's candidate query is \"assigned to me AND in an open sprint\", so a child missing either one is invisible to every later run and the remaining work is stranded. `assignee: \"currentUser\"` resolves the authenticated account server-side. The response's `sprint` field is the sentinel to check: `{\"assigned\": true}` means it landed, while `{\"assigned\": false, \"error\": \"…\"}` means the ticket EXISTS but is not in the sprint. On `assigned: false`, retry once (POST http://localhost:5555/api/jira/instances/<instanceId>/sprints/<sprintId>/issues with `{\"issueKeys\": [\"<KEY>\"]}`); if it still fails, mark that slice in the epic's checklist as **not sprinted** and say so in your Phase 7 report — never leave it silently stranded. Say `Part of <EPIC>` in the description and set `epicKey`; JIRA has no `Closes` auto-close, so the epic is closed by step 3's all-children-done branch on a later run. Add the equivalent hyphenated dispatch labels (`model-light|model-medium|model-heavy`, `effort-low|effort-medium|effort-high|effort-xhigh|effort-max`) and contributor labels (`good-first-issue`, `help-wanted`) only where that slice genuinely justifies them.\n6. **Write the checklist back to the epic** so the next run can follow it — keep the original description (step 1 returned it) and append a `## Decomposed into` list naming every child, flagging any that could not be sprinted:\n ```\n PUT http://localhost:5555/api/jira/instances/<instanceId>/tickets/<EPIC>\n {\"description\": \"<original description>\\n\\n## Decomposed into\\n\\n- [ ] <KEY-a> — <title>\\n- [ ] <KEY-b> — <title> (NOT SPRINTED — needs a human to add it)\"}\n ```\n The marker from step 5 is what stops the next run from splitting the same epic again; this checklist is what lets a claim aimed at the epic resolve the next available child. Leave the epic in its current status — it moves to Done when its last child closes.\n7. **Then claim the first slice you filed** — set `KEY` to it and continue at **Phase 2**, shipping that ONE slice normally. If claiming it fails because another run won the race, exit cleanly: the decomposition alone is a successful round, and the next claim run picks up the next linked child.\n\n## Phase 2 — Claim (In Progress + worktree)\n\nFirst move the ticket to **In Progress** (this is the claim, and it must happen BEFORE you start coding), then create the worktree. Transition names vary per project workflow, so resolve the id dynamically:\n\n1. GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transitions to list available transitions.\n2. Pick the transition whose target status best matches \"In Progress\" (e.g. \"In Progress\", \"Start Progress\", \"Start Work\"); match case-insensitively. If none clearly matches, pick the transition that moves the ticket out of the To Do / Backlog column.\n3. POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {\"transitionId\": \"<id>\"}. If this fails (the status is unreachable), the ticket may have been claimed concurrently — return to Phase 1 and pick the next eligible ticket.\n\nThen create the worktree on a branch named `claim/<KEY>`. Do all editing inside the worktree, NEVER in the source repo's working tree:\n\n```bash\nKEY=<picked-key>\nDEFAULT_BRANCH=\"$(git -C {repoPath} symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')\"\nDEFAULT_BRANCH=\"${DEFAULT_BRANCH:-main}\"\nWORKTREE=\"{worktreesRoot}/claim-${KEY}\"\nmkdir -p \"{worktreesRoot}\"\ngit -C {repoPath} fetch origin \"${DEFAULT_BRANCH}\"\ngit -C {repoPath} worktree add --no-track -b \"claim/${KEY}\" \"${WORKTREE}\" \"origin/${DEFAULT_BRANCH}\"\ncd \"${WORKTREE}\"\n```\n\n**If `git worktree add` fails because the `claim/<KEY>` branch already exists** (a concurrent run won the race), do NOT force or reuse it — that branch IS another run's claim. Move the ticket back to its prior status if you transitioned it, treat the ticket as in-flight, return to Phase 1, and pick the next eligible ticket. Stash `WORKTREE` — you'll need it for Phase 6 cleanup.\n\n## Phase 3 — Verify still valid\n\nRe-read the ticket (GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>) before writing any code. **Every exit from this phase must leave a CONVERGING status on the ticket — Done/Closed, or a held status backed by a Review Hub todo.** Transitioning back to a not-started status is NOT an exit: Phase 1's not-started-only filter makes the ticket immediately re-eligible again, so the next pass re-picks it and burns another no-op run — every pass, forever.\n\n- **Already fixed, superseded, or duplicated by another ticket** — a comment says so, or the change it asks for is already on the default branch. Post a ticket comment naming the PR/MR, commit, or ticket that already delivered it (POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/comments), transition the ticket to **Done/Closed**, remove the worktree, and return to Phase 1. **Evidence gate: if you cannot name the PR/MR, commit, or ticket that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the ticket as real work and continue to Phase 4.\n- **Stale reference** — the ticket names a function, file, or component that no longer exists (`grep -rn` the named identifiers; if they're gone, it's stale). Post a ticket comment naming what you searched for and what you found instead, create a Review Hub todo (POST http://localhost:5555/api/review/todo with title \"[<KEY>] Stale reference\" and what a human must re-scope), and transition the ticket to a **Blocked/On Hold status if the workflow has one — NOT back to a not-started status**; if the workflow has no held status, leave it **In Progress** so Phase 1's filter excludes it. Then remove the worktree and return to Phase 1.\n\n(A too-large scope is NOT in this list — it has its own park path below.)\n\n**A genuinely too-large ticket gets SPLIT, not parked.** If the work is bigger than one coherent claim — it would touch files far outside the ticket's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to ship first, promote it to an epic and decompose it: file the slices and rewrite the parent exactly as **Phase 1b** steps 4–6 describe (each slice carrying `Part of <KEY>` and `epicKey: \"<KEY>\"`). **Mark it on BOTH axes** — the queue skips a parent only when it is epic-shaped AND marked, so a ticket left carrying only `decomposed` stays claimable and gets re-split every pass. Add the marker label (POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/labels with `{\"labels\": [\"decomposed\"]}`) and make it epic-shaped: change its issue type to Epic if the project allows it, otherwise append \" (epic)\" to the summary (PUT http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>) — the title convention marks an epic on a project where the type can't change. Confirm both landed by re-reading the ticket. Then transition it back to a not-started status so the sprint board shows the parent as unstarted (the marker, not the status, is what keeps Phase 1 off it), remove the worktree, and continue at Phase 2 with the first slice you filed. Splitting an omnibus ticket is work you do, not a hand-off.\n\nPark instead ONLY when the ticket is too vague to slice against the code at all: create a Review Hub todo (POST http://localhost:5555/api/review/todo with title \"[<KEY>] Needs clarification\" and what a human must resolve), transition the ticket to a **Blocked/On Hold status if the workflow has one — NOT back to a not-started status**, which would re-queue it under Phase 1 (ticket selection never consults Review Hub todos, so a not-started ticket is immediately re-eligible and the run would re-park it every pass); if the workflow has no held status, leave it **In Progress**. Then remove the worktree and exit.\n\n**Ambiguity is NOT a release trigger — decide, don't defer.** If the ticket is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to a \"Needs clarification\" todo. Pick the most reasonable interpretation, record the approach you chose in a ticket comment (POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/comments) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the ticket parked waiting on a decision they didn't ask to make. Reserve the \"Needs clarification\" todo for cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, create the todo (POST http://localhost:5555/api/review/todo with title \"[<KEY>] Needs clarification\" and what a human must resolve), transition the ticket to a **Blocked/On Hold status if the workflow has one — NOT back to a not-started status** (which would re-queue it under Phase 1, since ticket selection never consults Review Hub todos); if the workflow has no held status, leave it **In Progress** so Phase 1's not-started-only filter excludes it. Then remove the worktree and **exit — do NOT proceed to Phase 4**.\n\nDo NOT leave an *unexplained* ticket in \"In Progress\" with no branch — that is the zombie to avoid. A deliberate park above is different: it always carries a Review Hub todo saying why (and a Blocked/On Hold status where the workflow supports one), so it reads as intentionally held, not abandoned.\n\n## Phase 4 — Implement\n\nWrite the code, tests, and any docs the ticket requires. Follow the repo conventions in AGENTS.md / CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.\n\n**Roll discovered backbone work INTO this MR/PR** — small supporting helpers, refactors, and tests the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work.\n\nCommit with a conventional message referencing the ticket so the trail is grep-able:\n\n```\n<type>: <one-line description> (<KEY>)\n```\n\n## Phase 5 — Review locally, then open the MR/PR and move to In Review\n\nThe audit trail is the merged MR/PR + `git log`. Detect the forge from the git origin and use the matching CLI (`gh` for GitHub, `glab` for GitLab).\n\nThe configured reviewers for this task, in order, are `{reviewers}`. Split them by where they can run, preserving order: **LOCAL reviewers** — every token that is NOT an `@<login>` (`claude` / `codex` / `antigravity` (CLI binary: `agy`) / `grok` / `cursor` invoke a local-CLI critique; `lmstudio` / `ollama` use the appended Local Reviewer Procedure) read the working tree and need no MR/PR, so they run in steps 1–2 below, BEFORE it is opened. **PR-SIDE reviewers** — every `@<login>` token, plus any review bot the repo requests automatically on open — review cloud-side and run in Phase 6, once the MR/PR exists.\n\n1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR/PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its `AGENTS.md` (or `CLAUDE.md`) and changelog README (e.g. `.changelog/README.md`) first. Some repos collect per-branch fragments in a directory (e.g. `.changelog/next/`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (`.changelog/NEXT.md`, or `## Unreleased` in `CHANGELOG.md`) in the repo's existing prose style only when no convention is documented. Otherwise skip it.\n2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff. Claude Code runs this as the three-agent `/simplify` pass; on other CLIs, do the equivalent by hand.\n3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR/PR diff.** Nothing is open yet, so use the CLI's own base-diff mode or `git diff \"origin/${DEFAULT_BRANCH}...HEAD\"`; local LLM reviewers go through the appended endpoint procedure. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR/PR on the strength of it. If a local reviewer stays unsatisfied after 3 rounds, or its fixes leave the build/tests red, do NOT open one — leave the branch and worktree in place, comment the failure on the ticket (POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/comments), and stop.\n4. Push the branch: `git push -u origin \"claim/${KEY}\"`, then confirm `git log --oneline @{u}..HEAD` is empty so every review fix from step 3 is in the MR/PR's diff.\n5. Open the MR/PR. Reference the JIRA `KEY` in the title and description (there is NO `Closes` auto-close for JIRA). Summarize what shipped + a short test plan.\n - GitHub: `gh pr create --fill --head \"claim/${KEY}\"` (then edit the body to mention `KEY` if `--fill` didn't).\n - GitLab: `glab mr create --fill --source-branch \"claim/${KEY}\" --target-branch \"${DEFAULT_BRANCH}\" --yes`.\n Capture the MR/PR URL as `PR_URL`.\n6. **Move the ticket to \"In Review\" — REQUIRED, not optional. Do not finish while it is still \"In Progress\":**\n - GET http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transitions again (transitions change once In Progress).\n - Pick the transition whose target status best matches \"In Review\" (e.g. \"In Review\", \"Code Review\", \"Review\", \"Ready for Review\"); match case-insensitively.\n - POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/transition with body {\"transitionId\": \"<id>\"}.\n7. Add the MR/PR link to the ticket: POST http://localhost:5555/api/jira/instances/<instanceId>/tickets/<KEY>/comments with body {\"comment\": \"Implementation complete. MR/PR: ${PR_URL}\\n\\nReady for code review.\"}. **If you shipped only PART of the ticket's scope** (a valuable slice with real work remaining), make the comment a `Done ✓ / Remaining ▢` summary so the remaining scope is not lost when a human lands the MR/PR; when that remainder is a clean, separable chunk, ALSO file a new follow-up ticket for it (POST http://localhost:5555/api/jira/instances/<instanceId>/tickets with a summary + a description referencing `KEY`, plus equivalent labels `model-light|model-medium|model-heavy`, `effort-low|effort-medium|effort-high|effort-xhigh|effort-max`, `good-first-issue`, `help-wanted` when independently justified) so it re-enters the sprint queue. If a transition in step 6 failed (status unreachable), say so in this comment AND in the Phase 7 summary — do not silently drop it.\n\n## Phase 6 — PR-side review and clean up\n\nThe local reviewers already ran in Phase 5, so only the reviewers that need an open MR/PR remain.\n\n1. **Satisfy the PR-SIDE reviewers.** For each `@<login>` from the Phase 5 split, request the review on the open MR/PR (GitHub: `gh pr edit <pr-number> --add-reviewer <login>`, dropping the `@`; GitLab: `glab mr update <MR_IID> --reviewer <login>`), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds per reviewer. Wait out any auto-requested review bot the same way. A missing reviewer, timeout, or unresolvable finding is UNSATISFIED, not clean: comment on the MR/PR naming the failure and stop. With no `@<login>` configured and no bot review appearing, this step is a no-op.\n2. **Leave the MR/PR open for a human to land.** Unlike the GitHub/GitLab issue flows, this flow does NOT auto-merge — the ticket is \"In Review\" and a human reviews + merges. After the reviewers finish, run the worktree-only cleanup so the source checkout is left clean:\n ```bash\n cd {repoPath}\n git worktree remove \"${WORKTREE}\"\n ```\n Leave the local `claim/<KEY>` branch and the open MR/PR in place. **Do NOT `git merge`, `gh pr merge`, `glab mr merge`, or `git pull`** — landing the change and moving the ticket to Done is the human's call.\n\n## Phase 7 — Report\n\nGenerate a short summary: the ticket KEY + summary worked, the MR/PR URL, the ticket's FINAL JIRA status (confirm it is \"In Review\"), reviewers run, and any status transition that failed and why.".replaceAll('http://localhost:5555', PORTOS_API_URL));
+// Outgoing claim-flow defaults before v23/v21/v16: required-review unavailability now publishes but blocks merging.
+PREVIOUS_DEFAULT_PROMPTS['claim-issue'].push("[Claim Issue: {appName}] Claim and ship the next open GitHub issue\n\nPick the next available unclaimed open GitHub issue, **create your own worktree at `claim/issue-<num>`**, implement the fix, ship a PR that closes the issue, and clean up. This is the `/claim --issues` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.\n\n{issueAuthorFilter}\n\n**How claiming works.** An issue is \"in flight\" when its number appears as the issue-position segment in either a `claim/issue-<num>` ref (the human/TUI pattern) or a `cos/<task>/issue-<num>/<agent>` ref (the CoS sub-agent pattern) across local branches, remote branches, or open PR head refs — OR the issue is assigned to another account OR carries an `in-progress` label. An issue already assigned to the authenticated account remains eligible for a retry. The `claim/issue-<num>` branch + the assignee/`in-progress` markers you set ARE the claim, visible to every other agent (including parallel machines) and to the human running `/claim --issues` in a TUI.\n\n## Phase 1 — Pick the target issue\n\nRun steps 1–5 in order.\n\n1. cd into the repo root ({repoPath}) and confirm GitHub is the forge: `gh repo view --json nameWithOwner -q .nameWithOwner`. If `gh` is not authenticated or the remote is not GitHub, exit cleanly — this task only works against GitHub issue trackers.\n2. List candidate open issues **oldest-first**, honoring the author filter described above. `gh issue list` defaults to newest-first, so order on the SERVER with `--search \"sort:created-asc\"` — a client-side `jq` sort would only reorder the already-truncated newest page, dropping the true oldest issues on repos with more than `--limit` open issues:\n ```bash\n git fetch --prune 2>/dev/null\n # Author filter (see the block above). Pass --author as a QUOTED single token —\n # do NOT pack flag+value into one variable: a bare `$VAR` holding \"--author x\"\n # is a single argv token in zsh (no word-splitting) and gh rejects it.\n # Owner-only mode (default): resolve the owner, then add --author \"$OWNER\"\n # --limit 500 (not 100): the blocking-label filter below runs on this\n # fetched page, so a small cap risks missing eligible work further down\n # a busy queue when the first page is full of excluded/in-flight issues.\n # Keep an issue assigned to this authenticated account eligible for retry;\n # if this lookup fails, leave ME empty and skip all assigned issues.\n GH_HOST=\"$(git remote get-url origin 2>/dev/null | sed -E -e 's#^[^:]+://([^@/]+@)?([^/:]+)(:[0-9]+)?/.*#\\2#' -e 's#^([^@]+@)?([^:]+):.*#\\2#')\"\nif [ \"$GH_HOST\" = \"ssh.github.com\" ]; then GH_HOST=\"github.com\"; fi\n ME=\"$(gh api --hostname \"$GH_HOST\" user -q .login 2>/dev/null || true)\"\n OWNER=\"$(gh repo view --json owner -q .owner.login)\"\n gh issue list --state open --author \"$OWNER\" --search \"sort:created-asc\" --json number,title,author,assignees,labels,createdAt --limit 500\n # Any-author mode: run the SAME command WITHOUT the --author \"$OWNER\" flag.\n ```\n3. Build the in-flight set. Collect every branch/PR ref:\n ```bash\n git branch -a --no-color --format='%(refname:short)'\n gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null\n ```\n For each ref (after stripping any leading `origin/` / `upstream/` prefix), extract the issue number **only when the ref matches** `claim/issue-<num>` (number after `claim/issue-`) or `cos/<task>/issue-<num>/<agent>` (the `issue-<num>` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.\n4. **Pick the target issue:** walk the candidate list oldest-first in TWO passes. First pass, consider only NON-epic issues and take the first that satisfies every rule below — atomic work always outranks an epic, whatever their relative age. Only if that pass finds nothing do you make a second pass for an undecomposed epic (same rules), and an epic you pick goes to **Phase 1b**, not Phase 2. A single oldest-first pass would enter a decomposition the moment an epic happened to be older than claimable work, which is exactly backwards. The rules:\n - Its number is NOT in the in-flight set.\n - It has no assignees, or at least one assignee's login matches `$ME` (an issue assigned only to another account is already claimed). If `$ME` is empty, skip every assigned issue.\n - It does NOT carry any of these blocking labels: {issueExcludeLabels}.\n - It is NOT an ALREADY-DECOMPOSED tracking/umbrella **epic**. An epic is recognized by an `epic` label, a title ending in \"(epic)\", OR a title beginning with an `[epic]` bracket or `Epic:` tag (e.g. \"[Epic] …\" / \"Epic: …\", case-insensitive); it counts as decomposed once it ALSO carries the `decomposed` label. Skip a decomposed epic — its child slices are ordinary claimable issues in this very list, so claiming the parent would duplicate them. An undecomposed epic is eligible only in the second pass above. **The bare `plan` label is NOT a skip signal.** `do-replan --issues` (and `/do:replan --issues`) labels EVERY migrated backlog item `plan` — atomic bug-fixes included — so `plan` marks the *claimable* queue exactly as `/do:next --issues` treats it (it is that flow's required candidate label). Skipping all `plan` issues would discard the entire actionable backlog and falsely report an empty queue.\n5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure. **But an open, undecomposed epic is NOT an empty queue**: never report \"no work available\" while one is unclaimed. Splitting it is the work — go to Phase 1b.\n\nCapture the issue number as `NUM`, its title, and its full body — you'll reuse them in the PR and the `Closes #<num>` trailer.\n\n## Phase 1b — Decompose an epic (only when Phase 1 landed on one)\n\nYou reach this phase two ways: Phase 1 found no eligible atomic issue and fell through to an undecomposed epic, or the user pinned this run to an epic. **Never end a run reporting \"nothing to do\" while an undecomposed epic is open** — turning it into shippable slices IS this round's work, and it is what refills the queue for every later run.\n\nCapture the epic's number as `EPIC`. This phase writes ONLY to the issue tracker: no worktree, no branch, no PR, no edits in the source repo.\n\n1. Read it in full, comments included: `gh issue view \"${EPIC}\" --comments`.\n2. **Find the children it already has** — an epic a human (or an earlier run) already split must never be re-split:\n ```bash\n gh issue view \"${EPIC}\" --json body -q .body\n gh issue list --state all --search \"in:body \\\"Part of #${EPIC}\\\"\" --json number,title,state,labels,assignees --limit 200\n ```\n Union that with every `#<num>` the epic's own body checklist references.\n3. **If children already exist, do NOT file more.**\n - **Some child still OPEN** → the epic is already decomposed. Make sure it carries the `decomposed` label and that its body checklist lists every child (step 6), then set `NUM` to the FIRST open child that passes Phase 1 step 4's eligibility rules (oldest-first) and continue at **Phase 2** with that child. If every open child is in flight, assigned elsewhere, or blocked, exit cleanly — that queue is busy, not empty.\n - **Every child CLOSED** → the epic's work is done. Post a comment naming the children that delivered it, close it (`gh issue close \"${EPIC}\" --reason completed`), and return to Phase 1 to look for other work.\n - **Labeled `decomposed` but NO children exist** → an earlier split claimed the epic and died before filing anything. Treat it as undecomposed and continue at step 4; the marker is already in place, so nothing needs re-claiming. (Auto-pick can't reach this state — the marker is exactly what makes Phase 1 skip the epic — so it is recovered only when a human or the work-item picker aims a claim straight at that epic. That is the deliberate trade: a stalled split waits for a human, rather than every marker-write failure re-splitting the same epic on every drain tick.)\n4. **Otherwise, plan the split.** Read the code the epic actually names before slicing — a split that never met the repo is worthless. Produce 2–8 slices, each of them independently shippable in ONE PR, valuable on its own, and written with concrete scope + acceptance criteria + the files/areas involved. Slice by user-visible behavior or subsystem; never one-issue-per-file, and never invent scope the epic doesn't ask for. Decide the boundaries yourself — an ambiguous epic is decided, not deferred (same rule as Phase 3). Only an epic so vague that no split survives contact with the code is a `needs-input` case: comment what is missing, `gh issue edit \"${EPIC}\" --add-label needs-input`, and exit.\n5. **Claim the epic, THEN file the slices.** Stamp the marker before the first `gh issue create` — the label IS this phase's claim (Phase 1 skips a `decomposed` epic). Like every other marker in this flow it **narrows** the window for two concurrent runs to collide — it does NOT eliminate it, since a label edit is an idempotent write, not a compare-and-set — so re-run step 2's child query immediately before the first create and abandon the split if children now exist. Marking last instead of first would leave the epic actionable forever whenever that final edit failed, and let a crashed run be re-split from scratch on the next tick:\n ```bash\n gh label create decomposed --color BFD4F2 --description 'Epic already split into per-slice child issues' 2>/dev/null || true\n gh issue edit \"${EPIC}\" --add-label decomposed\n gh issue comment \"${EPIC}\" --body \"Decomposing into per-slice issues — <one line on how you sliced it>\"\n # The queue label the slices carry must exist before the first create, or every\n # `gh issue create` below fails on a repo that has never used it.\n gh label create plan --color 0E8A16 --description \"Claimable backlog item\" 2>/dev/null || true\n ```\n Then file each slice, in the order you want them worked:\n ```bash\n gh issue create --title \"<specific, human-readable>\" --label plan \\\n --body \"<what + why + acceptance criteria + files/areas>\n\nPart of #${EPIC}\"\n ```\n Use `Part of #${EPIC}` — NEVER `Closes #${EPIC}`, which would close the whole epic on the first slice that merges. **Give every slice body the epic-closure instruction too** — a line telling the agent that ships it to check its box in #${EPIC} and, when it was the LAST open child, close #${EPIC} with a summarizing comment. That is what closes the epic: once it carries the marker, Phase 1 and the work detector both skip it, so no later claim run will revisit the parent on its own. Carry over the epic's `area:*` labels, and add dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) or contributor labels (`good first issue`, `help wanted`) only where that slice genuinely justifies them; create a missing label immediately before applying it.\n6. **Write the checklist back to the epic** so the next run can follow it — keep the original body and append a `## Decomposed into` list naming every child:\n ```bash\n EPIC_BODY=$(mktemp)\n gh issue view \"${EPIC}\" --json body -q .body > \"${EPIC_BODY}\"\n printf '\\n\\n## Decomposed into\\n\\n- [ ] #<a> — <title>\\n- [ ] #<b> — <title>\\n' >> \"${EPIC_BODY}\"\n gh issue edit \"${EPIC}\" --body-file \"${EPIC_BODY}\"\n rm -f \"${EPIC_BODY}\"\n ```\n The marker from step 5 is what stops the next run from splitting the same epic again; this checklist is what lets a claim aimed at the epic resolve the next available child. Leave the epic OPEN, unassigned, and WITHOUT `in-progress` — it closes when its last child closes.\n7. **Then claim the first slice you filed** — set `NUM` to it and continue at **Phase 2**, shipping that ONE slice normally (its PR closes the slice, never the epic). If claiming it fails because another run won the race, exit cleanly: the decomposition alone is a successful round, and the next claim run picks up the next linked child.\n\n## Phase 2 — Claim (worktree + markers)\n\nCreate the worktree on a branch named `claim/issue-<num>`, then set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.\n\n```bash\nNUM=<picked-number>\nWORKTREE=\"{worktreesRoot}/claim-issue-${NUM}\"\nmkdir -p {worktreesRoot}\ngit fetch origin main\ngit worktree add --no-track -b \"claim/issue-${NUM}\" \"${WORKTREE}\" origin/main\n# Cross-machine claim markers (best-effort — do not abort the run if these fail):\ngh issue edit \"${NUM}\" --add-assignee @me 2>/dev/null\ngh issue edit \"${NUM}\" --add-label in-progress 2>/dev/null\n# Retire the contributor invitations — this issue is taken now, so it must stop\n# advertising itself to a human looking for something to pick up. One edit per\n# label: `--remove-label` fails the WHOLE call when a named label is absent, so\n# a combined call on an issue carrying only one of them would remove neither.\ngh issue edit \"${NUM}\" --remove-label 'good first issue' 2>/dev/null\ngh issue edit \"${NUM}\" --remove-label 'help wanted' 2>/dev/null\ncd \"${WORKTREE}\"\n```\n\n(If the repo's default branch is not `main`, detect it with `gh repo view --json defaultBranchRef -q .defaultBranchRef.name` and substitute it for `main` above.)\n\nReleasing `good first issue` / `help wanted` is deliberate and one-way: they invite a human contributor, and every path out of this flow either closes the issue or returns it to the AUTONOMOUS queue, where those labels mean nothing. Do NOT restore them when Phase 3 or Phase 7 releases the claim — re-advertising the issue to humans is a call for the human who wants it re-advertised.\n\n**If `git worktree add` fails because the `claim/issue-<num>` branch already exists** (a concurrent run won the race, or a remote claim branch is now visible), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash `WORKTREE` — you'll need it for Phase 7 cleanup.\n\n## Phase 3 — Verify still valid\n\nRead the full issue (`gh issue view \"${NUM}\" --comments`) before writing any code. **Every exit from this phase must leave a CONVERGING outcome on the issue — closed, or labeled `needs-input`.** Phase 1 step 4 skips both, so an autonomous drain stops re-picking the item. Releasing an issue OPEN and unlabeled is NOT an exit: the work detector still reports it actionable, so the next pass re-picks it and burns another no-op agent — every pass, forever.\n\n- **Already fixed, superseded, or closed-then-reopened-for-tracking** — a comment says so, or the change it asks for is already on the default branch. **Close it:** post a comment naming the PR/commit (or issue) that already delivered it (`gh issue comment \"${NUM}\" --body \"...\"`), then `gh issue close \"${NUM}\" --reason completed` (use `--reason \"not planned\"` when it was superseded rather than delivered) and clear the markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`). Remove the worktree and return to Phase 1. **Evidence gate: if you cannot name the PR, commit, or issue that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the issue as real work and continue to Phase 4.\n- **Stale reference** — the request names a function, file, or component that no longer exists (`grep -rn` the named identifiers; if they're gone, the issue is stale). Post a comment naming what you searched for and what you found instead, **tag it `needs-input`** (`gh issue edit \"${NUM}\" --add-label needs-input`), release the claim markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`), remove the worktree, and return to Phase 1. Re-scoping a stale issue against today's code is a human call — and the label is what keeps the drain off it in the meantime.\n\n(A too-large scope is NOT in this list — it has its own park path below.)\n\n**A genuinely too-large issue gets SPLIT, not parked.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 6's `Refs` path, promote it to an epic and decompose it: file the slices and rewrite the parent exactly as **Phase 1b** steps 4–6 describe (each slice carrying `Part of #${NUM}`). **Promote it on BOTH axes, creating the umbrella label first** — the queue skips a parent only when it is epic-shaped AND marked, so an issue left carrying only `decomposed` stays claimable and gets re-split every pass:\n```bash\ngh label create epic --color B60205 --description 'Umbrella/tracking issue — shipped as per-slice children, never as one PR' 2>/dev/null || true\ngh issue edit \"${NUM}\" --add-label epic --add-label decomposed\n```\nVerify BOTH labels are actually on the issue afterwards (`gh issue view \"${NUM}\" --json labels`); if the `epic` label still won't stick, append \" (epic)\" to the title instead (`gh issue edit \"${NUM}\" --title \"… (epic)\"`) — the title convention marks an epic with no label at all. Then release its claim markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`), remove the worktree, and continue at Phase 2 with the first slice you filed. Splitting an omnibus issue is work you do, not a hand-off. Park to `needs-input` (`gh issue edit \"${NUM}\" --add-label needs-input`, release the markers, remove the worktree, exit) ONLY when the issue is too vague to slice against the code at all — that park is what stops a perpetual drain from re-picking an un-shippable issue every pass (Phase 1 step 4 skips `needs-input`).\n\n**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to `needs-input`. Pick the most reasonable interpretation, record the approach you chose in a brief issue comment (`gh issue comment \"${NUM}\" --body \"...\"`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve `needs-input` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining comment, **tag it `needs-input`** (`gh issue edit \"${NUM}\" --add-label needs-input`), release the claim markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips `needs-input` issues. Never leave a half-claimed issue.\n\n## Phase 4 — Implement\n\nWrite the code, tests, and any docs the issue requires. Follow the repo conventions in AGENTS.md / CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.\n\n**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (`gh issue create`) tagged `plan` that references this one (`Related to #<num>`) rather than appending to PLAN.md. Choose independent dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated `--label` flags; do not prefix the title with `[category]` / `[model:…]`.\n\nCommit with a conventional message referencing the issue so the trail is grep-able:\n\n```\n<type>: <one-line description> (#<num>)\n```\n\n## Phase 5 — Review locally (BEFORE any PR exists)\n\n**Every reviewer that can read the working tree runs HERE, while there is still no PR.** Open the PR only once the branch is already review-clean: the PR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until a PR is open.\n\nThe configured reviewers for this task, in order, are `{reviewers}`. Split that list in two, preserving its order:\n\n- **LOCAL reviewers — every token that is NOT an `@<login>`.** `claude` / `codex` / `antigravity` (CLI binary: `agy`) / `grok` / `cursor` invoke a local-CLI critique; `lmstudio` / `ollama` use the appended Local Reviewer Procedure. They read this branch's own diff and need no PR — run them in THIS phase.\n- **PR-SIDE reviewers — every `@<login>` token**, plus any review bot the repo requests automatically when a PR opens. They review cloud-side and cannot start before the PR exists — they run in Phase 6.\n\n1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its `AGENTS.md` (or `CLAUDE.md`) and changelog README (e.g. `.changelog/README.md`) first. Some repos collect per-branch fragments in a directory (e.g. `.changelog/next/`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (`.changelog/NEXT.md`, or `## Unreleased` in `CHANGELOG.md`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.\n2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent `/simplify` pass; on other CLIs, do the equivalent review by hand.\n3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not a PR diff.** No PR exists yet, so `gh pr diff` has nothing to read — use the CLI's own base-diff mode or `git diff origin/main...HEAD` (substitute the repo's default branch when it isn't `main`). Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open a PR on the strength of it.\n4. **If the branch cannot be brought to a shippable state here, do NOT open a PR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Comment on the ISSUE naming the reviewer and the failure (`gh issue comment \"${NUM}\" --body \"...\"`), leave the assignee and the `in-progress` label in place, remove ONLY the worktree (`cd {repoPath} && git worktree remove \"${WORKTREE}\"`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.\n\n## Phase 6 — Open the PR, satisfy PR-side review + CI, and merge\n\nEvery local reviewer's fixes are already committed, so the PR opens against finished work. This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + `git log`.\n\n1. Push the branch: `git push -u origin \"claim/issue-${NUM}\"`. Then confirm `git log --oneline @{u}..HEAD` is empty — if it isn't, a Phase 5 review fix never left the machine and the PR would be opened against a stale diff; push again before continuing.\n2. Open the PR with `gh pr create`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain `Closes #${NUM}` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use `Refs #${NUM}` instead (NOT `Closes`) and add a `## Remaining` section listing what's left — Phase 7 reconciles the issue so it is never stranded.\n3. **Satisfy the PR-SIDE reviewers.** For each `@<login>` from the Phase 5 split, request the review now (`gh pr edit <pr-number> --add-reviewer <login>`, drop the `@`), poll every 5–15s for it, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the repo auto-requests a review bot when the PR opens, wait that round out and address it the same way. With no `@<login>` configured and no bot review appearing, this step is a no-op.\n\n **Review-stuck cleanup** (a PR-side reviewer still unsatisfied after 3 rounds): post one summarizing PR comment (`gh pr comment`), then run the worktree-only cleanup (`cd {repoPath} && git worktree remove \"${WORKTREE}\"`). Leave the local branch, the open PR, the assignee, and the `in-progress` label in place so the human picks up cold. Do NOT run Phase 7.\n4. **Let required CI finish and go green** — `gh pr checks <pr-number> --required --watch --fail-fast` (scope the wait to REQUIRED checks so an optional job can't stall a merge branch protection would allow). A red required check is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.\n5. **Merge immediately via `gh pr merge`** — NEVER a local `git merge` and NEVER `--auto`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:\n ```bash\n PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch\n gh pr merge \"$PR_URL\" --merge --delete-branch || {\n [ \"$(gh pr view \"$PR_URL\" --json state -q .state)\" = \"MERGED\" ] || gh pr merge \"$PR_URL\" --squash --delete-branch || gh pr merge \"$PR_URL\" --rebase --delete-branch\n }\n STATE=$(gh pr view \"$PR_URL\" --json state -q .state)\n [ \"$STATE\" = \"MERGED\" ] || { echo \"Expected MERGED, got $STATE\" >&2; exit 1; }\n ```\n The exact comparison MUST succeed. `OPEN` means CI, review, or branch protection still blocks the merge; investigate, fix, and retry. `CLOSED` is also not success. Do not enter Phase 7 until remote GitHub state is exactly `MERGED`.\n\n## Phase 7 — Clean up (post-merge ONLY)\n\nThis phase runs only after the PR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):\n\n```bash\ncd {repoPath}\ngit worktree remove \"${WORKTREE}\"\ngit branch -d \"claim/issue-${NUM}\"\n```\n\nIf `git branch -d` refuses, fetch the default branch and re-check the PR's remote `MERGED` state. Retry `-d` only when Git can prove the branch is integrated; otherwise leave the local branch for the reconciliation task. Never force-delete with `-D`.\n\n**Reconcile the issue — did this PR FULLY satisfy its scope?**\n- **Yes (full)** — the `Closes #${NUM}` trailer already auto-closed it; if it's somehow still open, close it (`gh issue close \"${NUM}\"`) and remove the label (`gh issue edit \"${NUM}\" --remove-label in-progress`).\n- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing comment (shipped ✓ / moved to #NEW), remove `in-progress`, and file ONE tightly-scoped follow-up for the remainder: `gh issue create --title \"…\" --label plan [--label model:<tier>] [--label effort:<level>] [--label \"good first issue\"] [--label \"help wanted\"] --body \"…\\n\\nRefs #${NUM}\"` (carry over any `area:*` labels the issue had; choose the optional labels independently and only when justified — a leftover mechanical sweep is not a good first issue).\n- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a `Done ✓ / Remaining ▢` comment, and release the claim so the queue re-picks it. Remove the label and every current assignee, not only the authenticated account:\n `ASSIGNEES=\"$(gh issue view \"${NUM}\" --json assignees -q '[.assignees[].login] | join(\",\")')\"`\n `gh issue edit \"${NUM}\" --remove-label in-progress --remove-assignee \"${ASSIGNEES:-@me}\"`.\n\nNEVER leave the issue OPEN with `in-progress` still on it — that strands it as a zombie (the claim queue skips `in-progress`, so the remaining scope is never re-picked). **Do NOT `git pull`** from inside this phase — the work is already integrated on GitHub via `gh pr merge`; leave the user's working tree alone.");
+PREVIOUS_DEFAULT_PROMPTS['claim-issue-gitlab'].push("[Claim Issue: {appName}] Claim and ship the next open GitLab issue\n\nPick the next available unclaimed open GitLab issue, **create your own worktree at `claim/issue-<num>`**, implement the fix, ship a merge request (MR) that closes the issue, and clean up. This is the `/claim --issues` flow for GitLab — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's **GitLab** issue tracker and the forge CLI is `glab` (not `gh`). **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.\n\n{issueAuthorFilter}\n\n**How claiming works.** An issue is \"in flight\" when its number appears as the issue-position segment in either a `claim/issue-<num>` ref (the human/TUI pattern) or a `cos/<task>/issue-<num>/<agent>` ref (the CoS sub-agent pattern) across local branches, remote branches, or open MR source-branch refs — OR the issue is assigned to another account OR carries an `in-progress` label. An issue already assigned to the authenticated account remains eligible for a retry. The `claim/issue-<num>` branch + the assignee/`in-progress` markers you set ARE the claim, visible to every other agent (including parallel machines).\n\n## Phase 1 — Pick the target issue\n\nRun steps 1–5 in order.\n\n1. cd into the repo root ({repoPath}) and confirm GitLab is the forge and `glab` is authenticated: `glab auth status` and `glab repo view`. If `glab` is not authenticated or the remote is not GitLab, exit cleanly — this task only works against GitLab issue trackers.\n2. List candidate open issues, honoring the author filter described above. Fetch a JSON page and order **oldest-first** (GitLab returns newest-first by default; sort client-side by `created_at` since the page is bounded):\n ```bash\n git fetch --prune 2>/dev/null\n # Owner-only mode (default): add --author <owner> (resolve <owner> from the project namespace).\n # Keep an issue assigned to this authenticated account eligible for retry;\n # if this lookup fails, leave ME empty and skip all assigned issues.\n ME=\"$(glab api user -q .username 2>/dev/null || true)\"\n glab issue list --per-page 100 --output json\n # Any-author mode: run the SAME command WITHOUT --author.\n ```\n3. Build the in-flight set. Collect every branch/MR source ref:\n ```bash\n git branch -a --no-color --format='%(refname:short)'\n glab mr list --per-page 100 --output json # read each MR's source_branch\n ```\n For each ref (after stripping any leading `origin/` prefix), extract the issue number **only when the ref matches** `claim/issue-<num>` (number after `claim/issue-`) or `cos/<task>/issue-<num>/<agent>` (the `issue-<num>` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.\n4. **Pick the target issue:** walk the candidate list oldest-first in TWO passes. First pass, consider only NON-epic issues and take the first that satisfies every rule below — atomic work always outranks an epic, whatever their relative age. Only if that pass finds nothing do you make a second pass for an undecomposed epic (same rules), and an epic you pick goes to **Phase 1b**, not Phase 2. A single oldest-first pass would enter a decomposition the moment an epic happened to be older than claimable work, which is exactly backwards. The rules:\n - Its number (`iid`) is NOT in the in-flight set.\n - It has no assignees, or at least one assignee's username matches `$ME` (an issue assigned only to another account is already claimed). If `$ME` is empty, skip every assigned issue.\n - It does NOT carry any of these blocking labels: {issueExcludeLabels}.\n - It is NOT an ALREADY-DECOMPOSED tracking/umbrella **epic**. An epic is recognized by an `epic` label, a title ending in \"(epic)\", OR a title beginning with an `[epic]` bracket or `Epic:` tag (e.g. \"[Epic] …\" / \"Epic: …\", case-insensitive); it counts as decomposed once it ALSO carries the `decomposed` label. Skip a decomposed epic — its child slices are ordinary claimable issues in this very list. An undecomposed epic is eligible only in the second pass above. **The bare `plan` label is NOT a skip signal** — it marks the claimable queue, not a blocker.\n5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure. **But an open, undecomposed epic is NOT an empty queue** — go to Phase 1b instead of reporting \"no work available\".\n\nCapture the issue number (GitLab `iid`) as `NUM`, its title, and its full description — you'll reuse them in the MR and the `Closes #<num>` line.\n\n## Phase 1b — Decompose an epic (only when Phase 1 landed on one)\n\nSame contract as the GitHub flow: an undecomposed epic is work, not a dead end. Capture its `iid` as `EPIC`. This phase writes ONLY to the issue tracker — no worktree, no branch, no MR.\n\n1. Read it in full: `glab issue view \"${EPIC}\" --comments`.\n2. **Find the children it already has** — never re-split an epic somebody already split. Union the `#<num>` refs in its own description checklist with `glab issue list --all --search \"Part of #${EPIC}\" --output json --per-page 100`.\n3. **If children already exist, do NOT file more.** Some child still OPEN → make sure the epic carries the `decomposed` label and a complete checklist (step 6), set `NUM` to the FIRST open child passing Phase 1 step 4's rules (oldest-first), and continue at **Phase 2** with that child; if every open child is in flight/assigned/blocked, exit cleanly. Every child CLOSED → comment naming what delivered it, `glab issue close \"${EPIC}\"`, and return to Phase 1.\n4. **Otherwise, plan the split** against the actual code the epic names: 2–8 slices, each independently shippable in ONE MR, valuable on its own, each with concrete scope + acceptance criteria + the files/areas involved. Slice by user-visible behavior, never one-issue-per-file, never invent scope. Decide the boundaries yourself; only an epic too vague to slice against the code is a `needs-input` case (comment why, `glab issue update \"${EPIC}\" --label needs-input`, exit).\n5. **Claim the epic, THEN file the slices.** Stamp the marker before the first create — the label IS this phase's claim. Like every other marker in this flow it **narrows** the concurrent-collision window rather than closing it (a label write is idempotent, not a compare-and-set), so re-run step 2's child query immediately before the first create and abandon the split if children now exist. Marking last would instead leave the epic actionable forever whenever that final write failed: `glab label create --name decomposed --color '#BFD4F2' --description 'Epic already split into per-slice child issues' 2>/dev/null || true`, then `glab issue update \"${EPIC}\" --label decomposed`, then post a comment saying a split is under way. Create the `plan` queue label the same way if the project lacks it, or every create below fails. Then file each slice in the order you want them worked: `glab issue create --title \"<specific>\" --label plan --description \"<what + why + acceptance criteria + files/areas>\n\nPart of #${EPIC}\"`. Use `Part of #${EPIC}`, NEVER `Closes #${EPIC}`. Give every slice the epic-closure instruction too — check its box in #${EPIC}, and close #${EPIC} when it was the LAST open child; once the parent carries the marker, nothing else will revisit it. Carry over the epic's `area:*` labels; add `model:*`/`effort:*` or contributor labels only where justified.\n6. **Write the checklist back to the epic**: keep its description and append a `## Decomposed into` checklist (`- [ ] #<num> — <title>`) via `glab issue update \"${EPIC}\" --description \"<full text>\"`. Leave the epic OPEN, unassigned, and without `in-progress` — it closes when its last child closes. The step-5 marker is what stops the next run from re-splitting it; the checklist is what lets a claim aimed at the epic resolve the next available child. An epic already labeled `decomposed` with NO children is a split that died before filing — treat it as undecomposed and resume at step 4.\n7. **Then claim the first slice you filed** — set `NUM` to it and continue at **Phase 2**. If another run won the race, exit cleanly: the decomposition itself is a successful round.\n\n## Phase 2 — Claim (worktree + markers)\n\nDetect the default branch first (forge-agnostic), then create the worktree on `claim/issue-<num>` and set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.\n\n```bash\nNUM=<picked-number>\nDEFAULT_BRANCH=\"$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's@^origin/@@')\"\nDEFAULT_BRANCH=\"${DEFAULT_BRANCH:-main}\"\nWORKTREE=\"{worktreesRoot}/claim-issue-${NUM}\"\nmkdir -p {worktreesRoot}\ngit fetch origin \"${DEFAULT_BRANCH}\"\ngit worktree add --no-track -b \"claim/issue-${NUM}\" \"${WORKTREE}\" \"origin/${DEFAULT_BRANCH}\"\n# Cross-machine claim markers (best-effort — do not abort the run if these fail).\n# Resolve your own username first — glab's --assignee wants a username (the\n# `@me` gh-ism isn't universally supported), falling back to @me if the lookup fails:\nME=\"$(glab api user 2>/dev/null | sed -n 's/.*\"username\":\"\\([^\"]*\\)\".*/\\1/p')\"\nglab issue update \"${NUM}\" --assignee \"${ME:-@me}\" 2>/dev/null\nglab issue update \"${NUM}\" --label in-progress 2>/dev/null\n# Retire the contributor invitations — this issue is taken now, so it must stop\n# advertising itself to a human looking for something to pick up. One update per\n# label: `--unlabel` fails the WHOLE call when a named label is absent, so a\n# combined call on an issue carrying only one of them would remove neither.\nglab issue update \"${NUM}\" --unlabel 'good first issue' 2>/dev/null\nglab issue update \"${NUM}\" --unlabel 'help wanted' 2>/dev/null\ncd \"${WORKTREE}\"\n```\n\nReleasing `good first issue` / `help wanted` is deliberate and one-way: they invite a human contributor, and every path out of this flow either closes the issue or returns it to the AUTONOMOUS queue, where those labels mean nothing. Do NOT restore them when Phase 3 or Phase 7 releases the claim — re-advertising the issue to humans is a call for the human who wants it re-advertised.\n\n**If `git worktree add` fails because the `claim/issue-<num>` branch already exists** (a concurrent run won the race), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash `WORKTREE` — you'll need it for Phase 7 cleanup.\n\n## Phase 3 — Verify still valid\n\nRead the full issue (`glab issue view \"${NUM}\"`) before writing any code. **Every exit from this phase must leave a CONVERGING outcome on the issue — closed, or labeled `needs-input`.** Phase 1 step 4 skips both, so an autonomous drain stops re-picking the item. Releasing an issue OPEN and unlabeled is NOT an exit: the work detector still reports it actionable, so the next pass re-picks it and burns another no-op agent — every pass, forever.\n\n- **Already fixed, superseded, or closed-then-reopened-for-tracking** — a note says so, or the change it asks for is already on the default branch. **Close it:** post a note naming the MR/commit (or issue) that already delivered it (`glab issue note \"${NUM}\" -m \"...\"`), then `glab issue close \"${NUM}\"` and clear the markers (`glab issue update \"${NUM}\" --unassign --unlabel in-progress`). Remove the worktree and return to Phase 1. **Evidence gate: if you cannot name the MR, commit, or issue that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the issue as real work and continue to Phase 4.\n- **Stale reference** — the request names a function, file, or component that no longer exists (`grep -rn` the named identifiers; if they're gone, the issue is stale). Post a note naming what you searched for and what you found instead, **tag it `needs-input`** (`glab issue update \"${NUM}\" --label needs-input`), release the claim markers (`glab issue update \"${NUM}\" --unassign --unlabel in-progress`), remove the worktree, and return to Phase 1. Re-scoping a stale issue against today's code is a human call — and the label is what keeps the drain off it in the meantime.\n\n(A too-large scope is NOT in this list — it has its own park path below.)\n\n**A genuinely too-large issue gets SPLIT, not parked.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 6's `Refs` path, promote it to an epic and decompose it exactly as **Phase 1b** steps 4–6 describe (each slice carrying `Part of #${NUM}`). **Promote it on BOTH axes, creating the umbrella label first** — the queue skips a parent only when it is epic-shaped AND marked, so an issue left carrying only `decomposed` stays claimable and gets re-split every pass: `glab label create --name epic --color '#B60205' --description 'Umbrella/tracking issue — shipped as per-slice children, never as one PR' 2>/dev/null || true`, then `glab issue update \"${NUM}\" --label epic --label decomposed`. Confirm both landed (`glab issue view \"${NUM}\" --output json`); if the `epic` label won't stick, append \" (epic)\" to the title instead — the title convention marks an epic with no label at all. Then release its claim markers (`glab issue update \"${NUM}\" --unassign --unlabel in-progress`), remove the worktree, and continue at Phase 2 with the first slice you filed. Splitting an omnibus issue is work you do, not a hand-off. Park to `needs-input` (`glab issue update \"${NUM}\" --label needs-input`, release the markers, remove the worktree, exit) ONLY when the issue is too vague to slice against the code at all — that park stops a perpetual drain from re-picking an un-shippable issue every pass (Phase 1 step 4 skips `needs-input`).\n\n**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to `needs-input`. Pick the most reasonable interpretation, record the approach you chose in a brief issue note (`glab issue note \"${NUM}\" -m \"...\"`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve `needs-input` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining note, **tag it `needs-input`** (`glab issue update \"${NUM}\" --label needs-input`), release the claim markers (`glab issue update \"${NUM}\" --unassign --unlabel in-progress`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips `needs-input` issues. Never leave a half-claimed issue.\n\n## Phase 4 — Implement\n\nWrite the code, tests, and any docs the issue requires. Follow the repo conventions in AGENTS.md (or CLAUDE.md). Run the relevant test suite as you go.\n\n**Roll discovered backbone work INTO this MR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (`glab issue create`) tagged `plan` that references this one (`Related to #<num>`). Choose independent dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated `--label` flags; do not prefix the title with `[category]` / `[model:…]`.\n\nCommit with a conventional message referencing the issue:\n\n```\n<type>: <one-line description> (#<num>)\n```\n\n## Phase 5 — Review locally (BEFORE any MR exists)\n\n**Every reviewer that can read the working tree runs HERE, while there is still no MR.** Open the MR only once the branch is already review-clean: the MR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until an MR is open.\n\nThe configured reviewers for this task, in order, are `{reviewers}`. Split that list in two, preserving its order:\n\n- **LOCAL reviewers — every token that is NOT an `@<login>`.** `claude` / `codex` / `antigravity` (CLI binary: `agy`) / `grok` / `cursor` invoke a local-CLI critique; `lmstudio` / `ollama` use the appended Local Reviewer Procedure. They read this branch's own diff and need no MR — run them in THIS phase.\n- **MR-SIDE reviewers — every `@<login>` token**, plus any review bot the project requests automatically when an MR opens. They review server-side and cannot start before the MR exists — they run in Phase 6.\n\n1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its `AGENTS.md` (or `CLAUDE.md`) and changelog README (e.g. `.changelog/README.md`) first. Some repos collect per-branch fragments in a directory (e.g. `.changelog/next/`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (`.changelog/NEXT.md`, or `## Unreleased` in `CHANGELOG.md`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.\n2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent `/simplify` pass; on other CLIs, do the equivalent review by hand.\n3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR diff.** No MR exists yet, so `glab mr diff` has nothing to read — use the CLI's own base-diff mode or `git diff \"origin/${DEFAULT_BRANCH}...HEAD\"`. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR on the strength of it.\n4. **If the branch cannot be brought to a shippable state here, do NOT open an MR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Post a note on the ISSUE naming the reviewer and the failure (`glab issue note \"${NUM}\" -m \"...\"`), leave the assignee and the `in-progress` label in place, remove ONLY the worktree (`cd {repoPath} && git worktree remove \"${WORKTREE}\"`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.\n\n## Phase 6 — Open the merge request, satisfy MR-side review + CI, and merge\n\nEvery local reviewer's fixes are already committed, so the MR opens against finished work. This flow ships GitLab issues — it does NOT touch PLAN.md. The audit trail is the merged MR + `git log`.\n\n1. Push the branch: `git push -u origin \"claim/issue-${NUM}\"`. Then confirm `git log --oneline @{u}..HEAD` is empty — if it isn't, a Phase 5 review fix never left the machine and the MR would be opened against a stale diff; push again before continuing.\n2. Open the MR with `glab mr create --fill --source-branch \"claim/issue-${NUM}\" --target-branch \"${DEFAULT_BRANCH}\" --yes`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain `Closes #${NUM}` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use `Refs #${NUM}` instead (NOT `Closes`) and add a `## Remaining` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass `--description` if `--fill` didn't capture it).\n3. **Satisfy the MR-SIDE reviewers.** For each `@<login>` from the Phase 5 split, request the review now (resolve `MR_IID` from the source branch exactly as step 5 does, then `glab mr update \"${MR_IID}\" --reviewer <login>`, dropping the `@`; if glab rejects the flag, run `glab mr update --help` rather than guessing), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the project auto-requests a review bot when the MR opens, wait that round out and address it the same way. With no `@<login>` configured and no bot review appearing, this step is a no-op.\n\n **Review-stuck cleanup** (an MR-side reviewer still unsatisfied after 3 rounds): post one summarizing MR note (`glab mr note`), then run the worktree-only cleanup (`cd {repoPath} && git worktree remove \"${WORKTREE}\"`). Leave the local branch, the open MR, the assignee, and the `in-progress` label in place so the human picks up cold. Do NOT run Phase 7.\n4. **Let required CI finish and go green** — inspect the MR's pipeline (`glab ci status` on the branch, or `glab mr view \"${MR_IID}\"`). A red required pipeline is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.\n5. **Merge immediately via `glab mr merge`** — NEVER a local `git merge`. `glab mr merge` takes the **MR IID**, which is NOT the issue number — resolve it from the source branch first, merge, then verify remote state:\n ```bash\n MR_IID=\"$(glab mr list --source-branch \"claim/issue-${NUM}\" --output json | sed -n 's/.*\"iid\":\\([0-9]\\{1,\\}\\).*/\\1/p' | head -1)\"\n glab mr merge \"${MR_IID}\" --yes --remove-source-branch || {\n glab mr view \"${MR_IID}\" --output json | jq -e 'select((.state | ascii_downcase) == \"merged\")' >/dev/null || glab mr merge \"${MR_IID}\" --yes --squash --remove-source-branch\n }\n glab mr view \"${MR_IID}\" --output json | jq -er 'select((.state | ascii_downcase) == \"merged\") | .state'\n ```\n The verification command must succeed and print a merged state. An opened/closed state or missing value is not success; investigate CI, review, and branch protection, then retry. Do not enter Phase 7 until the forge confirms the MR is merged.\n\n## Phase 7 — Clean up (post-merge ONLY)\n\nThis phase runs only after the MR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):\n\n```bash\ncd {repoPath}\ngit worktree remove \"${WORKTREE}\"\ngit branch -d \"claim/issue-${NUM}\"\n```\n\nIf `git branch -d` refuses, fetch the default branch and re-check the MR's merged state. Retry `-d` only when Git proves the branch integrated; otherwise leave it for reconciliation. Never force-delete with `-D`.\n\n**Reconcile the issue — did this MR FULLY satisfy its scope?**\n- **Yes (full)** — the `Closes #${NUM}` line already auto-closed it on merge to the default branch; if it's somehow still open, close it (`glab issue close \"${NUM}\"`) and remove the label (`glab issue update \"${NUM}\" --unlabel in-progress`).\n- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing note (shipped ✓ / moved to #NEW), remove `in-progress`, and file ONE tightly-scoped follow-up for the remainder: `glab issue create --title \"…\" --label plan [--label model:<tier>] [--label effort:<level>] [--label \"good first issue\"] [--label \"help wanted\"] --description \"…\\n\\nRefs #${NUM}\"` (carry over any `area:*` labels the issue had; choose the optional labels independently and only when justified — a leftover mechanical sweep is not a good first issue).\n+ **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a `Done ✓ / Remaining ▢` note, and release the claim so the queue re-picks it: `glab issue update \"${NUM}\" --unassign --unlabel in-progress` (`--unassign` clears every current assignee).\n\nNEVER leave the issue OPEN with `in-progress` still on it — that strands it as a zombie (the claim queue skips `in-progress`, so the remaining scope is never re-picked). **Do NOT `git pull`** from inside this phase — the work is already integrated on GitLab via `glab mr merge`; leave the user's working tree alone.");
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index cd1d6debe2..8826a7b600 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -37,6 +37,8 @@ const UMBRELLA_LABEL_CREATE_GLAB = formatLabelCreateCommand(EPIC_LABEL, { cli: '
const CONTRIBUTOR_RELEASE_GH = formatContributorLabelReleaseCommands('"${NUM}"').join('\n');
const CONTRIBUTOR_RELEASE_GLAB = formatContributorLabelReleaseCommands('"${NUM}"', { cli: 'glab' }).join('\n');
+const REQUIRED_REVIEW_PUBLICATION_RULE = `**Required-review publication rule:** Before running local reviewers, initialize the worktree-private status file with \`REVIEW_STATUS_FILE="$(git rev-parse --git-path portos-review-status)"; printf 'REVIEW_STATUS=clean\\n' > "$REVIEW_STATUS_FILE"\`; if that write fails, stop before publication. A required local reviewer that cannot produce a verdict because its CLI/provider is unavailable, a quota or spend limit is exhausted, or the invocation has a timeout, transport failure, malformed/empty output, or no verdict is \`review-blocked\`, not a publication failure. Do NOT substitute a self-review. Record that state, continue to push and open the PR/MR, then post a comment saying it is intentionally left open and will not be merged until the required review completes. Preserve the claim markers and branch, and stop before merge. A substantive rejection or unresolved finding, failed build/test, unpushed fix, or state/publication failure still blocks publication.`;
+
const SCHEDULED_ISSUE_QUALITY_GATE = `## Scheduled issue-quality gate
${ISSUE_QUALITY_GUIDANCE}
@@ -1178,7 +1180,9 @@ Commit with a conventional message referencing the issue so the trail is grep-ab
## Phase 5 — Review locally (BEFORE any PR exists)
-**Every reviewer that can read the working tree runs HERE, while there is still no PR.** Open the PR only once the branch is already review-clean: the PR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until a PR is open.
+${REQUIRED_REVIEW_PUBLICATION_RULE}
+
+**Every reviewer that can read the working tree runs HERE, while there is still no PR.** Open the PR once the branch is review-clean or a required reviewer is recorded as review-blocked: the PR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until a PR is open.
The configured reviewers for this task, in order, are \`{reviewers}\`. Split that list in two, preserving its order:
@@ -1187,8 +1191,8 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split tha
1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.
2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.
-3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not a PR diff.** No PR exists yet, so \`gh pr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff origin/main...HEAD\` (substitute the repo's default branch when it isn't \`main\`). Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open a PR on the strength of it.
-4. **If the branch cannot be brought to a shippable state here, do NOT open a PR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Comment on the ISSUE naming the reviewer and the failure (\`gh issue comment "\${NUM}" --body "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.
+3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not a PR diff.** No PR exists yet, so \`gh pr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff origin/main...HEAD\` (substitute the repo's default branch when it isn't \`main\`). Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, quota/provider or transport failure, timeout, malformed response, empty response, or no-verdict result from a REQUIRED reviewer is unavailable, not clean: do NOT substitute your own self-review; record \`REVIEW_STATUS=review-blocked\` in the worktree-private status file and continue to Phase 6 when the code and tests are otherwise shippable. An optional inconclusive result remains non-blocking.
+4. **If the branch cannot be brought to a shippable state here, do NOT open a PR** — that means substantive reviewer findings remain after 3 rounds, fixes leave the build/tests red, a review fix is unpushed, or the review/status state cannot be persisted. Comment on the ISSUE naming the failure (\`gh issue comment "\${NUM}" --body "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. Reviewer unavailability alone is \`review-blocked\`, so it does not take this stop path. Do NOT run Phase 7.
## Phase 6 — Open the PR, satisfy PR-side review + CI, and merge
@@ -1196,6 +1200,7 @@ Every local reviewer's fixes are already committed, so the PR opens against fini
1. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`. Then confirm \`git log --oneline @{u}..HEAD\` is empty — if it isn't, a Phase 5 review fix never left the machine and the PR would be opened against a stale diff; push again before continuing.
2. Open the PR with \`gh pr create\`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain \`Closes #\${NUM}\` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded.
+2a. If Phase 5 recorded REVIEW_STATUS=review-blocked, source REVIEW_STATUS_FILE="$(git rev-parse --git-path portos-review-status)" and post exactly this comment before doing anything else: gh pr comment "$PR_URL" --body "Required code review was not completed before publication. This PR is intentionally left open and will not be merged until the required review completes." Verify the comment succeeds, preserve the claim markers and branch, leave the PR open, and stop before the PR-side review, CI, or merge steps.
3. **Satisfy the PR-SIDE reviewers.** For each \`@<login>\` from the Phase 5 split, request the review now (\`gh pr edit <pr-number> --add-reviewer <login>\`, drop the \`@\`), poll every 5–15s for it, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the repo auto-requests a review bot when the PR opens, wait that round out and address it the same way. With no \`@<login>\` configured and no bot review appearing, this step is a no-op.
**Review-stuck cleanup** (a PR-side reviewer still unsatisfied after 3 rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.
@@ -1350,7 +1355,9 @@ Commit with a conventional message referencing the issue:
## Phase 5 — Review locally (BEFORE any MR exists)
-**Every reviewer that can read the working tree runs HERE, while there is still no MR.** Open the MR only once the branch is already review-clean: the MR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until an MR is open.
+${REQUIRED_REVIEW_PUBLICATION_RULE}
+
+**Every reviewer that can read the working tree runs HERE, while there is still no MR.** Open the MR once the branch is review-clean or a required reviewer is recorded as review-blocked: the MR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until an MR is open.
The configured reviewers for this task, in order, are \`{reviewers}\`. Split that list in two, preserving its order:
@@ -1359,8 +1366,8 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split tha
1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this.
2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent review by hand.
-3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR diff.** No MR exists yet, so \`glab mr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR on the strength of it.
-4. **If the branch cannot be brought to a shippable state here, do NOT open an MR** — that is a local reviewer still unsatisfied after 3 rounds, or fixes that leave the build/tests red. Post a note on the ISSUE naming the reviewer and the failure (\`glab issue note "\${NUM}" -m "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. The branch stays for a human to pick up cold. Do NOT run Phase 7.
+3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR diff.** No MR exists yet, so \`glab mr diff\` has nothing to read — use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, quota/provider or transport failure, timeout, malformed response, empty response, or no-verdict result from a REQUIRED reviewer is unavailable, not clean: do NOT substitute your own self-review; record REVIEW_STATUS=review-blocked in the worktree-private status file and continue to Phase 6 when the code and tests are otherwise shippable. An optional inconclusive result remains non-blocking.
+4. **If the branch cannot be brought to a shippable state here, do NOT open an MR** — that means substantive reviewer findings remain after 3 rounds, fixes leave the build/tests red, a review fix is unpushed, or the review/status state cannot be persisted. Reviewer unavailability alone is review-blocked, so it does not take this stop path. Post a note on the ISSUE naming the reviewer and the failure (\`glab issue note "\${NUM}" -m "..."\`), leave the assignee and the \`in-progress\` label in place, remove ONLY the worktree (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`), and stop. Leave the branch and worktree in place for a human to pick up cold. Do NOT run Phase 7.
## Phase 6 — Open the merge request, satisfy MR-side review + CI, and merge
@@ -1368,6 +1375,7 @@ Every local reviewer's fixes are already committed, so the MR opens against fini
1. Push the branch: \`git push -u origin "claim/issue-\${NUM}"\`. Then confirm \`git log --oneline @{u}..HEAD\` is empty — if it isn't, a Phase 5 review fix never left the machine and the MR would be opened against a stale diff; push again before continuing.
2. Open the MR with \`glab mr create --fill --source-branch "claim/issue-\${NUM}" --target-branch "\${DEFAULT_BRANCH}" --yes\`. **Choose the issue trailer deliberately:** if this MR FULLY satisfies the issue's scope, the description MUST contain \`Closes #\${NUM}\` so the merge auto-closes it; if you deliberately shipped only PART of the issue (a valuable slice with real scope remaining), use \`Refs #\${NUM}\` instead (NOT \`Closes\`) and add a \`## Remaining\` section listing what's left — Phase 7 reconciles the issue so it is never stranded. Summarize what shipped + a short test plan (pass \`--description\` if \`--fill\` didn't capture it).
+2a. If Phase 5 recorded REVIEW_STATUS=review-blocked, source REVIEW_STATUS_FILE="$(git rev-parse --git-path portos-review-status)" and resolve MR_IID from the source branch. Post exactly this note before doing anything else: glab mr note "$MR_IID" --message "Required code review was not completed before publication. This MR is intentionally left open and will not be merged until the required review completes." Verify the note succeeds, preserve the claim markers and branch, leave the MR open, and stop before the MR-side review, CI, or merge steps.
3. **Satisfy the MR-SIDE reviewers.** For each \`@<login>\` from the Phase 5 split, request the review now (resolve \`MR_IID\` from the source branch exactly as step 5 does, then \`glab mr update "\${MR_IID}" --reviewer <login>\`, dropping the \`@\`; if glab rejects the flag, run \`glab mr update --help\` rather than guessing), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the project auto-requests a review bot when the MR opens, wait that round out and address it the same way. With no \`@<login>\` configured and no bot review appearing, this step is a no-op.
**Review-stuck cleanup** (an MR-side reviewer still unsatisfied after 3 rounds): post one summarizing MR note (\`glab mr note\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open MR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.
@@ -1531,18 +1539,21 @@ Commit with a conventional message referencing the ticket so the trail is grep-a
## Phase 5 — Review locally, then open the MR/PR and move to In Review
+${REQUIRED_REVIEW_PUBLICATION_RULE}
+
The audit trail is the merged MR/PR + \`git log\`. Detect the forge from the git origin and use the matching CLI (\`gh\` for GitHub, \`glab\` for GitLab).
The configured reviewers for this task, in order, are \`{reviewers}\`. Split them by where they can run, preserving order: **LOCAL reviewers** — every token that is NOT an \`@<login>\` (\`claude\` / \`codex\` / \`antigravity\` (CLI binary: \`agy\`) / \`grok\` / \`cursor\` invoke a local-CLI critique; \`lmstudio\` / \`ollama\` use the appended Local Reviewer Procedure) read the working tree and need no MR/PR, so they run in steps 1–2 below, BEFORE it is opened. **PR-SIDE reviewers** — every \`@<login>\` token, plus any review bot the repo requests automatically on open — review cloud-side and run in Phase 6, once the MR/PR exists.
1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the MR/PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its \`AGENTS.md\` (or \`CLAUDE.md\`) and changelog README (e.g. \`.changelog/README.md\`) first. Some repos collect per-branch fragments in a directory (e.g. \`.changelog/next/\`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (\`.changelog/NEXT.md\`, or \`## Unreleased\` in \`CHANGELOG.md\`) in the repo's existing prose style only when no convention is documented. Otherwise skip it.
2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff. Claude Code runs this as the three-agent \`/simplify\` pass; on other CLIs, do the equivalent by hand.
-3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR/PR diff.** Nothing is open yet, so use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`; local LLM reviewers go through the appended endpoint procedure. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance. A missing CLI, timeout, transport failure, malformed response, or empty response is UNSATISFIED, not clean. Do NOT substitute your own self-review, and do NOT open an MR/PR on the strength of it. If a local reviewer stays unsatisfied after 3 rounds, or its fixes leave the build/tests red, do NOT open one — leave the branch and worktree in place, comment the failure on the ticket (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments), and stop.
+3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not an MR/PR diff.** Nothing is open yet, so use the CLI's own base-diff mode or \`git diff "origin/\${DEFAULT_BRANCH}...HEAD"\`; local LLM reviewers go through the appended endpoint procedure. Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance. A missing CLI, quota/provider or transport failure, timeout, malformed response, empty response, or no-verdict result from a REQUIRED reviewer is unavailable, not clean: do NOT substitute your own self-review; record REVIEW_STATUS=review-blocked in the worktree-private status file and continue to Phase 6 when the code and tests are otherwise shippable. An optional inconclusive result remains non-blocking. If substantive findings remain after 3 rounds, fixes leave the build/tests red, a review fix is unpushed, or the review/status state cannot be persisted, do NOT open one — leave the branch and worktree in place, comment the failure on the ticket (POST ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/comments), and stop. Reviewer unavailability alone is REVIEW_STATUS=review-blocked, so it does not take this stop path.
4. Push the branch: \`git push -u origin "claim/\${KEY}"\`, then confirm \`git log --oneline @{u}..HEAD\` is empty so every review fix from step 3 is in the MR/PR's diff.
5. Open the MR/PR. Reference the JIRA \`KEY\` in the title and description (there is NO \`Closes\` auto-close for JIRA). Summarize what shipped + a short test plan.
- GitHub: \`gh pr create --fill --head "claim/\${KEY}"\` (then edit the body to mention \`KEY\` if \`--fill\` didn't).
- GitLab: \`glab mr create --fill --source-branch "claim/\${KEY}" --target-branch "\${DEFAULT_BRANCH}" --yes\`.
Capture the MR/PR URL as \`PR_URL\`.
+5a. If REVIEW_STATUS=review-blocked after the MR/PR opens, post exactly this message with the detected forge CLI before continuing: "Required code review was not completed before publication. This MR/PR is intentionally left open and will not be merged until the required review completes." Verify the note succeeds, preserve the branch, and continue the required In Review transition and ticket-link steps; the MR/PR remains open for the human handoff.
6. **Move the ticket to "In Review" — REQUIRED, not optional. Do not finish while it is still "In Progress":**
- GET ${PORTOS_API_URL}/api/jira/instances/<instanceId>/tickets/<KEY>/transitions again (transitions change once In Progress).
- Pick the transition whose target status best matches "In Review" (e.g. "In Review", "Code Review", "Review", "Ready for Review"); match case-insensitively.
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 079b174cf6..136e1f4105 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -12,9 +12,9 @@ export const PROMPT_VERSIONS = {
'do-replan': 2, // v2: scheduled issue-quality gate rejects speculative/future-only work and keeps valid current refactors claimable
'feature-ideas': 11, // v11: Phase 4 (Brainstorm) establishes product direction from the repo's own documents in precedence order — root `PRD.md` first, then `GOALS.md`, then README/docs — and the candidate test cites PRD requirements when one exists. v9's "read GOALS.md, else focus on general improvements" ignored a PRD entirely, so a repo whose product intent lives in PRD.md (PortOS included) had its most specific source unread. Mirrors plan-feature v2. v10: Phase 4 (Brainstorm) consults the repo's REJECTED.md and recently closed-unmerged PRs before proposing, so ideas the user already declined aren't re-proposed (mirrors idle-review's REJECTED.md contract). v9: drop DONE.md reads — use `.changelog/` + `git log` (last 50) as the completed-work signal
'plan-task': 18, // v18: scheduled plan-task no longer instructs a code-review loop; v17: the implement + changelog steps name `AGENTS.md` (or `CLAUDE.md`) as the repo-conventions file (#4852 made AGENTS.md canonical; the dual naming keeps a managed app that still carries only the old name discoverable). v16: every reviewer that can read the working tree runs BEFORE the PR is opened — Phase 6 splits the configured list into LOCAL reviewers (every non-`@<login>` token, reviewed against `git diff origin/main...HEAD`) and PR-SIDE reviewers (`@<login>` plus any auto-requested review bot), opens the PR only once the branch is review-clean, and then waits on those PR-side reviewers plus required CI. Previously the PR was opened first and every reviewer ran against its diff, so each round of findings landed as follow-up commits on an already-public PR. v14: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v13: Phase 5's changelog step reads the repo's documented convention FIRST (per-branch fragment directory + helper script, as PortOS now uses) and only falls back to detect-and-append when none is documented; the Phase 6 review-stuck note no longer names `.changelog/NEXT.md` as the file it wrote. v12: the reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — the bare `antigravity` slug is a command that exists nowhere, and a review-loop agent that probed for it concluded no reviewer was available and merged on its own self-review. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v11: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v10: Phase 3 "decide, don't defer" — an *ambiguous* PLAN.md item no longer jumps to the Phase 3b clarification PR; the agent picks the most reasonable reading, notes it, and implements. Phase 3b is reserved for destructive/irreversible or genuinely-human-gated items. Mirrors claim-issue v7 + CLAUDE.md. v9: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v8: Phase-6 merge fallback prefers --merge over --squash (after --auto), matching the /do:pr + review-loop default and PortOS's merge-only policy
- 'claim-issue': 22, // v22: Phase 2 releases `good first issue` / `help wanted` (one best-effort `--remove-label` per label, since a combined edit fails the whole call when either label is absent) alongside the assignee + `in-progress` markers, and does not restore them when the claim is later released. v21: an epic is no longer a dead end — Phase 1 treats an UNdecomposed epic as eligible (last-resort, after every atomic issue) and routes it to the new Phase 1b, which reuses an existing child split or files one (2–8 independently shippable slices, each `Part of #<epic>`), rewrites the epic body with a `## Decomposed into` checklist, stamps the `decomposed` label, and then claims the first slice. Phase 3's too-large branch decomposes instead of parking to `needs-input`. Before this, a queue holding only epics ended every run with nothing done. `decomposed` is the convergence marker the perpetualWork detector reads (isActionableIssue). v20: canonicalize GitHub's ssh.github.com SSH-over-443 alias before host-aware identity probes. v19: host-aware GitHub identity probes use the repository origin, and probe failures stay transient instead of parking an assigned-only queue. v18: explicit issue-page claims ignore existing assignees; auto-pick resolves the authenticated login so self-assigned issues remain retryable; open continuation handoffs clear in-progress and all assignees. v17: mirrors plan-task v17 — Phase 4 and Phase 5 name `AGENTS.md` (or `CLAUDE.md`) as the repo-conventions file (#4852). v16: Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder (resolveIssueExcludeLabelsBlock, cosTaskGenerator.js) — the fixed NON_ACTIONABLE_ISSUE_LABELS set plus any app-configured `taskMetadata.issueExcludeLabels` extras (e.g. `good first issue`), so the live claim agent honors the same per-app exclusions the perpetual-drain detector applies, not just the hardcoded set. The pinned-target constraint (`/do:next <num>` / the work-item picker) also re-checks that resolved list, not just the fixed 3, so a target that gained an excluded label after the picker snapshot still isn't force-claimed. Phase 1's candidate fetch widened to `--limit 500` (was 100), matching perpetualWork.js's detector — the label filter runs on the fetched page, so a small cap risked missing eligible work further down a busy queue. v15: Phase 5 is now the pre-PR local review (LOCAL reviewers = every non-`@<login>` token, run against the branch diff; an unsatisfied one blocks PR creation entirely) and Phase 6 opens the PR, satisfies the PR-SIDE reviewers (`@<login>` plus any auto-requested review bot) and required CI, then merges. v13: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v12: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v11: EVERY Phase-3 release now converges — the "already fixed / superseded" case CLOSES the issue (with a comment naming what delivered it) and the "stale reference" case tags `needs-input`, instead of both releasing the issue open and unlabeled. `isActionableIssue` (perpetualWork.js) can only see labels/assignees/epic/in-flight, so a body-or-comment-driven release left the issue looking actionable and the perpetual drain re-spawned a no-op agent on it every tick. v10: Phase 5's changelog step defers to the convention the repo documents (per-branch fragment directory + helper script when present) instead of prescribing an append to `.changelog/NEXT.md`. v9: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v8: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v7: Phase 3 no longer releases/parks an *ambiguous* issue to `needs-input` — the agent decides (picks the most reasonable reading, records it in an issue comment, ships) rather than punting the choice back to a human; `needs-input` is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. Mirrors the "Decide, don't defer" policy in CLAUDE.md. v6: Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix — mirrors the perpetualWork detector so a `[Epic]`-titled issue with no `epic` label stops re-spawning a claim agent that always skips it (perpetual drain now converges/parks). v5: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v4: Phase 5 chooses the issue trailer deliberately (Closes for a full ship, Refs + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the `in-progress` claim — so a partial ship is never left OPEN + `in-progress` (a zombie the claim queue skips forever). v3: Phase 3 tags an ambiguous/too-large issue `needs-input` (not just a comment) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge instead of re-picking the same un-actionable issue. v2: stop treating the bare `plan` label as a skip — `plan` is the claimable-queue label (do-replan --issues labels every migrated backlog item `plan`), so v1's exclusion emptied the whole actionable queue; now skip only true epics (`epic` label or "(epic)" title)
- 'claim-issue-gitlab': 20, // v20: mirrors claim-issue v22 — Phase 2 releases `good first issue` / `help wanted` (one best-effort `--unlabel` per label) alongside the assignee + `in-progress` markers. v19: mirrors claim-issue v21 — Phase 1b decomposes an undecomposed epic into per-slice issues (`Part of #<epic>`, `decomposed` marker label on the parent) and claims the first slice, and the too-large branch splits rather than parking. v18: explicit issue-page claims ignore existing assignees; auto-pick resolves the authenticated login so self-assigned issues remain retryable; open continuation handoffs clear in-progress and all assignees. v17: mirrors claim-issue v17 — the repo-conventions file is named `AGENTS.md` (or `CLAUDE.md`) (#4852). v16: the Phase 1 and Phase 6 glab recipes use `--output json` instead of `-F json`. On `glab issue list`, `-F` is `--output-format` (details|ids|urls) — a DIFFERENT flag from `--output` (text|json) — so that spelling was accepted, ignored, and answered with the human table at exit 0; an agent piping that to `jq` got nothing and could not distinguish it from "no issues". `--output json` is correct on every glab subcommand, so the mr recipes are normalized to the same spelling in this bump. v15: mirrors claim-issue v16 — Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder. v14: mirrors claim-issue v15 — Phase 5 runs the LOCAL reviewers against the branch diff before any MR exists, Phase 6 opens the MR and satisfies the MR-SIDE reviewers + pipeline before merging. v12: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v11: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v10: mirrors claim-issue v11 — every Phase-3 release converges (close the already-fixed/superseded issue, tag the stale-reference one `needs-input`) so the perpetual drain stops re-picking it. v9: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v8: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v7: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v6: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* issue (record the chosen reading in an issue note, ship) instead of parking it to `needs-input`, which is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. v5: mirrors claim-issue v6 — Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix, so the GitLab detector/agent converge on epic-titled issues too. v4: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v3: mirrors claim-issue v4 — Phase 5 chooses Closes-vs-Refs deliberately and Phase 7 reconciles the issue with the partial-ship hybrid (close + scoped follow-up when separable, else "done/remaining" note + release the `in-progress` claim) so a partial ship is never stranded. v2: Phase 3 tags an ambiguous/too-large issue `needs-input` (mirrors claim-issue v3) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge. v1: GitLab sibling of claim-issue — same 7-phase /claim --issues flow over `glab` issues + merge requests. Reached via the claim-work router when an app's resolved workTracker is 'gitlab'.
- 'claim-issue-jira': 15, // v15: mirrors claim-issue v21 / claim-issue-gitlab v19 — an epic is no longer a dead end. Phase 1 treats an UNdecomposed epic as eligible (last-resort, after every atomic ticket) and routes it to the new Phase 1b, which reuses an existing child split or files one (2–8 independently shippable slices, each assigned to the caller and dropped into the active sprint so the NEXT run can actually see them), rewrites the epic's description with a `## Decomposed into` checklist, stamps the `decomposed` label, and claims the first slice. Phase 3's too-large branch splits instead of parking. This became possible when #5042 taught the JIRA reads to carry the data: getIssue now projects labels/description/epic link, fetchMyCurrentSprintTickets returns labels, and a new getEpicChildren finds an epic's children (a failed lookup throws rather than reading as "no children"). v14: Phase 1 states WHY this flow leaves an epic for a human while claim-issue v21 / claim-issue-gitlab v19 now decompose one — the JIRA reads PortOS exposes (jira.js#getIssue, #fetchMyCurrentSprintTickets) return neither a ticket's labels nor its epic links, so an agent here can see no decomposition marker and cannot find an epic's existing children. Doc-only; the flow is unchanged, and porting Phase 1b here is tracked in #5042. v13: mirrors claim-issue v17 — the repo-conventions file is named `AGENTS.md` (or `CLAUDE.md`) (#4852). v12: mirrors claim-issue v15 in the JIRA flow — Phase 5 runs the LOCAL reviewers against the branch diff before the MR/PR is opened (and before the In Review transition), Phase 6 keeps only the PR-side reviewers plus the worktree cleanup. v10: follow-up tickets receive equivalent hyphenated dispatch (`model-*`/`effort-*`) and contributor (`good-first-issue`/`help-wanted`) labels when independently justified. v9: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v8: mirrors claim-issue v11 in JIRA's status vocabulary — an already-fixed/superseded ticket transitions to Done/Closed and a stale-reference ticket parks on a Blocked/On Hold status behind a Review Hub todo, instead of transitioning back to a not-started status that Phase 1 immediately re-picks. v7: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v6: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v5: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of `{repoPath}/data/cos/worktrees/`, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v4: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* ticket (record the chosen reading in a ticket comment, ship) instead of parking it to a "Needs clarification" Review Hub todo, and Phase 1 no longer skips a merely-underspecified ticket; the todo is reserved for destructive/irreversible or genuinely-human-gated cases. v3: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v2: Phase 5 records remaining scope in the ticket (Done/Remaining comment) and files a follow-up ticket when a partial ship's remainder is separable, so remaining work isn't lost when a human lands the MR/PR. v1: JIRA sibling of claim-issue — claim ONE ready sprint ticket, move it To Do→In Progress→In Review around a self-managed worktree + MR/PR. Reached via the claim-work router when an app's resolved workTracker is 'jira' (replaces the prior jira→jira-sprint-manager route).
+'claim-issue': 23, // v23: required local-review execution failures (including quota/provider exhaustion, timeout, transport, malformed/empty, or no-verdict results) record `review-blocked`, still publish the PR, and leave it open with a pending-review comment; substantive findings and publication failures still block. // v22: Phase 2 releases `good first issue` / `help wanted` (one best-effort `--remove-label` per label, since a combined edit fails the whole call when either label is absent) alongside the assignee + `in-progress` markers, and does not restore them when the claim is later released. v21: an epic is no longer a dead end — Phase 1 treats an UNdecomposed epic as eligible (last-resort, after every atomic issue) and routes it to the new Phase 1b, which reuses an existing child split or files one (2–8 independently shippable slices, each `Part of #<epic>`), rewrites the epic body with a `## Decomposed into` checklist, stamps the `decomposed` label, and then claims the first slice. Phase 3's too-large branch decomposes instead of parking to `needs-input`. Before this, a queue holding only epics ended every run with nothing done. `decomposed` is the convergence marker the perpetualWork detector reads (isActionableIssue). v20: canonicalize GitHub's ssh.github.com SSH-over-443 alias before host-aware identity probes. v19: host-aware GitHub identity probes use the repository origin, and probe failures stay transient instead of parking an assigned-only queue. v18: explicit issue-page claims ignore existing assignees; auto-pick resolves the authenticated login so self-assigned issues remain retryable; open continuation handoffs clear in-progress and all assignees. v17: mirrors plan-task v17 — Phase 4 and Phase 5 name `AGENTS.md` (or `CLAUDE.md`) as the repo-conventions file (#4852). v16: Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder (resolveIssueExcludeLabelsBlock, cosTaskGenerator.js) — the fixed NON_ACTIONABLE_ISSUE_LABELS set plus any app-configured `taskMetadata.issueExcludeLabels` extras (e.g. `good first issue`), so the live claim agent honors the same per-app exclusions the perpetual-drain detector applies, not just the hardcoded set. The pinned-target constraint (`/do:next <num>` / the work-item picker) also re-checks that resolved list, not just the fixed 3, so a target that gained an excluded label after the picker snapshot still isn't force-claimed. Phase 1's candidate fetch widened to `--limit 500` (was 100), matching perpetualWork.js's detector — the label filter runs on the fetched page, so a small cap risked missing eligible work further down a busy queue. v15: Phase 5 is now the pre-PR local review (LOCAL reviewers = every non-`@<login>` token, run against the branch diff; an unsatisfied one blocks PR creation entirely) and Phase 6 opens the PR, satisfies the PR-SIDE reviewers (`@<login>` plus any auto-requested review bot) and required CI, then merges. v13: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v12: claim worktree creation passes `--no-track`, so a branch based on `origin/main` cannot inherit `main` as its upstream and make a config-derived push write directly to the default branch; the later `git push -u` sets the intended branch upstream. v11: EVERY Phase-3 release now converges — the "already fixed / superseded" case CLOSES the issue (with a comment naming what delivered it) and the "stale reference" case tags `needs-input`, instead of both releasing the issue open and unlabeled. `isActionableIssue` (perpetualWork.js) can only see labels/assignees/epic/in-flight, so a body-or-comment-driven release left the issue looking actionable and the perpetual drain re-spawned a no-op agent on it every tick. v10: Phase 5's changelog step defers to the convention the repo documents (per-branch fragment directory + helper script when present) instead of prescribing an append to `.changelog/NEXT.md`. v9: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v8: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree. v7: Phase 3 no longer releases/parks an *ambiguous* issue to `needs-input` — the agent decides (picks the most reasonable reading, records it in an issue comment, ships) rather than punting the choice back to a human; `needs-input` is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. Mirrors the "Decide, don't defer" policy in CLAUDE.md. v6: Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix — mirrors the perpetualWork detector so a `[Epic]`-titled issue with no `epic` label stops re-spawning a claim agent that always skips it (perpetual drain now converges/parks). v5: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v4: Phase 5 chooses the issue trailer deliberately (Closes for a full ship, Refs + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the `in-progress` claim — so a partial ship is never left OPEN + `in-progress` (a zombie the claim queue skips forever). v3: Phase 3 tags an ambiguous/too-large issue `needs-input` (not just a comment) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge instead of re-picking the same un-actionable issue. v2: stop treating the bare `plan` label as a skip — `plan` is the claimable-queue label (do-replan --issues labels every migrated backlog item `plan`), so v1's exclusion emptied the whole actionable queue; now skip only true epics (`epic` label or "(epic)" title)
+'claim-issue-gitlab': 21, // v21: required local-review execution failures (including quota/provider exhaustion, timeout, transport, malformed/empty, or no-verdict results) record `review-blocked`, still publish the MR, and leave it open with a pending-review note; substantive findings and publication failures still block. // v20: mirrors claim-issue v22 — Phase 2 releases `good first issue` / `help wanted` (one best-effort `--unlabel` per label) alongside the assignee + `in-progress` markers. v19: mirrors claim-issue v21 — Phase 1b decomposes an undecomposed epic into per-slice issues (`Part of #<epic>`, `decomposed` marker label on the parent) and claims the first slice, and the too-large branch splits rather than parking. v18: explicit issue-page claims ignore existing assignees; auto-pick resolves the authenticated login so self-assigned issues remain retryable; open continuation handoffs clear in-progress and all assignees. v17: mirrors claim-issue v17 — the repo-conventions file is named `AGENTS.md` (or `CLAUDE.md`) (#4852). v16: the Phase 1 and Phase 6 glab recipes use `--output json` instead of `-F json`. On `glab issue list`, `-F` is `--output-format` (details|ids|urls) — a DIFFERENT flag from `--output` (text|json) — so that spelling was accepted, ignored, and answered with the human table at exit 0; an agent piping that to `jq` got nothing and could not distinguish it from "no issues". `--output json` is correct on every glab subcommand, so the mr recipes are normalized to the same spelling in this bump. v15: mirrors claim-issue v16 — Phase 1 step 4's blocking-label check is now the `{issueExcludeLabels}` placeholder. v14: mirrors claim-issue v15 — Phase 5 runs the LOCAL reviewers against the branch diff before any MR exists, Phase 6 opens the MR and satisfies the MR-SIDE reviewers + pipeline before merging. v12: follow-up issue recipes choose independent slashdo dispatch hints (`model:`/`effort:`) and contributor labels (`good first issue`/`help wanted`) instead of only `plan`. v11: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v10: mirrors claim-issue v11 — every Phase-3 release converges (close the already-fixed/superseded issue, tag the stale-reference one `needs-input`) so the perpetual drain stops re-picking it. v9: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v8: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v7: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of a repo-relative `data/cos/worktrees/` path, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v6: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* issue (record the chosen reading in an issue note, ship) instead of parking it to `needs-input`, which is reserved for destructive/irreversible or genuinely-human-gated (hardware/credentials) cases. v5: mirrors claim-issue v6 — Phase 1 epic skip also recognizes a leading `[epic]` bracket or `Epic:` colon title tag (e.g. "[Epic] …" / "Epic: …"), not just an `epic` label or a "(epic)" suffix, so the GitLab detector/agent converge on epic-titled issues too. v4: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v3: mirrors claim-issue v4 — Phase 5 chooses Closes-vs-Refs deliberately and Phase 7 reconciles the issue with the partial-ship hybrid (close + scoped follow-up when separable, else "done/remaining" note + release the `in-progress` claim) so a partial ship is never stranded. v2: Phase 3 tags an ambiguous/too-large issue `needs-input` (mirrors claim-issue v3) so it's excluded from future autonomous claims — required for `perpetual` (drain-until-done) mode to converge. v1: GitLab sibling of claim-issue — same 7-phase /claim --issues flow over `glab` issues + merge requests. Reached via the claim-work router when an app's resolved workTracker is 'gitlab'.
+'claim-issue-jira': 16, // v16: required local-review execution failures (including quota/provider exhaustion, timeout, transport, malformed/empty, or no-verdict results) record `review-blocked`, still publish the MR/PR, and leave it open with a pending-review note; substantive findings and publication failures still block. // v15: mirrors claim-issue v21 / claim-issue-gitlab v19 — an epic is no longer a dead end. Phase 1 treats an UNdecomposed epic as eligible (last-resort, after every atomic ticket) and routes it to the new Phase 1b, which reuses an existing child split or files one (2–8 independently shippable slices, each assigned to the caller and dropped into the active sprint so the NEXT run can actually see them), rewrites the epic's description with a `## Decomposed into` checklist, stamps the `decomposed` label, and claims the first slice. Phase 3's too-large branch splits instead of parking. This became possible when #5042 taught the JIRA reads to carry the data: getIssue now projects labels/description/epic link, fetchMyCurrentSprintTickets returns labels, and a new getEpicChildren finds an epic's children (a failed lookup throws rather than reading as "no children"). v14: Phase 1 states WHY this flow leaves an epic for a human while claim-issue v21 / claim-issue-gitlab v19 now decompose one — the JIRA reads PortOS exposes (jira.js#getIssue, #fetchMyCurrentSprintTickets) return neither a ticket's labels nor its epic links, so an agent here can see no decomposition marker and cannot find an epic's existing children. Doc-only; the flow is unchanged, and porting Phase 1b here is tracked in #5042. v13: mirrors claim-issue v17 — the repo-conventions file is named `AGENTS.md` (or `CLAUDE.md`) (#4852). v12: mirrors claim-issue v15 in the JIRA flow — Phase 5 runs the LOCAL reviewers against the branch diff before the MR/PR is opened (and before the In Review transition), Phase 6 keeps only the PR-side reviewers plus the worktree cleanup. v10: follow-up tickets receive equivalent hyphenated dispatch (`model-*`/`effort-*`) and contributor (`good-first-issue`/`help-wanted`) labels when independently justified. v9: claim worktree creation passes `--no-track`, so a branch based on the default-branch remote ref does not inherit it as an upstream; the later `git push -u` sets the intended branch upstream. v8: mirrors claim-issue v11 in JIRA's status vocabulary — an already-fixed/superseded ticket transitions to Done/Closed and a stale-reference ticket parks on a Blocked/On Hold status behind a Review Hub todo, instead of transitioning back to a not-started status that Phase 1 immediately re-picks. v7: mirrors claim-issue v10 — Phase 5's changelog step defers to the repo's documented convention (per-branch fragments) rather than prescribing a `.changelog/NEXT.md` append. v6: reviewer bullets name the antigravity reviewer's actual PATH binary (`agy`) — mirrors plan-task v12. The same bump adds the missing-binary guard: a reviewer whose CLI is not on PATH is UNSATISFIED, never a clean review the agent substitutes its own self-review for. v5: worktree is created under PortOS's shared worktrees dir (`{worktreesRoot}` → data/cos/worktrees) instead of `{repoPath}/data/cos/worktrees/`, so the agent's checkout no longer lands inside the managed app's working tree (mirrors claim-issue v8). v4: mirrors claim-issue v7 — Phase 3 decides an *ambiguous* ticket (record the chosen reading in a ticket comment, ship) instead of parking it to a "Needs clarification" Review Hub todo, and Phase 1 no longer skips a merely-underspecified ticket; the todo is reserved for destructive/irreversible or genuinely-human-gated cases. v3: per-kind reviewer bullets name `grok` alongside `claude`/`codex`/`antigravity` as a local-CLI reviewer (grok is now a selectable Review Loop reviewer). v2: Phase 5 records remaining scope in the ticket (Done/Remaining comment) and files a follow-up ticket when a partial ship's remainder is separable, so remaining work isn't lost when a human lands the MR/PR. v1: JIRA sibling of claim-issue — claim ONE ready sprint ticket, move it To Do→In Progress→In Review around a self-managed worktree + MR/PR. Reached via the claim-work router when an app's resolved workTracker is 'jira' (replaces the prior jira→jira-sprint-manager route).
'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)
'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)
'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)