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
let codex/grok/agy CoS agents run their own PR, review loop, and merge
[._.]/ Adam Eivy92664a70bd54
diff --git a/.changelog/next/changed-agent-0dfbc1dd.md b/.changelog/next/changed-agent-0dfbc1dd.mdnew file mode 100644index 0000000000..b883ad1f79--- /dev/null+++ b/.changelog/next/changed-agent-0dfbc1dd.md@@ -0,0 +1 @@+- CoS agents on codex, grok/agy, and OpenCode now drive their own push, PR, review loop, and merge in one session instead of handing off to a separate follow-up agentdiff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex b51107a639..09e661a515 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -260,6 +260,48 @@ export function canTypeSlashCommands({=== SLASHDO_INVOCATION_STYLES.SLASH_NAMESPACED;}+/**+ * 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.+ */+const HARNESS_PROVIDER_TYPES = new Set(['cli', 'tui']);++/**+ * True when a spawned session can drive the WHOLE change-request lifecycle+ * itself — commit, push, open the PR, run the configured review loop, merge+ * (#3733).+ *+ * This is a strictly weaker question than `canTypeSlashCommands`, and+ * conflating the two is what stranded every agy / grok / codex run in a+ * two-agent handoff. Those hosts can't TYPE `/do:pr` (slashdo installs there as+ * Agent Skills, not slash commands), so they used to be told "commit and stop"+ * — PortOS then opened the PR after the run and queued a separate `sys-rl-*`+ * follow-up agent just to run the review loop. But not typing a slash command+ * says nothing about running `gh pr create`: these are full coding harnesses,+ * and the follow-up agent they hand off TO is routinely one of them driving the+ * exact same inlined slashdo procedure. So the split bought nothing and cost a+ * whole extra agent, a cold context, and a queue hop per task.+ *+ * `leanMode` is the one local harness excluded: a small Ollama-backed model+ * behind `claude --bare` fumbles multi-step flows, and a half-run merge+ * procedure is worse than a clean handoff.+ *+ * The prompt builder, `agentCompletionCleanup`, and the spawners must all agree+ * on this answer or PortOS double-fires `gh pr create` — so the spawn path+ * persists the resolved value on the agent record (`metadata.ownsPrWorkflow`)+ * and cleanup reads it back rather than re-deriving it.+ *+ * @param {Object} [opts]+ * @param {string|null} [opts.providerType] - `'tui' | 'cli' | 'api'`+ * @param {boolean} [opts.leanMode]+ * @returns {boolean}+ */+export function agentOwnsPrWorkflow({ providerType = null, leanMode = false } = {}) {+ if (leanMode) return false;+ return HARNESS_PROVIDER_TYPES.has(providerType);+}+/*** Resolve the concrete invocation for a slashdo-backed task.*diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex 79005e692d..4a35cec123 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -4,6 +4,7 @@ import {SLASHDO_INVOCATION_STYLES,SLASHDO_REVIEWER_INCLUDES,SLASHDO_REVIEWER_INCLUDE_NAMES,+ agentOwnsPrWorkflow,buildSlashdoSection,canTypeSlashCommands,isValidSlashdoCommand,@@ -150,6 +151,34 @@ describe('canTypeSlashCommands', () => {});});+describe('agentOwnsPrWorkflow (#3733)', () => {+ it('is true for every local coding harness, slash commands or not', () => {+ expect(agentOwnsPrWorkflow({ providerType: 'tui' })).toBe(true);+ expect(agentOwnsPrWorkflow({ providerType: 'cli' })).toBe(true);+ });++ it('is a WEAKER question than canTypeSlashCommands — that is the whole point', () => {+ // codex/grok/agy can't type `/do:pr` (slashdo installs there as skills), but+ // they run `gh pr create` and the reviewer CLIs perfectly well. Conflating+ // the two is what forced a second `sys-rl-*` agent onto every one of their runs.+ for (const providerId of ['codex-tui', 'grok-tui', 'antigravity-tui', 'opencode-ollama-tui']) {+ expect(canTypeSlashCommands({ providerId })).toBe(false);+ expect(agentOwnsPrWorkflow({ providerType: 'tui' })).toBe(true);+ }+ });++ it('is false for a lean --bare session, which fumbles multi-step flows', () => {+ expect(agentOwnsPrWorkflow({ providerType: 'tui', leanMode: true })).toBe(false);+ expect(agentOwnsPrWorkflow({ providerType: 'cli', leanMode: true })).toBe(false);+ });++ it('is false for an HTTP api provider and for an unknown type — neither has a shell', () => {+ expect(agentOwnsPrWorkflow({ providerType: 'api' })).toBe(false);+ expect(agentOwnsPrWorkflow({})).toBe(false);+ expect(agentOwnsPrWorkflow()).toBe(false);+ });+});+describe('resolveSlashdoInvocation', () => {it('returns null without a valid command', () => {expect(resolveSlashdoInvocation({})).toBeNull();diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 48a260889f..33e00491ab 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -37,7 +37,7 @@ 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 { canTypeSlashCommands } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';import { doneSentinelPath } from '../lib/agentSentinel.js';import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';@@ -733,24 +733,25 @@ export async function spawnDirectly({const analysisBuffer = rawStreamBuffer || outputBuffer;const errorAnalysis = finalSuccess ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));- // Slashdo-capable CLI agents run `/simplify` + `/do:pr` themselves (see- // buildCliCompletionSection in agentPromptBuilder.js) — mirror the TUI- // cleanup contract so PortOS doesn't double-fire push+PR creation. Resolved- // BEFORE finalizeAgent because it also gates the PR-claim verification- // (#3358): a PortOS-owned PR is created by the cleanup below, i.e. AFTER- // finalize, so only an agent-owned PR can be verified there.- //- // Uses the SAME `canTypeSlashCommands` predicate the prompt builder and the- // runner-mode cleanup already use, not a provider-id allowlist: an allowlist- // misses a path-configured `claude` under a custom provider id (told to run- // `/do:pr`, then PortOS opens a second PR) and wrongly claims a lean `--bare`- // session owns a PR it was never told to open. Whoever the prompt told to- // open the PR must be who cleanup and verification believe opened it.+ // Every CLI agent that is a real coding harness drives its own push → PR →+ // review → merge (#3733): a slashdo-capable Claude runs `/simplify` ++ // `/do:pr`, codex/grok/agy/OpenCode run the plain `git`/`gh` equivalent from+ // the same prompt (see buildCliCompletionSection in agentPromptBuilder.js).+ // Mirror that here so PortOS doesn't double-fire push+PR creation.const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);- const directAgentOwnsPR = directOpenPR && canTypeSlashCommands({+ const directLeanMode = isOllamaClaudeProvider(provider);+ const directAgentOwnsPR = directOpenPR && agentOwnsPrWorkflow({+ providerType: PROVIDER_TYPES.CLI,+ leanMode: directLeanMode,+ });+ // PR-claim verification (#3358) stays on the SLASH-command predicate: it runs+ // BEFORE the cleanup below, and cleanup now backstops a harness that skipped+ // its own PR step — failing the run here for a PR that is about to exist+ // would turn a recovered handoff into a false needs-attention.+ const directPrClaimExpected = directOpenPR && canTypeSlashCommands({providerId: provider?.id,providerCommand: provider?.command,- leanMode: isOllamaClaudeProvider(provider),+ leanMode: directLeanMode,});// try/finally so a throw from finalizeAgent still runs the local@@ -775,7 +776,7 @@ export async function spawnDirectly({error: finalError || undefined,completionReason: terminatedByUser ? 'user-terminated' : undefined,workspacePath,- prExpected: directAgentOwnsPR,+ prExpected: directPrClaimExpected,// The run window the commit criterion is evaluated against (#3637).startedAt: agentData?.startedAt ?? null,});@@ -785,7 +786,8 @@ 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: directAgentOwnsPR ? false : directOpenPR,+ openPR: directOpenPR,+ openPRIfMissing: directAgentOwnsPR,prCompletion: directPrCompletion,...reviewOptions,skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 31a1dc8d40..375e233a72 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -348,18 +348,33 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, eff// 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.- const agentOwnsPR = taskOpenPR && canTypeSlashCommands({- providerId: agentState?.metadata?.providerId ?? agent.providerId,- providerCommand: agentState?.metadata?.providerCommand ?? agent.providerCommand ?? null,- leanMode: (agentState?.metadata?.leanMode ?? agent.leanMode) === true,- });+ //+ // #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,+ }));// 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, {- openPR: agentOwnsPR ? false : taskOpenPR,+ // 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,prCompletion: taskPrCompletion,...reviewOptions,skipMerge: taskReviewLoopFollowUp || agentOwnsPR,diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 937cd6971e..75b1bb1e16 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -148,38 +148,52 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()return cleanupAgentWorktree.mock.calls.at(-1)[2];};+ // #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([- ['claude-code', 'claude', false],- ['claude-code-bedrock', 'claude', false],- // 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', false],- ])('%s does not double-fire the PR (agent owns it)', async (providerId, providerCommand) => {- const opts = await cleanupCallFor({ providerId, providerCommand, leanMode: false });- expect(opts.openPR).toBe(false);+ ['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);expect(opts.skipMerge).toBe(true);});- it.each([- ['codex', 'codex'],- ['antigravity-cli', 'agy'],- ])('%s still gets PortOS post-exit push+PR (agent cannot run /do:pr)', async (providerId, providerCommand) => {- const opts = await cleanupCallFor({ providerId, providerCommand, leanMode: false });+ it('a lean --bare claude session does NOT own its PR (it fumbles multi-step flows)', async () => {+ 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.skipMerge).toBe(false);});- it('a lean --bare claude session does NOT own its PR (it has no project commands)', async () => {- const opts = await cleanupCallFor({ providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true });- expect(opts.openPR).toBe(true);+ it.each([+ ['claude-code', 'claude', true],+ ['claude-code-bedrock', 'claude', true],+ // 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) => {+ // 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);});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' })).openPR).toBe(false);- expect((await cleanupCallFor({ providerId: 'codex-tui' })).openPR).toBe(true);+ expect((await cleanupCallFor({ providerId: 'claude-code' })).openPRIfMissing).toBe(true);+ expect((await cleanupCallFor({ providerId: 'codex-tui' })).openPRIfMissing).toBe(false);});});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex d7344aefcd..3c4dca34cf 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -54,7 +54,7 @@ import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';-import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';@@ -465,6 +465,13 @@ async function runAgentSpawn(task) {// capable, and a lean `--bare` session is not.providerCommand: provider.command || null,leanMode,+ // Whether THIS run's prompt told the agent to push, open, review, and merge+ // its own PR (`agentOwnsPrWorkflow`). Persisted rather than re-derived at+ // cleanup time: the two must agree exactly or PortOS double-fires+ // `gh pr create`, and a pre-upgrade record has no value here at all — so+ // cleanup falls back to the old `canTypeSlashCommands` derivation when the+ // key is absent, which is what those older runs were actually prompted with.+ ownsPrWorkflow: agentOwnsPrWorkflow({ providerType: provider.type, leanMode }),model: selectedModel,// The reasoning-effort override this run was dispatched with (null when the// task pinned none). Persisted next to the model because the Resume Agent@@ -1072,12 +1079,15 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// Analyze failure if applicableconst errorAnalysis = effectiveSuccess ? null : analyzeAgentFailure(outputBuffer, task, model);- // Whether the AGENT (not PortOS) owned PR creation — the gate for- // finalizeAgent's PR-claim verification (#3358). Derived from the same- // `canTypeSlashCommands` predicate `runAgentCompletionCleanup` uses below, so- // the run that was told to open its own PR is exactly the run we check for- // one. When PortOS owns it the PR is created by that cleanup, i.e. AFTER- // finalize, so verifying here would fail every correct run.+ // The gate for finalizeAgent's PR-claim verification (#3358): a PortOS-owned+ // PR is created by `runAgentCompletionCleanup` below, i.e. AFTER finalize, so+ // verifying here would fail every correct run.+ //+ // Deliberately the SLASH-command predicate, not `agentOwnsPrWorkflow` — since+ // #3733 a slashdo-free harness also opens its own PR, but cleanup re-checks+ // the forge and opens one itself when it didn't, so failing the run here for+ // a PR that is about to exist would turn a recovered handoff into a false+ // needs-attention.//// `persistedAgent` is the record read once at the top of this callback — see// the note there for why the metadata must come off disk rather than thediff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex b6094f3cbc..9e22453157 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, resolveSlashdoInvocation, buildSlashdoSection, unreachableReviewerIncludes, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow, resolveSlashdoInvocation, buildSlashdoSection, 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';@@ -580,9 +580,19 @@ function isMergeOnlyFollowUp(metadata = {}) {* subprocess/`else` branch). Inlined when a spawnable CLI reviewer* (codex/antigravity/claude/grok) is in the list so the agent gets the exact* headless invocation and review-only contract instead of improvising it.+ * @param {string|null} [opts.localAgentLoopBodyPath=null] - Path to a staged copy+ * of that body. When set and the body is over `SLASHDO_INLINE_BUDGET_CHARS`,+ * the section points at the file instead of pasting it. Only the inline caller+ * passes this; a follow-up agent, whose whole job is the loop, still inlines.+ * @param {boolean} [opts.inline=false] - Emit the SAME loop for an agent that+ * opened the PR itself moments ago, rather than for a follow-up agent handed+ * someone else's PR (`buildInlineReviewLoopSection`). Only the framing differs:+ * the heading and opening sentence, and the fact that nothing pre-requested a+ * Copilot review. The loop body, notes, merge command, and MERGED verification+ * stay byte-identical so the two callers can't drift.* @returns {string}*/-export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null } = {}) {+export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false, rprBody = null, localAgentLoopBody = null, localAgentLoopBodyPath = null, inline = false, inlineExitStep = '' } = {}) {const prUrl = metadata.reviewLoopPRUrl || '';const prBranch = metadata.reviewLoopPRBranch || '';const prNumber = metadata.reviewLoopPRNumber ?? '';@@ -594,7 +604,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,+ prUrl, prBranch, prNumber, prOwner, prRepo, sourceTaskId, verbose, inline, inlineExitStep,prHost: metadata.reviewLoopPRHost ?? '',});}@@ -714,8 +724,9 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const multi = (reviewers.length + usernames.length) > 1;// The system pre-requests the initial Copilot review only when copilot LEADS the// order; otherwise the agent must request it at copilot's turn (so Copilot reviews- // the post-CLI-fix state, not a stale diff).- const copilotIsFirst = reviewers[0] === DEFAULT_REVIEWER;+ // the post-CLI-fix state, not a stale diff). An INLINE loop opened its own PR+ // moments ago and nothing pre-requested anything, so it always requests.+ const copilotIsFirst = !inline && reviewers[0] === DEFAULT_REVIEWER;const reviewerLabel = [...reviewers.map(r => `\`${r}\``),...usernames.map(u => `\`@${u}\``),@@ -817,7 +828,12 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l: "**Reviewer applies (off):** read each CLI reviewer's findings and apply the fixes yourself (default)."): '';- const initialReviewState = (hasCopilot && copilotIsFirst)+ // Inline runs opened the PR seconds ago inside their own completion workflow,+ // so nothing pre-requested anything — claiming otherwise would have the agent+ // poll forever for a Copilot review no one asked for.+ const initialReviewState = inline+ ? 'Nothing has reviewed this PR yet — you must request/invoke each configured reviewer yourself against its diff.'+ : (hasCopilot && copilotIsFirst)? 'The system has already requested the initial Copilot code review (Copilot leads the order).': hasCopilot? 'Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself.'@@ -863,8 +879,17 @@ Only a successfully extracted \`.findings\` value is the review text; treat it l// table, not a correction layered over it. Conditionals were resolved to the// subprocess (`else`) branch by loadSlashdoLib, so no in-process-Agent-tool// branch leaks in to confuse a non-Claude-Code host.+ //+ // Over budget WITH a staged copy on disk (`localAgentLoopBodyPath`, only ever+ // passed for an inline loop — see buildAgentPrompt) the agent is pointed at the+ // file instead. Same trade `buildSlashdoSection` makes: an initial run is+ // 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`;const cliReviewerProcedure = (hasCli && localAgentLoopBody)- ? `\n### CLI Reviewer Procedure (${cliReviewerHeading})\n\nDrive each spawnable CLI reviewer EXACTLY as the slashdo local-agent review loop below specifies — use its per-CLI invocation and review-only prompt contract verbatim; do NOT probe the CLI's \`--help\`, test it with throwaway prompts, or hand-roll flags. Run the reviewer once per round, capture its findings, and (unless reviewer-applies is set) apply the fixes yourself.\n\n${localAgentLoopBody}\n`+ ? (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`+ : `${cliProcedureHeader}${localAgentLoopBody}\n`): '';// A JIRA-tracked PR is a human's to land (its ticket is already "In Review" and@@ -874,12 +899,19 @@ Only a successfully extracted \`.findings\` value is the review text; treat it lconst objective = leaveOpen? '**Your job is to drive the review-and-fix loop to completion. Do NOT merge — this PR is tracked in JIRA and a human lands it.**': '**Your job is to drive the review-and-fix loop to completion and merge the PR.**';+ // Where the loop hands control back. A follow-up agent's whole task WAS the+ // 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+ ? `6. ${inlineExitStep}`+ : `6. Exit. Do **not** run \`/do:push\` or open a new PR${followUpTail}. 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>"\``}.`,- '6. Exit. Do **not** run `/do:push` or open a new PR. The system will clean up your worktree on exit.',+ 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):`,@@ -889,13 +921,19 @@ 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\`.`,- '6. Exit. Do **not** run `/do:push` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.',+ exitStep(' — the merge handles everything'),].filter(Boolean);+ // Framing only — everything below it is identical for both callers.+ const heading = inline ? '## Review Loop' : '## Review-Loop Follow-up (PRIMARY OBJECTIVE)';+ const opening = inline+ ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). ${initialReviewState} ${objective}`+ : `A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} ${objective}`;+if (verbose) {return `-## Review-Loop Follow-up (PRIMARY OBJECTIVE)-A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. ${initialReviewState} ${objective}+${heading}+${opening}**Reviewers (in order)**: ${reviewerLabel}${equiv}.${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}@@ -923,9 +961,12 @@ ${cliReviewerProcedure}${(rprBody && (hasCopilot || hasGithubUser)) ? `\n### /do}// Compact light-path variant.+ const compactOpening = inline+ ? opening+ : `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} ${leaveOpen ? 'Drive the review-and-fix loop to completion — do NOT merge (JIRA-tracked; a human lands it).' : 'Drive the review-and-fix loop to completion and merge.'}`;return [- '## Review-Loop Follow-up (PRIMARY OBJECTIVE)',- `A previous agent finished task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. ${initialReviewState} ${leaveOpen ? 'Drive the review-and-fix loop to completion — do NOT merge (JIRA-tracked; a human lands it).' : 'Drive the review-and-fix loop to completion and merge.'}`,+ heading,+ compactOpening,`**Reviewers (in order)**: ${reviewerLabel}${equiv}.`,...extraNotes,'',@@ -983,7 +1024,7 @@ const LEAVE_PR_OPEN_STEP = (step, jiraTracked = false) => `${step}. **Leave the* workflow, which runs before the PR exists) emits both, commented.* @returns {{lines: string[], nextStep: number}}*/-function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github' }) {+function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forge = 'github', alreadyMergedHint = ' (a saved `/do:pr` default can merge it for you)' }) {const gh = forge !== 'gitlab';const glab = forge !== 'github';const both = gh && glab;@@ -999,7 +1040,7 @@ function buildCiMergeGateSteps(startStep, { prRef, mrRef = '<MR_NUMBER>', forgeconst lines = [`${startStep}. **Wait for CI to finish**: ${checksCmd}. "No checks reported" is AMBIGUOUS — a just-opened PR reports it while checks are still attaching, and merging on it races the CI this gate exists to wait for. Treat it as green ONLY when the repo genuinely has no CI (${gh ? '`gh workflow list` is empty / nothing in `.github/workflows` triggers on pull_request, and no external status check is configured' : 'no `.gitlab-ci.yml` and no pipeline is configured'}). If CI IS expected, wait 30s and re-check for up to 5 minutes — and if it still hasn't attached, **leave the PR open and say so**; never merge on checks that were expected but never appeared.`,`${startStep + 1}. **Clear whatever blocks the merge, then re-check.** If a check failed, read the failing job's log (${gh ? `\`gh run view --log-failed\`${glab ? ' on GitHub, `glab ci trace` on GitLab' : ''}` : '`glab ci trace`'}), fix the cause here, run the project's tests, commit (\`fix:\` prefix, no Co-Authored-By), push, and go back to the previous step — cap this at 5 rounds. If ${mergeableCmd}, \`git fetch origin\`, rebase onto the base branch, resolve the conflicts keeping BOTH sides' intent, re-run the tests, \`git push --force-with-lease\`, and re-check.`,- `${startStep + 2}. **Merge** with exactly these flags, nothing else — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, and any merge-deferral flag leaves the PR open after you exit. If it is already merged (a saved \`/do:pr\` default can merge it for you), skip to the next step:`,+ `${startStep + 2}. **Merge** with exactly these flags, nothing else — a true merge commit keeps the branch tip in the base branch's history so automated worktree cleanup can prove the branch is merged, and any merge-deferral flag leaves the PR open after you exit. If it is already merged${alreadyMergedHint}, skip to the next step:`,' ```bash',gh ? ` ${both ? '# GitHub: ' : ''}gh pr merge ${prRef} --merge --delete-branch` : null,// `glab mr merge` takes an MR IID or source branch — a URL is not accepted.@@ -1022,7 +1063,7 @@ 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 }) {+function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '', prRepo = '', prHost = '', sourceTaskId = 'unknown', verbose = false, inline = false, inlineExitStep = '' }) {// 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@@ -1031,10 +1072,15 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = 'prRef: `"${prUrl}"`,mrRef: prNumber !== '' ? `${prNumber}` : '<MR_NUMBER>',forge: 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: '' } : {}),});const steps = [...gate.lines,- `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and do NOT start a code review — landing this PR is the whole job.`,+ inline+ ? `${gate.nextStep}. ${inlineExitStep} Do NOT start a code review — none is configured for this task.`+ : `${gate.nextStep}. Exit. Do NOT run \`/do:push\`, do NOT open a new PR, and do NOT start a code review — landing this PR is the whole job.`,];const prDetails = verbose ? ['',@@ -1047,8 +1093,10 @@ function buildMergeFollowUpSection({ prUrl, prBranch, prNumber = '', prOwner = '].filter(Boolean) : [];return [- '## Merge Follow-up (PRIMARY OBJECTIVE)',- `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **No code review was requested for this task, so nothing else will merge this PR — your job is to land it once CI is green.**`,+ inline ? '## Merge Gate' : '## Merge Follow-up (PRIMARY OBJECTIVE)',+ inline+ ? `This runs as **step ${INLINE_REVIEW_LOOP_STEP} of the Completion Workflow above**, against the PR you just opened on \`${prBranch}\` (\`${prUrl}\` / \`${prNumber}\` are the shell variables you captured there). **No code review was requested for this task, so nothing else will merge this PR — land it yourself once CI is green.**`+ : `A previous agent finished the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on \`${prBranch}\`. **No code review was requested for this task, so nothing else will merge this PR — your job is to land it once CI is green.**`,'',...steps,'',@@ -1373,14 +1421,34 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// CLI-reviewer invocation. Cheap + cached; only read for follow-ups — and not// for a merge-only follow-up, which has no reviewer to invoke and renders a// section that ignores this body entirely.- const needsReviewerRecipes = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)+ const isFollowUpNeedingRecipes = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp)&& !isMergeOnlyFollowUp(task.metadata || {});- const localAgentLoopBody = needsReviewerRecipes+ // …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 });+ const localAgentLoopBody = (isFollowUpNeedingRecipes || isInlineNeedingRecipes)? await loadSlashdoLib('local-agent-review-loop').catch(() => null): null;+ // The recipe is ~40KB. A follow-up agent inlines it — driving the loop is that+ // agent's entire job, so it will read all of it anyway. An INLINE loop is a+ // later phase of a run whose context is already carrying the actual task, so an+ // over-budget recipe is staged on disk and pointed at instead (#3110's split,+ // applied to the same body). Every host that reaches here has file tools.+ const localAgentLoopBodyPath = (isInlineNeedingRecipes && !isFollowUpNeedingRecipes+ && localAgentLoopBody && localAgentLoopBody.length > SLASHDO_INLINE_BUDGET_CHARS)+ ? await writeResolvedSlashdoBody('local-agent-review-loop', localAgentLoopBody).catch((err) => {+ console.warn(`⚠️ Could not stage the CLI-reviewer recipe, inlining instead: ${err.message}`);+ return null;+ })+ : null;if (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {- const lightOptions = { isTui, providerId, providerCommand, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody };+ const lightOptions = { isTui, providerId, providerCommand, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody, localAgentLoopBodyPath };return options.split === true? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions): buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions);@@ -1572,7 +1640,7 @@ After your task completes, the system will spawn a follow-up agent that runs theif (isReviewLoopFollowUp) {// `/do:rpr` is the Copilot/@github comment-resolution procedure — a merge-only// follow-up has no review to resolve, so skip the ~35KB read for it.- const rprBody = needsReviewerRecipes ? await loadSlashdoFile('rpr').catch(() => null) : null;+ const rprBody = isFollowUpNeedingRecipes ? await loadSlashdoFile('rpr').catch(() => null) : null;// localAgentLoopBody (the CLI-reviewer recipe) was already preloaded at the// top of buildAgentPrompt under the same reviewLoopFollowUp guard — reuse it// rather than re-reading the lib a second time.@@ -1802,7 +1870,7 @@ export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, iconst BEGIN_WORKING_LINE = 'Begin working on the task now.';-function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null } = {}) {+function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null, localAgentLoopBodyPath = null } = {}) {// Idempotent with the reconcile in buildAgentPrompt; also protects the// directly-exported buildLightContextPrompt/Parts entry points.task = reconcileSplitContext(task);@@ -1857,6 +1925,19 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// session (`--bare` skips project command discovery, and the small local models// lean mode targets fumble multi-step slashdo flows anyway).const tuiSlashdoFree = isTui && !canTypeSlash;+ // Whether this session drives commit → push → PR → review → merge itself.+ // Independent of `canTypeSlash`: a codex/grok/agy harness can't type `/do:pr`+ // but runs `gh` and the reviewer CLIs perfectly well (see `agentOwnsPrWorkflow`).+ // Only the light path reaches here, so the provider is `tui` or `cli`.+ const ownsPrWorkflow = agentOwnsPrWorkflow({+ providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,+ leanMode,+ });+ // The manual (slashdo-free) workflow drives the reviewers itself, so it needs+ // the same inlined review-loop section — and the same procedure body — the+ // `sys-rl-*` follow-up agent used to be spawned to carry.+ const emitsInlineReviewLoop = ownsPrWorkflow && !canTypeSlash && willOpenPR+ && !(leavesPrForHuman(task) || prCompletion === PR_COMPLETIONS.LEAVE_OPEN);const taskSections = [];const contractSections = [];@@ -1904,7 +1985,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet`- **Path**: \`${worktreeInfo.worktreePath}\``,worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,'',- worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }),+ worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }),'Do NOT manually switch branches or modify the worktree configuration.',// Resuming a previous failed agent's branch: establish what's already done// before writing code (see buildResumeSection). '' when not a resume.@@ -1974,7 +2055,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet}} else if (isTui) {sections.push(buildTuiCompletionSection({- willOpenPR, prCompletion, simplifyEnabled, slashdoFree: tuiSlashdoFree,+ willOpenPR, prCompletion, simplifyEnabled, slashdoFree: tuiSlashdoFree, ownsPrWorkflow,sentinelPath: resolveSentinelPath(worktreeInfo, workspaceDir, agentId),branchName: worktreeInfo?.branchName || null,baseBranch: worktreeInfo?.baseBranch || null,@@ -1982,7 +2063,33 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetreviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies}));} else {- sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));+ sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, hasSlashdo, ownsPrWorkflow, simplifyEnabled, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));+ }++ // The manual workflow's step 4 points here — it must follow the completion+ // section it is a step of, and only for a run that actually opens its own PR+ // (the read-only / no-code / discard / follow-up branches above all returned a+ // completion contract that never creates one).+ if (emitsInlineReviewLoop && !noCodeOutput && !discardWorktree && !isReadOnly && !isReviewLoopFollowUp) {+ sections.push(buildInlineReviewLoopSection({+ taskId: task.id,+ branchName: worktreeInfo?.branchName || null,+ runsReviewLoop: prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE,+ leaveOpen: false,+ localAgentLoopBody,+ localAgentLoopBodyPath,+ // Only the TUI completion workflow ends on a sentinel write; a CLI run+ // signals completion by exiting.+ writesSentinel: isTui,+ reviewers: lightReviewers,+ usernames: lightReviewerUsernames,+ optionalReviewers: lightOptionalReviewers,+ reviewerMaxRounds: lightReviewerMaxRounds,+ reviewerModels: lightReviewerModels,+ reviewerEfforts: lightReviewerEfforts,+ reviewStopMode: lightReviewStopMode,+ reviewerApplies: lightReviewerApplies,+ }));}return { taskSections, contractSections };@@ -1994,7 +2101,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet* push workflow (TUI or Claude Code CLI with slashdo), reuse an existing PR* branch (review fixes), or hand off to PortOS's post-exit push.*/-function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }) {+function worktreeCommitGuidance({ isTui, hasSlashdo, ownsPrWorkflow = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree }) {if (discardWorktree) return DISCARD_WORKTREE_NOTE;if (isTui) return 'Commit your changes to this branch — see **Completion Workflow** below.';if (isWorktreeOnExistingBranch) {@@ -2006,6 +2113,9 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,if (hasSlashdo) {return 'Commit your changes here — the **Completion** section below drives the push.';}+ if (ownsPrWorkflow && willOpenPR) {+ return 'Commit your changes here — the **Completion** section below drives the push, the PR, the review loop, and the merge.';+ }if (willOpenPR) {return 'Commit your changes here. The system will push and open a PR after you exit — do NOT push or open a PR yourself.';}@@ -2119,14 +2229,14 @@ function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail) {* return this IS a Claude session, so `/simplify` and `/do:pr` are both safe to* emit without a second provider check.*/-function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {+function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, ownsPrWorkflow = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;if (slashdoFree) {- // The manual path can't drive the reviewer CLIs, so with a review loop- // configured it opens the PR and stops. Without one, no reviewer and no- // follow-up is coming — it merges on green CI like every other flow.- return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen });+ // Plain `git`/`gh` instead of `/do:pr` — but still the whole lifecycle when+ // the session is a real coding harness (`ownsPrWorkflow`); the reviewer+ // procedure it needs is inlined in the Review Loop section that follows.+ return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow });}const cmd = willOpenPR ? '/do:pr' : '/do:push';// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out@@ -2170,27 +2280,80 @@ function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.M}/**- * Manual (slashdo-free) TUI completion-workflow block — for an OpenCode TUI that- * does NOT load Claude Code slash commands and so can't run `/do:pr` / `/do:push`.- * Drives a plain `git` commit → sentinel handshake. PortOS owns the post-exit- * push / PR / review / merge lifecycle, just as it does for non-TUI providers- * that cannot invoke project slash commands.+ * Which numbered step of the manual completion workflow the inline review-loop /+ * merge-gate section is. The manual workflow always emits step 1 (simplify, or+ * an explicit "disabled — skip" placeholder) and step 2 (commit) before the PR+ * steps, so the number is stable and the two sections can cross-reference each+ * other without threading a counter between them.+ */+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).+ */+function safeRefForShell(ref, fallback) {+ return (typeof ref === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(ref)) ? ref : fallback;+}++/**+ * The push + open-a-PR steps of the manual (slashdo-free) completion workflow.*- * Keeping PR creation system-owned also guarantees a real generated body rather- * than `gh pr create --fill` producing an empty description from a one-line- * commit, and lets the existing follow-up machinery run configured reviewers.+ * `$PR_URL` / `$PR_NUMBER` are captured into shell variables here because the+ * inline review-loop and merge-gate sections address the PR by those names —+ * they are rendered before the PR exists, so a literal URL is impossible.*/-function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, leavePrOpen = false }) {+function buildManualPrCreateStep(step, { branchName, baseBranch }) {+ const branch = safeRefForShell(branchName, '<branch>');+ const base = safeRefForShell(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:`,+ '',+ ' ```bash',+ ` git push -u origin ${branch}`,+ ` PR_URL=$(gh pr create --base ${base} --head ${branch} --title "<conventional title>" --body "<description>")`,+ ' PR_NUMBER=$(gh pr view "$PR_URL" --json number -q .number)',+ ' ```',+ // `--fill` on a one-line commit produces an empty description; PortOS used+ // to generate the body server-side, so spell out what it must contain now+ // 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`.',+ ];+}++/**+ * Manual (slashdo-free) completion-workflow block — every provider that can't+ * type `/do:pr` (codex, grok/agy, OpenCode, a lean `--bare` Claude session).+ *+ * When `ownsPrWorkflow` is set the agent drives the WHOLE lifecycle in one+ * session: commit → push → open the PR → run the inline review loop → merge.+ * That is the point of the flag — see `agentOwnsPrWorkflow`. Not typing a slash+ * command never meant "can't run `gh`", but this block used to conclude exactly+ * that, so every agy/grok/codex task ended in a commit and PortOS bought a+ * second cold agent (`sys-rl-*`) just to review and land the PR.+ *+ * `ownsPrWorkflow: false` (lean mode) keeps the original handoff: commit and+ * stop, PortOS owns the post-exit push / PR / review / merge lifecycle.+ */+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, ownsPrWorkflow = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;+ const drivesOwnPr = ownsPrWorkflow && willOpenPR;const simplifyStep = simplifyEnabled? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`: '1. (simplify disabled — skip)';- const sentinelTail = ' ## Branch\n <branch name>';+ const sentinelTail = drivesOwnPr ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';const lines = ['## Completion Workflow',- 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git`. Run these in order:',+ drivesOwnPr+ ? 'This provider does NOT have slashdo (`/do:*`) commands, so drive the handoff with plain `git` and `gh`. **You own this PR end to end — nothing else will open, review, or merge it.** Run these in order:'+ : 'This provider does NOT have slashdo (`/do:*`) commands, so finish the handoff with plain `git`. Run these in order:','',simplifyStep,'2. Stage only the files you changed (never `git add -A` / `git add .`) and commit with a conventional message (`feat:`/`fix:`/`breaking:` prefix, no Co-Authored-By annotations):',@@ -2202,7 +2365,12 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET];let step = 3;- if (willOpenPR) {+ if (drivesOwnPr) {+ lines.push(...buildManualPrCreateStep(step++, { branchName, baseBranch }));+ lines.push((leavePrOpen || policyLeavesOpen)+ ? LEAVE_PR_OPEN_STEP(step++, leavePrOpen)+ : `${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR. Come back here when it is done.`);+ } else if (willOpenPR) {const handoff = policyLeavesOpen? 'PortOS will push the branch, create a pull request with your completion summary as its description, and leave it open for inspection.': leavePrOpen@@ -2220,6 +2388,47 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETreturn lines.join('\n');}+/**+ * 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.+ *+ * Deliberately the SAME builder the `sys-rl-*` follow-up agent gets, driven off+ * a synthesized `reviewLoop*` metadata shape: the procedure a follow-up runs and+ * the procedure an inline run needs are the same procedure, and the whole+ * regression this fixes came from having two of them. The PR coordinates are the+ * shell variables `buildManualPrCreateStep` captured, because the section is+ * rendered before the PR exists.+ */+function buildInlineReviewLoopSection({+ taskId, branchName, runsReviewLoop, leaveOpen, localAgentLoopBody, localAgentLoopBodyPath = null, writesSentinel = false,+ reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies,+}) {+ // Where control goes after the merge. A TUI run still owes PortOS its+ // `.agent-done` sentinel — telling it to "exit" here is how a finished merge+ // idles into a false timeout — while a CLI run signals completion by exiting.+ const inlineExitStep = writesSentinel+ ? 'Return to the **Completion Workflow** above and write the completion sentinel — the run is not done until you have. Do NOT open a second PR.'+ : 'You are done — exit. Do NOT open a second PR or push anything further.';+ return buildReviewLoopFollowUpSection({+ reviewLoopPRUrl: '$PR_URL',+ reviewLoopPRNumber: '$PR_NUMBER',+ reviewLoopPRBranch: branchName || '<branch>',+ reviewLoopReviewers: reviewers,+ reviewLoopReviewerUsernames: usernames,+ reviewLoopOptionalReviewers: optionalReviewers,+ reviewLoopReviewerMaxRounds: reviewerMaxRounds,+ reviewLoopReviewerModels: reviewerModels,+ reviewLoopReviewerEfforts: reviewerEfforts,+ reviewLoopStopMode: reviewStopMode,+ reviewLoopReviewerApplies: reviewerApplies,+ reviewLoopLeaveOpen: leaveOpen,+ // No reviewer configured ⇒ the merge-gate variant (CI is the whole gate),+ // exactly as the merge-only follow-up gets.+ reviewLoopMergeOnly: !runsReviewLoop,+ sourceTaskId: taskId || 'unknown',+ }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inline: true, inlineExitStep });+}+/*** CLI (non-TUI) completion block.*@@ -2230,7 +2439,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET* CLI providers fall through to the legacy commit-only block where PortOS* handles push+PR on exit.*/-function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {+function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, ownsPrWorkflow = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;if (hasSlashdo && worktreeInfo && willOpenPR) {@@ -2271,6 +2480,26 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PRlines.push(`${step++}. \`/do:push\` — commits your changes and pushes the branch.`);return lines.join('\n');}+ // Non-slashdo CLI that IS a real coding harness (codex, grok/agy, OpenCode):+ // it can't type `/do:pr`, but it can run `git push` / `gh pr create` and drive+ // the reviewer CLIs — so it owns the same end-to-end lifecycle the TUI manual+ // path does, with the reviewer procedure inlined in the section that follows.+ if (ownsPrWorkflow && worktreeInfo && willOpenPR) {+ const lines = ['## Completion', '**You own this PR end to end — nothing else will open, review, or merge it.** When finished, run these in order:'];+ let step = 1;+ lines.push(simplifyEnabled+ ? `${step++}. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`+ : `${step++}. (simplify disabled — skip)`);+ lines.push(`${step++}. Stage only the files you changed (never \`git add -A\` / \`git add .\`) and commit with a conventional message (\`feat:\`/\`fix:\`/\`breaking:\` prefix, no Co-Authored-By annotations).`);+ lines.push(...buildManualPrCreateStep(step++, {+ branchName: worktreeInfo?.branchName || null,+ baseBranch: worktreeInfo?.baseBranch || null,+ }));+ lines.push((leavePrOpen || policyLeavesOpen)+ ? LEAVE_PR_OPEN_STEP(step, leavePrOpen)+ : `${step}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR.`);+ return lines.join('\n');+ }let body;if (worktreeInfo && willOpenPR) {body = 'Commit your changes (stage specific files, `feat:`/`fix:` prefix, no Co-Authored-By). Do NOT push — PortOS will push and open the PR after you exit.';diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 8feb0cccce..1651bb2b4a 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -413,15 +413,20 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/gh pr merge/);});- it('an OpenCode TUI JIRA task leaves its PR open instead of merging', () => {+ it('an OpenCode TUI JIRA task opens its own PR but leaves it open instead of merging', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true, analysisType: 'jira-sprint-manager' } }),'/r',{ branchName: 'claim/x', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });- expect(prompt).not.toMatch(/gh pr create/);- expect(prompt).toMatch(/JIRA-linked human handoff/);+ // The harness opens the PR itself (#3733) — but a JIRA-tracked PR is a+ // human's to land, so no merge steps and no inline review loop.+ expect(prompt).toMatch(/gh pr create/);+ expect(prompt).toMatch(/Leave the PR open — do NOT merge it/);+ expect(prompt).toMatch(/tracked in JIRA/);+ expect(prompt).not.toMatch(/## Review Loop/);+ expect(prompt).not.toMatch(/## Merge Gate/);expect(prompt).not.toMatch(/gh pr merge/);expect(prompt).not.toMatch(/glab mr merge/);});@@ -489,10 +494,11 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/gh pr merge/);});- it('hands a slashdo-free OpenCode TUI PR to PortOS for description, review, and merge', () => {+ it('a slashdo-free OpenCode TUI drives its own PR, review loop, and merge', () => {// OpenCode TUI doesn't load Claude Code slash commands, so /do:pr / /do:push- // would be uninvokable. The agent commits and writes the sentinel; PortOS- // owns the PR body, configured reviewer follow-up, and merge.+ // would be uninvokable — but it runs `git`/`gh` and the reviewer CLIs fine,+ // so it owns the whole lifecycle in one session rather than handing off to a+ // `sys-rl-*` follow-up agent (#3733).const prompt = buildLightContextPrompt(makeTask({ metadata: { simplify: true, openPR: true, reviewLoop: true } }),'/r',@@ -506,31 +512,33 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/`\/simplify`/);// /simplify is a Claude built-in — OpenCode gets the inline equivalent.expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);- // Plain git commit only — no agent-owned push or forge action.+ // Commit → push → PR → review loop → merge, all in this session.expect(prompt).toMatch(/git commit -m/);- expect(prompt).not.toMatch(/git push/);- expect(prompt).not.toMatch(/gh pr create/);- expect(prompt).not.toMatch(/glab mr create/);- expect(prompt).not.toMatch(/gh pr merge/);- expect(prompt).not.toMatch(/glab mr merge/);- expect(prompt).toMatch(/PortOS will push the branch, create a pull request with your completion summary as its description, run the configured reviewer follow-up, and merge only after review and CI pass/);+ expect(prompt).toMatch(/git push -u origin claim\/issue-1/);+ expect(prompt).toMatch(/PR_URL=\$\(gh pr create --base main --head claim\/issue-1/);+ expect(prompt).toMatch(/## Review Loop/);+ expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --delete-branch/);+ // PortOS no longer promises to do any of it.+ expect(prompt).not.toMatch(/PortOS will push the branch/);// Sentinel handshake still drives completion; never tell the agent to run /quit.expect(prompt).toMatch(/\.agent-done/);expect(prompt).toMatch(/NOT run `\/quit`/);expect(prompt).not.toMatch(/^\s*\d+\.\s*`\/quit`/m);});- it('hands a slashdo-free OpenCode TUI PR to PortOS for a green-CI merge', () => {+ it('a slashdo-free OpenCode TUI with no reviewer gets the CI merge gate, not a review loop', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { simplify: true, openPR: true } }),'/r',{ branchName: 'claim/issue-1', worktreePath: '/tmp/wt', baseBranch: 'main' },isTruthyMeta,{ isTui: true, providerId: 'opencode-ollama-tui', providerCommand: 'opencode' });- expect(prompt).not.toMatch(/gh pr create/);- expect(prompt).not.toMatch(/gh pr checks/);- expect(prompt).not.toMatch(/gh pr merge/);- expect(prompt).toMatch(/PortOS will push the branch, create a pull request with your completion summary as its description, and merge it once CI is green/);+ expect(prompt).toMatch(/gh pr create/);+ expect(prompt).toMatch(/## Merge Gate/);+ expect(prompt).not.toMatch(/## Review Loop/);+ expect(prompt).toMatch(/gh pr checks/);+ expect(prompt).toMatch(/gh pr merge "\$PR_URL" --merge --delete-branch/);+ expect(prompt).not.toMatch(/PortOS will push the branch/);});it('OpenCode TUI without openPR leaves the committed branch for PortOS to merge', () => {@@ -578,14 +586,117 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/does NOT have slashdo/);expect(prompt).not.toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/`\/do:push`/);- // Plain commit + system-owned PR handoff instead.+ // Plain git/gh equivalent of the whole slashdo workflow (#3733).expect(prompt).toMatch(/git commit -m/);- expect(prompt).not.toMatch(/git push/);- expect(prompt).not.toMatch(/gh pr create/);- expect(prompt).toMatch(/PortOS will push the branch/);+ expect(prompt).toMatch(/git push -u origin claim\/x/);+ expect(prompt).toMatch(/gh pr create --base main --head claim\/x/);+ expect(prompt).toMatch(/## Review Loop/);+ expect(prompt).not.toMatch(/PortOS will push the branch/);expect(prompt).toMatch(/\.agent-done/);});+ // #3733 — the inline review loop is the SAME builder the `sys-rl-*` follow-up+ // agent gets, so the only things that can be wrong are its framing.+ it('the inline review loop never claims a reviewer was pre-requested', () => {+ // The follow-up variant says "the system already requested the initial+ // Copilot review". Inline, nothing did — the agent opened the PR seconds+ // ago, so that wording would have it poll forever for a review no one asked for.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['copilot'] } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'antigravity-tui', providerCommand: 'agy' });+ expect(prompt).toMatch(/## Review Loop/);+ expect(prompt).not.toMatch(/## Review-Loop Follow-up/);+ expect(prompt).not.toMatch(/already requested the initial Copilot/);+ expect(prompt).toMatch(/request\/invoke each configured reviewer yourself/);+ // …and it must not tell an agent that never ran `/do:pr` that a saved+ // `/do:pr` default might have merged the PR for it.+ expect(prompt).not.toMatch(/a saved `\/do:pr` default can merge it/);+ });++ it('the inline review loop hands control back to the sentinel, not to an exit', () => {+ // The follow-up variant ends "Exit — the system will clean up your+ // worktree". A TUI run that exits there never writes `.agent-done` and+ // idles into a false timeout with the PR already merged.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ expect(prompt).toMatch(/write the completion sentinel — the run is not done until you have/);+ expect(prompt).not.toMatch(/The system will clean up your worktree on exit/);+ });++ it('a CLI inline review loop ends by exiting — a CLI run has no sentinel to write', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: false, providerId: 'codex', providerCommand: 'codex' });+ expect(prompt).toMatch(/## Review Loop/);+ expect(prompt).toMatch(/You are done — exit/);+ expect(prompt).not.toMatch(/write the completion sentinel — the run is not done/);+ });++ it('inlines the slashdo CLI-reviewer recipe into the inline loop, as the follow-up gets', () => {+ // Without it the agent only sees "invoke that CLI" and reverse-engineers+ // the invocation — the failure that had a codex agent burn a dozen+ // `--help` probes before stumbling into a working review call.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ {+ isTui: true, providerId: 'codex-tui', providerCommand: 'codex',+ localAgentLoopBody: 'RECIPE: codex --sandbox read-only review --base <base>',+ });+ expect(prompt).toMatch(/### CLI Reviewer Procedure \(codex\)/);+ expect(prompt).toMatch(/RECIPE: codex --sandbox read-only review/);+ expect(prompt).toMatch(/do NOT probe the CLI/);+ });++ it('points an over-budget CLI-reviewer recipe at its staged file instead of pasting 40KB', () => {+ // The real recipe is ~40KB. A follow-up agent inlines it because the loop+ // is its whole job; an initial run is already carrying the actual task.+ const body = 'RECIPE HEADER\n' + 'x'.repeat(40_000);+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ {+ isTui: true, providerId: 'codex-tui', providerCommand: 'codex',+ localAgentLoopBody: body,+ localAgentLoopBodyPath: '/data/slashdo-resolved/local-agent-review-loop.md',+ });+ expect(prompt).toMatch(/### CLI Reviewer Procedure \(codex\)/);+ expect(prompt).toMatch(/READ THAT FILE/);+ expect(prompt).toMatch(/\/data\/slashdo-resolved\/local-agent-review-loop\.md/);+ expect(prompt).not.toMatch(/RECIPE HEADER/);+ expect(prompt.length).toBeLessThan(20_000);+ });++ it('does not interpolate a hostile branch ref into 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.+ 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/);+ });+it('a path-configured claude binary under a custom provider id gets the slashdo workflow', () => {// The old `hasSlashdo` gate was an id allowlist (`claude-code` /// `claude-code-bedrock`), so a renamed or path-configured claude provider@@ -637,7 +748,11 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/^## Completion$/m);expect(prompt).not.toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/`\/quit`/);- expect(prompt).toMatch(/PortOS will push and open the PR/);+ // Owns the lifecycle via plain git/gh instead of handing it to PortOS (#3733),+ // and — being a CLI, not a TUI — never mentions a completion sentinel.+ expect(prompt).toMatch(/gh pr create/);+ expect(prompt).not.toMatch(/PortOS will push and open the PR/);+ expect(prompt).not.toMatch(/\.agent-done/);});it('inlines a simplify-equivalent self-review (no /simplify command) for non-Claude CLI agents', () => {@@ -653,7 +768,8 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/^## Completion$/m);expect(prompt).not.toMatch(/`\/simplify`/);expect(prompt).toMatch(/review your changed code for reuse, quality, and efficiency/i);- expect(prompt).toMatch(/PortOS will push and open the PR/);+ expect(prompt).toMatch(/gh pr create/);+ expect(prompt).not.toMatch(/PortOS will push and open the PR/);});// #3114 — the gates now derive from `resolveSlashdoStyle` with the spawners'diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex ee043d53bb..9782a4e106 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -22,7 +22,8 @@ import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSenimport { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';import { resolvePrCompletion } from '../lib/prDisposition.js';-import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';+import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { normalizeReviewers } from '../lib/validation.js';import * as git from './git.js';import { resolveReviewLoopOptions } from './codeReview.js';@@ -1063,18 +1064,20 @@ export async function spawnTuiAgent({completionError: finalError,});- // A slashdo-capable Claude TUI owns /do:pr itself. Slashdo-free TUIs- // (Codex, Antigravity, OpenCode, lean Claude) only commit and signal;- // PortOS must own their push + PR + reviewer/merge follow-up. Derive this- // from the same predicate used by the prompt builder so neither side can- // believe the other owns the PR.- //- // Resolved BEFORE finalizeAgent (not just in the cleanup below) because it is- // also the gate for the PR-claim verification (#3358): only a run that owned- // its own PR creation can be expected to have produced one by finalize time.+ // Every TUI that is a real coding harness drives its own push → PR → review+ // → merge, whether or not it can type `/do:pr` (#3733) — a Claude TUI runs+ // the slashdo command, codex/antigravity/grok/OpenCode run the plain+ // `git`/`gh` equivalent from the same prompt. Only a lean `--bare` session+ // still hands the lifecycle back to PortOS. Derived from the same predicate+ // the prompt builder used so neither side can believe the other owns the PR.const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);const taskReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);- const agentOwnsPR = taskOpenPR && canTypeSlashCommands({+ const agentOwnsPR = taskOpenPR && agentOwnsPrWorkflow({ providerType: PROVIDER_TYPES.TUI, leanMode });+ // …but PR-claim verification (#3358) stays keyed on the SLASH-command+ // predicate. A run PortOS still backstops (it re-checks the forge at cleanup+ // and opens the PR itself when the agent skipped it) must not be failed here+ // for a PR that is about to exist — finalize runs before that net.+ const prClaimExpected = taskOpenPR && canTypeSlashCommands({providerId: provider?.id,providerCommand: provider?.command,leanMode,@@ -1107,7 +1110,7 @@ export async function spawnTuiAgent({error: finalError || undefined,completionReason: reason,workspacePath,- prExpected: agentOwnsPR,+ prExpected: prClaimExpected,// The run window the commit criterion is evaluated against (#3637).startedAt: agentData?.startedAt ?? null,});@@ -1117,7 +1120,9 @@ export async function spawnTuiAgent({// its own file and may still be running.if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});- const reviewOptions = cleanupSuccess && taskOpenPR && !agentOwnsPR+ // Resolved even when the agent owns the PR: cleanup's safety net may find+ // it never opened one, and the follow-up it then spawns needs these.+ const reviewOptions = cleanupSuccess && taskOpenPR? await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn }).catch(err => {emitLog('warn', `TUI review options unavailable for ${agentId}: ${err.message}`, { agentId });@@ -1125,7 +1130,8 @@ export async function spawnTuiAgent({}): {};await cleanupWorktreeFn(agentId, cleanupSuccess, {- openPR: agentOwnsPR ? false : taskOpenPR,+ openPR: taskOpenPR,+ openPRIfMissing: agentOwnsPR,prCompletion: resolvePrCompletion(task.metadata),...reviewOptions,skipMerge: taskReviewLoopFollowUp || agentOwnsPR,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex d4906748f6..d376ccada7 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -521,6 +521,7 @@ describe('spawnTuiAgent runtime', () => {executionId,laneName,checkOnlineFn,+ leanMode: overrides.leanMode ?? false,useDurableRunner: overrides.useDurableRunner ?? false,...helpers,});@@ -671,7 +672,7 @@ describe('spawnTuiAgent runtime', () => {await completeDone;});- it('hands a slashdo-free TUI PR to PortOS for creation and review/merge follow-up', async () => {+ it('backstops a slashdo-free TUI PR instead of creating one outright (#3733)', async () => {const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);const spawnPromise = runSpawn({provider: { id: 'codex-tui', name: 'Codex TUI', type: 'tui', command: 'codex', envVars: {} },@@ -687,10 +688,37 @@ describe('spawnTuiAgent runtime', () => {await capturedOnExit({ exitCode: 0, killed: false });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.expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({openPR: true,+ openPRIfMissing: true,prCompletion: 'review-then-merge',reviewers: ['codex'],+ skipMerge: true,+ }));+ });++ it('a lean --bare TUI still hands its PR to PortOS outright', async () => {+ const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);+ const spawnPromise = runSpawn({+ provider: { id: 'claude-ollama-tui', name: 'Lean Claude TUI', type: 'tui', command: 'claude', ollamaBacked: true, envVars: {} },+ leanMode: true,+ task: {+ id: 'task-1',+ description: 'do the thing',+ metadata: { openPR: true, prCompletion: 'review-then-merge' },+ },+ helpers: { cleanupWorktreeFn, isTruthyMetaFn: (value) => value === true || value === 'true' },+ });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await spawnPromise;++ expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({+ openPR: true,+ openPRIfMissing: false,skipMerge: false,}));});@@ -712,7 +740,8 @@ describe('spawnTuiAgent runtime', () => {await spawnPromise;expect(cleanupWorktreeFn).toHaveBeenCalledWith('agent-1', true, expect.objectContaining({- openPR: false,+ openPR: true,+ openPRIfMissing: true,prCompletion: 'review-then-merge',skipMerge: true,}));diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex d6b0592480..3dfd91aa47 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -49,6 +49,11 @@ 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.* `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.@@ -79,7 +84,7 @@ export async function cleanupAgentWorktree(agentId, success, options = {}) {return run;}-async function runCleanupAgentWorktree(agentId, success, { openPR = 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, { 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 } = {}) {const { getAgent: getAgentState } = await import('./cos.js');const agentState = await getAgentState(agentId).catch(() => null);if (!agentState?.metadata?.isWorktree) return [];@@ -113,8 +118,37 @@ async function runCleanupAgentWorktree(agentId, success, { openPR = false, prComreturn 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.+ //+ // 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.+ 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 }));+ if (verdict.category === PR_MISSING_CATEGORY) {+ 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 {+ emitLog('info', `🌳 ${agentId} owns its own pull request for ${worktreeBranch} — PortOS is standing down${verdict.ok ? '' : ` (${verdict.category})`}`, { agentId, branchName: worktreeBranch });+ openPRHere = false;+ }+ }+// When openPR is set and task succeeded, push branch and create PR instead of auto-merging- if (openPR && success) {+ if (openPRHere && success) {emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 8faf34190e..c890da83ec 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -198,6 +198,14 @@ vi.mock('./prWatcher.js', () => ({queuePendingMerge: (...args) => queuePendingMergeMock(...args)}));+// The `openPRIfMissing` 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', () => ({+ PR_MISSING_CATEGORY: 'pr-missing',+ verifyPrClaim: (...args) => verifyPrClaimMock(...args)+}));+vi.mock('./runner.js', () => ({executeApiRun: vi.fn(),executeCliRun: vi.fn(),@@ -480,6 +488,61 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });});+ // #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' };++ it('stands down when the agent already opened its own PR', async () => {+ verifyPrClaimMock.mockResolvedValue({ ok: true, branch: 'cos/task-abc123' });+ git.push.mockResolvedValue(undefined);++ await cleanupAgentWorktree('agent-1', true, netOpts);++ expect(git.push).not.toHaveBeenCalled();+ expect(git.createPR).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ });++ it('opens the PR itself when the forge confirms the agent opened none', async () => {+ verifyPrClaimMock.mockResolvedValue({ ok: false, category: 'pr-missing', branch: 'cos/task-abc123' });+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/42' });++ const warnings = await cleanupAgentWorktree('agent-1', true, netOpts);++ expect(git.createPR).toHaveBeenCalled();+ expect(warnings.some(w => w.includes('was told to open its own pull request'))).toBe(true);+ });++ 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' });++ await cleanupAgentWorktree('agent-1', true, netOpts);++ expect(git.createPR).not.toHaveBeenCalled();+ });++ it('stands down when the branch holds no commits — there was nothing to open a PR for', async () => {+ verifyPrClaimMock.mockResolvedValue({ ok: true, noChangesToShip: true, branch: 'cos/task-abc123' });++ await cleanupAgentWorktree('agent-1', true, netOpts);++ expect(git.createPR).not.toHaveBeenCalled();+ });++ it('still creates the PR outright when the net is off (a lean session hands off)', async () => {+ 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' });++ expect(verifyPrClaimMock).not.toHaveBeenCalled();+ expect(git.createPR).toHaveBeenCalled();+ });+ });+it('should record warning but still complete cleanup when Copilot review request fails', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/10' });