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

address review (codex): honor the JIRA hand-off everywhere, gate the wire version

[._.]/ Adam Eivyeddd7e4b6d9b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c15c6108c0..f06c526324 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -146,7 +146,7 @@
## Changed
-- **A CoS task that opens a PR without a Review Loop now merges it once CI is green, instead of leaving it open forever** — "Review Loop off" was being treated as "nobody merges this": the agent's completion workflow only got merge instructions when a reviewer was configured, and PortOS's own post-exit PR path only spawned a follow-up when there was a review to run. So every no-review-loop task ended with an orphaned PR and a leaked branch someone had to notice and merge by hand. The merge now always happens — gated on the review verdict when a loop is configured, on CI alone when it isn't: wait for the checks, fix a failing check or a base conflict, merge with a real merge commit, and verify the PR actually reached `MERGED` before exiting. Where PortOS opens the PR itself after the agent exits, it spawns a merge follow-up agent that does the same. **What to know:** scheduled task types that open a PR without a reviewer (`feature-ideas`, `do-replan`, `jira-sprint-manager`, `refresh-local-llm-catalog`) now land on the default branch on green CI rather than queueing a PR for you — turn on Review Loop for those if you want a reviewer first. A PR is still left open, with the reason stated, when CI stays red after a genuine fix attempt or a conflict needs a human decision. Fixed alongside: a copilot-only Review Loop on a **GitLab** MR used to spawn no follow-up at all (Copilot is GitHub-only) and orphaned the MR — it now degrades to the same merge-on-green-CI follow-up, with `glab` commands instead of `gh`.
+- **A CoS task that opens a PR without a Review Loop now merges it once CI is green, instead of leaving it open forever** — "Review Loop off" was being treated as "nobody merges this": the agent's completion workflow only got merge instructions when a reviewer was configured, and PortOS's own post-exit PR path only spawned a follow-up when there was a review to run. So every no-review-loop task ended with an orphaned PR and a leaked branch someone had to notice and merge by hand. The merge now always happens — gated on the review verdict when a loop is configured, on CI alone when it isn't: wait for the checks, fix a failing check or a base conflict, merge with a real merge commit, and verify the PR actually reached `MERGED` before exiting. Where PortOS opens the PR itself after the agent exits, it spawns a merge follow-up agent that does the same. **What to know:** scheduled task types that open a PR without a reviewer (`feature-ideas`, `do-replan`, `refresh-local-llm-catalog`) now land on the default branch on green CI rather than queueing a PR for you — turn on Review Loop for those if you want a reviewer first. **JIRA-tracked work is deliberately exempt**: `jira-sprint-manager` (and any task carrying a JIRA ticket) moves its ticket to "In Review" and hands the PR to a human, so nothing auto-merges it — a configured reviewer still runs, it just stops short of the merge. A PR is still left open, with the reason stated, when CI stays red after a genuine fix attempt or a conflict needs a human decision. Fixed alongside: a copilot-only Review Loop on a **GitLab** MR used to spawn no follow-up at all (Copilot is GitHub-only) and orphaned the MR — it now degrades to the same merge-on-green-CI follow-up, with `glab` commands instead of `gh`.
- **[issue-2833] Decompose the ~1000-line `spawnTuiAgent()`** — extract the output buffering/spooling pipeline into `agentTuiSpawning/outputSpooler.js` and the failure-analysis + worktree-inspection helpers into `agentTuiSpawning/finalizeHelpers.js`, leaving `spawnTuiAgent` as a thinner orchestrator. No behavior change to spawn/timeout/completion semantics; adds unit coverage for both extracted modules.
- Route client `localStorage` access through the `safeStorage` helpers (Layout, MorseTrainer, calendar persisted-state, MoodBoard reference strip, VoiceWidget, WorkEditor, Tribe) — several sites previously threw uncaught in Safari private mode instead of degrading gracefully.
- Replace inline `new Promise(r => setTimeout(r, …))` delays with the shared `sleep(ms)` helper across nine server modules.
diff --git a/server/lib/README.md b/server/lib/README.md
index e69c6212b7..ef729be4f3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -282,6 +282,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |
+| `prDisposition.js` | `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` — whether a CoS task's pull request must be left open for a human instead of merged by a follow-up (today: `jira-sprint-manager`, or any task carrying a `jiraTicketId`, whose ticket status is the hand-off PortOS can't transition). Shared by the agent prompt builder (agent-owned PR flows) and `agentWorktreeCleanup` (PortOS-owned ones) so both halves agree. |
| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |
| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). |
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `promptRunner.js`'s fallback mark-and-pick. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 3896f89b07..d516593be7 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -253,6 +253,7 @@ export * from './markedSection.js';
export * from './mirrorParity.js';
export * from './objects.js';
export * from './openapiSpec.js';
+export * from './prDisposition.js';
export * from './shellQuote.js';
export * from './sidecarProcess.js';
export * from './singleFlight.js';
diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.js
new file mode 100644
index 0000000000..4628bcaf07
--- /dev/null
+++ b/server/lib/prDisposition.js
@@ -0,0 +1,43 @@
+/**
+ * PR disposition for CoS agent tasks — who lands the pull request a task opens.
+ *
+ * The default is that *something* lands it: the review-loop follow-up when a
+ * Review Loop is configured, a merge follow-up (or the agent's own completion
+ * workflow) on green CI when it isn't. A PR nobody merges is a leaked branch.
+ *
+ * The exception is a task that deliberately hands its PR to a human AND records
+ * that hand-off somewhere PortOS can't update afterwards. `jira-sprint-manager`
+ * is the case that exists today: its prompt transitions the ticket to "In
+ * Review", so merging the PR behind the board's back would leave the work merged
+ * and the ticket permanently in review — and nothing in the completion path
+ * knows the ticket key to transition it to Done.
+ *
+ * This lives in `lib/` because both halves of the decision need it: the prompt
+ * builder (agent-owned PR flows, where the agent merges) and the worktree
+ * cleanup (PortOS-owned PR flows, where a follow-up agent merges). A predicate
+ * that only one half consults produces exactly the split-brain it's meant to
+ * prevent.
+ */
+
+/**
+ * Scheduled task types whose prompt hands the PR to a human. Keep this tiny —
+ * every entry is a PR a person must remember to merge.
+ */
+export const PR_STAYS_OPEN_TASK_TYPES = Object.freeze(['jira-sprint-manager']);
+
+const PR_STAYS_OPEN_SET = new Set(PR_STAYS_OPEN_TASK_TYPES);
+
+/**
+ * True when a task's PR must be left open for a human rather than merged: an
+ * exempt task type, or any task carrying a JIRA ticket (the ticket status is the
+ * hand-off, and no completion path here can transition it).
+ *
+ * Reviewers still run when configured — this governs the *merge*, not the review.
+ *
+ * @param {Object|null} task - the CoS task (or its metadata holder).
+ * @returns {boolean}
+ */
+export function leavesPrForHuman(task) {
+ const metadata = task?.metadata || {};
+ return PR_STAYS_OPEN_SET.has(metadata.analysisType) || !!metadata.jiraTicketId;
+}
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 2276373583..8d7d426498 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -499,7 +499,19 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// permissive `metadata` map and round-trips the markdown store like any other
// metadata, so no new top-level wire field is added — only the status vocab
// widened. Per-category gate → only cos-tasks sync pauses with old peers.
- cosTasks: 2,
+ // v3 = the PR-follow-up disposition markers `reviewLoopMergeOnly` /
+ // `reviewLoopLeaveOpen`. This is an EXECUTION-semantics break, not a shape
+ // change: both ride the permissive `metadata` map, so a ≤v2 receiver validates
+ // and stores the task fine — and then MIS-RUNS it. Its prompt builder doesn't
+ // know either marker, so it re-defaults the deliberately-empty reviewer list
+ // back to `[copilot]` and runs a review the task explicitly disabled; on a
+ // GitLab MR (the copilot-only fallback) it emits GitHub-only commands that
+ // cannot land the MR, orphaning it; and on a JIRA hand-off it merges a PR that
+ // must stay open. A claimed-and-mis-run task then LWW-pushes its damaged state
+ // back onto the v3 peer, which is exactly the bump trigger (see the
+ // `creativeDirectorProjects` 2→3 precedent). Per-category gate → only cos-tasks
+ // sync pauses until the peer upgrades.
+ cosTasks: 3,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 37f99d58e1..1a2d15aacc 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -21,6 +21,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { isOpencodeCommand } from '../lib/providerModels.js';
import { shellQuote } from '../lib/shellQuote.js';
import { detectForgeCli } from '../lib/gitForge.js';
+import { leavesPrForHuman } from '../lib/prDisposition.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
import { PORTOS_APP_ID } from './apps.js';
@@ -491,10 +492,34 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,
? `\n### CLI Reviewer Procedure (codex / antigravity / claude / grok)\n\nDrive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop below 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${localAgentLoopBody}\n`
: '';
+ // A JIRA-tracked PR is a human's to land (its ticket is already "In Review" and
+ // nothing here can transition it), so this follow-up reviews and stops. Emitted
+ // as the same steps 4-6 so the loop body above stays identical either way.
+ const leaveOpen = metadata.reviewLoopLeaveOpen === true || metadata.reviewLoopLeaveOpen === 'true';
+ const objective = leaveOpen
+ ? '**Your job is to drive the review-and-fix loop to completion. Do NOT merge — this PR is tracked in JIRA and a human lands it.**'
+ : '**Your job is to drive the review-and-fix loop to completion and merge the PR.**';
+ const closingSteps = leaveOpen
+ ? [
+ '4. When the reviewer list is exhausted (or the stop mode triggers), **leave the PR open** — do NOT merge it, and do NOT delete the branch. Its JIRA ticket is sitting in review and a human lands both together; merging here would leave the work merged and the ticket stuck in review.',
+ `5. Post a short PR comment summarising what the reviewers raised and what you fixed, so the human landing it knows the state: \`gh pr comment "${prUrl}" --body "<summary>"\`.`,
+ '6. Exit. Do **not** run `/do:push` or open a new PR. The system will clean up your worktree on exit.',
+ ]
+ : [
+ `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',
+ ` gh pr merge "${prUrl}" --merge --delete-branch`,
+ ' ```',
+ prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null,
+ ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',
+ `5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.`,
+ '6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.',
+ ].filter(Boolean);
+
if (verbose) {
return `
## Review-Loop Follow-up (PRIMARY OBJECTIVE)
-A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} **Your job is to drive the review-and-fix loop to completion and merge the PR.**
+A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} ${objective}
**Reviewers (in order)**: ${reviewerLabel}${equiv}.
${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}
@@ -503,14 +528,7 @@ ${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}
1. ${waitOrInvokeStep}
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
-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
- gh pr merge "${prUrl}" --merge --delete-branch
- \`\`\`
- ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : ''}
- You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.
-5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.
-6. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
+${closingSteps.join('\n')}
**Hard stop:** if a reviewer's loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.
@@ -531,7 +549,7 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
// Compact light-path variant.
return [
'## Review-Loop Follow-up (PRIMARY OBJECTIVE)',
- `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} Drive the review-and-fix loop to completion and merge.`,
+ `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} ${leaveOpen ? 'Drive the review-and-fix loop to completion — do NOT merge (JIRA-tracked; a human lands it).' : 'Drive the review-and-fix loop to completion and merge.'}`,
`**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,
...extraNotes,
'',
@@ -539,14 +557,7 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
`1. ${waitOrInvokeStep}`,
'2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.'),
'3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.',
- '4. When the list is exhausted (or the stop mode triggers), merge **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',
- ` gh pr merge "${prUrl}" --merge --delete-branch`,
- ' ```',
- prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null,
- ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',
- `5. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection) — fix and retry. Do NOT exit until state is \`MERGED\`.`,
- '6. Exit — do NOT run `/do:push` or open a new PR.',
+ ...closingSteps,
'',
'**Hard stop:** if a reviewer is not converged after 10 rounds, post a PR comment summarising blockers and exit.',
repeatedCommentsNote,
@@ -556,6 +567,14 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
].filter(Boolean).join('\n');
}
+/**
+ * The step that replaces the merge steps when a PR is a human's to land — a
+ * JIRA-tracked task whose ticket is already "In Review" (see
+ * `lib/prDisposition.js`). Merging would land the work while the board still
+ * shows it in review, and no completion path here can transition the ticket.
+ */
+const LEAVE_PR_OPEN_STEP = (step) => `${step}. **Leave the PR open — do NOT merge it.** This task is tracked in JIRA: its ticket is in review and a human lands the PR and the ticket together. Report the PR URL in your summary and stop.`;
+
/**
* The CI-gated merge procedure, in numbered steps starting at `startStep`.
*
@@ -983,6 +1002,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
? buildTuiCompletionSection({
willOpenPR, willReviewLoop, simplifyEnabled, providerId,
sentinelPath,
+ leavePrOpen: leavesPrForHuman(task),
reviewers: taskReviewers,
usernames: taskReviewerUsernames,
optionalReviewers: taskOptionalReviewers,
@@ -1361,10 +1381,11 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
branchName: worktreeInfo?.branchName || null,
baseBranch: worktreeInfo?.baseBranch || null,
+ leavePrOpen: leavesPrForHuman(task),
reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies
}));
} else {
- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop, hasSlashdo, simplifyEnabled, reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));
+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop, hasSlashdo, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));
}
return { taskSections, contractSections };
@@ -1456,12 +1477,12 @@ function buildPostPRMergeSteps(startStep, { willReviewLoop = true, reviewers = D
* slash commands), the agent can't run `/do:pr` / `/do:push`, so it delegates to
* the plain-git/`gh` variant below — same sentinel handshake, no slashdo.
*/
-function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
+function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
if (slashdoFree) {
// The manual path can't drive the reviewer CLIs, so with a review loop
// configured it opens the PR and stops. Without one, no reviewer and no
// follow-up is coming — it merges on green CI like every other flow.
- return buildManualTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, branchName, baseBranch });
+ return buildManualTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen });
}
const cmd = willOpenPR ? '/do:pr' : '/do:push';
const reviewUsernames = normalizeReviewUsernames(usernames);
@@ -1487,11 +1508,12 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
? (canRunSimplifyCommand ? '1. `/simplify`' : `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`)
: '1. (simplify disabled — skip)';
const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';
- // A PR always gets merge steps — gated on the review verdict when a loop runs,
- // on CI alone when it doesn't (nothing else merges a no-review-loop PR).
- const merge = willOpenPR
+ // A PR gets merge steps — gated on the review verdict when a loop runs, on CI
+ // alone when it doesn't (nothing else merges a no-review-loop PR). The one
+ // exception is a PR a human lands (JIRA-tracked; see lib/prDisposition.js).
+ const merge = (willOpenPR && !leavePrOpen)
? buildPostPRMergeSteps(3, { willReviewLoop, reviewers, usernames: reviewUsernames, reviewStopMode })
- : { lines: [], nextStep: 3 };
+ : { lines: leavePrOpen && willOpenPR ? [LEAVE_PR_OPEN_STEP(3)] : [], nextStep: leavePrOpen && willOpenPR ? 4 : 3 };
const sentinelStep = merge.nextStep;
return [
@@ -1539,7 +1561,7 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
*/
// `willReviewLoop` defaults to the conservative side (same as buildPostPRMergeSteps):
// an omitted flag leaves the PR open for review rather than merging unreviewed work.
-function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null }) {
+function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false }) {
const branchRef = shellQuote(branchName || 'HEAD');
// Pin the PR base to the worktree's base branch when known, so the forge CLI
// doesn't guess (and a fork install targets the intended branch). `--fill`
@@ -1571,9 +1593,11 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, si
let step = 4;
if (willOpenPR) {
- const openNote = willReviewLoop
- ? '**Leave it open for review — do NOT merge it yourself.** This provider can\'t run the reviewer loop, and PortOS won\'t merge it for a TUI task, so a configured reviewer or a human reviews and merges it.'
- : 'No review loop is configured for this task, so you merge it yourself in the next step — nothing else will.';
+ const openNote = leavePrOpen
+ ? '**Leave it open — do NOT merge it.** This task is tracked in JIRA: its ticket is in review and a human lands the PR and the ticket together.'
+ : willReviewLoop
+ ? '**Leave it open for review — do NOT merge it yourself.** This provider can\'t run the reviewer loop, and PortOS won\'t merge it for a TUI task, so a configured reviewer or a human reviews and merges it.'
+ : 'No review loop is configured for this task, so you merge it yourself in the next step — nothing else will.';
lines.push(
`${step++}. Open a pull/merge request against the base branch using the CLI for this repo's forge (check \`git remote -v\`), and capture the URL it prints. ${openNote}`,
'',
@@ -1582,7 +1606,7 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, si
` # GitLab: glab mr create --fill${glabBaseArg}`,
' ```',
);
- if (!willReviewLoop) {
+ if (!willReviewLoop && !leavePrOpen) {
// Same CI-gate procedure the slashdo workflow and the merge follow-up use.
const gate = buildCiMergeGateSteps(step, { prRef: '"<PR_URL>"', forge: 'unknown' });
lines.push(...gate.lines);
@@ -1619,7 +1643,7 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, si
* CLI providers fall through to the legacy commit-only block where PortOS
* handles push+PR on exit.
*/
-function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop = false, hasSlashdo = false, simplifyEnabled = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
+function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop = false, hasSlashdo = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
const reviewUsernames = normalizeReviewUsernames(usernames);
if (hasSlashdo && worktreeInfo && willOpenPR) {
const lines = ['## Completion', 'When finished, run these in order:'];
@@ -1637,9 +1661,14 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop =
: `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`)
: 'with external review disabled.';
lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);
- // Merge steps always follow — review-gated with a loop, CI-gated without one.
- const merge = buildPostPRMergeSteps(step, { willReviewLoop, reviewers, usernames: reviewUsernames, reviewStopMode });
- lines.push(...merge.lines);
+ // Merge steps follow — review-gated with a loop, CI-gated without one — unless
+ // this PR is a human's to land (JIRA-tracked; see lib/prDisposition.js).
+ if (leavePrOpen) {
+ lines.push(LEAVE_PR_OPEN_STEP(step));
+ } else {
+ const merge = buildPostPRMergeSteps(step, { willReviewLoop, reviewers, usernames: reviewUsernames, reviewStopMode });
+ lines.push(...merge.lines);
+ }
return lines.join('\n');
}
if (hasSlashdo && worktreeInfo) {
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 1762315705..ed07275dcd 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -333,6 +333,67 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/review loop reports/);
});
+ it('a jira-sprint-manager TUI task leaves its PR open instead of merging', () => {
+ // The task's prompt moves the ticket to "In Review" and a human lands both;
+ // merging here would leave the work merged and the board stuck in review.
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { simplify: true, openPR: true, analysisType: 'jira-sprint-manager' } }),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta,
+ { isTui: true });
+ expect(prompt).toMatch(/Leave the PR open — do NOT merge it/);
+ expect(prompt).toMatch(/tracked in JIRA/);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ expect(prompt).not.toMatch(/gh pr checks/);
+ });
+
+ it('a JIRA-ticketed Claude Code CLI task leaves its PR open instead of merging', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { openPR: true, jiraTicketId: 'PROJ-9' } }),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta,
+ { isTui: false, providerId: 'claude-code' });
+ expect(prompt).toMatch(/`\/do:pr --review-with none`/);
+ expect(prompt).toMatch(/Leave the PR open — do NOT merge it/);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ });
+
+ it('an OpenCode TUI JIRA task leaves its PR open instead of merging', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { openPR: true, analysisType: 'jira-sprint-manager' } }),
+ '/r',
+ { branchName: 'claim/x', worktreePath: '/tmp/wt', baseBranch: 'main' },
+ isTruthyMeta,
+ { isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });
+ expect(prompt).toMatch(/gh pr create --fill/);
+ expect(prompt).toMatch(/do NOT merge it/);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ expect(prompt).not.toMatch(/glab mr merge/);
+ });
+
+ it('a review-loop follow-up on a JIRA PR reviews but does not merge', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: {
+ reviewLoopFollowUp: true,
+ reviewLoopLeaveOpen: true,
+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',
+ reviewLoopPRBranch: 'b',
+ reviewLoopPRNumber: 9,
+ reviewLoopReviewers: ['codex'],
+ sourceTaskId: 'task-src-5',
+ }}),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta);
+ expect(prompt).toMatch(/## Review-Loop Follow-up/);
+ // The review still runs — only the merge is withheld.
+ expect(prompt).toMatch(/codex/);
+ expect(prompt).toMatch(/leave the PR open/i);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ });
+
it('TUI simplify step is provider-aware — non-Claude TUI (codex-tui) gets the inline equivalent, not /simplify', () => {
// /simplify is a Claude Code TUI built-in; codex-tui / antigravity-tui can't run it.
const prompt = buildLightContextPrompt(
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 8c40fdf9a1..2d5d2f5fd5 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -23,29 +23,9 @@ import { isTruthyMeta } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { detectForgeCli } from '../lib/gitForge.js';
+import { leavesPrForHuman } from '../lib/prDisposition.js';
import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_CAPABLE_CLI_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers } from '../lib/validation.js';
-/**
- * Scheduled task types whose prompt deliberately hands the PR to a human and
- * records that hand-off somewhere PortOS can't update afterwards. For
- * `jira-sprint-manager` that's the ticket it transitions to "In Review": merging
- * the PR here would land the work while the board still shows it in review, and
- * nothing in this path knows the ticket key to transition it to Done.
- *
- * Keep this list tiny — the default for an opened PR is that something lands it.
- */
-const PR_STAYS_OPEN_TASK_TYPES = new Set(['jira-sprint-manager']);
-
-/**
- * True when a task's PR must be left open for a human rather than merged by a
- * follow-up: an exempt task type, or any task carrying a JIRA ticket (the ticket
- * status is the hand-off, and this path can't transition it).
- */
-function leavesPrForHuman(task) {
- const analysisType = task?.metadata?.analysisType;
- return (!!analysisType && PR_STAYS_OPEN_TASK_TYPES.has(analysisType)) || !!task?.metadata?.jiraTicketId;
-}
-
/**
* Clean up a worktree for a completed agent.
* Reads worktree metadata from the agent's registered state and removes the worktree.
@@ -198,12 +178,14 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
// Deciding it there rather than here is what keeps a stripped reviewer list
// from silently producing an orphaned PR.
//
- // The exception is a JIRA-tracked task (see PR_STAYS_OPEN_TASK_TYPES): its
- // prompt moves the ticket to "In Review" and hands the PR to a human, and
- // nothing here can transition the ticket afterwards — merging behind the
- // board's back would leave the work merged but permanently "In Review".
- if (leavesPrForHuman(originalTask)) {
- emitLog('info', `🤝 Leaving ${prResult.url} open for a human — JIRA-tracked task keeps its ticket in review`, { agentId, prUrl: prResult.url });
+ // A JIRA-tracked task (see lib/prDisposition.js) hands its PR to a human —
+ // its ticket is already "In Review" and nothing here can transition it — so
+ // the follow-up must NOT merge. It still RUNS the configured reviewers when
+ // there are any (leaving the PR open is about the merge, not the review);
+ // with no reviewers there is nothing for a follow-up to do at all.
+ const leaveOpen = leavesPrForHuman(originalTask);
+ if (leaveOpen && !shouldRequestCopilot) {
+ emitLog('info', `🤝 Leaving ${prResult.url} open for a human — JIRA-tracked task, no reviewers configured`, { agentId, prUrl: prResult.url });
} else {
await spawnReviewLoopFollowUp({
originalAgentId: agentId,
@@ -216,7 +198,8 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
optionalReviewers: shouldRequestCopilot ? optionalReviewers : [],
reviewStopMode,
reviewerApplies,
- reviewerModels
+ reviewerModels,
+ leaveOpen
}).catch(err => {
emitLog('warn', `🤖 Failed to spawn PR follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
warnings.push(`PR follow-up spawn failed for ${prResult.url}: ${err.message}`);
@@ -281,7 +264,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
* branch (via createWorktree's `existingBranch` option) so it can fix-and-push
* without trampling concurrent agents.
*/
-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, leaveOpen = false }) {
if (!prUrl || !prBranch) return null;
const parsedPr = git.parsePullRequestUrl(prUrl);
@@ -305,6 +288,10 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
const effectiveOptionalReviewers = normalizeOptionalReviewers(optionalReviewers) || [];
// Nothing left to review → this follow-up's only job is to land the PR.
const mergeOnly = effectiveReviewers.length === 0 && effectiveUsernames.length === 0;
+ // ...and with nothing to review AND nothing to merge there is no follow-up at
+ // all (a JIRA-tracked task whose reviewers were all stripped). The caller
+ // normally catches this; the guard keeps the invariant local to this function.
+ if (mergeOnly && leaveOpen) return null;
// Reviewer-keyed CLI model map, narrowed to the model-capable reviewers actually
// in this loop's list (e.g. `{ codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }`); the
@@ -348,6 +335,8 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
reviewLoopFollowUp: true,
// Merge-only run: no reviewers, the prompt is a CI-gate-and-merge procedure.
reviewLoopMergeOnly: mergeOnly,
+ // Review, but do NOT merge — the PR is a human's to land (JIRA hand-off).
+ reviewLoopLeaveOpen: leaveOpen,
reviewLoopPRUrl: prUrl,
reviewLoopPRBranch: prBranch,
reviewLoopPRNumber: parsedPr?.number ?? null,
diff --git a/server/services/sharing/cosTasksSync.test.js b/server/services/sharing/cosTasksSync.test.js
index c7e3d8c369..e6de6990a7 100644
--- a/server/services/sharing/cosTasksSync.test.js
+++ b/server/services/sharing/cosTasksSync.test.js
@@ -69,7 +69,7 @@ describe('buildCosTasksPayload', () => {
vi.mocked(getUserTasks).mockResolvedValue({ tasks: [task('task-a', 'pending')] });
vi.mocked(getCosTasks).mockResolvedValue({ tasks: [task('sys-b', 'in_progress', { metadata: { claimedBy: 'i1' } })] });
const p = await buildCosTasksPayload();
- expect(p.schemaVersion).toBe(2); // v2: `challenged` status + challenge metadata (#2441)
+ expect(p.schemaVersion).toBe(3); // v3: PR-follow-up disposition markers (mergeOnly / leaveOpen)
expect(p.listHash).toMatch(/^[a-f0-9]{64}$/);
expect(p.tasks).toHaveLength(2);
const user = p.tasks.find((t) => t.id === 'task-a');
@@ -104,7 +104,7 @@ describe('buildCosTasksPayload', () => {
it('returns an empty payload when there are no tasks', async () => {
const p = await buildCosTasksPayload();
expect(p.tasks).toEqual([]);
- expect(p.schemaVersion).toBe(2); // v2: `challenged` status + challenge metadata (#2441)
+ expect(p.schemaVersion).toBe(3); // v3: PR-follow-up disposition markers (mergeOnly / leaveOpen)
});
});