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
fix three ways the PR-ownership split could strand or duplicate a change request
[._.]/ Adam Eivy4d230f203683
diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.jsindex 931777146e..8acf471a06 100644--- a/server/lib/prDisposition.js+++ b/server/lib/prDisposition.js@@ -107,3 +107,24 @@ export function resolvePrCreation({ taskOpenPR, agentOwnsPr, prClaimVerified })if (!agentOwnsPr) return PR_CREATION.ALWAYS;return prClaimVerified ? PR_CREATION.NEVER : PR_CREATION.IF_MISSING;}++/**+ * Did a `verifyPrClaim` result actually come from the forge about a real branch?+ *+ * `{ ok: true }` alone does NOT mean "a PR exists" — it is also what the+ * function returns when there was nothing to verify (`prExpected` false, a+ * failed run, no workspace), when the branch could not be named (detached+ * HEAD → `{ ok: true, branch: null }`), and what the callers substitute when+ * the check itself threw or the run was user-terminated. Every one of those is+ * "we did not ask", and collapsing them into "asked and it's there" is how a+ * branch with no PR gets cleaned up as if it had one.+ *+ * A verified verdict therefore requires BOTH `ok` and a named `branch` — which+ * only the `found` and `noChangesToShip` shapes carry.+ *+ * @param {{ok?: boolean, branch?: string|null}|null|undefined} prVerdict+ * @returns {boolean}+ */+export function prClaimWasVerified(prVerdict) {+ return prVerdict?.ok === true && !!prVerdict.branch;+}diff --git a/server/lib/prDisposition.test.js b/server/lib/prDisposition.test.jsindex 9ee6f1686c..d676e655d8 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, PR_CREATION, resolvePrCompletion, resolvePrCreation } from './prDisposition.js';+import { PR_COMPLETIONS, PR_CREATION, prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from './prDisposition.js';describe('resolvePrCompletion', () => {it('prefers an explicit valid disposition', () => {@@ -37,9 +37,41 @@ describe('resolvePrCreation (#3733)', () => {expect(resolvePrCreation({ taskOpenPR: true, agentOwnsPr: true, prClaimVerified: false })).toBe(PR_CREATION.IF_MISSING);});+ it('backstops an owner whose claim was never actually verified', () => {+ // `prClaimVerified` is the ACTUAL verdict, not "was one expected" — finalize+ // substitutes a bare `{ok:true}` when its check throws or the run was+ // user-terminated, and a throw from finalize skips the assignment entirely.+ 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);});});++describe('prClaimWasVerified (#3733)', () => {+ it('accepts only a forge answer about a real branch', () => {+ expect(prClaimWasVerified({ ok: true, branch: 'feature-x' })).toBe(true);+ expect(prClaimWasVerified({ ok: true, branch: 'feature-x', noChangesToShip: true })).toBe(true);+ });++ it('rejects a bare ok — that is "nothing was verified", not "a PR exists"', () => {+ // verifyPrClaim returns this shape for a run it never checked (prExpected+ // false, a failed run, no workspace) and for a branch it could not name+ // (detached HEAD); both finalize and cleanup also substitute it when the+ // check throws or the run was user-terminated. Reading it as a confirmed PR+ // is what let a stand-down delete an unpushed branch with no PR.+ expect(prClaimWasVerified({ ok: true })).toBe(false);+ expect(prClaimWasVerified({ ok: true, branch: null })).toBe(false);+ expect(prClaimWasVerified({ ok: true, branch: '' })).toBe(false);+ });++ it('rejects a real negative verdict, and a missing one', () => {+ expect(prClaimWasVerified({ ok: false, branch: 'b', category: 'pr-missing' })).toBe(false);+ expect(prClaimWasVerified({ ok: false, branch: 'b', category: 'forge-unreachable' })).toBe(false);+ expect(prClaimWasVerified(undefined)).toBe(false);+ expect(prClaimWasVerified(null)).toBe(false);+ });+});diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 88deee3403..67f55360e3 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, resolvePrCreation } from '../lib/prDisposition.js';+import { prClaimWasVerified, 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';@@ -753,6 +753,12 @@ export async function spawnDirectly({providerCommand: provider?.command,leanMode: directLeanMode,});+ // Whether finalize's check ACTUALLY produced a forge answer (filled in from+ // its return below) — not the same question as whether one was expected.+ // Finalize substitutes `{ok:true}` for a user-terminated run and for a check+ // that threw, and a throw from finalize skips the assignment entirely; in all+ // three cases nothing was verified, so cleanup must ask rather than stand down.+ let directPrClaimVerified = false;// try/finally so a throw from finalizeAgent still runs the local// cleanup (worktree, pid unregister, activeAgents delete). Mirrors the@@ -781,6 +787,7 @@ export async function spawnDirectly({startedAt: agentData?.startedAt ?? null,});if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;+ directPrClaimVerified = prClaimWasVerified(finalized?.prVerdict);} finally {const directPrCompletion = resolvePrCompletion(task.metadata);const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);@@ -789,7 +796,7 @@ export async function spawnDirectly({prCreation: resolvePrCreation({taskOpenPR: directOpenPR,agentOwnsPr: directAgentOwnsPR,- prClaimVerified: directPrClaimExpected,+ prClaimVerified: directPrClaimVerified,}),prCompletion: directPrCompletion,...reviewOptions,diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 44bb792ed4..aa8825b3ca 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -29,7 +29,7 @@ import { isTruthyMeta } from './agentState.js';import { resolveReviewLoopOptions } from './codeReview.js';import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';import { resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';-import { canTypeSlashCommands, resolveOwnsPrWorkflow } from '../lib/slashdoInvocation.js';+import { resolveOwnsPrWorkflow } from '../lib/slashdoInvocation.js';const ROOT_DIR = PATHS.root;@@ -184,7 +184,7 @@ export async function handlePipelineProgression(task, agentId, success) {** @param {{ agentId: string, task: object, agent: object, effectiveSuccess: boolean, outputBuffer: string }} params*/-export async function runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess, outputBuffer }) {+export async function runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess, outputBuffer, prClaimVerified = false }) {// Fetch agent state once for JIRA, plan-question, and the resume pointer. Its// worktree fields are stamped once at registerAgent and never mutated, so passing// it to the release spares a re-read that would re-split the whole output.txt.@@ -192,7 +192,7 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectivconst agentState = await getAgentState(agentId).catch(() => null);try {- await runCompletionCleanupSteps({ agentId, task, agent, agentState, effectiveSuccess, outputBuffer });+ await runCompletionCleanupSteps({ agentId, task, agent, agentState, effectiveSuccess, outputBuffer, prClaimVerified });} finally {await releaseRetryHold({agentId,@@ -207,7 +207,7 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv* The cleanup steps themselves. Split from the public entry point above only so* the retry-hold release can wrap them in a `finally` without re-indenting them.*/-async function runCompletionCleanupSteps({ agentId, task, agent, agentState, effectiveSuccess, outputBuffer }) {+async function runCompletionCleanupSteps({ agentId, task, agent, agentState, effectiveSuccess, outputBuffer, prClaimVerified = false }) {// JIRA integration: push branch, create PR, comment on ticketconst jiraTicketId = task?.metadata?.jiraTicketId;const jiraBranch = task?.metadata?.jiraBranch;@@ -347,9 +347,11 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, effpersisted: 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);+ // `prClaimVerified` is the caller's — it carries whether finalize's check+ // ACTUALLY produced a forge answer for this run. Re-deriving it here from+ // `canTypeSlashCommands` would answer a different question ("was one+ // expected?") off a different expression than the one finalize used, and the+ // two silently disagree the moment a run's check throws or its finalize does.// 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 invokeddiff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex b4c697252f..4348429f6f 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -140,9 +140,12 @@ describe('handlePipelineProgression', () => {describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', () => {const prTask = { id: 't', taskType: 'user', metadata: { openPR: true } };- const cleanupCallFor = async (agent) => {+ // `prClaimVerified` is the caller's answer to "did finalize's PR-claim check+ // actually produce a forge verdict for this run?" — threaded in, never+ // re-derived here (see the note at its use site).+ const cleanupCallFor = async (agent, { prClaimVerified = false } = {}) => {await runAgentCompletionCleanup({- agentId: 'a1', task: prTask, agent, effectiveSuccess: true, outputBuffer: '',+ agentId: 'a1', task: prTask, agent, effectiveSuccess: true, outputBuffer: '', prClaimVerified,});// cleanupAgentWorktree(agentId, success, options) — options is the 3rd arg.return cleanupAgentWorktree.mock.calls.at(-1)[2];@@ -159,14 +162,28 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()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 });+ it('a claude session whose claim finalize VERIFIED needs no second forge query', async () => {+ // Finalize already asked the forge and got an answer; re-asking would be a+ // duplicate `gh pr list` on every completing Claude agent.+ const opts = await cleanupCallFor(+ { providerId: 'claude-code', providerCommand: 'claude', leanMode: false, ownsPrWorkflow: true },+ { prClaimVerified: true });expect(opts.prCreation).toBe('never');expect(opts.skipMerge).toBe(true);});+ it('an owner whose claim finalize did NOT verify still gets the backstop', async () => {+ // The regression this guards: `prExpected` being true does NOT mean a verdict+ // was produced. Finalize substitutes `{ok:true}` when the check throws or the+ // run was user-terminated, and a throw from finalize itself skips the+ // assignment entirely — deriving "already verified" from the provider would+ // stand cleanup down on a run whose PR was never confirmed, orphaning it.+ const opts = await cleanupCallFor(+ { providerId: 'claude-code', providerCommand: 'claude', leanMode: false, ownsPrWorkflow: true },+ { prClaimVerified: false });+ expect(opts.prCreation).toBe('if-missing');+ });+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,@@ -185,27 +202,27 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()});it.each([- ['claude-code', 'claude', 'never'],- ['claude-code-bedrock', 'claude', 'never'],+ ['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', 'never'],+ ['my-custom-agent', '/opt/homebrew/bin/claude', true],// 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) => {+ ['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.prCreation).toBe(prCreation);- expect(opts.skipMerge).toBe(prCreation === 'never');+ const opts = await cleanupCallFor({ providerId, providerCommand, leanMode: false }, { prClaimVerified: owns });+ expect(opts.prCreation).toBe(owns ? 'never' : 'always');+ 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' })).prCreation).toBe('never');+ expect((await cleanupCallFor({ providerId: 'claude-code' }, { prClaimVerified: true })).prCreation).toBe('never');expect((await cleanupCallFor({ providerId: 'codex-tui' })).prCreation).toBe('always');});});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 3c4dca34cf..1493d60b67 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -52,9 +52,10 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { createAgentRun } from './agentRunTracking.js';import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';-import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';+import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';-import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';+import { prClaimWasVerified } from '../lib/prDisposition.js';import { composeProviderEnv } from '../lib/cliChildEnv.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';@@ -466,12 +467,27 @@ async function runAgentSpawn(task) {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 }),+ // its own PR. Persisted rather than re-derived at cleanup time: the two+ // must agree exactly or PortOS double-fires `gh pr create`. A pre-upgrade+ // record has no value here, so cleanup falls back to the old+ // `canTypeSlashCommands` derivation — what those runs were prompted with.+ //+ // Stamped from `inlinePrLifecycleSection`, the SAME predicate that decided+ // whether the prompt above emitted the PR steps — NOT from `provider.type`+ // alone. Ownership depends on task shape too (read-only, no-code-output,+ // discard-worktree, JIRA/leave-open, and no-worktree runs are all told+ // PortOS owns the PR), and a provider-only stamp claimed ownership for+ // every one of them — routing a Creative Director reasoning run into the+ // did-you-open-it net, which then opened a PR for it and filed a HIGH+ // notification blaming the agent for skipping a step it was never given.+ ownsPrWorkflow: inlinePrLifecycleSection(task, {+ providerType: provider.type,+ providerId: provider.id,+ providerCommand: provider.command,+ leanMode,+ worktreeInfo,+ isTruthyMetaFn: isTruthyMeta,+ }) !== null,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@@ -1128,6 +1144,11 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// reach the cleanup below, which otherwise removes the worktree, deletes the// local branch, and skips the resume pointer for a run it believes succeeded.let cleanupSuccess = effectiveSuccess;+ // Whether finalize's PR-claim check actually produced a forge answer. Threaded+ // to cleanup rather than re-derived there: a run whose check threw, was+ // user-terminated, or whose finalize threw outright verified nothing, and+ // cleanup must ask the forge itself rather than assume the PR exists.+ let runnerPrClaimVerified = false;try {const finalized = await finalizeAgent({agentId,@@ -1146,6 +1167,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationstartedAt: Number.isFinite(runStartedAt) ? runStartedAt : null,});if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;+ runnerPrClaimVerified = prClaimWasVerified(finalized?.prVerdict);} catch (err) {finalizeError = err;emitLog('error', `finalizeAgent threw for ${agentId} (continuing cleanup): ${err.message}`, { agentId, error: err.message });@@ -1155,7 +1177,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// pipeline progression, the Creative Director chain hook, and worktree// cleanup (+ cleanup-warning notification and merge-recovery task). Runs// inside this try so a throw still hits the finally below.- await runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess: cleanupSuccess, outputBuffer });+ await runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess: cleanupSuccess, outputBuffer, prClaimVerified: runnerPrClaimVerified });// Surface a finalizeAgent throw to the caller after best-effort// cleanup completed — without this the runner harness would never seediff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 39f184699f..5bfb2c49d7 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -1441,11 +1441,15 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// …and a slashdo-free harness driving its OWN review loop inline needs the// 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.+ // leave-open, JIRA, or a merge gate with no reviewer to invoke — doesn't pay+ // for the read and the staging write. The reviewer-list term matters too: the+ // section only inlines the recipe when a SPAWNABLE CLI reviewer resolves, so a+ // copilot-only or username-only list (the default install) would otherwise+ // read + `atomicWrite` 56KB and then render nothing from it.const isInlineNeedingRecipes = inlinePrLifecycleSection(task, {- providerType, providerId, providerCommand, leanMode, isTruthyMetaFn,- }) === 'review-loop';+ providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,+ }) === 'review-loop'+ && resolveReviewerConfig(task.metadata, codeReviewDefaults, defaultReviewers).reviewers.some(isCliReviewer);const localAgentLoopBody = (isFollowUpNeedingRecipes || isInlineNeedingRecipes)? await loadSlashdoLib('local-agent-review-loop').catch(() => null): null;@@ -1940,19 +1944,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({+ // Does this session drive commit → push → PR → review → merge itself?+ //+ // ONE value answers both "emit the manual PR steps" and "emit the Review Loop+ // / Merge Gate section they point at", because they are the same decision:+ // the agent opens its own PR exactly when it also lands it. Splitting them let+ // a JIRA run be told to open a PR whose merge section was suppressed — and+ // PortOS opened that PR too. `inlineSection` also names WHICH section follows,+ // so the completion step's cross-reference can't name the wrong one.+ const inlineSection = inlinePrLifecycleSection(task, {providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,- leanMode,+ providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,});- // 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 ownsPrWorkflow = inlineSection !== null;const taskSections = [];const contractSections = [];@@ -2082,14 +2086,14 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet}// 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) {+ // section it is a step of. Gated on the SAME value that made that step emit,+ // so a dangling "step 4" cross-reference and an orphaned Review Loop section+ // are both unrepresentable.+ if (ownsPrWorkflow) {sections.push(buildInlineReviewLoopSection({taskId: task.id,branchName: worktreeInfo?.branchName || null,- runsReviewLoop: prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE,+ runsReviewLoop: inlineSection === 'review-loop',leaveOpen: false,localAgentLoopBody,localAgentLoopBodyPath,@@ -2303,6 +2307,9 @@ function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.M*/const INLINE_REVIEW_LOOP_STEP = 4;+/** Same coercion the callers pass in; a default so external callers needn't. */+const isTruthyMetaDefault = (v) => v === true || v === 'true';+/*** A git ref rendered into a shell command line in the prompt, or `fallback` when* there is no ref to render. Branch names are usually PortOS's own, but a@@ -2357,7 +2364,10 @@ function buildManualPrCreateStep(step, { branchName, baseBranch }) {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;+ // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the+ // leave-open exclusions — it is `inlinePrLifecycleSection() !== null` (see the+ // caller). Re-testing any of them here is how the two drifted apart before.+ const drivesOwnPr = ownsPrWorkflow;const simplifyStep = simplifyEnabled? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`: '1. (simplify disabled — skip)';@@ -2381,9 +2391,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETlet step = 3;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.`);+ lines.push(`${step++}. Work through the **${runsReviewLoop ? 'Review Loop' : 'Merge Gate'}** section below in full — it ends by merging the PR. Come back here when it is done.`);} 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.'@@ -2417,11 +2425,18 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET** @returns {'review-loop'|'merge-gate'|null}*/-function inlinePrLifecycleSection(task, { providerType, providerId, providerCommand, leanMode, isTruthyMetaFn }) {+export function inlinePrLifecycleSection(task, { providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn = isTruthyMetaDefault }) {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;+ // No worktree ⇒ no branch to name in `git push -u origin <branch>`, and the+ // one production shape here is a JIRA-ticket run (agentWorkspacePrep skips+ // worktree creation when a jiraBranch is set). Its PR is PortOS's to open and+ // a human's to land; telling the agent to open one too yields a PR opened+ // against a branch it had to guess at, and then a second `gh pr create` from+ // cleanup that fails "a pull request already exists".+ if (!worktreeInfo) return null;const metadata = task?.metadata || {};if (!isTruthyMetaFn(metadata.openPR)) return null;@@ -2475,7 +2490,7 @@ function buildInlineReviewLoopSection({// exactly as the merge-only follow-up gets.reviewLoopMergeOnly: !runsReviewLoop,sourceTaskId: taskId || 'unknown',- }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inline: true, inlineExitStep });+ }, { verbose: false, localAgentLoopBody, localAgentLoopBodyPath, inlineExitStep });}/**@@ -2533,7 +2548,9 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR// 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) {+ // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the+ // leave-open exclusions (it is `inlinePrLifecycleSection() !== null`).+ if (ownsPrWorkflow) {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@@ -2544,9 +2561,7 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PRbranchName: 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.`);+ lines.push(`${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;diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex a81bc19686..e8181ef902 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -413,24 +413,62 @@ describe('buildLightContextPrompt', () => {expect(prompt).not.toMatch(/gh pr merge/);});- it('an OpenCode TUI JIRA task opens its own PR but leaves it open instead of merging', () => {+ it('an OpenCode TUI JIRA task still hands its PR to PortOS — the agent opens one only when it also lands it', () => {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' });- // 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/);+ // A JIRA-tracked PR is a human's to land, so there is no merge section for+ // the agent to drive — and an agent told to open a PR it will never land+ // just races PortOS's own `gh pr create` for the same branch.+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).toMatch(/JIRA-linked human handoff/);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/);});+ it('a non-worktree run never gets the PR steps — there is no branch name to put in them', () => {+ // The production shape is a JIRA-ticket run (agentWorkspacePrep skips+ // worktree creation when a jiraBranch is set). Emitting the steps anyway+ // rendered a literal `<branch>` placeholder for the agent to guess at.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { openPR: true, reviewLoop: true, reviewers: ['codex'] } }),+ '/r',+ null,+ isTruthyMeta,+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).not.toMatch(/git push -u origin/);+ // …and no dangling "step 4 of the Completion Workflow above" pointing at+ // a section that was never emitted.+ expect(prompt).not.toMatch(/## Review Loop/);+ expect(prompt).not.toMatch(/\$PR_URL/);+ });++ it.each([+ ['a read-only task', { openPR: true, readOnly: true }],+ ['a no-code-output task', { openPR: true, noCodeOutput: true }],+ ['a Creative Director task', { openPR: true, creativeDirector: true }],+ ['a discard-worktree reasoning task', { openPR: true, discardWorktree: true }],+ ])('%s is never told it owns a PR, and gets no inline loop', (_label, metadata) => {+ // These completion contracts never mention a PR. Claiming ownership for+ // them routed a reasoning run into cleanup's did-you-open-it net, which+ // opened a PR for it and filed a HIGH notification blaming the agent.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata }),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMeta,+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' });+ expect(prompt).not.toMatch(/gh pr create/);+ expect(prompt).not.toMatch(/## Review Loop/);+ expect(prompt).not.toMatch(/## Merge Gate/);+ });+it('a leave-open review follow-up on a GitLab MR comments with glab, not gh', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex c24851247d..f1003d43d6 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, resolvePrCreation } from '../lib/prDisposition.js';+import { prClaimWasVerified, 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';@@ -1082,6 +1082,12 @@ export async function spawnTuiAgent({providerCommand: provider?.command,leanMode,});+ // Whether finalize's check ACTUALLY produced a forge answer, filled in from+ // its return below. Deliberately not `prClaimExpected`: finalize substitutes+ // `{ok:true}` for a user-terminated run and for a check that threw, and a+ // throw from finalize itself skips the assignment entirely — in all three+ // cases nothing was verified, so cleanup must ask rather than stand down.+ let prClaimVerified = false;// try/finally so a throw from finalizeAgent (e.g. processAgentCompletion// hook crash) still runs the local cleanup — sentinel removal, worktree@@ -1115,6 +1121,7 @@ export async function spawnTuiAgent({startedAt: agentData?.startedAt ?? null,});if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;+ prClaimVerified = prClaimWasVerified(finalized?.prVerdict);} finally {// This run's sentinel only — a sibling agent sharing this workspace owns// its own file and may still be running.@@ -1130,7 +1137,7 @@ export async function spawnTuiAgent({}): {};await cleanupWorktreeFn(agentId, cleanupSuccess, {- prCreation: resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified: prClaimExpected }),+ prCreation: resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified }),prCompletion: resolvePrCompletion(task.metadata),...reviewOptions,skipMerge: taskReviewLoopFollowUp || agentOwnsPR,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 6e759ec327..c870629e18 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -723,6 +723,11 @@ describe('spawnTuiAgent runtime', () => {it('does not double-fire a PR owned by a slashdo-capable Claude TUI', async () => {const cleanupWorktreeFn = vi.fn().mockResolvedValue(undefined);+ // finalize asked the forge and got an answer for a real branch — the only+ // shape that lets cleanup skip its own query (see `prClaimWasVerified`).+ vi.mocked(agentLifecycle.finalizeAgent).mockResolvedValueOnce({+ success: true, prVerdict: { ok: true, branch: 'cos/task-1/agent-1' },+ });const spawnPromise = runSpawn({provider: { id: 'claude-code-tui', name: 'Claude TUI', type: 'tui', command: 'claude', envVars: {} },task: {diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex c5678532c9..8f7453f97e 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, PR_CREATION, leavesPrForHuman } from '../lib/prDisposition.js';+import { PR_COMPLETIONS, PR_COMPLETION_VALUES, PR_CREATION, leavesPrForHuman, prClaimWasVerified } 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@@ -145,14 +145,25 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREATcreatePr = 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) {+ } else if (prClaimWasVerified(verdict)) {// `found`, or `noChangesToShip` — the branch holds nothing a PR could be// opened for. Either way the agent's contract was met.+ //+ // The `verdict.branch` term is load-bearing: `verifyPrClaim` has a THIRD+ // `ok: true` shape — `{ ok: true, branch: null }`, its explicit "we could+ // not name a branch, so nothing was verified" sentinel (a detached HEAD,+ // e.g. an agent that left an aborted rebase behind). Reading that as a+ // confirmed PR would stand down AND, because the stand-down is not marked+ // uncertain, let the cleanup below `git branch -D` a branch that was never+ // pushed and has no PR. Absent must not collapse into verified.emitLog('info', `🌳 ${agentId} opened its own pull request for ${worktreeBranch} — PortOS is standing down`, { agentId, branchName: worktreeBranch });} else {+ // `forge-unreachable`, or the no-branch sentinel above. Neither is+ // evidence a PR exists, and neither is evidence one is missing.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.`);+ const why = verdict.category || 'nothing to verify against';+ emitLog('warn', `🌳 Could not confirm a pull request for ${worktreeBranch} (${why}) — keeping the branch rather than opening a possible duplicate`, { agentId, branchName: worktreeBranch });+ warnings.push(`Could not confirm a pull request for ${worktreeBranch} (${why}); the branch was preserved for manual follow-up rather than risking a duplicate PR.`);}}@@ -340,6 +351,42 @@ async function runCleanupAgentWorktree(agentId, success, { prCreation = PR_CREATreturn warnings;}+ // A run that owned its PR workflow and FAILED may still have opened the PR+ // before it died — the prompt has it open one at step 3 and merge at step 4,+ // so a reap in between (max-runtime, idle reaper, spend limit, host shutdown)+ // leaves a real PR with nothing watching it (#3733). The old flow could not+ // produce this: PortOS opened the PR only on success and spawned the follow-up+ // in the same breath. The retry adopts the PR ("if `gh` reports the pull+ // request already exists, adopt it"), but a task that exhausts its retry+ // budget and goes `blocked` would strand it — and the orphaned-PR notifier+ // keys on a follow-up task's `reviewLoopPRUrl`, which an inline run never+ // creates. So hand it to the same follow-up machinery the old flow used.+ if (prCreation === PR_CREATION.IF_MISSING && !success) {+ const worktreePath = agentState.metadata.workspacePath || join(PATHS.worktrees, agentId);+ const { findPullRequestForBranch } = await import('./github.js');+ const { env } = await git.resolveForgeForRepo(worktreePath).catch(() => ({ env: null }));+ const found = await findPullRequestForBranch(worktreeBranch, { cwd: worktreePath, env: env || null })+ .catch(() => ({ status: 'unavailable' }));+ if (found.status === 'found' && found.url) {+ emitLog('warn', `🌳 ${agentId} failed after opening ${found.url} — handing the PR to a follow-up so it isn't stranded`, { agentId, prUrl: found.url, branchName: worktreeBranch });+ warnings.push(`Agent ${agentId} failed after opening ${found.url}; a follow-up was queued to land it.`);+ await spawnReviewLoopFollowUp({+ originalAgentId: agentId,+ originalTask,+ prUrl: found.url,+ prBranch: worktreeBranch,+ sourceWorkspace,+ prCompletion: PR_COMPLETION_VALUES.includes(prCompletion) ? prCompletion : PR_COMPLETIONS.REVIEW_THEN_MERGE,+ reviewers, usernames, optionalReviewers, reviewerMaxRounds,+ reviewStopMode, reviewerApplies, reviewerModels, reviewerEfforts,+ leaveOpen: leavesPrForHuman(originalTask),+ }).catch(err => {+ emitLog('warn', `🌳 Failed to spawn a follow-up for orphaned ${found.url}: ${err.message}`, { agentId });+ warnings.push(`Could not queue a follow-up for ${found.url}: ${err.message}`);+ });+ }+ }+// Default: auto-merge on success, just cleanup on failure.// Review-loop follow-up agents pass skipMerge: true because gh pr merge already// handled the merge upstream — re-merging the worktree branch into the localdiff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 482d2599ee..75d26e5acd 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -541,6 +541,23 @@ describe('cleanupAgentWorktree - PR-creation path', () => {expect(warnings).toEqual([]);});+ it('treats the no-branch sentinel as uncertain — it is NOT a confirmed PR', async () => {+ // `verifyPrClaim` returns `{ok:true, branch:null}` when it could not name a+ // branch (detached HEAD — e.g. an agent that left an aborted rebase+ // behind). Reading that third `ok:true` shape as "the agent opened its PR"+ // stood cleanup down AND, because the stand-down was not marked uncertain,+ // let `removeWorktree` force-delete a branch that was never pushed and has+ // no PR — losing the commits outright.+ verifyPrClaimMock.mockResolvedValue({ ok: true, branch: null });++ const warnings = 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 }));+ expect(warnings.some(w => w.includes('Could not confirm a pull request'))).toBe(true);+ });+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'));