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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
keep the branch when a stand-down can't confirm the PR, and collapse the PR-creation flags
[._.]/ Adam Eivyaaeca2f342ed
diff --git a/server/lib/README.md b/server/lib/README.mdindex 7515b0f7e3..597ee2408b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -334,11 +334,11 @@ 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` | `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. |+| `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. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `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). || `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so the TUI idle reaper does not score a filed-issue/printed-report run as `idle-no-changes`). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. |-| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |+| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. Over `SLASHDO_INLINE_BUDGET_CHARS` (24,000) with a `bodyPath` it emits a filesystem pointer instead of the text — #3110), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. || `slashdoLoader.js` | Loads bundled slashdo command/lib markdown (`lib/slashdo/` submodule) and resolves it the way slashdo's own per-environment installer would, since PortOS inlines these bodies into CoS-agent prompts WITHOUT running that installer. `loadSlashdoFile(cmd, {stripFrontmatter, skipIncludes})` / `loadSlashdoLib(name, {teams})` resolve the `` !`cat ~/.claude/lib/…` `` includes + `if:teams` conditionals, with `skipIncludes` pruning lib includes the run can never reach (each leaves a one-line "not applicable" marker — #3110); `writeResolvedSlashdoBody(cmd, body, {skipIncludes})` → absolute path, writing the already-loaded body under `PATHS.slashdoResolved` (`data/cos/slashdo-resolved/`, gitignored derived cache) at most once per (command, body) per process, so a file-tool host can be handed a path instead of a 250KB paste. Split out of `fileUtils.js` (a generic file-utilities module) as its own feature module — pairs with `slashdoInvocation.js`, which resolves how a workflow is TYPED per host CLI rather than how its body is loaded. || `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. || `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.jsindex 0fe51b4718..931777146e 100644--- a/server/lib/prDisposition.js+++ b/server/lib/prDisposition.js@@ -68,3 +68,42 @@ export function leavesPrForHuman(task) {const metadata = task?.metadata || {};return PR_STAYS_OPEN_SET.has(metadata.analysisType) || !!metadata.jiraTicketId;}++/**+ * Who opens the change request for a completing worktree agent (#3733).+ *+ * One tri-state rather than two booleans, because two booleans have an+ * unrepresentable-in-practice pair ("check first, but never create") and a+ * caller has to keep them consistent by hand.+ *+ * - `NEVER` — the agent owns it and finalize ALREADY verified the claim+ * (`prExpected`), so a run that reaches cleanup as a success has+ * a confirmed PR. Also the no-PR-at-all case.+ * - `IF_MISSING` — the agent owns it and finalize did NOT verify (a slashdo-free+ * harness). Cleanup asks the forge once and creates one only on a+ * definite "none".+ * - `ALWAYS` — PortOS owns it (a lean `--bare` session hands the lifecycle back).+ */+export const PR_CREATION = Object.freeze({+ NEVER: 'never',+ IF_MISSING: 'if-missing',+ ALWAYS: 'always',+});++/**+ * Resolve `PR_CREATION` for a completing agent — one place, so the three+ * completion paths (runner, TUI spawner, direct-CLI spawner) can't drift into+ * double-firing `gh pr create` or into leaving a branch with no PR.+ *+ * @param {Object} opts+ * @param {boolean} opts.taskOpenPR - the task asked for a PR at all+ * @param {boolean} opts.agentOwnsPr - the prompt told the agent to open it+ * @param {boolean} opts.prClaimVerified - finalize ran `verifyPrClaim` for this+ * run (i.e. `prExpected` was true), so cleanup must not ask a second time+ * @returns {string} a `PR_CREATION` value+ */+export function resolvePrCreation({ taskOpenPR, agentOwnsPr, prClaimVerified }) {+ if (!taskOpenPR) return PR_CREATION.NEVER;+ if (!agentOwnsPr) return PR_CREATION.ALWAYS;+ return prClaimVerified ? PR_CREATION.NEVER : PR_CREATION.IF_MISSING;+}diff --git a/server/lib/prDisposition.test.js b/server/lib/prDisposition.test.jsindex c7eec083cc..9ee6f1686c 100644--- a/server/lib/prDisposition.test.js+++ b/server/lib/prDisposition.test.js@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { PR_COMPLETIONS, resolvePrCompletion } from './prDisposition.js';+import { PR_COMPLETIONS, PR_CREATION, resolvePrCompletion, resolvePrCreation } from './prDisposition.js';describe('resolvePrCompletion', () => {it('prefers an explicit valid disposition', () => {@@ -21,3 +21,25 @@ describe('resolvePrCompletion', () => {.toBe(PR_COMPLETIONS.REVIEW_THEN_MERGE);});});++describe('resolvePrCreation (#3733)', () => {+ it('never creates one for a task that asked for no PR', () => {+ expect(resolvePrCreation({ taskOpenPR: false, agentOwnsPr: false, prClaimVerified: false })).toBe(PR_CREATION.NEVER);+ // …even if the agent would otherwise have owned it.+ expect(resolvePrCreation({ taskOpenPR: false, agentOwnsPr: true, prClaimVerified: false })).toBe(PR_CREATION.NEVER);+ });++ it('creates one outright when PortOS owns the lifecycle (a lean --bare session)', () => {+ expect(resolvePrCreation({ taskOpenPR: true, agentOwnsPr: false, prClaimVerified: false })).toBe(PR_CREATION.ALWAYS);+ });++ it('backstops an owner finalize did NOT verify — the slashdo-free harnesses', () => {+ expect(resolvePrCreation({ taskOpenPR: true, agentOwnsPr: true, prClaimVerified: false })).toBe(PR_CREATION.IF_MISSING);+ });++ it('stands down for an owner finalize already verified, rather than re-asking the forge', () => {+ // A slashdo-capable run that reaches cleanup as a success already passed+ // verifyPrClaim; a second `gh pr list` would be pure duplication.+ expect(resolvePrCreation({ taskOpenPR: true, agentOwnsPr: true, prClaimVerified: true })).toBe(PR_CREATION.NEVER);+ });+});diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex 09e661a515..3f77b86641 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -29,6 +29,7 @@*/import { isClaudeProvider, isOpencodeProvider } from './providerModels.js';import { inferTuiCommand } from './tuiHandshake.js';+import { PROVIDER_TYPES } from './aiToolkit/constants.js';/** slashdo's command namespace — `commands/do/<cmd>.md` in the submodule. */export const SLASHDO_NAMESPACE = 'do';@@ -264,8 +265,11 @@ export function canTypeSlashCommands({* Provider types spawned as a local coding harness — a real shell, real file* tools, and a PATH that has `git` / `gh` / the reviewer CLIs on it. An HTTP* `api` provider has none of that, so it can never drive its own PR.+ *+ * Built from `PROVIDER_TYPES` rather than string literals: a typo'd literal here+ * silently returns `false` and PortOS starts double-driving the PR.*/-const HARNESS_PROVIDER_TYPES = new Set(['cli', 'tui']);+const HARNESS_PROVIDER_TYPES = new Set([PROVIDER_TYPES.CLI, PROVIDER_TYPES.TUI]);/*** True when a spawned session can drive the WHOLE change-request lifecycle@@ -302,6 +306,30 @@ export function agentOwnsPrWorkflow({ providerType = null, leanMode = false } =return HARNESS_PROVIDER_TYPES.has(providerType);}+/**+ * The same answer for a COMPLETED agent, read off its record.+ *+ * `metadata.ownsPrWorkflow` is stamped at spawn time from the resolved provider,+ * and is authoritative: cleanup must act on what the prompt actually said, not+ * on a fresh derivation that could disagree with it.+ *+ * A record written before #3733 carries no such key. Those runs really were+ * prompted by the old builder, whose gate was `canTypeSlashCommands` — so that+ * is the correct answer for them, and it lives here next to the predicate rather+ * than inline in a service, where the next caller would miss it.+ *+ * @param {Object} opts+ * @param {boolean|undefined} opts.persisted - `metadata.ownsPrWorkflow`+ * @param {string|null} [opts.providerId]+ * @param {string|null} [opts.providerCommand]+ * @param {boolean} [opts.leanMode]+ * @returns {boolean}+ */+export function resolveOwnsPrWorkflow({ persisted, providerId = null, providerCommand = null, leanMode = false }) {+ if (typeof persisted === 'boolean') return persisted;+ return canTypeSlashCommands({ providerId, providerCommand, leanMode });+}+/*** Resolve the concrete invocation for a slashdo-backed task.*@@ -338,6 +366,20 @@ export function resolveSlashdoInvocation({return { command, skillName, style, args: trimmedArgs, invocation };}+/**+ * The "it's on disk, go read it" line for a procedure body too large to paste+ * (#3110). Shared so every pointer an agent meets reads the same — a second+ * hand-typed copy is how one caller ends up omitting the read-it-in-sections+ * instruction that makes a 40KB file usable.+ *+ * @param {string} bodyPath - absolute path to the resolved copy+ * @param {string} body - the body itself, for its size+ * @returns {string}+ */+export function oversizedBodyPointer(bodyPath, body) {+ return `The full procedure is on disk at \`${bodyPath}\` (${Math.round(body.length / 1000)}KB) — too large to paste here. READ THAT FILE before you start and follow it exactly rather than improvising. It is long: read it in sections as you need them, and do not assume a step you have not read.`;+}+/*** Render the prompt section for a resolved slashdo invocation. Pure — the* caller loads `body` (via `loadSlashdoFile`) and passes it in, so this module@@ -415,10 +457,7 @@ export function buildSlashdoSection(resolved, body = null, { bodyPath = null, relines.push('', reviewerEffortNote);}if (body && bodyPath && body.length > SLASHDO_INLINE_BUDGET_CHARS) {- lines.push(- '',- `The full procedure is on disk at \`${bodyPath}\` (${Math.round(body.length / 1000)}KB) — too large to paste here. READ THAT FILE before you start and follow it exactly rather than improvising. It is long: read it in sections as you need them, and do not assume a step you have not read.`- );+ lines.push('', oversizedBodyPointer(bodyPath, body));} else if (body) {lines.push('',diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex 4a35cec123..77209cfe70 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -7,6 +7,7 @@ import {agentOwnsPrWorkflow,buildSlashdoSection,canTypeSlashCommands,+ resolveOwnsPrWorkflow,isValidSlashdoCommand,resolveSlashdoInvocation,resolveSlashdoStyle,@@ -179,6 +180,29 @@ describe('agentOwnsPrWorkflow (#3733)', () => {});});+describe('resolveOwnsPrWorkflow (#3733)', () => {+ it('trusts the stamp — cleanup must act on what the prompt actually said', () => {+ // Including when the stamp disagrees with a fresh derivation: a provider+ // reconfigured mid-run must not change the answer for an agent already+ // prompted under the old one.+ expect(resolveOwnsPrWorkflow({ persisted: true, providerId: 'codex', providerCommand: 'codex' })).toBe(true);+ expect(resolveOwnsPrWorkflow({ persisted: false, providerId: 'claude-code', providerCommand: 'claude' })).toBe(false);+ });++ it('falls back to the slash-command gate for a pre-#3733 record', () => {+ // Those runs really were prompted by the old builder, whose gate this was.+ expect(resolveOwnsPrWorkflow({ persisted: undefined, providerId: 'claude-code', providerCommand: 'claude' })).toBe(true);+ expect(resolveOwnsPrWorkflow({ persisted: undefined, providerId: 'codex', providerCommand: 'codex' })).toBe(false);+ expect(resolveOwnsPrWorkflow({ persisted: undefined, providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true })).toBe(false);+ });++ it('treats a non-boolean stamp as absent, not as false', () => {+ // `null` from a JSON round-trip must not silently claim PortOS owns the PR.+ expect(resolveOwnsPrWorkflow({ persisted: null, providerId: 'claude-code' })).toBe(true);+ expect(resolveOwnsPrWorkflow({ persisted: 'true', providerId: 'codex', providerCommand: 'codex' })).toBe(false);+ });+});+describe('resolveSlashdoInvocation', () => {it('returns null without a valid command', () => {expect(resolveSlashdoInvocation({})).toBeNull();diff --git a/server/lib/slashdoLoader.js b/server/lib/slashdoLoader.jsindex 713fa817f3..1ebab5f237 100644--- a/server/lib/slashdoLoader.js+++ b/server/lib/slashdoLoader.js@@ -208,7 +208,16 @@ export async function loadSlashdoLib(libName, { teams = false } = {}) {const libDir = join(PATHS.slashdo, 'lib');let content = await readFile(join(libDir, `${libName}.md`), 'utf-8').catch(() => null);- if (!content) return null;+ // Cache the MISS too. An install whose `lib/slashdo` submodule was never+ // initialized (`npm run install:all` is what fetches it) would otherwise+ // re-attempt the read on every spawn that asks — and since #3733 that is every+ // slashdo-free PR-opening agent, not just review-loop follow-ups. The+ // submodule can't appear without a restart, which is the same assumption the+ // hit path already makes.+ if (!content) {+ slashdoLibCache.set(cacheKey, null);+ return null;+ }content = await resolveSlashdoIncludes(content, libDir);content = resolveSlashdoConditionals(content, { teams });slashdoLibCache.set(cacheKey, content);diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 33e00491ab..88deee3403 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -36,7 +36,7 @@ import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider }import { resolveForgeTokenEnv } from './git.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';-import { resolvePrCompletion } from '../lib/prDisposition.js';+import { resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';import { doneSentinelPath } from '../lib/agentSentinel.js';import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';@@ -786,8 +786,11 @@ export async function spawnDirectly({const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);const reviewOptions = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn });await cleanupWorktreeFn(agentId, cleanupSuccess, {- openPR: directOpenPR,- openPRIfMissing: directAgentOwnsPR,+ prCreation: resolvePrCreation({+ taskOpenPR: directOpenPR,+ agentOwnsPr: directAgentOwnsPR,+ prClaimVerified: directPrClaimExpected,+ }),prCompletion: directPrCompletion,...reviewOptions,skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 375e233a72..44bb792ed4 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -28,8 +28,8 @@ import * as git from './git.js';import { isTruthyMeta } from './agentState.js';import { resolveReviewLoopOptions } from './codeReview.js';import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';-import { resolvePrCompletion } from '../lib/prDisposition.js';-import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';+import { resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';+import { canTypeSlashCommands, resolveOwnsPrWorkflow } from '../lib/slashdoInvocation.js';const ROOT_DIR = PATHS.root;@@ -329,52 +329,37 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, eff// body — re-merging the worktree branch into the source workspace would// duplicate the squashed commits, so suppress the auto-merge fallback.const taskReviewLoopFollowUp = isTruthyMeta(task?.metadata?.reviewLoopFollowUp);- // Claude Code CLI agents run `/simplify` + `/do:pr` themselves (see- // buildCliCompletionSection in agentPromptBuilder.js) — they push the- // branch and open the PR on their own. Mirror the TUI cleanup contract- // so PortOS doesn't double-fire `gh pr create` ("a pull request already- // exists" would preserve the worktree as a false-positive failure).+ // Who opens the PR, and whether finalize already checked that they did.+ // These two must match what the prompt actually told the agent or PortOS+ // double-fires `gh pr create` ("a pull request already exists" would then+ // preserve the worktree as a false-positive failure).//- // Derived from the SAME `canTypeSlashCommands` predicate the prompt's- // `hasSlashdo` gate uses (#3114) — these two must agree or the double-fire- // this comment describes is exactly what happens. An id allowlist here would- // miss a path-configured `claude` under a custom provider id (told to run- // `/do:pr`, then PortOS opens a second PR) and would wrongly claim a lean- // `--bare` session owns a PR it was never told to open. `providerCommand` /- // `leanMode` are persisted on the agent record for this; a pre-upgrade record- // carries neither, and a blank command reads as `claude` — which is what the- // old id allowlist effectively assumed for the claude-code ids anyway.- // Read off the PERSISTED record first (#3358): the in-memory `runnerAgents`- // entry carries only `providerId`, so a lean `--bare` or path-configured- // provider would be misjudged here — and finalizeAgent's PR verification- // keys on the same question, so the two must resolve it identically.- //- // #3733: the answer is now STAMPED on the record at spawn time- // (`metadata.ownsPrWorkflow`) rather than re-derived, because it no longer- // tracks `canTypeSlashCommands` — a codex/grok/agy harness can't type- // `/do:pr` but is told to run `gh pr create` itself. Re-deriving from the- // slash-command predicate would have PortOS open a SECOND PR for every one- // of those runs. A pre-upgrade record carries no such key; those runs were- // prompted by the old builder, so they fall back to the old derivation.- const persistedOwnsPrWorkflow = agentState?.metadata?.ownsPrWorkflow ?? agent.ownsPrWorkflow;- const agentOwnsPR = taskOpenPR && (typeof persistedOwnsPrWorkflow === 'boolean'- ? persistedOwnsPrWorkflow- : canTypeSlashCommands({- providerId: agentState?.metadata?.providerId ?? agent.providerId,- providerCommand: agentState?.metadata?.providerCommand ?? agent.providerCommand ?? null,- leanMode: (agentState?.metadata?.leanMode ?? agent.leanMode) === true,- }));+ // Read off the PERSISTED record (#3358): the in-memory `runnerAgents` entry+ // carries only `providerId`, so a lean `--bare` or path-configured provider+ // would be misjudged from it. `resolveOwnsPrWorkflow` owns the stamped-vs-+ // derived fallback for pre-#3733 records, alongside the predicate itself.+ const providerDescriptor = {+ providerId: agentState?.metadata?.providerId ?? agent.providerId,+ providerCommand: agentState?.metadata?.providerCommand ?? agent.providerCommand ?? null,+ leanMode: (agentState?.metadata?.leanMode ?? agent.leanMode) === true,+ };+ const agentOwnsPR = taskOpenPR && resolveOwnsPrWorkflow({+ persisted: agentState?.metadata?.ownsPrWorkflow ?? agent.ownsPrWorkflow,+ ...providerDescriptor,+ });+ // Mirrors the `prExpected` the runner path handed finalizeAgent — when that+ // was true, finalize already asked the forge, so cleanup must not ask again.+ const prClaimVerified = taskOpenPR && canTypeSlashCommands(providerDescriptor);// Merge per-task reviewer metadata with the user's Code Review Defaults// (AI Providers → Code Review Defaults panel). Settings I/O is cached// inside the resolver, so this is effectively free even when invoked// from a tight CoS sweep.const reviewOptions = await resolveReviewLoopOptions(task?.metadata, { normalize: normalizeReviewers, isTruthyMeta });const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {- // Never a flat `false` for an agent-owned PR any more: cleanup asks the- // forge first and only stands down once a PR actually exists, so a harness- // that skipped its completion workflow can't strand the branch (#3733).- openPR: taskOpenPR,- openPRIfMissing: agentOwnsPR,+ // `if-missing` for an agent-owned PR that finalize did NOT verify: cleanup+ // asks the forge once and only stands down when a PR actually exists, so a+ // harness that skipped its completion workflow can't strand the branch.+ prCreation: resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified }),prCompletion: taskPrCompletion,...reviewOptions,skipMerge: taskReviewLoopFollowUp || agentOwnsPR,diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 75b1bb1e16..b4c697252f 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -151,15 +151,19 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()// #3733: the record now STAMPS the answer at spawn time, because it no longer// tracks `canTypeSlashCommands` — a codex/grok/agy harness can't type `/do:pr`// but is told to run `gh pr create` itself.- it.each([- ['a codex harness', 'codex', 'codex'],- ['a claude session', 'claude-code', 'claude'],- ])('%s that owns its PR workflow is backstopped, not double-fired', async (_label, providerId, providerCommand) => {- const opts = await cleanupCallFor({ providerId, providerCommand, leanMode: false, ownsPrWorkflow: true });- // openPR stays true so cleanup can still recover a PR the agent never opened;- // openPRIfMissing is what makes that a check-first safety net.- expect(opts.openPR).toBe(true);- expect(opts.openPRIfMissing).toBe(true);+ it('a codex harness that owns its PR workflow is backstopped, not double-fired', async () => {+ // Finalize skipped `verifyPrClaim` for it (`prExpected` keys on the+ // slash-command predicate), so cleanup asks the forge once itself.+ const opts = await cleanupCallFor({ providerId: 'codex', providerCommand: 'codex', leanMode: false, ownsPrWorkflow: true });+ expect(opts.prCreation).toBe('if-missing');+ expect(opts.skipMerge).toBe(true);+ });++ it('a claude session that owns its PR workflow needs no second forge query', async () => {+ // Finalize already ran `verifyPrClaim`, and a run that reaches cleanup as a+ // success passed it — re-asking would be a duplicate `gh pr list`.+ const opts = await cleanupCallFor({ providerId: 'claude-code', providerCommand: 'claude', leanMode: false, ownsPrWorkflow: true });+ expect(opts.prCreation).toBe('never');expect(opts.skipMerge).toBe(true);});@@ -167,33 +171,42 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()const opts = await cleanupCallFor({providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true, ownsPrWorkflow: false,});- expect(opts.openPR).toBe(true);- expect(opts.openPRIfMissing).toBe(false);+ expect(opts.prCreation).toBe('always');expect(opts.skipMerge).toBe(false);});+ it('a task that asked for no PR never creates one', async () => {+ await runAgentCompletionCleanup({+ agentId: 'a1', task: { id: 't', taskType: 'user', metadata: {} },+ agent: { providerId: 'codex', providerCommand: 'codex', ownsPrWorkflow: true },+ effectiveSuccess: true, outputBuffer: '',+ });+ expect(cleanupAgentWorktree.mock.calls.at(-1)[2].prCreation).toBe('never');+ });+it.each([- ['claude-code', 'claude', true],- ['claude-code-bedrock', 'claude', true],+ ['claude-code', 'claude', 'never'],+ ['claude-code-bedrock', 'claude', 'never'],// The case an id allowlist missed: a path-configured claude under a custom id// IS told to run /do:pr, so PortOS must not open a second PR.- ['my-custom-agent', '/opt/homebrew/bin/claude', true],- ['codex', 'codex', false],- ['antigravity-cli', 'agy', false],- ])('a pre-upgrade %s record falls back to the slash-command derivation it was prompted with', async (providerId, providerCommand, owns) => {+ ['my-custom-agent', '/opt/homebrew/bin/claude', 'never'],+ // Prompted by the OLD builder, which told these to commit and stop.+ ['codex', 'codex', 'always'],+ ['antigravity-cli', 'agy', 'always'],+ ])('a pre-upgrade %s record falls back to the slash-command derivation it was prompted with', async (providerId, providerCommand, prCreation) => {// No `ownsPrWorkflow` key: written before #3733, so the run really was// prompted by the old builder and the old gate is the correct answer.const opts = await cleanupCallFor({ providerId, providerCommand, leanMode: false });- expect(opts.openPRIfMissing).toBe(owns);- expect(opts.skipMerge).toBe(owns);+ expect(opts.prCreation).toBe(prCreation);+ expect(opts.skipMerge).toBe(prCreation === 'never');});it('a pre-upgrade agent record with only providerId still resolves', async () => {// Records written before providerCommand/leanMode were persisted: a blank// command reads as `claude`, which is what the old id allowlist effectively// assumed for the claude-code ids anyway.- expect((await cleanupCallFor({ providerId: 'claude-code' })).openPRIfMissing).toBe(true);- expect((await cleanupCallFor({ providerId: 'codex-tui' })).openPRIfMissing).toBe(false);+ expect((await cleanupCallFor({ providerId: 'claude-code' })).prCreation).toBe('never');+ expect((await cleanupCallFor({ providerId: 'codex-tui' })).prCreation).toBe('always');});});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 9e22453157..39f184699f 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -20,7 +20,7 @@ import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../liimport { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, MODEL_CAPABLE_CLI_REVIEWERS, describeReviewerCli, isCliReviewer, reviewerCliBinary, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds, resolveReviewerConfig, reviewerEffortArgs, buildReviewerEffortNote, resolveKeyedReviewers, buildReviewWithArgs, buildReviewersCsv } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { doneSentinelName } from '../lib/agentSentinel.js';-import { canTypeSlashCommands, agentOwnsPrWorkflow, resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow, resolveSlashdoInvocation, buildSlashdoSection, oversizedBodyPointer, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';import { shellQuote } from '../lib/shellQuote.js';import { detectForgeCli } from '../lib/gitForge.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';@@ -592,7 +592,11 @@ function isMergeOnlyFollowUp(metadata = {}) {* stay byte-identical so the two callers can't drift.* @returns {string}*/-export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inline = false, inlineExitStep = '' } = {}) {+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inlineExitStep = null } = {}) {+ // One parameter, not two: an `inline` boolean alongside it could disagree with+ // it, and the disagreement renders silently — `inline` with a blank exit step+ // emits a bare "6." and a truncated merge-gate hand-back.+ const inline = inlineExitStep !== null;const prUrl = metadata.reviewLoopPRUrl || '';const prBranch = metadata.reviewLoopPRBranch || '';const prNumber = metadata.reviewLoopPRNumber ?? '';@@ -604,7 +608,7 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,// below, which would otherwise resolve the empty list back to `[copilot]`.if (isMergeOnlyFollowUp(metadata)) {return buildMergeFollowUpSection({- prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inline, inlineExitStep,+ prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inlineExitStep,prHost: metadata.reviewLoopPRHost ?? '',});}@@ -886,9 +890,14 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// already carrying the real task, and pasting 40KB of reviewer recipe up front// to be read at step 4 is the wrong place to spend that context.const cliProcedureHeader = `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\nDrive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop specifies — use its per-CLI invocation and review-only prompt contract verbatim; do NOT probe the CLI's \`--help\`, test it with throwaway prompts, or hand-roll flags. Run the reviewer once per round, capture its findings, and (unless reviewer-applies is set) apply the fixes yourself.\n\n`;+ //+ // The path IS the decision — it is non-null only when the caller already+ // measured the body over budget and staged it. Re-testing the length here+ // would give the two sites a way to disagree, and the disagreement is silent:+ // the file gets written AND the 40KB still gets pasted.const cliReviewerProcedure = (hasCli && localAgentLoopBody)- ? (localAgentLoopBodyPath && localAgentLoopBody.length > SLASHDO_INLINE_BUDGET_CHARS- ? `${cliProcedureHeader}The procedure is on disk at \`${localAgentLoopBodyPath}\` (${Math.round(localAgentLoopBody.length / 1000)}KB) — too large to paste here. READ THAT FILE before you invoke a reviewer and follow it exactly rather than improvising.\n`+ ? (localAgentLoopBodyPath+ ? `${cliProcedureHeader}${oversizedBodyPointer(localAgentLoopBodyPath, localAgentLoopBody)}\n`: `${cliProcedureHeader}${localAgentLoopBody}\n`): '';@@ -903,15 +912,15 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// loop, so it exits; an inline loop is one step of a larger completion// workflow that still owes the run its `.agent-done` sentinel — telling it to// "exit" here is how a finished merge idles into a false timeout.- const exitStep = (followUpTail) => (inline+ const exitStep = inline? `6. ${inlineExitStep}`- : `6. Exit. Do **not** run \`/do:push\` or open a new PR${followUpTail}. The system will clean up your worktree on exit.`);+ : `6. Exit. Do **not** run \`/do:push\` or open a new PR${leaveOpen ? '' : ' — the merge handles everything'}. The system will clean up your worktree on exit.`;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.',// Forge-aware: `gh pr comment` fails outright on a GitLab MR URL.`5. Post a short comment on the ${detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? 'MR' : 'PR'} summarising what the reviewers raised and what you fixed, so the human landing it knows the state: ${detectForgeCli(metadata.reviewLoopPRHost) === 'glab' ? `\`glab mr note ${prNumber !== '' ? prNumber : '<MR_NUMBER>'} --message "<summary>"\`` : `\`gh pr comment "${prUrl}" --body "<summary>"\``}.`,- exitStep(''),+ exitStep,]: [`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):`,@@ -921,7 +930,7 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lprOwner && 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\`.`,- exitStep(' — the merge handles everything'),+ exitStep,].filter(Boolean);// Framing only — everything below it is identical for both callers.@@ -1063,18 +1072,24 @@ function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge* @param {Object} opts - PR coordinates + `verbose` (full/api path) vs compact.* @returns {string}*/-function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inline = false, inlineExitStep = '' }) {+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inlineExitStep = null }) {+ const inline = inlineExitStep !== null;// PortOS opens GitLab MRs via `glab` too, so a GitLab host must not be handed// `gh` commands (the host is persisted by spawnReviewLoopFollowUp). Classify// with the shared detector — a GitHub Enterprise host is still `gh`, which a// bare `host !== 'github.com'` test would get wrong.+ //+ // An INLINE gate has no persisted host to classify — its PR does not exist yet+ // — so it takes the `unknown` posture and emits both CLIs, matching the+ // create step that feeds it. Reading the empty host as `github` would print a+ // gh-only merge gate under a create step that offers `glab mr create`.const gate = buildCiMergeGateSteps(1, {prRef: `"${prUrl}"`,mrRef: prNumber !== '' ? `${prNumber}` : '<MR_NUMBER>',- forge: detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github',+ forge: inline ? 'unknown' : (detectForgeCli(prHost) === 'glab' ? 'gitlab' : 'github'),// An inline run reached this gate through plain `git`/`gh` — it never ran// `/do:pr`, so a saved slashdo merge default can't have landed the PR for it.- ...(inline ? { alreadyMergedHint: '' } : {}),+ alreadyMergedHint: inline ? '' : undefined,});const steps = [...gate.lines,@@ -1424,13 +1439,13 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoconst isFollowUpNeedingRecipes = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)&& !isMergeOnlyFollowUp(task.metadata || {});// …and a slashdo-free harness driving its OWN review loop inline needs the- // identical recipe (`buildInlineReviewLoopSection`). Deliberately loose — this- // only decides whether to READ a cached file; the section builder still emits- // it only when a spawnable CLI reviewer resolves.- const isInlineNeedingRecipes = LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)- && isTruthyMetaFn(task.metadata?.openPR)- && agentOwnsPrWorkflow({ providerType, leanMode })- && !canTypeSlashCommands({ providerId, providerCommand, leanMode });+ // identical recipe (`buildInlineReviewLoopSection`). Same predicate the render+ // side uses, so a run whose section never materializes — read-only,+ // leave-open, or a merge gate with no reviewer to invoke — doesn't pay for the+ // read and the staging write.+ const isInlineNeedingRecipes = inlinePrLifecycleSection(task, {+ providerType, providerId, providerCommand, leanMode, isTruthyMetaFn,+ }) === 'review-loop';const localAgentLoopBody = (isFollowUpNeedingRecipes || isInlineNeedingRecipes)? await loadSlashdoLib('local-agent-review-loop').catch(() => null): null;@@ -2290,14 +2305,13 @@ const INLINE_REVIEW_LOOP_STEP = 4;/*** A git ref rendered into a shell command line in the prompt, or `fallback` when- * it carries anything a shell would interpret. Branch names mostly come from- * PortOS itself, but a JIRA-derived one is external input — and this text is- * pasted straight into an agent's terminal, so a ref is only ever emitted when- * it is unambiguously inert (`git check-ref-format`'s legal character set,- * minus the shell-significant ones it still permits).+ * there is no ref to render. Branch names are usually PortOS's own, but a+ * JIRA-derived one is external input and this text is pasted straight into an+ * agent's terminal — so it goes through `shellQuote`, which leaves a bare-safe+ * ref readable and single-quotes anything else into inertness.*/-function safeRefForShell(ref, fallback) {- return (typeof ref === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref)) ? ref : fallback;+function promptRef(ref, fallback) {+ return (typeof ref === 'string' && ref) ? shellQuote(ref) : fallback;}/**@@ -2308,8 +2322,8 @@ function safeRefForShell(ref, fallback) {* they are rendered before the PR exists, so a literal URL is impossible.*/function buildManualPrCreateStep(step, { branchName, baseBranch }) {- const branch = safeRefForShell(branchName, '<branch>');- const base = safeRefForShell(baseBranch, '<base-branch>');+ const branch = promptRef(branchName, '<branch>');+ const base = promptRef(baseBranch, '<base-branch>');return [`${step}. Push the branch and open the pull request yourself, capturing its URL and number — the section below addresses the PR by these shell variables:`,'',@@ -2322,7 +2336,7 @@ function buildManualPrCreateStep(step, { branchName, baseBranch }) {// to generate the body server-side, so spell out what it must contain now// that the agent writes it.' Write a real `--body`: a **Summary** section and a **Test plan** section, no AI-attribution footer. Do NOT use `--fill`. If `gh` reports the pull request already exists, adopt it instead of failing: `PR_URL=$(gh pr view --json url -q .url)`.',- ' On a GitLab remote use `glab mr create --source-branch ' + branch + ' --target-branch ' + base + ' --title "…" --description "…"` and read the MR URL/IID back with `glab mr view`.',+ ` On a GitLab remote use \`glab mr create --source-branch ${branch} --target-branch ${base} --title "…" --description "…"\` and read the MR URL/IID back with \`glab mr view\`.`,];}@@ -2388,6 +2402,41 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETreturn lines.join('\n');}+/**+ * Which inline PR-lifecycle section — if any — a run gets after its manual+ * completion workflow: `'review-loop'`, `'merge-gate'` (no reviewer configured,+ * so CI is the whole gate), or `null`.+ *+ * ONE definition, used by both the prompt assembly that renders the section and+ * the `buildAgentPrompt` preload that decides whether to read + stage the ~56KB+ * CLI-reviewer recipe for it. They were two conditions at opposite ends of the+ * file, and the loose one paid for a 56KB read and an `atomicWrite` on every+ * read-only / leave-open / merge-gate run whose section never rendered — while+ * the strict one restated four branches of the completion if/else chain by hand,+ * 130 lines away from the chain it mirrored.+ *+ * @returns {'review-loop'|'merge-gate'|null}+ */+function inlinePrLifecycleSection(task, { providerType, providerId, providerCommand, leanMode, isTruthyMetaFn }) {+ if (!LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) return null;+ if (!agentOwnsPrWorkflow({ providerType, leanMode })) return null;+ // A slashdo-capable session drives all of this through `/do:pr` instead.+ if (canTypeSlashCommands({ providerId, providerCommand, leanMode })) return null;++ const metadata = task?.metadata || {};+ if (!isTruthyMetaFn(metadata.openPR)) return null;+ // The completion branches that hand back a contract which never opens a PR.+ if (isTruthyMetaFn(metadata.noCodeOutput) || metadata.creativeDirector) return null;+ if (isTruthyMetaFn(metadata.discardWorktree)) return null;+ if (isTruthyMetaFn(metadata.readOnly)) return null;+ if (isTruthyMetaFn(metadata.reviewLoopFollowUp)) return null;+ // A PR a human lands gets neither a review loop nor a merge gate.+ const prCompletion = resolvePrCompletion(metadata);+ if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task)) return null;++ return prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE ? 'review-loop' : 'merge-gate';+}+/*** The inline review-loop (or, with no reviewer configured, merge-gate) section* for an agent that opened its own PR under the manual completion workflow.diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 1651bb2b4a..a81bc19686 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -681,20 +681,39 @@ describe('buildLightContextPrompt', () => {expect(prompt.length).toBeLessThan(20_000);});- it('does not interpolate a hostile branch ref into the PR-create command line', () => {+ it('quotes a hostile branch ref inert in the PR-create command line', () => {// Branch names are usually PortOS's own, but a JIRA-derived one is external- // input — and this text is pasted straight into an agent's terminal.+ // input — and this text is pasted straight into an agent's terminal, so it+ // goes through the canonical `shellQuote` rather than being dropped for a+ // placeholder the agent would have to guess at.const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true } }),'/r',{ branchName: 'weird;rm -rf /', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });- // The ref is quoted as prose in the worktree header, but never rendered- // into a runnable command line.- expect(prompt).toMatch(/git push -u origin <branch>/);- expect(prompt).toMatch(/gh pr create --base main --head <branch>/);- expect(prompt).not.toMatch(/(git|gh|glab) [^\n]*weird;rm -rf/);+ expect(prompt).toMatch(/git push -u origin 'weird;rm -rf \/'/);+ expect(prompt).toMatch(/gh pr create --base main --head 'weird;rm -rf \/'/);+ // Never bare — that would be a command substitution waiting to happen.+ expect(prompt).not.toMatch(/origin weird;rm/);+ });++ it('leaves a readable branch unquoted, and falls back to a placeholder with no ref', () => {+ const readable = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true } }),+ '/r',+ { branchName: 'cos/task-1/agent-2', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ expect(readable).toMatch(/git push -u origin cos\/task-1\/agent-2/);++ const noBase = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ expect(noBase).toMatch(/gh pr create --base <base-branch> --head b/);});it('a path-configured claude binary under a custom provider id gets the slashdo workflow', () => {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 9782a4e106..c24851247d 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -21,7 +21,7 @@ import { PATHS } from '../lib/fileUtils.js';import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';-import { resolvePrCompletion } from '../lib/prDisposition.js';+import { resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { normalizeReviewers } from '../lib/validation.js';@@ -1130,8 +1130,7 @@ export async function spawnTuiAgent({}): {};await cleanupWorktreeFn(agentId, cleanupSuccess, {- openPR: taskOpenPR,- openPRIfMissing: agentOwnsPR,+ prCreation: resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified: prClaimExpected }),prCompletion: resolvePrCompletion(task.metadata),...reviewOptions,skipMerge: taskReviewLoopFollowUp || agentOwnsPR,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex d376ccada7..6e759ec327 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -689,10 +689,9 @@ describe('spawnTuiAgent runtime', () => {await spawnPromise;// The codex TUI drives its own push → PR → review → merge, so PortOS only- // steps in when the forge says no PR exists — hence openPRIfMissing.+ // steps in when the forge says no PR exists — hence prCreation: if-missing.expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({- openPR: true,- openPRIfMissing: true,+ prCreation: 'if-missing',prCompletion: 'review-then-merge',reviewers: ['codex'],skipMerge: true,@@ -717,8 +716,7 @@ describe('spawnTuiAgent runtime', () => {await spawnPromise;expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({- openPR: true,- openPRIfMissing: false,+ prCreation: 'always',skipMerge: false,}));});@@ -739,9 +737,10 @@ describe('spawnTuiAgent runtime', () => {await capturedOnExit({ exitCode: 0, killed: false });await spawnPromise;+ // `never`, not `if-missing`: finalize already ran `verifyPrClaim` for a+ // slashdo-capable session, so a second forge query would be pure duplication.expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({- openPR: true,- openPRIfMissing: true,+ prCreation: 'never',prCompletion: 'review-then-merge',skipMerge: true,}));diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 3dfd91aa47..c5678532c9 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -25,7 +25,7 @@ import { PATHS } from '../lib/fileUtils.js';import { isRetryHoldOwner, clearedRetryHoldMetadata } from '../lib/taskRetryHold.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { detectForgeCli } from '../lib/gitForge.js';-import { PR_COMPLETIONS, PR_COMPLETION_VALUES, leavesPrForHuman } from '../lib/prDisposition.js';+import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, leavesPrForHuman } from '../lib/prDisposition.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, EFFORT_SELECTABLE_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds } from '../lib/validation.js';// In-flight cleanup per agentId, so two completion paths racing to clean the@@ -45,15 +45,14 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SE// this is one actor's duplicate in-flight operation, not two competing humans.const inFlightCleanups = new Map();+/*** 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.- * `openPRIfMissing` makes that a SAFETY NET rather than the primary path: the run- * owned its own PR workflow, so cleanup asks the forge whether a PR already- * exists on the branch and only pushes + creates one when the answer is a- * definite "none" (#3733). An unreachable forge stands down — a duplicate PR is- * worse than a missing one, and `verifyPrClaim` has already flagged the run.+ * `prCreation` (see `PR_CREATION`) decides who opens the change request:+ * `'always'` pushes and creates one instead of auto-merging; `'if-missing'` does+ * that only when the forge confirms the agent — which owned its own PR workflow —+ * opened none (#3733); `'never'` leaves it entirely to the agent.* `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.@@ -84,7 +83,7 @@ export async function cleanupAgentWorktree(agentId, success, options = {}) {return run;}-async function runCleanupAgentWorktree(agentId, success, { openPR = false, openPRIfMissing = false, prCompletion = null, requestCopilotReview: legacyRequestCopilotReview = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {+async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREATION.NEVER, prCompletion = null, requestCopilotReview: legacyRequestCopilotReview = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = 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 [];@@ -118,37 +117,47 @@ async function runCleanupAgentWorktree(agentId, success, { openPR = false, openPreturn result?.warnings || [];}- // Safety net for a run that OWNED its PR workflow (#3733): the prompt told the- // agent to push, open, review, and merge the PR itself, so PortOS stands down —- // but only once the forge confirms it actually did. A harness that skipped its- // completion workflow would otherwise leave the branch with no change request- // and nothing watching it, which is exactly the orphan this net exists to catch.+ // Safety net for a run that OWNED its PR workflow (#3733, `prCreation:+ // 'if-missing'`): the prompt told the agent to push, open, review, and merge+ // the PR itself, so PortOS stands down — but only once the forge confirms it+ // actually did. A harness that skipped its completion workflow would otherwise+ // leave the branch with no change request and nothing watching it, which is+ // exactly the orphan this net exists to catch.//- // Only an affirmative "a PR already exists" cancels PortOS's own creation.- // `unavailable` is NOT evidence of one — but opening a duplicate on a guess is- // the worse failure, so it warns and stands down too (`verifyPrClaim` has- // already recorded the run as needs-attention in that case).- let openPRHere = openPR;- if (openPR && success && openPRIfMissing) {- // Reuses finalize's own PR-claim check rather than re-asking the forge:- // `pr-missing` is precisely "the forge answered and there is no change- // request for a branch that HOLDS commits", and every other verdict —- // found, nothing-to-ship, forge-unreachable — is a correct stand-down.+ // Only reached when finalize did NOT already verify the claim (`'never'`+ // covers that case), so this is one forge round-trip, not a second one.+ let createPr = prCreation === PR_CREATION.ALWAYS;+ // An UNCERTAIN stand-down must not also discard the work. Creating a second+ // change request on a guess is unsafe; keeping the branch never is — and the+ // default cleanup below deletes an unmerged branch outright on a `success`+ // run, so a transient `gh pr list` failure would take the agent's only copy of+ // the commits with it.+ let preserveBranchOnStandDown = false;+ if (prCreation === PR_CREATION.IF_MISSING && success) {+ // Reuses finalize's own PR-claim check rather than re-implementing the forge+ // dispatch: `pr-missing` is precisely "the forge answered and there is no+ // change request for a branch that HOLDS commits".const { verifyPrClaim, PR_MISSING_CATEGORY } = await import('./agentFinalization.js');const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);- const verdict = await verifyPrClaim({ task: originalTask, workspacePath: worktreePath, success: true, prExpected: true })- .catch(err => ({ ok: true, category: null, detail: err.message }));+ const verdict = await verifyPrClaim({ workspacePath: worktreePath, success: true, prExpected: true })+ .catch(err => ({ ok: false, category: 'forge-unreachable', message: err.message }));if (verdict.category === PR_MISSING_CATEGORY) {+ createPr = true;emitLog('warn', `🌳 ${agentId} owned its PR workflow but opened no pull request for ${worktreeBranch} — PortOS is opening one`, { agentId, branchName: worktreeBranch });warnings.push(`Agent ${agentId} was told to open its own pull request for ${worktreeBranch} but did not; PortOS opened it instead.`);+ } else if (verdict.ok) {+ // `found`, or `noChangesToShip` — the branch holds nothing a PR could be+ // opened for. Either way the agent's contract was met.+ emitLog('info', `🌳 ${agentId} opened its own pull request for ${worktreeBranch} — PortOS is standing down`, { agentId, branchName: worktreeBranch });} else {- emitLog('info', `🌳 ${agentId} owns its own pull request for ${worktreeBranch} — PortOS is standing down${verdict.ok ? '' : ` (${verdict.category})`}`, { agentId, branchName: worktreeBranch });- openPRHere = false;+ preserveBranchOnStandDown = true;+ emitLog('warn', `🌳 Could not confirm a pull request for ${worktreeBranch} (${verdict.category}) — keeping the branch rather than opening a possible duplicate`, { agentId, branchName: worktreeBranch });+ warnings.push(`Could not confirm a pull request for ${worktreeBranch} (${verdict.category}); the branch was preserved for manual follow-up rather than risking a duplicate PR.`);}}// When openPR is set and task succeeded, push branch and create PR instead of auto-merging- if (openPRHere && success) {+ if (createPr && success) {emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);@@ -345,7 +354,9 @@ async function runCleanupAgentWorktree(agentId, success, { openPR = false, openP// A FAILED agent's branch is the only record of what it got done. Keep it when// it holds commits so the task's retry can attach to it and resume rather than// redo the work (see resolveResumeBranch below + removeWorktree's flag docs).- preserveBranchWithCommits: !success,+ // Same reasoning for a SUCCESSFUL run whose PR we could not confirm: we chose+ // not to push it, so the local branch is the only copy.+ preserveBranchWithCommits: !success || preserveBranchOnStandDown,}).catch(err => {emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });return { warnings: [`Worktree cleanup failed: ${err.message}`] };diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex c890da83ec..482d2599ee 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -198,7 +198,7 @@ vi.mock('./prWatcher.js', () => ({queuePendingMerge: (...args) => queuePendingMergeMock(...args)}));-// The `openPRIfMissing` safety net asks finalize's own PR-claim check whether+// The `if-missing` safety net asks finalize's own PR-claim check whether// the agent actually opened the PR it was told to open (#3733).const verifyPrClaimMock = vi.fn();vi.mock('./agentFinalization.js', () => ({@@ -239,7 +239,7 @@ function mockWorktreeAgent(overrides = {}) {};}-describe('cleanupAgentWorktree - openPR path', () => {+describe('cleanupAgentWorktree - PR-creation path', () => {beforeEach(() => {vi.clearAllMocks();queuePendingMergeMock.mockResolvedValue(false);@@ -257,11 +257,11 @@ describe('cleanupAgentWorktree - openPR path', () => {);});- it('should run PR flow when openPR is true and success is true', async () => {+ it('should run PR flow when prCreation is always and success is true', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test task' });expect(git.push).toHaveBeenCalledWith('/mock/root/data/cos/worktrees/agent-1', 'cos/task-abc123');expect(git.createPR).toHaveBeenCalledWith('/mock/root/data/cos/worktrees/agent-1', {@@ -277,7 +277,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/2' });- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(removeWorktree).toHaveBeenCalledTimes(1);expect(removeWorktree).toHaveBeenCalledWith(@@ -291,7 +291,7 @@ describe('cleanupAgentWorktree - openPR path', () => {it('should preserve worktree when push fails (no removeWorktree call)', async () => {git.push.mockRejectedValue(new Error('push rejected'));- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test task' });expect(git.push).toHaveBeenCalled();expect(git.createPR).not.toHaveBeenCalled();@@ -302,7 +302,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: false, error: 'PR already exists' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test task' });expect(git.createPR).toHaveBeenCalled();expect(removeWorktree).not.toHaveBeenCalled();@@ -312,7 +312,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: false, error: 'GraphQL: No commits between main and cos/task-abc123 (createPullRequest)' });- const warnings = await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });+ const warnings = await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test task' });expect(git.createPR).toHaveBeenCalled();// Agent made no changes — delete remote branch and clean up silently without a warning@@ -321,15 +321,15 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(warnings).toHaveLength(0);});- it('should use auto-merge path when openPR is false (success)', async () => {- await cleanupAgentWorktree('agent-1', true, { openPR: false });+ it('should use auto-merge path when prCreation is never (success)', async () => {+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'never' });expect(git.push).not.toHaveBeenCalled();expect(git.createPR).not.toHaveBeenCalled();expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false });});- it('should use auto-merge path when openPR is not provided (defaults to false)', async () => {+ it('should use auto-merge path when prCreation is not provided (defaults to never)', async () => {await cleanupAgentWorktree('agent-1', true);expect(git.push).not.toHaveBeenCalled();@@ -337,8 +337,8 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false });});- it('should skip PR flow when openPR is true but success is false', async () => {- await cleanupAgentWorktree('agent-1', false, { openPR: true });+ it('should skip PR flow when prCreation is always but success is false', async () => {+ await cleanupAgentWorktree('agent-1', false, { prCreation: 'always' });expect(git.push).not.toHaveBeenCalled();expect(git.createPR).not.toHaveBeenCalled();@@ -353,7 +353,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/3' });git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: 'develop' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test' });expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({base: 'main'@@ -365,7 +365,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/4' });git.getRepoBranches.mockRejectedValue(new Error('not a git repo'));- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test' });expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({base: 'main'@@ -376,7 +376,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockRejectedValue(new Error('network error'));- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test' });// PR creation failed — worktree preserved for manual interventionexpect(removeWorktree).not.toHaveBeenCalled();@@ -387,7 +387,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/5' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: longDesc });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: longDesc });expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({title: 'A'.repeat(100)@@ -399,7 +399,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/7' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: multilineDesc });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: multilineDesc });expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({title: '[Improvement: grace] Error Handling'@@ -410,7 +410,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/6' });- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(git.createPR).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({title: 'CoS automated task',@@ -423,7 +423,7 @@ describe('cleanupAgentWorktree - openPR path', () => {it('should no-op when agent is not a worktree agent', async () => {getAgent.mockResolvedValue({ metadata: { isWorktree: false } });- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(git.push).not.toHaveBeenCalled();expect(removeWorktree).not.toHaveBeenCalled();@@ -432,7 +432,7 @@ describe('cleanupAgentWorktree - openPR path', () => {it('should no-op when agent state is null', async () => {getAgent.mockResolvedValue(null);- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(git.push).not.toHaveBeenCalled();expect(removeWorktree).not.toHaveBeenCalled();@@ -441,7 +441,7 @@ describe('cleanupAgentWorktree - openPR path', () => {it('should no-op for persistent worktree agents', async () => {getAgent.mockResolvedValue(mockWorktreeAgent({ isPersistentWorktree: true }));- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(git.push).not.toHaveBeenCalled();expect(removeWorktree).not.toHaveBeenCalled();@@ -450,7 +450,7 @@ describe('cleanupAgentWorktree - openPR path', () => {it('should no-op when sourceWorkspace or worktreeBranch is missing', async () => {getAgent.mockResolvedValue(mockWorktreeAgent({ sourceWorkspace: null }));- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(git.push).not.toHaveBeenCalled();expect(removeWorktree).not.toHaveBeenCalled();@@ -462,7 +462,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/7' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', requestCopilotReview: true, description: 'Test' });expect(git.requestCopilotReview).toHaveBeenCalledWith('/mock/root/data/cos/worktrees/agent-1', 'https://github.com/test/repo/pull/7');});@@ -471,18 +471,18 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/8' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: false, description: 'Test' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', requestCopilotReview: false, description: 'Test' });expect(git.requestCopilotReview).not.toHaveBeenCalled();});- it('should still create PR (not auto-merge) when both openPR and requestCopilotReview are true — regression', async () => {+ it('should still create PR (not auto-merge) when both prCreation:always and requestCopilotReview are set — regression', async () => {// Regression for the bug where `openPR: taskOpenPR && !taskReviewLoop` skipped// PR creation when both flags were set, causing auto-merge into main with no PR/review.git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/9' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', requestCopilotReview: true, description: 'Test' });expect(git.createPR).toHaveBeenCalled();expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });@@ -491,8 +491,8 @@ describe('cleanupAgentWorktree - openPR path', () => {// #3733: a slashdo-free harness now opens its own PR, so cleanup's job flips// from "create the PR" to "make sure one exists". Getting this wrong in either// direction is expensive — a duplicate PR, or a branch nobody ever reviews.- describe('openPRIfMissing safety net', () => {- const netOpts = { openPR: true, openPRIfMissing: true, description: 'Test task' };+ describe('prCreation: if-missing safety net', () => {+ const netOpts = { prCreation: 'if-missing', description: 'Test task' };it('stands down when the agent already opened its own PR', async () => {verifyPrClaimMock.mockResolvedValue({ ok: true, branch: 'cos/task-abc123' });@@ -519,9 +519,37 @@ describe('cleanupAgentWorktree - openPR path', () => {it('stands down on an unreachable forge — a duplicate PR is worse than a flagged one', async () => {verifyPrClaimMock.mockResolvedValue({ ok: false, category: 'forge-unreachable', branch: 'cos/task-abc123' });+ const warnings = await cleanupAgentWorktree('agent-1', true, netOpts);++ expect(git.createPR).not.toHaveBeenCalled();+ // …but standing down must NOT also throw the work away. `removeWorktree`+ // deletes an unmerged branch outright on a `success` run, so without this+ // a transient `gh pr list` failure takes the agent's only copy of the+ // commits with it — we chose not to push, so the branch IS the copy.+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',+ expect.objectContaining({ preserveBranchWithCommits: true }));+ expect(warnings.some(w => w.includes('Could not confirm a pull request'))).toBe(true);+ });++ it('lets the branch be tidied up when the agent DID open its PR', async () => {+ verifyPrClaimMock.mockResolvedValue({ ok: true, branch: 'cos/task-abc123' });++ const warnings = await cleanupAgentWorktree('agent-1', true, netOpts);++ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',+ expect.objectContaining({ preserveBranchWithCommits: false }));+ expect(warnings).toEqual([]);+ });++ it('treats a thrown verification as uncertain, not as "no PR"', async () => {+ // Failing open here would open a duplicate PR on every transient error.+ verifyPrClaimMock.mockRejectedValue(new Error('boom'));+await cleanupAgentWorktree('agent-1', true, netOpts);expect(git.createPR).not.toHaveBeenCalled();+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123',+ expect.objectContaining({ preserveBranchWithCommits: true }));});it('stands down when the branch holds no commits — there was nothing to open a PR for', async () => {@@ -536,7 +564,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/43' });- await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', description: 'Test task' });expect(verifyPrClaimMock).not.toHaveBeenCalled();expect(git.createPR).toHaveBeenCalled();@@ -548,7 +576,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/10' });git.requestCopilotReview.mockResolvedValue({ success: false, error: 'gh exited with code 1' });- const warnings = await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });+ const warnings = await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', requestCopilotReview: true, description: 'Test' });expect(warnings.some(w => w.includes('Copilot review request failed'))).toBe(true);expect(removeWorktree).toHaveBeenCalled();@@ -562,7 +590,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://gitlab.com/group/proj/-/merge_requests/11' });git.requestCopilotReview.mockResolvedValue({ success: true, skipped: true });- const warnings = await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });+ const warnings = await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', requestCopilotReview: true, description: 'Test' });expect(warnings.some(w => w.includes('Copilot review'))).toBe(false);expect(removeWorktree).toHaveBeenCalled();@@ -579,7 +607,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-x' });await cleanupAgentWorktree('agent-1', true, {- openPR: true,+ prCreation: 'always',requestCopilotReview: true,description: 'Build the thing',originalTask: { id: 'task-orig', priority: 'HIGH', metadata: { app: 'sparsetree' }, description: 'Build the thing' }@@ -612,7 +640,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-q' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, description: 'X',+ prCreation: 'always', requestCopilotReview: true, description: 'X',originalTask: { id: 'task-orig', metadata: {}, description: 'X' }});@@ -633,7 +661,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-p' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: false, description: 'X',+ prCreation: 'always', requestCopilotReview: false, description: 'X',originalTask: {id: 'task-orig',metadata: { provider: 'claude-code', providerId: 'claude-code', model: 'claude-opus-5', effort: 'high' },@@ -656,7 +684,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-q' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: false, description: 'X',+ prCreation: 'always', requestCopilotReview: false, description: 'X',originalTask: { id: 'task-orig', metadata: { model: 'claude-opus-5', effort: 'high' }, description: 'X' }});@@ -675,7 +703,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/77' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: false, description: 'X',+ prCreation: 'always', requestCopilotReview: false, description: 'X',originalTask: { id: 'task-orig', metadata: { analysisType: 'jira-sprint-manager' }, description: 'X' }});@@ -688,7 +716,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/78' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: false, description: 'X',+ prCreation: 'always', requestCopilotReview: false, description: 'X',originalTask: { id: 'task-orig', metadata: { jiraTicketId: 'PROJ-1' }, description: 'X' }});@@ -700,7 +728,7 @@ describe('cleanupAgentWorktree - openPR path', () => {git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/79' });await cleanupAgentWorktree('agent-1', true, {- openPR: true,+ prCreation: 'always',prCompletion: 'leave-open',reviewers: ['copilot'],description: 'X',@@ -722,7 +750,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-gl' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, description: 'X',+ prCreation: 'always', requestCopilotReview: true, description: 'X',originalTask: { id: 'task-orig', metadata: {}, description: 'X' }});@@ -739,7 +767,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-m' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: false, description: 'X',+ prCreation: 'always', requestCopilotReview: false, description: 'X',originalTask: { id: 'task-orig', metadata: {}, description: 'X' }});@@ -764,7 +792,7 @@ describe('cleanupAgentWorktree - openPR path', () => {queuePendingMergeMock.mockResolvedValue(true);await cleanupAgentWorktree('agent-1', true, {- openPR: true,+ prCreation: 'always',requestCopilotReview: false,description: 'Build with deterministic merge',originalTask: {@@ -793,7 +821,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-y' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['claude'], description: 'X',+ prCreation: 'always', requestCopilotReview: true, reviewers: ['claude'], description: 'X',originalTask: { id: 'task-orig', metadata: {}, description: 'X' }});@@ -806,7 +834,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-z' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['codex'], description: 'Build with codex review',+ prCreation: 'always', requestCopilotReview: true, reviewers: ['codex'], description: 'Build with codex review',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -823,7 +851,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-w' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'codex', 'antigravity'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot', 'codex', 'antigravity'],reviewStopMode: 'on-findings', reviewerApplies: true,reviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }, description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }@@ -849,7 +877,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-max' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'ollama'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot', 'ollama'],// `nope` is not a reviewer and `codex: -1` is not a cap — both dropped.// An explicit 0 (loop until clean) survives.reviewerMaxRounds: { ollama: 1, copilot: 0, nope: 2, codex: -1 },@@ -867,7 +895,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-nomax' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, prCompletion: 'merge-on-green', reviewers: ['copilot', 'ollama'],+ prCreation: 'always', prCompletion: 'merge-on-green', reviewers: ['copilot', 'ollama'],reviewerMaxRounds: { ollama: 1 }, description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -883,7 +911,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-cl' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'claude'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot', 'claude'],reviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }, description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -909,7 +937,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-eff' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'antigravity', 'claude', 'grok'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot', 'antigravity', 'claude', 'grok'],reviewerModels: { claude: 'qwen2.5:7b', grok: 'grok-code-fast-1' },// `codex` isn't in the reviewer list; `copilot` has no effort control at all,// and neither does `grok` — its CLI takes no effort flag.@@ -933,7 +961,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-noeff' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot'],reviewerEfforts: { claude: 'high' }, description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -949,7 +977,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-nc' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot', 'antigravity'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot', 'antigravity'],reviewerModels: { codex: 'gpt-5.6-sol', claude: 'qwen2.5:7b' }, description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -965,7 +993,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-v' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['codex', 'antigravity', 'copilot'], description: 'Build',+ prCreation: 'always', requestCopilotReview: true, reviewers: ['codex', 'antigravity', 'copilot'], description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -985,7 +1013,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-u' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot'],usernames: ['@CodeReviewbot', 'bad token', 'codereviewbot'], description: 'Build',originalTask: { id: 'task-orig', priority: 'MEDIUM', metadata: { app: 'sparsetree' }, description: 'Build' }});@@ -1003,7 +1031,7 @@ describe('cleanupAgentWorktree - openPR path', () => {addTask.mockResolvedValue({ id: 'sys-rl-uonly' });await cleanupAgentWorktree('agent-1', true, {- openPR: true, requestCopilotReview: true, reviewers: ['copilot'],+ prCreation: 'always', requestCopilotReview: true, reviewers: ['copilot'],usernames: ['CodeReviewbot'], description: 'Build',originalTask: { id: 'task-orig', metadata: {}, description: 'Build' }});@@ -1021,7 +1049,7 @@ describe('cleanupAgentWorktree - openPR path', () => {it('should pass merge: false in the auto-merge fallback when skipMerge is true (review-loop follow-up cleanup)', async () => {// The follow-up agent already merged via `gh pr merge`; re-merging the worktree// branch into source workspace would duplicate the squashed commits.- await cleanupAgentWorktree('agent-1', true, { openPR: false, skipMerge: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'never', skipMerge: true });expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false, preserveBranchWithCommits: false }@@ -1029,7 +1057,7 @@ describe('cleanupAgentWorktree - openPR path', () => {});it('should still pass merge: true in the auto-merge fallback when skipMerge is false on success', async () => {- await cleanupAgentWorktree('agent-1', true, { openPR: false, skipMerge: false });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'never', skipMerge: false });expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true, preserveBranchWithCommits: false }@@ -1770,7 +1798,7 @@ describe('cleanupAgentWorktree - discardWorktree (throwaway reasoning worktree)'it('removes the worktree with merge:false and never pushes/opens a PR — even with openPR:true', async () => {await cleanupAgentWorktree('agent-1', true, {- openPR: true,+ prCreation: 'always',originalTask: { metadata: { discardWorktree: true } }});@@ -1786,7 +1814,7 @@ describe('cleanupAgentWorktree - discardWorktree (throwaway reasoning worktree)'it('treats the re-parsed string "true" as discard (metadata round-trips through the task store)', async () => {await cleanupAgentWorktree('agent-1', true, {- openPR: true,+ prCreation: 'always',originalTask: { metadata: { discardWorktree: 'true' } }});@@ -1800,7 +1828,7 @@ describe('cleanupAgentWorktree - discardWorktree (throwaway reasoning worktree)'git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/9' });await cleanupAgentWorktree('agent-1', true, {- openPR: true,+ prCreation: 'always',originalTask: { metadata: {} }});@@ -1842,9 +1870,9 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()}));});- const first = cleanupAgentWorktree('agent-1', true, { openPR: true });+ const first = cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });await removeCalled;- const second = cleanupAgentWorktree('agent-1', true, { openPR: true });+ const second = cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });releaseRemove();const [firstWarnings, secondWarnings] = await Promise.all([first, second]);@@ -1859,7 +1887,7 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()});// The guard is keyed per agent — two agents finishing together must NOT be- // collapsed into one cleanup. `openPR: false` keeps this on the plain merge+ // collapsed into one cleanup. `prCreation: 'never'` keeps this on the plain merge// path so it asserts the keying and nothing else.it('does NOT coalesce across different agents', async () => {// Park each pass inside removeWorktree so both are in flight at once, and@@ -1876,10 +1904,10 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()// overlap the guard has to distinguish — started sequentially so the two// passes don't race the lazy module graph and make the test flaky.const aParked = nextArrival();- cleanupAgentWorktree('agent-A', true, { openPR: false });+ cleanupAgentWorktree('agent-A', true, { prCreation: 'never' });await aParked;const bParked = nextArrival();- cleanupAgentWorktree('agent-B', true, { openPR: false });+ cleanupAgentWorktree('agent-B', true, { prCreation: 'never' });await bParked;expect(reached).toEqual(['agent-A', 'agent-B']);@@ -1888,8 +1916,8 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()it('releases the guard so a LATER cleanup of the same agent still runs', async () => {removeWorktree.mockResolvedValue({ merged: false, removed: true, warnings: [] });- await cleanupAgentWorktree('agent-1', true, { openPR: true });- await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always' });expect(removeWorktree).toHaveBeenCalledTimes(2);});@@ -1906,9 +1934,9 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()}));});- const first = cleanupAgentWorktree('agent-1', true, { openPR: false });+ const first = cleanupAgentWorktree('agent-1', true, { prCreation: 'never' });await removeCalled;- const second = cleanupAgentWorktree('agent-1', true, { openPR: false });+ const second = cleanupAgentWorktree('agent-1', true, { prCreation: 'never' });releaseRemove();const [firstWarnings, secondWarnings] = await Promise.all([first, second]);@@ -1918,7 +1946,7 @@ describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', ()// Guard cleared → a later cleanup is not wedged on the failed pass.removeWorktree.mockResolvedValue({ merged: false, removed: true, warnings: [] });- await cleanupAgentWorktree('agent-1', true, { openPR: false });+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'never' });expect(removeWorktree).toHaveBeenCalledTimes(2);});});