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

feat: add explicit PR completion policies (#3060)

[._.]/ Adam Eivyf883218df4e2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 76585e305f..53f101ea5b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -160,6 +160,7 @@
## Changed
+- **[issue-3060] CoS PR completion is now an explicit choice** — when a task opens a PR, choose **Review then merge**, **Merge on green CI**, or **Leave PR open** instead of inferring the outcome from a review-loop checkbox. The same default is available per managed app, new tasks save the selected policy, and existing tasks keep their current review-loop behavior without a migration. Prompt instructions and post-run cleanup now use that one policy too, so a leave-open task never starts a hidden review/merge follow-up.
- **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.
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsx
index d6a531c398..86372653d6 100644
--- a/client/src/components/apps/EditAppDrawer.jsx
+++ b/client/src/components/apps/EditAppDrawer.jsx
@@ -11,6 +11,7 @@ import useDrawerTab from '../../hooks/useDrawerTab';
import { copyToClipboard } from '../../lib/clipboard';
import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate, buildLayeredIntelligenceScheduleUpdate } from './LayeredIntelligenceTab';
import { PROVIDER_TYPES } from '../../utils/providers';
+import { DEFAULT_PR_COMPLETION, PR_COMPLETION_OPTIONS } from '../cos/constants';
const WORK_TRACKER_OPTIONS = [
{ value: 'auto', label: 'Auto (detect from git origin)' },
@@ -63,6 +64,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
editorCommand: app.editorCommand || 'code .',
workTracker: app.workTracker || 'auto',
defaultOpenPR: app.defaultOpenPR || false,
+ defaultPrCompletion: app.defaultPrCompletion || DEFAULT_PR_COMPLETION,
defaultUseWorktree: app.defaultUseWorktree || app.defaultOpenPR || false,
jiraEnabled: app.jira?.enabled || false,
jiraInstanceId: app.jira?.instanceId || '',
@@ -368,6 +370,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
workTracker: formData.workTracker || 'auto',
defaultUseWorktree: formData.defaultUseWorktree || formData.defaultOpenPR,
defaultOpenPR: formData.defaultOpenPR,
+ defaultPrCompletion: formData.defaultPrCompletion,
jira: formData.jiraEnabled ? {
enabled: true,
instanceId: formData.jiraInstanceId || undefined,
@@ -684,8 +687,25 @@ export default function EditAppDrawer({ app, onClose, onSave }) {
className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent disabled:opacity-40"
/>
<GitPullRequest size={14} className="text-blue-400" />
- <span className={`text-sm ${formData.defaultUseWorktree ? 'text-white' : 'text-gray-600'}`} title="When checked, agents open a PR to the default branch and merge it once it passes — the review loop if one is configured, CI alone if not. When unchecked with worktree enabled, agents merge the branch directly on completion.">Default to Open PR for new tasks</span>
+ <span className={`text-sm ${formData.defaultUseWorktree ? 'text-white' : 'text-gray-600'}`} title="When checked, agents open a PR to the default branch. Choose below whether new PRs are reviewed and merged, merged on green CI, or left open. When unchecked with worktree enabled, agents merge the branch directly on completion.">Default to Open PR for new tasks</span>
</label>
+ <div className="ml-6 mt-2 max-w-sm">
+ <label htmlFor="edit-app-default-pr-completion" className={`block text-sm mb-1 ${formData.defaultOpenPR ? 'text-gray-400' : 'text-gray-600'}`}>Default PR completion</label>
+ <select
+ id="edit-app-default-pr-completion"
+ value={formData.defaultPrCompletion}
+ disabled={!formData.defaultOpenPR}
+ onChange={e => setFormData(prev => ({ ...prev, defaultPrCompletion: e.target.value }))}
+ className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-hidden disabled:opacity-40"
+ >
+ {PR_COMPLETION_OPTIONS.map(option => (
+ <option key={option.value} value={option.value}>{option.label}</option>
+ ))}
+ </select>
+ <p className="mt-1 text-xs text-gray-500">
+ {PR_COMPLETION_OPTIONS.find(option => option.value === formData.defaultPrCompletion)?.description}
+ </p>
+ </div>
</div>
)}
diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsx
index 1559378020..a816701396 100644
--- a/client/src/components/apps/EditAppDrawer.test.jsx
+++ b/client/src/components/apps/EditAppDrawer.test.jsx
@@ -136,6 +136,19 @@ describe('EditAppDrawer work tracker selector', () => {
expect(id).toBe('app-1');
expect(payload.workTracker).toBe('gitlab');
});
+
+ it('saves the selected default PR completion policy', async () => {
+ renderDrawer({ app: { ...APP, defaultUseWorktree: true, defaultOpenPR: true } });
+ await openTab('Workflow');
+
+ const select = await screen.findByLabelText('Default PR completion');
+ expect(select).toHaveValue('review-then-merge');
+ fireEvent.change(select, { target: { value: 'leave-open' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+
+ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());
+ expect(api.updateApp.mock.calls[0][1].defaultPrCompletion).toBe('leave-open');
+ });
});
describe('EditAppDrawer required-field validation across tabs', () => {
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index ca1e2a710d..823ebe8dd8 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
-import { Plus, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText, Zap, Bookmark, Ticket, GitBranch, GitPullRequest, Wand2, RefreshCw } from 'lucide-react';
+import { Plus, Image, X, ChevronDown, ChevronRight, Sparkles, Loader2, Paperclip, FileText, Zap, Bookmark, Ticket, GitBranch, GitPullRequest, Wand2 } from 'lucide-react';
import toast from '../ui/Toast';
import AppContextPicker from '../AppContextPicker';
import * as api from '../../services/api';
@@ -7,7 +7,7 @@ import { processScreenshotUploads, processAttachmentUploads, ATTACHMENT_ACCEPT }
import FilePickerButton from '../ui/FilePickerButton';
import { formatBytes } from '../../utils/formatters';
import { filterSelectableModels, isTuiProvider, isCliProvider, isProcessProvider, isCodexProvider, effortLevelsForProvider } from '../../utils/providers';
-import { DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE } from './constants';
+import { DEFAULT_PR_COMPLETION, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, PR_COMPLETION_OPTIONS } from './constants';
import { clickableProps } from '../../lib/a11yKeyboard';
import ReviewerPicker from './ReviewerPicker';
@@ -19,7 +19,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
const [useWorktree, setUseWorktree] = useState(false);
const [openPR, setOpenPR] = useState(false);
const [simplify, setSimplify] = useState(true);
- const [reviewLoop, setReviewLoop] = useState(false);
+ const [prCompletion, setPrCompletion] = useState(DEFAULT_PR_COMPLETION);
const [reviewers, setReviewers] = useState(DEFAULT_REVIEWERS);
const [reviewUsernames, setReviewUsernames] = useState([]);
const [optionalReviewers, setOptionalReviewers] = useState([]);
@@ -104,7 +104,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
// `apps` array reference) so periodic re-fetches in the parent don't
// stomp manual checkbox toggles between renders.
const appDefaultsSig = useMemo(() => selectedApp
- ? `${selectedApp.id}|${!!selectedApp.defaultOpenPR}|${!!selectedApp.defaultUseWorktree}|${!!selectedApp.jira?.enabled}`
+ ? `${selectedApp.id}|${!!selectedApp.defaultOpenPR}|${selectedApp.defaultPrCompletion || DEFAULT_PR_COMPLETION}|${!!selectedApp.defaultUseWorktree}|${!!selectedApp.jira?.enabled}`
: `none:${newTask.app || ''}`,
[selectedApp, newTask.app]
);
@@ -114,6 +114,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
setCreateJiraTicket(!!selectedApp?.jira?.enabled);
setUseWorktree(defaultUseWorktree);
setOpenPR(defaultOpenPR);
+ setPrCompletion(selectedApp?.defaultPrCompletion || DEFAULT_PR_COMPLETION);
}, [appDefaultsSig]);
// Get models for selected provider
@@ -260,12 +261,12 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
useWorktree,
openPR: useWorktree && openPR,
simplify,
- reviewLoop,
- reviewers: reviewLoop ? reviewers : undefined,
- usernames: reviewLoop ? reviewUsernames : undefined,
- optionalReviewers: reviewLoop ? optionalReviewers : undefined,
- reviewStopMode: reviewLoop ? reviewStopMode : undefined,
- reviewerApplies: reviewLoop ? reviewerApplies : undefined,
+ prCompletion: useWorktree && openPR ? prCompletion : undefined,
+ reviewers: openPR && prCompletion === 'review-then-merge' ? reviewers : undefined,
+ usernames: openPR && prCompletion === 'review-then-merge' ? reviewUsernames : undefined,
+ optionalReviewers: openPR && prCompletion === 'review-then-merge' ? optionalReviewers : undefined,
+ reviewStopMode: openPR && prCompletion === 'review-then-merge' ? reviewStopMode : undefined,
+ reviewerApplies: openPR && prCompletion === 'review-then-merge' ? reviewerApplies : undefined,
screenshots: screenshots.length > 0 ? screenshots.map(s => s.path) : undefined,
attachments: attachments.length > 0 ? attachments.map(a => ({
filename: a.filename,
@@ -487,19 +488,23 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
Simplify
</span>
</label>
- <label className="flex items-center gap-2 cursor-pointer select-none whitespace-nowrap py-1">
- <input
- type="checkbox"
- checked={reviewLoop}
- onChange={(e) => setReviewLoop(e.target.checked)}
- className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent focus:ring-offset-0"
- />
- <span className="flex items-center gap-1.5 text-sm text-gray-400" title="After the agent opens a PR during its run, keep iterating on review feedback until checks pass.">
- <RefreshCw size={14} className="text-amber-400" />
- Review Loop
- </span>
- </label>
- {reviewLoop && (
+ {openPR && (
+ <label htmlFor="task-pr-completion" className="flex items-center gap-2 py-1 basis-full sm:basis-auto">
+ <span className="text-sm text-gray-400">After opening PR</span>
+ <select
+ id="task-pr-completion"
+ value={prCompletion}
+ title={PR_COMPLETION_OPTIONS.find(option => option.value === prCompletion)?.description}
+ onChange={(e) => setPrCompletion(e.target.value)}
+ className="min-w-44 rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-white focus:border-port-accent focus:outline-hidden"
+ >
+ {PR_COMPLETION_OPTIONS.map(option => (
+ <option key={option.value} value={option.value}>{option.label}</option>
+ ))}
+ </select>
+ </label>
+ )}
+ {openPR && prCompletion === 'review-then-merge' && (
<div className="basis-full mt-1">
<ReviewerPicker
reviewers={reviewers}
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index d43b270ad2..d56661bef2 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -158,14 +158,21 @@ export const STATE_MESSAGES = {
ideating: "Analyzing options...",
};
-// Agent option toggles for task metadata (useWorktree, openPR, simplify, reviewLoop)
+// Agent option toggles for task metadata (useWorktree, openPR, simplify).
export const AGENT_OPTIONS = [
{ field: 'useWorktree', label: 'Worktree', shortLabel: 'WT', description: 'Work in an isolated git worktree on a feature branch. If unchecked, commits directly to the default branch.' },
- { field: 'openPR', label: 'Open PR', shortLabel: 'PR', description: 'Open a pull request to the default branch (implies worktree). The PR is merged once it passes — the review loop when one is configured, CI alone when it is not. If unchecked with worktree enabled, auto-merges to the default branch on completion.' },
- { field: 'simplify', label: 'Run /simplify', shortLabel: '/s', description: 'Review code for reuse and quality before committing' },
- { field: 'reviewLoop', label: 'Review Loop', shortLabel: 'RL', description: 'Run the configured reviewers against the PR and keep iterating on their feedback until they are satisfied, then merge. Needs Open PR — with it off, the PR is merged on green CI with no review.' }
+ { field: 'openPR', label: 'Open PR', shortLabel: 'PR', description: 'Open a pull request to the default branch (implies worktree). Choose whether PortOS reviews and merges it, merges on green CI, or leaves it open. If unchecked with worktree enabled, auto-merges to the default branch on completion.' },
+ { field: 'simplify', label: 'Run /simplify', shortLabel: '/s', description: 'Review code for reuse and quality before committing' }
];
+export const PR_COMPLETION_OPTIONS = [
+ { value: 'review-then-merge', label: 'Review then merge', description: 'Run the configured reviewer chain, then merge when it is clean.' },
+ { value: 'merge-on-green', label: 'Merge on green CI', description: 'Skip external review and merge after required checks pass.' },
+ { value: 'leave-open', label: 'Leave PR open', description: 'Open the PR and stop so you can inspect and merge it yourself.' }
+];
+
+export const DEFAULT_PR_COMPLETION = 'review-then-merge';
+
// Reviewer choices for the Review Loop. `copilot` requests a GitHub Copilot
// review via the native reviewer API; CLI reviewers (claude/antigravity/codex/grok)
// instruct the follow-up agent to invoke the named CLI; local-LLM reviewers
diff --git a/server/lib/README.md b/server/lib/README.md
index b93e214c8e..ef8fa4894b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -283,7 +283,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. |
+| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` 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/cosValidation.js b/server/lib/cosValidation.js
index 6ce2fc762f..9d556bdcc6 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -11,6 +11,7 @@
import { z } from 'zod';
import { emptyToUndefined, emptyToNull } from './zodCompat.js';
import { EFFORT_LEVELS } from './providerModels.js';
+import { PR_COMPLETION_VALUES } from './prDisposition.js';
// =============================================================================
// COS TASK SCHEMAS
@@ -321,6 +322,7 @@ export const createCosTaskSchema = z.object({
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
),
+ prCompletion: z.enum(PR_COMPLETION_VALUES).optional(),
simplify: z.preprocess(
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
@@ -469,6 +471,7 @@ export const createCosJobSchema = z.object({
taskMetadata: z.object({
useWorktree: z.boolean().optional(),
openPR: z.boolean().optional(),
+ prCompletion: z.enum(PR_COMPLETION_VALUES).optional(),
simplify: z.boolean().optional(),
}).optional(),
});
@@ -545,7 +548,7 @@ export const codeReviewSettingsSchema = z.object({
// =============================================================================
// Agent behavior flags that can be overridden per-pipeline-stage
-export const PIPELINE_BEHAVIOR_FLAGS = ['useWorktree', 'openPR', 'simplify', 'reviewLoop'];
+export const PIPELINE_BEHAVIOR_FLAGS = ['useWorktree', 'openPR', 'prCompletion', 'simplify', 'reviewLoop'];
// Absolute cap on total agent spawns per task (across all retry types)
export const MAX_TOTAL_SPAWNS = 5;
@@ -595,11 +598,9 @@ export const SWARM_COUNT_MAX = 6;
/**
* Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags
* (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`reviewerApplies`)
- * are kept only when actually boolean; the review-loop keys are constrained by
- * value — `reviewer` to a known reviewer, `reviewers` to a filtered/deduped list
- * of known reviewers, `usernames` to shell-safe GitHub reviewer usernames,
- * `reviewStopMode` to a known stop-mode — plus a validated `pipeline` object.
- * Prevents prototype pollution and reserved-field overrides.
+ * are kept only when actually boolean; constrained values include `prCompletion`,
+ * reviewers, reviewer usernames, and `reviewStopMode` — plus a validated pipeline
+ * object. Prevents prototype pollution and reserved-field overrides.
* Returns a clean plain object or null if input is empty/invalid.
*/
export function sanitizeTaskMetadata(raw) {
@@ -612,6 +613,10 @@ export function sanitizeTaskMetadata(raw) {
hasKeys = true;
}
}
+ if (Object.prototype.hasOwnProperty.call(raw, 'prCompletion') && PR_COMPLETION_VALUES.includes(raw.prCompletion)) {
+ clean.prCompletion = raw.prCompletion;
+ hasKeys = true;
+ }
// `reviewer` is a legacy single constrained string.
const normalizedReviewer = REVIEWER_ALIASES[raw.reviewer] || raw.reviewer;
if (Object.prototype.hasOwnProperty.call(raw, 'reviewer') && REVIEWER_VALUES.includes(normalizedReviewer)) {
diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.js
index 4628bcaf07..0fe51b4718 100644
--- a/server/lib/prDisposition.js
+++ b/server/lib/prDisposition.js
@@ -1,5 +1,5 @@
/**
- * PR disposition for CoS agent tasks — who lands the pull request a task opens.
+ * PR disposition for CoS agent tasks — how a pull request completes.
*
* 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
@@ -19,6 +19,33 @@
* prevent.
*/
+export const PR_COMPLETIONS = Object.freeze({
+ REVIEW_THEN_MERGE: 'review-then-merge',
+ MERGE_ON_GREEN: 'merge-on-green',
+ LEAVE_OPEN: 'leave-open',
+});
+
+export const PR_COMPLETION_VALUES = Object.freeze(Object.values(PR_COMPLETIONS));
+
+const PR_COMPLETION_SET = new Set(PR_COMPLETION_VALUES);
+
+/**
+ * Resolve a task's PR completion policy without migrating stored task data.
+ *
+ * New tasks persist `prCompletion`; legacy records retain their `reviewLoop`
+ * bit and resolve to the same behavior they had before this field existed.
+ * `openPR` remains the separate decision of whether to create a PR at all.
+ *
+ * @param {Object|null|undefined} metadata
+ * @returns {'review-then-merge'|'merge-on-green'|'leave-open'}
+ */
+export function resolvePrCompletion(metadata = {}) {
+ if (PR_COMPLETION_SET.has(metadata?.prCompletion)) return metadata.prCompletion;
+ return metadata?.reviewLoop === true || metadata?.reviewLoop === 'true'
+ ? PR_COMPLETIONS.REVIEW_THEN_MERGE
+ : PR_COMPLETIONS.MERGE_ON_GREEN;
+}
+
/**
* 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.
diff --git a/server/lib/prDisposition.test.js b/server/lib/prDisposition.test.js
new file mode 100644
index 0000000000..c7eec083cc
--- /dev/null
+++ b/server/lib/prDisposition.test.js
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { PR_COMPLETIONS, resolvePrCompletion } from './prDisposition.js';
+
+describe('resolvePrCompletion', () => {
+ it('prefers an explicit valid disposition', () => {
+ expect(resolvePrCompletion({ prCompletion: PR_COMPLETIONS.LEAVE_OPEN, reviewLoop: true }))
+ .toBe(PR_COMPLETIONS.LEAVE_OPEN);
+ });
+
+ it.each([
+ [{ openPR: true, reviewLoop: true }, PR_COMPLETIONS.REVIEW_THEN_MERGE],
+ [{ openPR: true, reviewLoop: 'true' }, PR_COMPLETIONS.REVIEW_THEN_MERGE],
+ [{ openPR: true, reviewLoop: false }, PR_COMPLETIONS.MERGE_ON_GREEN],
+ [{ openPR: true }, PR_COMPLETIONS.MERGE_ON_GREEN],
+ ])('preserves legacy behavior for %o', (metadata, expected) => {
+ expect(resolvePrCompletion(metadata)).toBe(expected);
+ });
+
+ it('falls back to legacy behavior when an unrecognized value is stored', () => {
+ expect(resolvePrCompletion({ prCompletion: 'later', reviewLoop: true }))
+ .toBe(PR_COMPLETIONS.REVIEW_THEN_MERGE);
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index b23ce3226a..e679cdd363 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -8,6 +8,7 @@ import { CHROMA_KEY_HEXES } from '../services/sprites/chromaKey.js';
import { WALK_TRACK, SCANNER_TRACK, getAnimationTrack } from '../services/sprites/animationTracks.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
+import { PR_COMPLETION_VALUES } from './prDisposition.js';
// Clip lengths grok's image_to_video delivers, as a Zod union built from the
// single shared list (see grokVideoClip.js). `z.literal` per value rather than
@@ -242,6 +243,7 @@ export const appSchema = z.object({
})).optional(), // Per-task overrides: { [taskType]: { enabled, interval, intervalMs, providerId, model, taskMetadata } }
defaultUseWorktree: z.boolean().optional(),
defaultOpenPR: z.boolean().optional(),
+ defaultPrCompletion: z.enum(PR_COMPLETION_VALUES).optional(),
jira: jiraConfigSchema.optional().nullable(),
datadog: datadogConfigSchema.optional().nullable(),
// Where this app's autonomous work items live (single source per app).
diff --git a/server/lib/validation.test.js b/server/lib/validation.test.js
index 9daca6f7a9..612a03faff 100644
--- a/server/lib/validation.test.js
+++ b/server/lib/validation.test.js
@@ -369,6 +369,12 @@ describe('validation.js', () => {
expect(result.data).not.toHaveProperty('archived');
expect(result.data).not.toHaveProperty('defaultUseWorktree');
expect(result.data).not.toHaveProperty('defaultOpenPR');
+ expect(result.data).not.toHaveProperty('defaultPrCompletion');
+ });
+
+ it('accepts only known app PR completion defaults', () => {
+ expect(appUpdateSchema.safeParse({ defaultPrCompletion: 'leave-open' }).success).toBe(true);
+ expect(appUpdateSchema.safeParse({ defaultPrCompletion: 'later' }).success).toBe(false);
});
it('preserves per-app taskTypeOverrides scheduling fields (intervalMs/providerId/model/taskMetadata)', () => {
@@ -685,6 +691,14 @@ describe('validation.js', () => {
.toEqual({ useWorktree: true, openPR: true, simplify: true, reviewLoop: false });
});
+ it('should accept only known PR completion metadata', () => {
+ expect(sanitizeTaskMetadata({ prCompletion: 'review-then-merge' }))
+ .toEqual({ prCompletion: 'review-then-merge' });
+ expect(sanitizeTaskMetadata({ prCompletion: 'leave-open' }))
+ .toEqual({ prCompletion: 'leave-open' });
+ expect(sanitizeTaskMetadata({ prCompletion: 'later' })).toBeNull();
+ });
+
it('should drop non-boolean values for allowed keys', () => {
expect(sanitizeTaskMetadata({ useWorktree: 'yes' })).toBeNull();
expect(sanitizeTaskMetadata({ simplify: 1 })).toBeNull();
@@ -982,6 +996,11 @@ describe('validation.js', () => {
});
describe('createCosTaskSchema reviewers fields', () => {
+ it('accepts an explicit PR completion policy and rejects unknown values', () => {
+ expect(createCosTaskSchema.safeParse({ description: 'inspect', prCompletion: 'leave-open' }).success).toBe(true);
+ expect(createCosTaskSchema.safeParse({ description: 'inspect', prCompletion: 'later' }).success).toBe(false);
+ });
+
it('accepts reviewers/reviewStopMode/reviewerApplies', () => {
const parsed = createCosTaskSchema.safeParse({
description: 'do a thing',
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 6955f522ee..524766eb88 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -34,6 +34,7 @@ import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { resolveForgeTokenEnv } from './git.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
+import { resolvePrCompletion } from '../lib/prDisposition.js';
const AGENTS_DIR = PATHS.cosAgents;
@@ -844,12 +845,13 @@ export async function spawnDirectly({
// agentPromptBuilder.js) — mirror the TUI cleanup contract so PortOS
// doesn't double-fire push+PR creation.
const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
+ const directPrCompletion = resolvePrCompletion(task.metadata);
const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');
const reviewOptions = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn });
await cleanupWorktreeFn(agentId, finalSuccess, {
openPR: directAgentOwnsPR ? false : directOpenPR,
- requestCopilotReview: !directAgentOwnsPR && directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
+ prCompletion: directPrCompletion,
...reviewOptions,
skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,
description: task.description,
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 79687bb879..1a18daeffc 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -28,6 +28,7 @@ import * as git from './git.js';
import { isTruthyMeta } from './agentState.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
+import { resolvePrCompletion } from '../lib/prDisposition.js';
const ROOT_DIR = PATHS.root;
@@ -296,7 +297,7 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
// Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)
if (!jiraBranch) {
const taskOpenPR = isTruthyMeta(task?.metadata?.openPR);
- const taskReviewLoop = isTruthyMeta(task?.metadata?.reviewLoop);
+ const taskPrCompletion = resolvePrCompletion(task?.metadata);
// Review-loop follow-up agents already merged via `gh pr merge` in the agent
// body — re-merging the worktree branch into the source workspace would
// duplicate the squashed commits, so suppress the auto-merge fallback.
@@ -314,7 +315,7 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv
const reviewOptions = await resolveReviewLoopOptions(task?.metadata, { normalize: normalizeReviewers, isTruthyMeta });
const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {
openPR: agentOwnsPR ? false : taskOpenPR,
- requestCopilotReview: !agentOwnsPR && taskOpenPR && taskReviewLoop,
+ prCompletion: taskPrCompletion,
...reviewOptions,
skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
description: task?.description,
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 1cc6e64cc2..f6434056fc 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -21,7 +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 { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';
import * as jiraService from './jira.js';
import { emitLog } from './cosEvents.js';
import { PORTOS_APP_ID } from './apps.js';
@@ -574,7 +574,9 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do
* `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.`;
+const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Leave the PR open — do NOT merge it.** ${jiraTracked
+ ? 'This task is tracked in JIRA: its ticket is in review and a human lands the PR and the ticket together.'
+ : 'This task is configured to stop after opening the PR so a human can inspect and land it.'} Report the PR URL in your summary and stop.`;
/**
* The CI-gated merge procedure, in numbered steps starting at `startStep`.
@@ -699,12 +701,12 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '
* points at the manual git/gh Completion Workflow instead of a `/do:*` command.
* @param {Object|null} opts.worktreeInfo
* @param {boolean} opts.willOpenPR
- * @param {boolean} opts.willReviewLoop
+ * @param {'review-then-merge'|'merge-on-green'|'leave-open'} opts.prCompletion
* @returns {string|null}
*/
export function buildCompletionGuidelineBullet({
isReadOnly, isTui, tuiCompletionCommand, slashdoFree = false,
- worktreeInfo, willOpenPR, willReviewLoop, discardWorktree = false, noCodeOutput = false,
+ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, discardWorktree = false, noCodeOutput = false,
leavePrOpen = false, isPrFollowUp = false,
}) {
// A PR follow-up (review-loop or merge-only) already carries its own PRIMARY
@@ -735,9 +737,13 @@ export function buildCompletionGuidelineBullet({
return `On successful completion, YOU run ${howTo}, then write the sentinel and stop — PortOS closes the session once it sees the sentinel; do NOT run \`/quit\`.`;
}
if (worktreeInfo && willOpenPR) {
- const reviewSuffix = leavePrOpen
- ? ' This task is tracked in JIRA, so the PR is left OPEN for a human to land alongside the ticket — nothing merges it automatically.' + (willReviewLoop ? ' A follow-up agent still runs the configured reviewers against it.' : '')
- : willReviewLoop
+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
+ const reviewSuffix = policyLeavesOpen
+ ? ' This task is configured to leave the PR OPEN for you to inspect — no follow-up agent will review or merge it automatically.'
+ : leavePrOpen
+ ? ' This task is tracked in JIRA, so the PR is left OPEN for a human to land alongside the ticket — nothing merges it automatically.' + (runsReviewLoop ? ' A follow-up agent still runs the configured reviewers against it.' : '')
+ : runsReviewLoop
? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — do NOT run `/do:rpr` or attempt to address review comments yourself; you will have already exited.'
: ' No review was requested for this task, so a follow-up agent merges the PR once CI is green — do NOT try to merge it yourself; you will have already exited.';
return `On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${reviewSuffix}`;
@@ -916,7 +922,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// Build worktree context section if applicable
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);
+ const prCompletion = resolvePrCompletion(task.metadata);
// A discard (reasoning-only) worktree: the agent reasons in it but it's thrown
// away on exit with no commit/merge/PR (see agentWorktreeCleanup.js). Suppresses
// all commit/push/PR completion guidance in favor of the sentinel-only contract.
@@ -1014,7 +1020,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
? buildActionOutputCompletionSection({ isTui, sentinelPath })
: isTui
? buildTuiCompletionSection({
- willOpenPR, willReviewLoop, simplifyEnabled, providerId,
+ willOpenPR, prCompletion, simplifyEnabled, providerId,
sentinelPath,
leavePrOpen: leavesPrForHuman(task),
reviewers: taskReviewers,
@@ -1034,7 +1040,7 @@ After completing your work and before committing, ${simplifyInstruction}. Fix an
// PR URL. Suppressed for TUI agents because TUI agents open the PR themselves
// and the Completion Workflow above instructs them to request the Copilot
// review inline — the system-side post-exit handler never fires for TUI.
- const reviewLoopSection = willReviewLoop && willOpenPR && !isTui ? `
+ const reviewLoopSection = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE && willOpenPR && !isTui ? `
## Code Review
After your task completes, the system will spawn a follow-up agent that runs the review-and-fix loop until all configured reviewers are satisfied, then merges the PR. The follow-up uses **${taskReviewers.join(' → ')}** (in order). ${taskReviewers[0] === DEFAULT_REVIEWER
? 'Copilot leads the list, so for GitHub PRs the system pre-requests its initial review automatically (skipped on GitLab MRs and other non-GitHub forges); the follow-up then drives the rest of the chain.'
@@ -1193,7 +1199,7 @@ ${(() => {
const bullet = buildCompletionGuidelineBullet({
isReadOnly: isTruthyMetaFn(task.metadata?.readOnly),
isTui, tuiCompletionCommand, slashdoFree: isTui && isOpencodeCommand(providerCommand),
- worktreeInfo, willOpenPR, willReviewLoop, discardWorktree, noCodeOutput,
+ worktreeInfo, willOpenPR, prCompletion, discardWorktree, noCodeOutput,
leavePrOpen: leavesPrForHuman(task),
isPrFollowUp: isReviewLoopFollowUp,
});
@@ -1269,7 +1275,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
// directly-exported buildLightContextPrompt/Parts entry points.
task = reconcileSplitContext(task);
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);
+ const prCompletion = resolvePrCompletion(task.metadata);
const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);
const isReadOnly = isTruthyMetaFn(task.metadata?.readOnly);
const discardWorktree = isTruthyMetaFn(task.metadata?.discardWorktree);
@@ -1397,7 +1403,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
sections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody }));
} else if (isTui) {
sections.push(buildTuiCompletionSection({
- willOpenPR, willReviewLoop, simplifyEnabled, providerId, slashdoFree: tuiSlashdoFree,
+ willOpenPR, prCompletion, simplifyEnabled, providerId, slashdoFree: tuiSlashdoFree,
sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`,
branchName: worktreeInfo?.branchName || null,
baseBranch: worktreeInfo?.baseBranch || null,
@@ -1405,7 +1411,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet
reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies
}));
} else {
- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop, hasSlashdo, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));
+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));
}
return { taskSections, contractSections };
@@ -1447,16 +1453,14 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,
* both agent flows converge on the same final state. `reviewers` only colors
* the wording — the merge step itself is reviewer-agnostic.
*
- * With `willReviewLoop: false` the same two steps are emitted, but the merge
- * gate is CI instead of a review verdict: nothing else will ever merge that PR
- * (no review-loop follow-up is spawned), so "no reviewer configured" must mean
- * "merge it yourself once the checks pass", not "leave it open forever".
+ * `prCompletion` selects the review gate or CI-only merge gate. Leave-open
+ * callers do not invoke this helper.
*/
-function buildPostPRMergeSteps(startStep, { willReviewLoop = true, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {
+function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE } = {}) {
// No review loop → CI is the whole gate, so emit the shared CI procedure that
// the manual-TUI workflow and the merge follow-up agent also use. The PR URL
// isn't known when this prompt is written, hence the placeholder.
- if (!willReviewLoop) {
+ if (prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN) {
const gate = buildCiMergeGateSteps(startStep, { prRef: '"<PR_URL>"', forge: 'unknown' });
return {
lines: [
@@ -1497,12 +1501,14 @@ 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, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
+function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, providerId = null, slashdoFree = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
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, leavePrOpen });
+ return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen });
}
const cmd = willOpenPR ? '/do:pr' : '/do:push';
const reviewUsernames = normalizeReviewUsernames(usernames);
@@ -1510,16 +1516,16 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
// when the task's Review Loop control is off so that default cannot start a
// Copilot (or other external) review unexpectedly.
const reviewArgs = willOpenPR
- ? (willReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies, reviewUsernames, optionalReviewers) : '--review-with none')
+ ? (runsReviewLoop ? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies, reviewUsernames, optionalReviewers) : '--review-with none')
: '';
// A saved slashdo `merge: true` default would otherwise merge a PR that must
// stay open — dropping our own merge steps isn't enough, `/do:pr` has to be
// told not to merge (see lib/prDisposition.js).
- const mergeArg = (willOpenPR && leavePrOpen) ? ' --no-merge' : '';
+ const mergeArg = (willOpenPR && (leavePrOpen || policyLeavesOpen)) ? ' --no-merge' : '';
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 reviewSuffix = willOpenPR && willReviewLoop
+ 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 after the PR opens.`)
@@ -1535,9 +1541,9 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
// 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: leavePrOpen && willOpenPR ? [LEAVE_PR_OPEN_STEP(3)] : [], nextStep: leavePrOpen && willOpenPR ? 4 : 3 };
+ const merge = (willOpenPR && !leavePrOpen && !policyLeavesOpen)
+ ? buildPostPRMergeSteps(3, { prCompletion, reviewers, usernames: reviewUsernames, reviewStopMode })
+ : { lines: (leavePrOpen || policyLeavesOpen) && willOpenPR ? [LEAVE_PR_OPEN_STEP(3, leavePrOpen)] : [], nextStep: (leavePrOpen || policyLeavesOpen) && willOpenPR ? 4 : 3 };
const sentinelStep = merge.nextStep;
return [
@@ -1573,7 +1579,7 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
* agentTuiSpawning.js), so nothing happens after the agent exits — the agent owns
* the push and the PR itself.
*
- * With a review loop configured (`willReviewLoop`), it opens the PR/MR and stops:
+ * With review-then-merge configured, it opens the PR/MR and stops:
* this provider can't drive the reviewer CLIs (no slashdo `/do:pr` review loop)
* and PortOS runs no post-exit review for a TUI, so merging here would ship work
* the user asked to have reviewed. With the review loop OFF there is no reviewer
@@ -1583,9 +1589,9 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled
* Forge-aware (GitHub `gh` + GitLab `glab`) to match the slashdo path; refs are
* shell-quoted because a git ref can legally contain shell metacharacters.
*/
-// `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, leavePrOpen = false }) {
+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false }) {
+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
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`
@@ -1617,9 +1623,11 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, si
let step = 4;
if (willOpenPR) {
- const openNote = leavePrOpen
+ const openNote = policyLeavesOpen
+ ? '**Leave it open — do NOT merge it.** This task is configured to stop after opening the PR so you can inspect it.'
+ : 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
+ : runsReviewLoop
? '**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(
@@ -1630,7 +1638,7 @@ function buildManualTuiCompletionSection({ willOpenPR, willReviewLoop = true, si
` # GitLab: glab mr create --fill${glabBaseArg}`,
' ```',
);
- if (!willReviewLoop && !leavePrOpen) {
+ if (!runsReviewLoop && !leavePrOpen && !policyLeavesOpen) {
// 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);
@@ -1667,7 +1675,9 @@ 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, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
+function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {
+ const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;
+ const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
const reviewUsernames = normalizeReviewUsernames(usernames);
if (hasSlashdo && worktreeInfo && willOpenPR) {
const lines = ['## Completion', 'When finished, run these in order:'];
@@ -1675,13 +1685,13 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop =
if (simplifyEnabled) {
lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);
}
- const reviewArgs = willReviewLoop
+ const reviewArgs = runsReviewLoop
? buildReviewWithArgs(reviewers, reviewStopMode, reviewerApplies, reviewUsernames, optionalReviewers)
: '--review-with none';
// `--no-merge` overrides a saved slashdo `merge: true` default, which would
// otherwise merge a PR this task must leave open (see lib/prDisposition.js).
- const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + (leavePrOpen ? ' --no-merge' : '');
- const completionNote = willReviewLoop
+ const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen) ? ' --no-merge' : '');
+ const completionNote = runsReviewLoop
? ((reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0)
? 'and drives the Copilot review loop until clean.'
: `and drives the review loop for ${[...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ')} in order until clean.`)
@@ -1689,10 +1699,10 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, willReviewLoop =
lines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);
// 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));
+ if (leavePrOpen || policyLeavesOpen) {
+ lines.push(LEAVE_PR_OPEN_STEP(step, leavePrOpen));
} else {
- const merge = buildPostPRMergeSteps(step, { willReviewLoop, reviewers, usernames: reviewUsernames, reviewStopMode });
+ const merge = buildPostPRMergeSteps(step, { prCompletion, reviewers, usernames: reviewUsernames, reviewStopMode });
lines.push(...merge.lines);
}
return lines.join('\n');
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index a776ceea40..01ee53a2a3 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -355,6 +355,19 @@ describe('buildLightContextPrompt', () => {
expect(prompt).not.toMatch(/gh pr checks/);
});
+ it('leaves an explicitly leave-open TUI task without review or merge instructions', () => {
+ const prompt = buildLightContextPrompt(
+ makeTask({ metadata: { simplify: true, openPR: true, prCompletion: 'leave-open', reviewLoop: true } }),
+ '/r',
+ { branchName: 'b', worktreePath: '/tmp/wt' },
+ isTruthyMeta,
+ { isTui: true });
+ expect(prompt).toMatch(/Leave the PR open — do NOT merge it/);
+ expect(prompt).toMatch(/`\/do:pr --review-with none --no-merge`/);
+ expect(prompt).not.toMatch(/gh pr merge/);
+ expect(prompt).not.toMatch(/review loop/i);
+ });
+
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' } }),
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 97b7b34a1b..8be9fee343 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -23,16 +23,16 @@ 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 { PR_COMPLETIONS, PR_COMPLETION_VALUES, 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';
/**
* Clean up a worktree for a completed agent.
* Reads worktree metadata from the agent's registered state and removes the worktree.
* When openPR is true, pushes the branch and creates a PR instead of auto-merging.
- * When requestCopilotReview is also true, spawns a follow-up internal task that drives
- * the multi-reviewer loop and merges once the review chain is clean — that follow-up is
- * the part the user expects to "keep looping until ready to merge."
+ * `prCompletion` decides whether the PR is reviewed then merged, merged after
+ * green CI, or intentionally left open. The explicit leave-open policy does
+ * not spawn a post-PR agent.
* `reviewers` is the ordered reviewer list (e.g. `[codex, antigravity, copilot]`); the native
* GitHub Copilot review is pre-requested here only when copilot LEADS the list (otherwise
* the follow-up requests it at its turn so Copilot sees the post-fix diff). `reviewStopMode`
@@ -43,7 +43,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_CA
* the worktree branch into the source workspace because `gh pr merge` already handled it.
* Otherwise, merges the worktree branch back to the source branch on success.
*/
-export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
+export async function cleanupAgentWorktree(agentId, success, { openPR = false, prCompletion = null, requestCopilotReview: legacyRequestCopilotReview = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
if (!agentState?.metadata?.isWorktree) return [];
@@ -140,6 +140,12 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
const cliName = prResult.cli || 'gh';
emitLog('success', `🌳 Created PR: ${prResult.url} (${cliName}${prResult.account ? ` authed as ${prResult.account}` : ''})`, { agentId, branchName: worktreeBranch, cli: prResult.cli, account: prResult.account, owner: prResult.owner, host: prResult.host });
+ // Production completion paths pass a resolver-backed policy. Keep the
+ // former option as a narrow compatibility fallback for direct callers.
+ const resolvedPrCompletion = PR_COMPLETION_VALUES.includes(prCompletion)
+ ? prCompletion
+ : (legacyRequestCopilotReview ? PR_COMPLETIONS.REVIEW_THEN_MERGE : PR_COMPLETIONS.MERGE_ON_GREEN);
+ const runsReviewLoop = resolvedPrCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;
const reviewerList = normalizeReviewers({ reviewers });
const copilotIsFirst = reviewerList[0] === DEFAULT_REVIEWER;
const nonCopilotReviewers = reviewerList.filter(r => r !== DEFAULT_REVIEWER);
@@ -150,7 +156,7 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
// turn, after the earlier reviewer's fixes are pushed. This pre-request is a
// latency optimization only — the follow-up requests Copilot at its turn
// regardless, so a failed/absent pre-request is recoverable (no reviewer dropped).
- if (shouldRequestCopilot && copilotIsFirst) {
+ if (runsReviewLoop && copilotIsFirst) {
const reviewResult = await git.requestCopilotReview(worktreePath, prResult.url).catch(err => ({ success: false, error: err.message }));
if (reviewResult.success && reviewResult.skipped) {
emitLog('info', `🤖 Skipping Copilot pre-request for ${prResult.url} (non-GitHub forge)`, { agentId, prUrl: prResult.url });
@@ -161,30 +167,17 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
warnings.push(`Copilot review request failed for ${prResult.url}: ${reviewResult.error}`);
}
}
- if (shouldRequestCopilot && nonCopilotReviewers.length > 0) {
+ if (runsReviewLoop && nonCopilotReviewers.length > 0) {
emitLog('info', `🤖 Follow-up will run CLI reviewers: ${nonCopilotReviewers.join(', ')}`, { agentId, prUrl: prResult.url });
}
- // Spawn the review-loop follow-up agent that runs the multi-reviewer loop until
- // clean and merges. Hand it the FULL ordered list — the follow-up requests Copilot
- // at copilot's turn (so a failed pre-request or copilot-only config still gets a
- // review pass) and invokes the CLI reviewers itself. The only reviewer dropped is
- // copilot on a non-GitHub forge, handled centrally in spawnReviewLoopFollowUp.
- //
- // A follow-up is spawned for a PR PortOS opened, because something has to
- // land it. `spawnReviewLoopFollowUp` picks the mode from what actually
- // survives reviewer resolution: reviewers left → review-then-merge; none left
- // (Review Loop off, or copilot-only on a GitLab forge) → merge on green CI.
- // Deciding it there rather than here is what keeps a stripped reviewer list
- // from silently producing an orphaned PR.
- //
- // 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.
+ // JIRA remains a legacy human hand-off: configured reviewers can still
+ // run, but the follow-up must not merge. An explicit leave-open policy is
+ // different — opening the PR is the entire requested outcome.
const leaveOpen = leavesPrForHuman(originalTask);
- if (leaveOpen && !shouldRequestCopilot) {
+ if (resolvedPrCompletion === PR_COMPLETIONS.LEAVE_OPEN) {
+ emitLog('info', `🤝 Leaving ${prResult.url} open by task completion policy`, { agentId, prUrl: prResult.url });
+ } else if (leaveOpen && !runsReviewLoop) {
emitLog('info', `🤝 Leaving ${prResult.url} open for a human — JIRA-tracked task, no reviewers configured`, { agentId, prUrl: prResult.url });
} else {
await spawnReviewLoopFollowUp({
@@ -193,9 +186,10 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
prUrl: prResult.url,
prBranch: worktreeBranch,
sourceWorkspace,
- reviewers: shouldRequestCopilot ? reviewerList : [],
- usernames: shouldRequestCopilot ? usernames : [],
- optionalReviewers: shouldRequestCopilot ? optionalReviewers : [],
+ prCompletion: resolvedPrCompletion,
+ reviewers: runsReviewLoop ? reviewerList : [],
+ usernames: runsReviewLoop ? usernames : [],
+ optionalReviewers: runsReviewLoop ? optionalReviewers : [],
reviewStopMode,
reviewerApplies,
reviewerModels,
@@ -252,20 +246,17 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
* forges. `usernames` are arbitrary GitHub reviewer usernames the follow-up
* requests as PR reviewers to gate the merge — forge-agnostic, so never stripped.
*
- * **Mode is derived, not passed.** When nothing survives reviewer resolution —
- * the task's Review Loop was off (caller passes an explicitly empty list), or
- * copilot was the only reviewer and this is a GitLab MR — the follow-up runs in
- * **merge-only** mode: no review, just land the PR (wait for CI, fix a failing
- * check or a conflict, merge). Deriving it here means there is no combination
- * that spawns nothing and leaves the PR open forever, which is what used to
- * happen both with the Review Loop off and with copilot-only on GitLab.
+ * `prCompletion` is resolved before this function is called. It selects review
+ * then merge versus merge on green directly; `leave-open` is intentional and
+ * returns without creating a follow-up.
*
* The follow-up task uses an isolated worktree attached to the existing PR
* 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, leaveOpen = false }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, leaveOpen = false }) {
if (!prUrl || !prBranch) return null;
+ if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN) return null;
const parsedPr = git.parsePullRequestUrl(prUrl);
// Copilot is GitHub-only; CLI-based reviewers (claude/antigravity/codex/grok) work on any
@@ -286,8 +277,12 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// Non-blocking (`~opt`) marker set — forge-agnostic, threaded verbatim so the
// follow-up's `--review-with` marks the same reviewers optional.
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;
+ // Merge-on-green deliberately skips every reviewer. A legacy review loop
+ // whose GitHub-only reviewer vanishes on another forge retains its prior
+ // merge-only fallback instead of leaving an orphaned PR.
+ const mergeOnly = prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN
+ || (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE
+ && 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.
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 58376e129f..cdb490f4e1 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -606,6 +606,23 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ it('leaves an explicitly leave-open PR without spawning a follow-up', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/79' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true,
+ prCompletion: 'leave-open',
+ reviewers: ['copilot'],
+ description: 'X',
+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
+ });
+
+ expect(git.requestCopilotReview).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ expect(removeWorktree).toHaveBeenCalled();
+ });
+
it('spawns a merge-only follow-up on non-GitHub forges when copilot was the only reviewer', async () => {
// Copilot can't review a GitLab MR, so the review loop has nothing to run — but
// the MR still has to land, so the follow-up degrades to merge-only rather than
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 4f04e22942..10fd250e91 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -40,6 +40,7 @@ import { isRecoveryTask } from './recoveryTasks.js';
import { getCodeReviewDefaults } from './codeReview.js';
import { isHeldByOther, getClaimOwner } from './cosTaskClaim.js';
import { ensureInstanceId } from './instances.js';
+import { PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
/**
* Block a task that has exceeded the max spawn limit. Returns true if blocked.
@@ -1612,6 +1613,13 @@ export function applyAppWorktreeDefault(metadata, app) {
} else if (finalWorktreeOff) {
metadata.openPR = false;
}
+
+ // Legacy apps without this field keep resolving their persisted reviewLoop
+ // metadata. Once an app explicitly configures a default, stamp it onto new
+ // PR tasks so the policy survives later app-default changes.
+ if (finalOpenPR && metadata.prCompletion === undefined && PR_COMPLETION_VALUES.includes(app.defaultPrCompletion)) {
+ metadata.prCompletion = app.defaultPrCompletion;
+ }
}
async function generateManagedAppImprovementTask(app, state) {
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index fe33e963f1..8d2e072cb5 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -17,6 +17,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { parseTasksMarkdown, groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks, generateTasksMarkdown, hasKnownPrefix } from '../lib/taskParser.js';
import { REVIEW_STOP_MODES, normalizeReviewers, normalizeReviewUsernames } from '../lib/validation.js';
+import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';
import { loadState, withStateLock, ROOT_DIR } from './cosState.js';
import { cosEvents } from './cosEvents.js';
import { CLAIM_METADATA_KEYS } from './cosTaskClaim.js';
@@ -278,6 +279,13 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
// their existing auto-merge behavior so automation isn't silently gated on a
// human merging a PR.
else if (taskData.useWorktree === true && taskType === 'user') metadata.openPR = true;
+ if (PR_COMPLETION_VALUES.includes(taskData.prCompletion)) {
+ metadata.prCompletion = taskData.prCompletion;
+ } else if (metadata.openPR === true && taskType === 'user') {
+ // New user tasks should persist their explicit default; legacy records
+ // remain untouched and resolve from reviewLoop at read time.
+ metadata.prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE;
+ }
if (taskData.simplify === true) metadata.simplify = true;
else if (taskData.simplify === false) metadata.simplify = false;
if (taskData.reviewLoop === true) metadata.reviewLoop = true;
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 91647a0668..7a8d7cf20a 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -386,6 +386,12 @@ describe('cosTaskStore.addTask', () => {
const task = await addTask({ description: 'flagged', useWorktree: false, openPR: true }, 'user');
expect(task.metadata.useWorktree).toBe(false);
expect(task.metadata.openPR).toBe(true);
+ expect(task.metadata.prCompletion).toBe('review-then-merge');
+ });
+
+ it('persists an explicit PR completion policy on new user tasks', async () => {
+ const task = await addTask({ description: 'inspect first', useWorktree: true, openPR: true, prCompletion: 'leave-open' }, 'user');
+ expect(task.metadata.prCompletion).toBe('leave-open');
});
it('defaults a worktree USER task to openPR:true when openPR is unspecified', async () => {
diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.js
index 487e036fbf..a702f1fcde 100644
--- a/server/services/subAgentSpawner.test.js
+++ b/server/services/subAgentSpawner.test.js
@@ -354,6 +354,18 @@ describe('Worktree & metadata flag helpers', () => {
expect(metadata.openPR).toBe(true);
});
+ it('copies an explicit app PR completion default onto new PR tasks', () => {
+ const metadata = {};
+ applyAppWorktreeDefault(metadata, { defaultOpenPR: true, defaultPrCompletion: 'leave-open' });
+ expect(metadata).toMatchObject({ useWorktree: true, openPR: true, prCompletion: 'leave-open' });
+ });
+
+ it('does not invent a disposition for a legacy app default', () => {
+ const metadata = {};
+ applyAppWorktreeDefault(metadata, { defaultOpenPR: true });
+ expect(metadata.prCompletion).toBeUndefined();
+ });
+
it('should not let defaultUseWorktree:false override explicit openPR:true', () => {
const metadata = { openPR: true };
applyAppWorktreeDefault(metadata, { defaultUseWorktree: false });