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
stop cleanup re-creating the PR a slashdo-capable agent already opened (#6869)
[._.]/ Adam Eivy6cd0178796ba
diff --git a/server/lib/README.md b/server/lib/README.mdindex 06fbb27aaa..3cc2877119 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -567,8 +567,8 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `orchestrationProfile.js` | Orchestrated CoS execution (#5992) — `ORCHESTRATION_MODES` / `ORCHESTRATION_ROLES` (architect, implementer, reviewer), `normalizeOrchestrationProfile` / `normalizeOrchestrationMode`, `isOrchestratedTask` / `roleAssignment` (both inert on a `direct` task, so a stored profile stays opt-in), the six-part `SPEC_PARTS` contract a delegated context-free lane needs, plus `parseReasoningDirective` (an unsupported rung is an error, never a silent downgrade). || `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. || `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. |-| `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, ownsPrWorkflow, leaveOpen})` decides whether a completing run actually owed its own PR merge; `resolveMergeGateVerdict({prProbe, summary, alreadyReprompted})` classifies a run that did (`merged` / `unreadable` / `leave-open-stated` / `needs-reprompt` / `reprompt-exhausted`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |-| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |+| `mergeGateContract.js` | `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary, alreadyReprompted})` classifies a run that did (`merged` / `unreadable` / `leave-open-stated` / `needs-reprompt` / `reprompt-exhausted`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |+| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. || `prReviewReport.js` | Owns the structured PR-decision contract end to end: `PR_REVIEW_DECISION_CONTRACT` is the envelope both review producers (pr-reviewer stage 3, issue-watcher reasoning pass) interpolate into their prompts, `normalizeReviewReport` bounds what comes back, `reviewReportText` hands every model-authored string to the abuse scan, and `renderReviewBody`/`renderFinding` turn it into the markdown a human reads on the PR page — verdict banner, scope line, blocking/non-blocking index anchored to `path:line`, test-evidence bullets (`TEST_EVIDENCE_STATUSES` keeps `fail` for "the change is broken", with `expected-fail` and `blocked` for the non-zero exits that say nothing about it), notes, collapsed verified-claims list, and inline comments with an optional GitHub suggestion block. Bounded by `MAX_REVIEW_BODY_CHARS`, dropping whole low-priority sections instead of truncating mid-sentence. Pure. || `repoStateExpectations.js` | Post-completion repo-state audit, pure half. `resolveRepoStateExpectation({...})` answers whether one finished worktree agent should be audited — naming every not-audited path via `REPO_STATE_SKIPS` (a failed run is preserved for its retry; a review-loop follow-up or pr-watcher pending merge still owns the branch) — and returns just `staysOpen` + `prExpected`, from which `classifyRepoStateIssues(expectation, observed)` derives every check into `REPO_STATE_ISSUES` codes. Observations are tri-state: `null` ("could not ask") never produces an issue. `repoStateVerificationEnabled(app)` reads the per-app `verifyRepoStateOnCompletion` switch (unset = on). Probing + remediation live in `services/agentRepoStateVerification.js`. |@@ -580,7 +580,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `shellReadinessProbe.js` | `buildReadinessProbe(nonce, shell)` — the round-trip "can this shell actually run commands yet?" probe `createShellSession`'s `waitForPromptReady` sends and watches for, in the dialect the session speaks: POSIX `printf '%s\n' 'PORTOSRDY''<nonce>'` (unchanged), PowerShell `Write-Output ('PORTOSRDY' + '<nonce>')`, `cmd.exe` → `null` (no split-literal concatenation operator exists there, so the caller skips straight to the bounded fallback timer instead of risking an always-matching probe). The split-literal property is load-bearing in every dialect: the probe source never contains the assembled marker, so seeing it in the output can only mean the shell executed the probe. || `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). || `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. `client/src/lib/slashdoCatalog.js` decorates this list with button styling rather than restating it. |-| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `resolveOwnsPrWorkflow({persisted, …})` reading the value stamped on a completed agent record and falling back to the slash-command gate for pre-#3733 records; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); `resolvePrOwnership({task, isTruthyMeta, persisted, providerId, providerCommand, leanMode})` → `{taskOpenPR, agentOwnsPR, prClaimExpected}` — the persisted-first, task-shape-aware ownership verdict plus provider descriptor that both in-process spawners (TUI `finish()`, direct-CLI `close`) hand to `runSpawnerCompletionCleanup`, so the ownership question and the cleanup acting on it cannot disagree; and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. |+| `slashdoInvocation.js` | Resolves how a bundled slashdo workflow is invoked on a given host CLI. `resolveSlashdoInvocation({command, args, providerId, providerCommand, leanMode})` → `{command, args, style, invocation, skillName}` for the three shapes slashdo's installer produces (`slash-namespaced` `/do:x` for Claude Code, `slash-flat` `/do-x` for OpenCode, `skill` — an Agent Skill selected by name — for codex/grok/antigravity and any unidentified provider). Plus `buildSlashdoSection(resolved, body, {bodyPath, reviewWith})` (pure renderer; the caller loads the body via `loadSlashdoFile`. With a staged `bodyPath` it emits a filesystem pointer for deferred bundles or bodies over `SLASHDO_INLINE_BUDGET_CHARS` (24,000)), `unreachableReviewerIncludes({reviewers, usernames})` → the reviewer-variant lib includes a run can never reach (the `skipIncludes` set for `loadSlashdoFile`; defaults to pruning NOTHING for an unresolved/unrecognized reviewer set, since an over-pruned prompt is worse than a fat one), `SLASHDO_REVIEWER_INCLUDES`/`SLASHDO_REVIEWER_INCLUDE_NAMES`, `slashdoSkillName`, `isValidSlashdoCommand` (the one definition of the safe bare-command shape, also gating the Zod schemas), `agentOwnsPrWorkflow({providerType, leanMode})` — a strictly WEAKER question than typing a slash command: any local `cli`/`tui` harness that is not a lean `--bare` session drives its own commit → push → PR → review → merge (#3733), with `PR_OPENED_BY` (`agent-slashdo` / `agent-inline` / `portos`) naming WHO opens a run’s PR per the prompt it was given (stamped as `metadata.prOpenedBy` by `promptOpensOwnPr`, services/promptSections/completion.js) and `resolvePrOpenedBy({persistedPrOpenedBy, persistedOwnsPrWorkflow, …})` reading it back for a completed agent — mapping both the legacy #3733 `ownsPrWorkflow` boolean and a pre-#3733 record with no stamp at all; `oversizedBodyPointer(bodyPath, body)` (the shared "it is on disk, go read it" line); `resolvePrOwnership({task, isTruthyMeta, persistedPrOpenedBy, persistedOwnsPrWorkflow, providerId, providerCommand, leanMode})` → `{taskOpenPR, prOpenedBy, agentOpensOwnPr, prClaimExpected}` — the persisted-first, task-shape-aware ownership verdict plus provider descriptor that both in-process spawners (TUI `finish()`, direct-CLI `close`) hand to `runSpawnerCompletionCleanup`, so the ownership question and the cleanup acting on it cannot disagree; and `canTypeSlashCommands()` — the single predicate behind `agentPromptBuilder.js`'s completion-workflow gates (can this session TYPE `/do:pr` / `/simplify`?), which reads `resolveSlashdoStyle`'s `assumeClaudeWhenUnknown` posture because the spawners resolve a blank command to `claude`. Provider is only known at spawn time, so a task persists the BARE command name — never a rendered `/do:x` string. || `slashdoLoader.js` | Shared slashdo renderer adapter: `loadSlashdoBundle(cmd, {stripFrontmatter, skipIncludes, defer})` returns an entrypoint and supporting files using the bundled transformer; `loadSlashdoFile` returns a self-contained command; `loadSlashdoLib` expands explicit reads for legacy recipes without traversing see-also links. `writeResolvedSlashdoBody(cmd, body, {files})` stages immutable content-addressed bundles under `PATHS.slashdoResolved`, with relative library paths and the entrypoint written last. Missing required references fail dispatch rather than silently removing workflow gates. || `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `services/promptRunner.js`'s fallback mark-and-pick. || `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 59befd2162..3ca8dfd40a 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -49,7 +49,7 @@ export function buildAgentRegistration({providerEndpoint,localPromptBudget,leanMode,- ownsPrWorkflow,+ prOpenedBy,claimFlowTask,selectedModel,modelSelection,@@ -79,11 +79,11 @@ export function buildAgentRegistration({taskType: task.taskType,priority: task.priority,providerId: provider.id,- // Persisted alongside the id because the cleanup path's `agentOwnsPR` gate- // must derive from the SAME `canTypeSlashCommands` predicate the prompt used- // to decide whether the agent opens its own PR (#3114). An id alone can't- // answer that — a path-configured `claude` under a custom id is slashdo-- // capable, and a lean `--bare` session is not.+ // Persisted alongside the id because the cleanup path's `agentOpensOwnPr`+ // gate must derive from the SAME `canTypeSlashCommands` predicate the prompt+ // used to decide whether the agent opens its own PR (#3114). An id alone+ // can't answer that — a path-configured `claude` under a custom id is+ // slashdo-capable, and a lean `--bare` session is not.providerCommand: provider.command || null,// The endpoint this agent's inference actually lands on, stamped for the// same reason as the command above: the per-local-endpoint spawn cap@@ -104,21 +104,31 @@ export function buildAgentRegistration({// "no estimate", never as a small one, so it stays absent rather than 0.localPromptBudget,leanMode,- // Whether THIS run's prompt told the agent to push, open, review, and merge- // 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.+ // WHO opens this run's PR (`agent-slashdo` / `agent-inline` / `portos`),+ // per the prompt this run was actually given. 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+ // `resolvePrOpenedBy` maps whatever it does carry.//- // 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,+ // Stamped from `promptOpensOwnPr`, the SAME predicate that decided what the+ // completion section above says — NOT from `provider.type` alone. It+ // depends on the task shape (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.+ //+ // It ALSO depends on whether the host can type a slash command, and that is+ // the half the predecessor got backwards (#6869). The stamp used to be+ // `inlinePrLifecycleSection(…) !== null`, which is FALSE for a slashdo-+ // capable Claude TUI/CLI — the host that most often opens its own PR, via+ // `/do:pr`. Those runs read as PortOS-owned, so cleanup pushed the branch+ // again and re-created a PR that already existed. `agent-slashdo` is that+ // case; `agent-inline` is the codex/grok/agy harness handed the plain+ // `git`/`gh` steps, and it is the only value that owes the #5876 merge-gate+ // check, because it is the only prompt carrying a Merge Gate section.+ prOpenedBy,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 Agentdiff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.jsindex 83e3eabc89..bdb9d4f8d8 100644--- a/server/lib/mergeGateContract.js+++ b/server/lib/mergeGateContract.js@@ -1,9 +1,10 @@/*** Merge Gate contract check (#5876)*- * A worktree agent told to own its own PR lifecycle (`ownsPrWorkflow`) is- * handed a "Merge Gate" section that ends with "Confirm the merge before- * exiting: … must return MERGED". Nothing verified that it actually did —+ * A worktree agent handed the INLINE PR lifecycle — the plain `git`/`gh` steps,+ * because its host cannot type `/do:pr` — gets a "Merge Gate" section that ends+ * with "Confirm the merge before exiting: … must return MERGED". Nothing+ * verified that it actually did —* the completion sentinel was accepted on its face, and only the post-* teardown `agentRepoStateVerification.js` audit ever caught a run that quit* with the PR still open, at the cost of a whole cold recovery agent to@@ -19,20 +20,24 @@*//**- * Did this run's own task shape ask it to own the merge?+ * Did this run's own prompt ask it to work a Merge Gate?*- * Only the AND of all three counts: a run PortOS itself opens or merges the- * PR for (`taskOpenPR` false, or `ownsPrWorkflow` false — a lean `--bare`- * session, a read-only/no-code-output run, or an HTTP `api` provider) never- * owed one, and neither does a run whose prompt explicitly hands the PR to a- * human (`leaveOpen` true — JIRA hand-off, claim flow, or an exempt task- * type; see `leavesPrForHuman` in `prDisposition.js`).+ * Only the AND of all three counts, and `rendersInlinePrLifecycle` is the+ * narrow one: there is a gate to hold the agent to only when the prompt+ * actually rendered that section. A run PortOS opens or merges the PR for+ * (`taskOpenPR` false, or a lean `--bare` session / read-only / no-code-output+ * run / HTTP `api` provider) never owed one; nor does a run whose prompt hands+ * the PR to a human (`leaveOpen` true — JIRA hand-off, claim flow, or an exempt+ * task type; see `leavesPrForHuman` in `prDisposition.js`); nor does a+ * slashdo-capable run, whose `/do:pr` merges inside that one command and whose+ * prompt therefore carries no Merge Gate steps for the re-prompt to point back+ * at. Callers pass `prOpenedBy === 'agent-inline'` (#6869).*- * @param {{taskOpenPR: boolean, ownsPrWorkflow: boolean, leaveOpen: boolean}} params+ * @param {{taskOpenPR: boolean, rendersInlinePrLifecycle: boolean, leaveOpen: boolean}} params* @returns {boolean}*/-export function mergeGateOwed({ taskOpenPR, ownsPrWorkflow, leaveOpen }) {- return !!taskOpenPR && !!ownsPrWorkflow && !leaveOpen;+export function mergeGateOwed({ taskOpenPR, rendersInlinePrLifecycle, leaveOpen }) {+ return !!taskOpenPR && !!rendersInlinePrLifecycle && !leaveOpen;}// What the Merge Gate's own step 4 asks the agent to say when it deliberatelydiff --git a/server/lib/mergeGateContract.test.js b/server/lib/mergeGateContract.test.jsindex ca42e897ec..72d6e57b2f 100644--- a/server/lib/mergeGateContract.test.js+++ b/server/lib/mergeGateContract.test.js@@ -3,23 +3,23 @@ import { mergeGateOwed, summaryStatesLeaveOpen, resolveMergeGateVerdict, buildMedescribe('mergeGateOwed', () => {it('is owed only when the task asked for a PR, the agent owns the workflow, and nobody hands it to a human', () => {- expect(mergeGateOwed({ taskOpenPR: true, ownsPrWorkflow: true, leaveOpen: false })).toBe(true);+ expect(mergeGateOwed({ taskOpenPR: true, rendersInlinePrLifecycle: true, leaveOpen: false })).toBe(true);});it('is not owed when the task never asked for a PR (PortOS still backstops it)', () => {- expect(mergeGateOwed({ taskOpenPR: false, ownsPrWorkflow: true, leaveOpen: false })).toBe(false);+ expect(mergeGateOwed({ taskOpenPR: false, rendersInlinePrLifecycle: true, leaveOpen: false })).toBe(false);});it('is not owed when the agent does not own the PR workflow (a lean --bare session)', () => {- expect(mergeGateOwed({ taskOpenPR: true, ownsPrWorkflow: false, leaveOpen: false })).toBe(false);+ expect(mergeGateOwed({ taskOpenPR: true, rendersInlinePrLifecycle: false, leaveOpen: false })).toBe(false);});it('is not owed when the task hands the PR to a human (JIRA, claim flow)', () => {- expect(mergeGateOwed({ taskOpenPR: true, ownsPrWorkflow: true, leaveOpen: true })).toBe(false);+ expect(mergeGateOwed({ taskOpenPR: true, rendersInlinePrLifecycle: true, leaveOpen: true })).toBe(false);});it('is not owed for a read-only / no-code-output run (neither openPR nor ownership)', () => {- expect(mergeGateOwed({ taskOpenPR: false, ownsPrWorkflow: false, leaveOpen: false })).toBe(false);+ expect(mergeGateOwed({ taskOpenPR: false, rendersInlinePrLifecycle: false, leaveOpen: false })).toBe(false);});});diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.jsindex bd30790888..abca442df7 100644--- a/server/lib/prDisposition.js+++ b/server/lib/prDisposition.js@@ -97,16 +97,16 @@ export const PR_CREATION = Object.freeze({** @param {Object} opts* @param {boolean} opts.taskOpenPR - the task asked for a PR at all- * @param {boolean} opts.agentOwnsPr - the prompt told the agent to open it+ * @param {boolean} opts.agentOpensOwnPr - the prompt told the agent to open it* @param {boolean} opts.prClaimVerified - finalize ran `verifyPrClaim` for this* run (i.e. `prExpected` was true), so cleanup must not ask a second time* @param {boolean} [opts.noChangesToShip] - finalize verified an opted-in audit* left no commits and no change request, so cleanup must not create an empty PR* @returns {string} a `PR_CREATION` value*/-export function resolvePrCreation({ taskOpenPR, agentOwnsPr, prClaimVerified, noChangesToShip = false }) {+export function resolvePrCreation({ taskOpenPR, agentOpensOwnPr, prClaimVerified, noChangesToShip = false }) {if (!taskOpenPR || noChangesToShip) return PR_CREATION.NEVER;- if (!agentOwnsPr) return PR_CREATION.ALWAYS;+ if (!agentOpensOwnPr) return PR_CREATION.ALWAYS;return prClaimVerified ? PR_CREATION.NEVER : PR_CREATION.IF_MISSING;}diff --git a/server/lib/prDisposition.test.js b/server/lib/prDisposition.test.jsindex 45b7d01b00..be30656afb 100644--- a/server/lib/prDisposition.test.js+++ b/server/lib/prDisposition.test.js@@ -24,39 +24,39 @@ describe('resolvePrCompletion', () => {describe('resolvePrCreation (#3733)', () => {it('never creates one for a task that asked for no PR', () => {- expect(resolvePrCreation({ taskOpenPR: false, agentOwnsPr: false, prClaimVerified: false })).toBe(PR_CREATION.NEVER);+ expect(resolvePrCreation({ taskOpenPR: false, agentOpensOwnPr: false, prClaimVerified: false })).toBe(PR_CREATION.NEVER);// …even if the agent would otherwise have owned it.- expect(resolvePrCreation({ taskOpenPR: false, agentOwnsPr: true, prClaimVerified: false })).toBe(PR_CREATION.NEVER);+ expect(resolvePrCreation({ taskOpenPR: false, agentOpensOwnPr: true, prClaimVerified: false })).toBe(PR_CREATION.NEVER);});it('creates one outright when PortOS owns the lifecycle (a lean --bare session)', () => {- expect(resolvePrCreation({ taskOpenPR: true, agentOwnsPr: false, prClaimVerified: false })).toBe(PR_CREATION.ALWAYS);+ expect(resolvePrCreation({ taskOpenPR: true, agentOpensOwnPr: false, prClaimVerified: false })).toBe(PR_CREATION.ALWAYS);});it('never creates an empty PR after finalize proves an opted-in audit is a no-op', () => {expect(resolvePrCreation({taskOpenPR: true,- agentOwnsPr: false,+ agentOpensOwnPr: false,prClaimVerified: false,noChangesToShip: true,})).toBe(PR_CREATION.NEVER);});it('backstops an owner finalize did NOT verify — the slashdo-free harnesses', () => {- expect(resolvePrCreation({ taskOpenPR: true, agentOwnsPr: true, prClaimVerified: false })).toBe(PR_CREATION.IF_MISSING);+ expect(resolvePrCreation({ taskOpenPR: true, agentOpensOwnPr: 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);+ expect(resolvePrCreation({ taskOpenPR: true, agentOpensOwnPr: 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);+ expect(resolvePrCreation({ taskOpenPR: true, agentOpensOwnPr: true, prClaimVerified: true })).toBe(PR_CREATION.NEVER);});});diff --git a/server/lib/slashdoInvocation.js b/server/lib/slashdoInvocation.jsindex ec93adcfc8..fcf52e359b 100644--- a/server/lib/slashdoInvocation.js+++ b/server/lib/slashdoInvocation.js@@ -503,10 +503,12 @@ const HARNESS_PROVIDER_TYPES = new Set([PROVIDER_TYPES.CLI, PROVIDER_TYPES.TUI])* 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.+ * This is the HOST half of the question only. Whether a given run's prompt+ * actually handed it the PR depends on the task shape too, and that combined+ * answer is stamped on the agent record as `metadata.prOpenedBy` — see+ * `promptOpensOwnPr` in `services/promptSections/completion.js`, which is the+ * predicate the prompt itself is rendered from, and `resolvePrOpenedBy` below,+ * which reads the stamp back at cleanup time.** @param {Object} [opts]* @param {string|null} [opts.providerType] - `'tui' | 'cli' | 'api'`@@ -519,63 +521,119 @@ export function agentOwnsPrWorkflow({ providerType = null, leanMode = false } =}/**- * The same answer for a COMPLETED agent, read off its record.- *- * `metadata.ownsPrWorkflow` is stamped at spawn time from the resolved provider,- * and is authoritative: cleanup must act on what the prompt actually said, not- * on a fresh derivation that could disagree with it.- *- * A record written before #3733 carries no such key. Those runs really were- * prompted by the old builder, whose gate was `canTypeSlashCommands` — so that- * is the correct answer for them, and it lives here next to the predicate rather- * than inline in a service, where the next caller would miss it.+ * WHO opens a run's pull request, per the prompt that run was actually given.+ * Stamped on the agent record at spawn time as `metadata.prOpenedBy` and read+ * back by cleanup; `promptOpensOwnPr` (services/promptSections/completion.js)+ * is the single producer.+ *+ * Three values rather than a boolean because the two agent-owned cases behave+ * differently downstream and a boolean kept collapsing them:+ * - `agent-slashdo` — the completion section handed it `/do:pr`, which pushes,+ * opens, reviews and merges the PR in one command.+ * - `agent-inline` — the completion section handed it the plain `git`/`gh`+ * steps plus the inline Review Loop / **Merge Gate** section. Only this value+ * owes the #5876 merge-gate check, because only this prompt has that section.+ * - `portos` — the prompt told the agent NOT to open a PR; the+ * post-completion cleanup opens it.+ */+export const PR_OPENED_BY = Object.freeze({+ AGENT_SLASHDO: 'agent-slashdo',+ AGENT_INLINE: 'agent-inline',+ PORTOS: 'portos',+});++const PR_OPENED_BY_VALUES = new Set(Object.values(PR_OPENED_BY));++/**+ * The stamp for a COMPLETED agent, read off its record — accepting every shape+ * a record can carry, because other installs upgrade on their own schedule and+ * their older records keep arriving here.+ *+ * 1. `metadata.prOpenedBy` (this version) is authoritative: cleanup must act on+ * what the prompt actually said, not on a fresh derivation that could+ * disagree with it.+ * 2. A slashdo-capable host resolves to `agent-slashdo` whatever else the record+ * carries. This is where #6869 lands on legacy data: the #3733 boolean+ * `metadata.ownsPrWorkflow` answered "did the prompt render the INLINE PR+ * section", which is `false` for exactly the hosts that run `/do:pr` — so+ * reading that boolean at face value for a Claude record is what had cleanup+ * re-push and re-create a PR the agent had already opened.+ * 3. Otherwise the #3733 boolean, when the record has one: a slashdo-free+ * harness stamped `true` really was told to run `gh pr create` itself.+ * 4. Otherwise `portos` — which for a record written before #3733 (no key at+ * all) is the same answer the old `canTypeSlashCommands` fallback gave, since+ * rule 2 already claimed every slashdo-capable one.** @param {Object} opts- * @param {boolean|undefined} opts.persisted - `metadata.ownsPrWorkflow`+ * @param {string|undefined} opts.persistedPrOpenedBy - `metadata.prOpenedBy`+ * @param {boolean|undefined} [opts.persistedOwnsPrWorkflow] - the legacy+ * `metadata.ownsPrWorkflow` boolean (#3733)* @param {string|null} [opts.providerId]* @param {string|null} [opts.providerCommand]* @param {boolean} [opts.leanMode]- * @returns {boolean}+ * @returns {string} a `PR_OPENED_BY` value*/-export function resolveOwnsPrWorkflow({ persisted, providerId = null, providerCommand = null, leanMode = false }) {- if (typeof persisted === 'boolean') return persisted;- return canTypeSlashCommands({ providerId, providerCommand, leanMode });+export function resolvePrOpenedBy({+ persistedPrOpenedBy,+ persistedOwnsPrWorkflow,+ providerId = null,+ providerCommand = null,+ leanMode = false,+}) {+ if (PR_OPENED_BY_VALUES.has(persistedPrOpenedBy)) return persistedPrOpenedBy;+ if (canTypeSlashCommands({ providerId, providerCommand, leanMode })) return PR_OPENED_BY.AGENT_SLASHDO;+ if (persistedOwnsPrWorkflow === true) return PR_OPENED_BY.AGENT_INLINE;+ return PR_OPENED_BY.PORTOS;}/**- * The three PR answers a spawned run needs, from ONE reading of the task and- * the persisted prompt verdict and provider descriptor. Both in-process spawners+ * The PR answers a spawned run needs, from ONE reading of the task, the+ * persisted prompt verdict and the provider descriptor. Both in-process spawners* call this once — the TUI `finish()` path up front, because its merge-gate contract check (#5876)- * reads `agentOwnsPR` before the run completes; the direct-CLI `close` handler+ * reads the ownership answer before the run completes; the direct-CLI `close` handler* at exit — and hand the result to `runSpawnerCompletionCleanup`, so the* ownership question and the cleanup that acts on it can never read different* answers (#3733).*- * `agentOwnsPR` (does the harness drive its own push → PR → merge?) and- * `prClaimExpected` (does finalize verify a PR claim for it?) are deliberately- * two predicates: a harness that owns the workflow but cannot TYPE `/do:pr` is- * backstopped by cleanup, which re-checks the forge and opens the PR itself- * when the agent skipped it — failing it at finalize for a PR that is about to- * exist would turn a recovered hand-off into a false needs-attention (#3358).- *- * Like the runner-event path, ownership reads the prompt's persisted,- * task-shape-aware verdict first, falling back to the slash-command gate only- * for legacy runs without a stamp.+ * `agentOpensOwnPr` (did the prompt hand this run its own push → PR → merge?)+ * and `prClaimExpected` (does finalize verify a PR claim for it?) are+ * deliberately two predicates: a harness that owns the workflow but cannot TYPE+ * `/do:pr` is backstopped by cleanup, which re-checks the forge and opens the PR+ * itself when the agent skipped it — failing it at finalize for a PR that is+ * about to exist would turn a recovered hand-off into a false needs-attention+ * (#3358). `prClaimExpected` therefore stays the raw slash-command capability,+ * matching the runner path's own derivation in `agentLifecycle.js`; it asks+ * "will a PR already be there when finalize looks?", not "who was told to open+ * one".** @param {Object} opts* @param {Object} opts.task* @param {(value: unknown) => boolean} opts.isTruthyMeta- * @param {boolean|undefined} opts.persisted - `metadata.ownsPrWorkflow`+ * @param {string|undefined} opts.persistedPrOpenedBy - `metadata.prOpenedBy`+ * @param {boolean|undefined} [opts.persistedOwnsPrWorkflow] - the legacy+ * `metadata.ownsPrWorkflow` boolean (#3733)* @param {string|null} [opts.providerId]* @param {string|null} [opts.providerCommand]* @param {boolean} [opts.leanMode]- * @returns {{ taskOpenPR: boolean, agentOwnsPR: boolean, prClaimExpected: boolean }}+ * @returns {{ taskOpenPR: boolean, prOpenedBy: string, agentOpensOwnPr: boolean, prClaimExpected: boolean }}*/-export function resolvePrOwnership({ task, isTruthyMeta, persisted, providerId = null, providerCommand = null, leanMode = false }) {+export function resolvePrOwnership({+ task,+ isTruthyMeta,+ persistedPrOpenedBy,+ persistedOwnsPrWorkflow,+ providerId = null,+ providerCommand = null,+ leanMode = false,+}) {const taskOpenPR = isTruthyMeta(task?.metadata?.openPR);+ const prOpenedBy = resolvePrOpenedBy({+ persistedPrOpenedBy, persistedOwnsPrWorkflow, providerId, providerCommand, leanMode,+ });return {taskOpenPR,- agentOwnsPR: taskOpenPR && resolveOwnsPrWorkflow({ persisted, providerId, providerCommand, leanMode }),+ prOpenedBy,+ agentOpensOwnPr: taskOpenPR && prOpenedBy !== PR_OPENED_BY.PORTOS,prClaimExpected: taskOpenPR && canTypeSlashCommands({ providerId, providerCommand, leanMode }),};}diff --git a/server/lib/slashdoInvocation.test.js b/server/lib/slashdoInvocation.test.jsindex 457e6cc97d..9aae2ae41e 100644--- a/server/lib/slashdoInvocation.test.js+++ b/server/lib/slashdoInvocation.test.js@@ -7,7 +7,8 @@ import {agentOwnsPrWorkflow,buildSlashdoSection,canTypeSlashCommands,- resolveOwnsPrWorkflow,+ PR_OPENED_BY,+ resolvePrOpenedBy,resolvePrOwnership,isValidSlashdoCommand,parseExplicitReviewWith,@@ -183,26 +184,57 @@ describe('agentOwnsPrWorkflow (#3733)', () => {});});-describe('resolveOwnsPrWorkflow (#3733)', () => {+describe('resolvePrOpenedBy', () => {+ const resolveFor = (overrides = {}) => resolvePrOpenedBy({ providerId: 'codex', providerCommand: 'codex', ...overrides });+it('trusts the stamp — cleanup must act on what the prompt actually said', () => {// Including when the stamp disagrees with a fresh derivation: a provider// reconfigured mid-run must not change the answer for an agent already// prompted under the old one.- expect(resolveOwnsPrWorkflow({ persisted: true, providerId: 'codex', providerCommand: 'codex' })).toBe(true);- expect(resolveOwnsPrWorkflow({ persisted: false, providerId: 'claude-code', providerCommand: 'claude' })).toBe(false);+ expect(resolveFor({ persistedPrOpenedBy: PR_OPENED_BY.PORTOS, providerId: 'claude-code', providerCommand: 'claude' }))+ .toBe(PR_OPENED_BY.PORTOS);+ expect(resolveFor({ persistedPrOpenedBy: PR_OPENED_BY.AGENT_INLINE })).toBe(PR_OPENED_BY.AGENT_INLINE);+ expect(resolveFor({ persistedPrOpenedBy: PR_OPENED_BY.AGENT_SLASHDO, leanMode: true })).toBe(PR_OPENED_BY.AGENT_SLASHDO);+ });++ it('ignores an unrecognized stamp rather than trusting it', () => {+ // A value from a NEWER install (other installs upgrade on their own+ // schedule) must fall through to a derivation this version understands,+ // not be handed to `!== PORTOS` as if it named an agent.+ expect(resolveFor({ persistedPrOpenedBy: 'agent-something-new' })).toBe(PR_OPENED_BY.PORTOS);+ expect(resolveFor({ persistedPrOpenedBy: null, persistedOwnsPrWorkflow: true })).toBe(PR_OPENED_BY.AGENT_INLINE);+ });++ // Legacy shapes. Other installs run older versions, so records carrying the+ // #3733 boolean — or nothing at all — keep arriving here.+ it('reads a slashdo-capable legacy record as a /do:pr run whatever boolean it carries', () => {+ // The #6869 defect on legacy data: `ownsPrWorkflow` answered "did the+ // prompt render the INLINE PR section", which is false for exactly the+ // hosts that run `/do:pr`. Trusting it re-created their PR at cleanup.+ for (const persistedOwnsPrWorkflow of [true, false, undefined]) {+ expect(resolveFor({ persistedOwnsPrWorkflow, providerId: 'claude-code', providerCommand: 'claude' }))+ .toBe(PR_OPENED_BY.AGENT_SLASHDO);+ }+ // Including the case a provider-id allowlist missed.+ expect(resolveFor({ persistedOwnsPrWorkflow: false, providerId: 'custom', providerCommand: '/opt/bin/claude' }))+ .toBe(PR_OPENED_BY.AGENT_SLASHDO);});- it('falls back to the slash-command gate for a pre-#3733 record', () => {- // Those runs really were prompted by the old builder, whose gate this was.- expect(resolveOwnsPrWorkflow({ persisted: undefined, providerId: 'claude-code', providerCommand: 'claude' })).toBe(true);- expect(resolveOwnsPrWorkflow({ persisted: undefined, providerId: 'codex', providerCommand: 'codex' })).toBe(false);- expect(resolveOwnsPrWorkflow({ persisted: undefined, providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true })).toBe(false);+ it('keeps a slashdo-free legacy boolean answering exactly as it did', () => {+ expect(resolveFor({ persistedOwnsPrWorkflow: true })).toBe(PR_OPENED_BY.AGENT_INLINE);+ expect(resolveFor({ persistedOwnsPrWorkflow: false })).toBe(PR_OPENED_BY.PORTOS);+ expect(resolveFor({ persistedOwnsPrWorkflow: true, providerId: 'antigravity-cli', providerCommand: 'agy' }))+ .toBe(PR_OPENED_BY.AGENT_INLINE);+ // A lean `--bare` session is not slashdo-capable, so its `false` stands.+ expect(resolveFor({ persistedOwnsPrWorkflow: false, providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true }))+ .toBe(PR_OPENED_BY.PORTOS);});- it('treats a non-boolean stamp as absent, not as false', () => {- // `null` from a JSON round-trip must not silently claim PortOS owns the PR.- expect(resolveOwnsPrWorkflow({ persisted: null, providerId: 'claude-code' })).toBe(true);- expect(resolveOwnsPrWorkflow({ persisted: 'true', providerId: 'codex', providerCommand: 'codex' })).toBe(false);+ it('falls back to the slash-command gate for a pre-#3733 record with no key at all', () => {+ // Those runs really were prompted by the old builder, whose gate this was.+ expect(resolveFor({ providerId: 'claude-code', providerCommand: 'claude' })).toBe(PR_OPENED_BY.AGENT_SLASHDO);+ expect(resolveFor({})).toBe(PR_OPENED_BY.PORTOS);+ expect(resolveFor({ providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true })).toBe(PR_OPENED_BY.PORTOS);});});@@ -463,15 +495,29 @@ describe('resolvePrOwnership', () => {});it('uses the prompt stamp while keeping claim verification tied to slash commands', () => {- expect(resolve({ persisted: true })).toEqual({ taskOpenPR: true, agentOwnsPR: true, prClaimExpected: false });- expect(resolve({ persisted: false, providerId: 'claude-code', providerCommand: 'claude' }))- .toEqual({ taskOpenPR: true, agentOwnsPR: false, prClaimExpected: true });- expect(resolve({ persisted: true, task: { metadata: { openPR: false } } }))- .toEqual({ taskOpenPR: false, agentOwnsPR: false, prClaimExpected: false });+ expect(resolve({ persistedPrOpenedBy: PR_OPENED_BY.AGENT_INLINE })).toEqual({+ taskOpenPR: true, prOpenedBy: PR_OPENED_BY.AGENT_INLINE, agentOpensOwnPr: true, prClaimExpected: false,+ });+ // The #6869 case: a slashdo-capable host opens its OWN PR, and finalize+ // verifies the claim — two true answers where the old stamp said one was+ // false. `prClaimExpected` stays the raw capability, matching the runner+ // path's own derivation.+ expect(resolve({ persistedPrOpenedBy: PR_OPENED_BY.AGENT_SLASHDO, providerId: 'claude-code', providerCommand: 'claude' })).toEqual({+ taskOpenPR: true, prOpenedBy: PR_OPENED_BY.AGENT_SLASHDO, agentOpensOwnPr: true, prClaimExpected: true,+ });+ // A prompt that told the agent NOT to open one, on a host that could have.+ expect(resolve({ persistedPrOpenedBy: PR_OPENED_BY.PORTOS, providerId: 'claude-code', providerCommand: 'claude' })).toEqual({+ taskOpenPR: true, prOpenedBy: PR_OPENED_BY.PORTOS, agentOpensOwnPr: false, prClaimExpected: true,+ });+ // No PR asked for at all: nothing to own and nothing to verify.+ expect(resolve({ persistedPrOpenedBy: PR_OPENED_BY.AGENT_INLINE, task: { metadata: { openPR: false } } })).toEqual({+ taskOpenPR: false, prOpenedBy: PR_OPENED_BY.AGENT_INLINE, agentOpensOwnPr: false, prClaimExpected: false,+ });});- it('falls back to the legacy slash-command gate without a stamp', () => {- expect(resolve().agentOwnsPR).toBe(false);- expect(resolve({ providerId: 'claude-code', providerCommand: 'claude' }).agentOwnsPR).toBe(true);+ it('resolves a legacy record through the same fallback cleanup uses', () => {+ expect(resolve().agentOpensOwnPr).toBe(false);+ expect(resolve({ persistedOwnsPrWorkflow: true }).agentOpensOwnPr).toBe(true);+ expect(resolve({ providerId: 'claude-code', providerCommand: 'claude' }).agentOpensOwnPr).toBe(true);});});diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 70a9f86385..5bc5c758a5 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -164,7 +164,7 @@ export async function spawnDirectly({executionId,laneName,isTruthyMetaFn,- ownsPrWorkflow,+ prOpenedBy,safetyProfile = null,}) {const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;@@ -739,11 +739,11 @@ export async function spawnDirectly({// Resolved from the live provider descriptor — the same reading the TUI// path takes up front — so PortOS doesn't double-fire push+PR creation; see// `resolvePrOwnership` for why finalize's `prClaimExpected` and cleanup's- // `agentOwnsPR` are two predicates (#3358).+ // `agentOpensOwnPr` are two predicates (#3358).const prOwnership = resolvePrOwnership({task,isTruthyMeta: isTruthyMetaFn,- persisted: ownsPrWorkflow,+ persistedPrOpenedBy: prOpenedBy,providerId: provider?.id,providerCommand: provider?.command,leanMode: isOllamaClaudeProvider(provider),diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 6fb4159924..12f1e69dcf 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -124,6 +124,7 @@ vi.mock('../lib/privateSecuritySandbox.js', () => ({}));import { buildCliSpawnConfig, spawnDirectly } from './agentCliSpawning.js';+import { promptOpensOwnPr } from './promptSections/completion.js';import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';@@ -468,6 +469,19 @@ describe('stream error containment', () => {return proc;}+ // The stamp `agentLifecycle` writes for a run, derived through the REAL+ // predicate instead of hand-written — a literal here is what let the suite+ // pin an ownership value the spawn path never produces for a Claude host+ // (#6869). `minimalArgs.provider` is the slashdo-capable `claude-code` CLI.+ const stampPrOpenedBy = (task, provider = minimalArgs.provider) => promptOpensOwnPr(task, {+ providerType: provider.type,+ providerId: provider.id,+ providerCommand: provider.command,+ leanMode: false,+ worktreeInfo: { branchName: 'agent/t', worktreePath: '/tmp/wt', baseBranch: 'main' },+ isTruthyMetaFn: (v) => v === true || v === 'true',+ });+const minimalArgs = {agentId: 'agent-test',task: { id: 'task-1', description: 'do stuff' },@@ -1176,7 +1190,7 @@ describe('stream error containment', () => {metadata: { openPR: true, reviewers: ['codex', 'antigravity'], reviewStopMode: 'on-clean' },};- spawnDirectly({ ...minimalArgs, task, isTruthyMetaFn: (v) => v === true });+ spawnDirectly({ ...minimalArgs, task, prOpenedBy: stampPrOpenedBy(task), isTruthyMetaFn: (v) => v === true });await new Promise((r) => setTimeout(r, 10));fakeProcess.stdout.emit('data', Buffer.from('{"type":"result","result":"ok"}\n'));await new Promise((r) => setTimeout(r, 50));@@ -1192,7 +1206,7 @@ describe('stream error containment', () => {agentId: minimalArgs.agentId,task,success: true,- prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: true },+ prOwnership: { taskOpenPR: true, prOpenedBy: 'agent-slashdo', agentOpensOwnPr: true, prClaimExpected: true },prClaimVerified: false,}));// The claim predicate, not the ownership one, is what finalize verifies (#3358).@@ -1201,13 +1215,13 @@ describe('stream error containment', () => {it('hands a read-only CLI run to PortOS using the prompt ownership stamp', async () => {const task = { id: 'task-read-only', description: 'analyze the code', metadata: { openPR: true, readOnly: true } };- const spawnPromise = spawnDirectly({ ...minimalArgs, task, ownsPrWorkflow: false, isTruthyMetaFn: (v) => v === true });+ const spawnPromise = spawnDirectly({ ...minimalArgs, task, prOpenedBy: stampPrOpenedBy(task), isTruthyMetaFn: (v) => v === true });await vi.waitFor(() => expect(fakeProcess.listenerCount('close')).toBeGreaterThan(0));fakeProcess.emit('close', 0);await spawnPromise;await vi.waitFor(() => expect(runSpawnerCompletionCleanup).toHaveBeenCalledTimes(1));expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({- prOwnership: { taskOpenPR: true, agentOwnsPR: false, prClaimExpected: true },+ prOwnership: { taskOpenPR: true, prOpenedBy: 'portos', agentOpensOwnPr: false, prClaimExpected: true },}));});diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex c5940eb575..5a8d21c3b7 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -41,7 +41,7 @@ import { isTruthyMeta } from './agentState.js';import { resolveReviewLoopOptions } from './codeReview.js';import { cleanupAgentWorktree, spawnMergeRecoveryTask, releaseRetryHold } from './agentWorktreeCleanup.js';import { PR_CREATION, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';-import { resolveOwnsPrWorkflow } from '../lib/slashdoInvocation.js';+import { resolvePrOpenedBy, PR_OPENED_BY } from '../lib/slashdoInvocation.js';import { isPublicReviewRestrictedProfile, publicReviewPostureForProfile } from '../lib/agentExecutionProfiles.js';const ROOT_DIR = PATHS.root;@@ -222,9 +222,9 @@ export async function handlePipelineProgression(task, agentId, success) {* (`runSpawnerCompletionCleanup`). It used to be three inline copies, and the* reviewer-resolve hardening below reached only one of them.*- * `taskOpenPR` / `agentOwnsPR` are the CALLER's: the spawners read them off the- * live provider descriptor (`resolvePrOwnership`), the runner path off the- * persisted agent record (`resolveOwnsPrWorkflow`) — see #3358 for why the two+ * `taskOpenPR` / `agentOpensOwnPr` are the CALLER's: the spawners read them off+ * the live provider descriptor (`resolvePrOwnership`), the runner path off the+ * persisted agent record (`resolvePrOpenedBy`) — see #3358 for why the two* sources exist. `prClaimVerified` likewise carries whether finalize's check* ACTUALLY produced a forge answer for this run, which is a different question* from whether one was expected.@@ -237,11 +237,11 @@ export async function handlePipelineProgression(task, agentId, success) {** @returns {Promise<Object>} the third argument to `cleanupAgentWorktree`*/-async function resolveWorktreeCleanupOptions({ agentId, task, outputBuffer, taskOpenPR, agentOwnsPR, prClaimVerified = false, noChangesToShip = false }) {+async function resolveWorktreeCleanupOptions({ agentId, task, outputBuffer, taskOpenPR, agentOpensOwnPr, prClaimVerified = false, noChangesToShip = false }) {// `if-missing` for an agent-owned PR that finalize did NOT verify: cleanup// asks the forge once and only stands down when a PR actually exists, so a// harness that skipped its completion workflow can't strand the branch.- const prCreation = resolvePrCreation({ taskOpenPR, agentOwnsPr: agentOwnsPR, prClaimVerified, noChangesToShip });+ const prCreation = resolvePrCreation({ taskOpenPR, agentOpensOwnPr, prClaimVerified, noChangesToShip });// Merge per-task reviewer metadata with the user's Code Review Defaults// (Settings → Code Reviewers page). Settings I/O is cached inside the// resolver, so this is effectively free even when invoked from a tight CoS@@ -259,9 +259,9 @@ async function resolveWorktreeCleanupOptions({ agentId, task, outputBuffer, task...reviewOptions,// Review-loop follow-up agents already merged via `gh pr merge` in the agent// body — re-merging the worktree branch into the source workspace would- // duplicate the squashed commits — and a harness that owns its PR workflow- // lands its own PR; suppress the auto-merge fallback for both.- skipMerge: isTruthyMeta(task?.metadata?.reviewLoopFollowUp) || agentOwnsPR,+ // duplicate the squashed commits — and a harness that opens its own PR+ // lands it too; suppress the auto-merge fallback for both.+ skipMerge: isTruthyMeta(task?.metadata?.reviewLoopFollowUp) || agentOpensOwnPr,description: task?.description,agentOutput: outputBuffer,originalTask: task,@@ -433,17 +433,20 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, eff//// Read off the PERSISTED record (#3358): the in-memory `runnerAgents` entry// carries only `providerId`, so a lean `--bare` or path-configured provider- // would be misjudged from it. `resolveOwnsPrWorkflow` owns the stamped-vs-- // derived fallback for pre-#3733 records, alongside the predicate itself.+ // would be misjudged from it. `resolvePrOpenedBy` owns the stamped-vs-+ // derived fallback, including the legacy `ownsPrWorkflow` boolean records+ // written before #6869 and the pre-#3733 records that carry nothing.const providerDescriptor = {providerId: agentState?.metadata?.providerId ?? agent.providerId,providerCommand: agentState?.metadata?.providerCommand ?? agent.providerCommand ?? null,leanMode: (agentState?.metadata?.leanMode ?? agent.leanMode) === true,};- const agentOwnsPR = taskOpenPR && resolveOwnsPrWorkflow({- persisted: agentState?.metadata?.ownsPrWorkflow ?? agent.ownsPrWorkflow,+ const prOpenedBy = resolvePrOpenedBy({+ persistedPrOpenedBy: agentState?.metadata?.prOpenedBy ?? agent.prOpenedBy,+ persistedOwnsPrWorkflow: agentState?.metadata?.ownsPrWorkflow ?? agent.ownsPrWorkflow,...providerDescriptor,});+ const agentOpensOwnPr = taskOpenPR && prOpenedBy !== PR_OPENED_BY.PORTOS;// `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@@ -454,7 +457,7 @@ async function runCompletionCleanupSteps({ agentId, task, agent, agentState, efftask,outputBuffer,taskOpenPR,- agentOwnsPR,+ agentOpensOwnPr,prClaimVerified,noChangesToShip,}));@@ -525,7 +528,7 @@ export async function runSpawnerCompletionCleanup({ agentId, task, success, prOwtask,outputBuffer,taskOpenPR: prOwnership.taskOpenPR,- agentOwnsPR: prOwnership.agentOwnsPR,+ agentOpensOwnPr: prOwnership.agentOpensOwnPr,prClaimVerified,noChangesToShip,});diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 900edeba81..18b74d2332 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -33,6 +33,7 @@ import { handlePipelineProgression, runAgentCompletionCleanup, runSpawnerCompletimport { updateTask, addTask, reviveBlockedTask, getAgent } from './cos.js';import { cleanupAgentWorktree, releaseRetryHold } from './agentWorktreeCleanup.js';import { resolveReviewLoopOptions } from './codeReview.js';+import { promptOpensOwnPr } from './promptSections/completion.js';const runningPipeline = (overrides = {}) => ({id: 'p1',@@ -241,64 +242,105 @@ describe('handlePipelineProgression — execution profile hand-off', () => {});});-describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', () => {+describe('runAgentCompletionCleanup — agentOpensOwnPr mirrors the prompt gate', () => {const prTask = { id: 't', taskType: 'user', metadata: { openPR: true } };+ const worktreeInfo = { branchName: 'agent/t', worktreePath: '/tmp/wt', baseBranch: 'main' };++ // The stamp is DERIVED through the real predicate the spawn path writes with,+ // never hand-written: a literal here is how the suite came to pin+ // `ownsPrWorkflow: true` for a Claude host, a value the spawn path has never+ // produced for one (#6869). `providerType` mirrors the descriptor the+ // registration record carries.+ const stampFor = ({ providerType = 'tui', providerId, providerCommand, leanMode = false, task = prTask, worktree = worktreeInfo }) =>+ promptOpensOwnPr(task, {+ providerType, providerId, providerCommand, leanMode,+ worktreeInfo: worktree,+ isTruthyMetaFn: (v) => v === true || v === 'true',+ });// `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, noChangesToShip = false } = {}) => {+ const cleanupCallFor = async (agent, { prClaimVerified = false, noChangesToShip = false, task = prTask } = {}) => {await runAgentCompletionCleanup({- agentId: 'a1', task: prTask, agent, effectiveSuccess: true, outputBuffer: '', prClaimVerified, noChangesToShip,+ agentId: 'a1', task, agent, effectiveSuccess: true, outputBuffer: '', prClaimVerified, noChangesToShip,});// cleanupAgentWorktree(agentId, success, options) — options is the 3rd arg.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('a codex harness that owns its PR workflow is backstopped, not double-fired', async () => {+ // The #6869 regression: the old stamp answered "did the prompt render the+ // INLINE `git`/`gh` PR section", which is false for exactly the hosts that+ // run `/do:pr`. Cleanup then re-pushed the branch and called `git.createPR`+ // for a PR the agent had already opened and often already merged.+ it.each([+ ['tui', 'claude-code', 'claude'],+ ['cli', 'claude-code', 'claude'],+ // The case an id allowlist missed: a path-configured claude under a custom+ // id IS handed `/do:pr`, so PortOS must not open a second PR.+ ['cli', 'my-custom-agent', '/opt/homebrew/bin/claude'],+ ])('a slashdo-capable claude %s opens its own PR — PortOS must not re-create it', async (providerType, providerId, providerCommand) => {+ const prOpenedBy = stampFor({ providerType, providerId, providerCommand });+ expect(prOpenedBy).toBe('agent-slashdo');++ // Finalize verified the claim: nothing left for cleanup to ask or create.+ expect(await cleanupCallFor(+ { providerId, providerCommand, leanMode: false, prOpenedBy }, { prClaimVerified: true },+ )).toMatchObject({ prCreation: 'never', skipMerge: true });++ // Finalize did NOT verify (its check threw, or the run was user-terminated):+ // cleanup asks the forge once and only creates on a definite "none".+ expect(await cleanupCallFor(+ { providerId, providerCommand, leanMode: false, prOpenedBy }, { prClaimVerified: false },+ )).toMatchObject({ prCreation: 'if-missing', skipMerge: true });+ });++ // #3733: a codex/grok/agy harness can't type `/do:pr` but is told to run+ // `gh pr create` itself, so it is backstopped rather than double-fired.+ it('a codex harness that owns its inline PR workflow is backstopped, not double-fired', async () => {+ const prOpenedBy = stampFor({ providerType: 'tui', providerId: 'codex', providerCommand: 'codex' });+ expect(prOpenedBy).toBe('agent-inline');// Finalize skipped `verifyPrClaim` for it (`prExpected` keys on the// slash-command predicate), so cleanup asks the forge once itself.- const opts = await cleanupCallFor({ providerId: 'codex', providerCommand: 'codex', leanMode: false, ownsPrWorkflow: true });+ const opts = await cleanupCallFor({ providerId: 'codex', providerCommand: 'codex', leanMode: false, prOpenedBy });expect(opts.prCreation).toBe('if-missing');expect(opts.skipMerge).toBe(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 prOpenedBy = stampFor({ providerType: 'tui', providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true });+ expect(prOpenedBy).toBe('portos');const opts = await cleanupCallFor({- providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true, ownsPrWorkflow: false,+ providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true, prOpenedBy,});expect(opts.prCreation).toBe('always');expect(opts.skipMerge).toBe(false);});+ // The task shapes whose prompt hands the PR back to PortOS keep today's+ // answer even on a slashdo-capable host — the stamp is task-shape-aware, not+ // provider-only (see agentRegistrationRecord.js).+ it.each([+ ['read-only', { openPR: true, readOnly: true }, worktreeInfo],+ ['discard-worktree', { openPR: true, discardWorktree: true }, worktreeInfo],+ ['no-code-output', { openPR: true, noCodeOutput: true }, worktreeInfo],+ ['JIRA hand-off (no worktree)', { openPR: true, jiraTicketId: 'ABC-1' }, null],+ ])('a %s claude run stays PortOS-owned', async (_label, metadata, worktree) => {+ const task = { id: 't', taskType: 'user', metadata };+ const prOpenedBy = stampFor({ providerId: 'claude-code', providerCommand: 'claude', task, worktree });+ expect(prOpenedBy).toBe('portos');+ const opts = await cleanupCallFor(+ { providerId: 'claude-code', providerCommand: 'claude', leanMode: false, prOpenedBy },+ { task },+ );+ expect(opts.prCreation).toBe('always');+ expect(opts.skipMerge).toBe(false);+ });+it('does not create an empty PR after finalize proves a no-change audit', async () => {+ const prOpenedBy = stampFor({ providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true });const opts = await cleanupCallFor(- { providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true, ownsPrWorkflow: false },+ { providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true, prOpenedBy },{ noChangesToShip: true },);expect(opts.prCreation).toBe('never');@@ -307,11 +349,48 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()it('a task that asked for no PR never creates one', async () => {await runAgentCompletionCleanup({agentId: 'a1', task: { id: 't', taskType: 'user', metadata: {} },- agent: { providerId: 'codex', providerCommand: 'codex', ownsPrWorkflow: true },+ agent: { providerId: 'codex', providerCommand: 'codex', prOpenedBy: 'agent-inline' },effectiveSuccess: true, outputBuffer: '',});expect(cleanupAgentWorktree.mock.calls.at(-1)[2].prCreation).toBe('never');});+});++// Other installs upgrade on their own schedule, so records written before the+// `prOpenedBy` stamp keep arriving here forever. They carry either the #3733+// boolean `ownsPrWorkflow` (which answered "did the prompt render the INLINE PR+// section") or nothing at all (pre-#3733).+describe('runAgentCompletionCleanup — legacy records with no prOpenedBy stamp', () => {+ const prTask = { id: 't', taskType: 'user', metadata: { openPR: true } };+ const cleanupCallFor = async (agent, { prClaimVerified = false } = {}) => {+ await runAgentCompletionCleanup({+ agentId: 'a1', task: prTask, agent, effectiveSuccess: true, outputBuffer: '', prClaimVerified,+ });+ return cleanupAgentWorktree.mock.calls.at(-1)[2];+ };++ it('a slashdo-free harness stamped `ownsPrWorkflow: true` still owns its PR', async () => {+ const opts = await cleanupCallFor({ providerId: 'codex', providerCommand: 'codex', leanMode: false, ownsPrWorkflow: true });+ expect(opts.prCreation).toBe('if-missing');+ expect(opts.skipMerge).toBe(true);+ });++ it('a lean session stamped `ownsPrWorkflow: false` still hands the PR back', async () => {+ const opts = await cleanupCallFor({ providerId: 'claude-ollama', providerCommand: 'claude', leanMode: true, ownsPrWorkflow: false });+ expect(opts.prCreation).toBe('always');+ expect(opts.skipMerge).toBe(false);+ });++ // The one legacy shape whose ANSWER changes, because it is the defect: a+ // slashdo-capable record stamped `false` really did run `/do:pr`, and cleanup+ // re-created its PR. Reading it as `agent-slashdo` applies the #6869 fix to+ // records written by an older version too.+ it('a slashdo-capable record stamped `ownsPrWorkflow: false` is read as a /do:pr run', async () => {+ expect(await cleanupCallFor(+ { providerId: 'claude-code', providerCommand: 'claude', leanMode: false, ownsPrWorkflow: false },+ { prClaimVerified: true },+ )).toMatchObject({ prCreation: 'never', skipMerge: true });+ });it.each([['claude-code', 'claude', true],@@ -322,8 +401,8 @@ describe('runAgentCompletionCleanup — agentOwnsPR mirrors the prompt gate', ()// Prompted by the OLD builder, which told these to commit and stop.['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+ ])('a pre-#3733 %s record falls back to the slash-command derivation it was prompted with', async (providerId, providerCommand, owns) => {+ // No ownership key at all: 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 }, { prClaimVerified: owns });expect(opts.prCreation).toBe(owns ? 'never' : 'always');@@ -411,8 +490,8 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (agentId: 'a1',task: { id: 't', taskType: 'user', description: 'do it', metadata: { openPR: true } },success: true,- // A task that asked for a PR from a harness that does not own the workflow.- prOwnership: { taskOpenPR: true, agentOwnsPR: false, prClaimExpected: false },+ // A task that asked for a PR from a run whose prompt hands it back to PortOS.+ prOwnership: { taskOpenPR: true, prOpenedBy: 'portos', agentOpensOwnPr: false, prClaimExpected: false },prClaimVerified: false,noChangesToShip: false,outputBuffer: 'out',@@ -495,7 +574,7 @@ describe('runSpawnerCompletionCleanup — the in-process spawners\' dispatch', (// spawn no follow-up, so the reviewer defaults are never even read.it('skips the reviewer resolve for a run whose own PR claim finalize verified', async () => {await runSpawnerCompletionCleanup(spawnerArgs({- prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: true },+ prOwnership: { taskOpenPR: true, prOpenedBy: 'agent-slashdo', agentOpensOwnPr: true, prClaimExpected: true },prClaimVerified: true,}));diff --git a/server/services/agentLifecycle.blockAndBail.test.js b/server/services/agentLifecycle.blockAndBail.test.jsindex 803438bf10..32e67396eb 100644--- a/server/services/agentLifecycle.blockAndBail.test.js+++ b/server/services/agentLifecycle.blockAndBail.test.js@@ -111,7 +111,7 @@ vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent: vi.fn(async () => ({ avi.mock('./agentPromptBuilder.js', () => ({buildAgentPrompt: vi.fn(),getAppWorkspace: vi.fn(),- inlinePrLifecycleSection: vi.fn(() => null),+ promptOpensOwnPr: vi.fn(() => 'portos'),isClaimFlowTask: vi.fn(() => false),}));vi.mock('./workspaceContext.js', () => ({ snapshotOnRepoSwitch: vi.fn().mockResolvedValue(null) }));diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 54ee44260d..fd084ffbc8 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -55,7 +55,7 @@ import { createAgentRun } from './agentRunTracking.js';import { appendRunEvent } from './agentRunEventLog.js';import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';-import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection, isClaimFlowTask } from './agentPromptBuilder.js';+import { buildAgentPrompt, getAppWorkspace, isClaimFlowTask, promptOpensOwnPr } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';import { prClaimWasVerified } from '../lib/prDisposition.js';@@ -642,14 +642,18 @@ async function runAgentSpawn(task) {? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR): null;- const ownsPrWorkflow = inlinePrLifecycleSection(task, {+ // WHO opens this run's PR, per the prompt just built for it — the SAME+ // predicate that decided what the completion section says, so the record and+ // the prompt cannot disagree (#6869). Read back at cleanup by+ // `resolvePrOpenedBy`.+ const prOpenedBy = promptOpensOwnPr(task, {providerType: provider.type,providerId: provider.id,providerCommand: provider.command,leanMode,worktreeInfo,isTruthyMetaFn: isTruthyMeta,- }) !== null;+ });// Evaluated once: `configClaimFlow` and `configCodingOnMain` below are two// faces of the same fact, and two separate calls could drift on the// `isTruthyMetaFn` argument — which is exactly the split that made a claim@@ -678,7 +682,7 @@ async function runAgentSpawn(task) {providerEndpoint: providerBaseUrl(provider),localPromptBudget,leanMode,- ownsPrWorkflow,+ prOpenedBy,claimFlowTask,selectedModel,modelSelection,@@ -813,7 +817,7 @@ async function runAgentSpawn(task) {laneName,isTruthyMetaFn: isTruthyMeta,leanMode,- ownsPrWorkflow,+ prOpenedBy,useDurableRunner: dispatchUseRunner,safetyProfile,});@@ -835,7 +839,7 @@ async function runAgentSpawn(task) {executionId: toolExecution.id,laneName,isTruthyMetaFn: isTruthyMeta,- ownsPrWorkflow,+ prOpenedBy,safetyProfile,});} catch (err) {@@ -1345,16 +1349,17 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// 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.+ // Deliberately the SLASH-command predicate, not the `prOpenedBy` ownership+ // stamp — 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. `resolvePrOwnership`'s+ // `prClaimExpected` is the same expression, for the same reason.//// `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 the// in-memory entry.- const runnerAgentOwnsPR = isTruthyMeta(task?.metadata?.openPR) && canTypeSlashCommands({+ const runnerPrClaimExpected = isTruthyMeta(task?.metadata?.openPR) && canTypeSlashCommands({providerId: persistedAgent?.metadata?.providerId ?? agent.providerId,providerCommand: persistedAgent?.metadata?.providerCommand ?? null,leanMode: persistedAgent?.metadata?.leanMode === true,@@ -1409,7 +1414,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationerrorAnalysis,isTruthyMetaFn: isTruthyMeta,workspacePath: agent.workspacePath || null,- prExpected: runnerAgentOwnsPR,+ prExpected: runnerPrClaimExpected,// The run window the commit criterion is evaluated against (#3637).startedAt: Number.isFinite(runStartedAt) ? runStartedAt : null,});diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.jsindex 761c726191..8c7350ef0c 100644--- a/server/services/agentLifecycle.postureGate.test.js+++ b/server/services/agentLifecycle.postureGate.test.js@@ -115,7 +115,7 @@ vi.mock('./agentPromptBuilder.js', () => ({getAppWorkspace: vi.fn(),// Read by the `registerAgent` projection on the way to the dispatch; the real// predicates are pinned in agentPromptBuilder's own suite.- inlinePrLifecycleSection: vi.fn(() => null),+ promptOpensOwnPr: vi.fn(() => 'portos'),isClaimFlowTask: vi.fn(() => false),}));// Dynamically imported mid-spawn purely to snapshot workspace context. Stubbeddiff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 1a3b23b619..02ed989795 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -75,6 +75,7 @@ export {buildReadOnlyCompletionSection,buildResumeSection,inlinePrLifecycleSection,+ promptOpensOwnPr,} from './promptSections/completion.js';export { buildReviewLoopFollowUpSection } from './promptSections/reviewLifecycle.js';export { createJiraTicketForTask, generateJiraTitle, getAppDataForTask, getAppWorkspace } from './promptSections/appContext.js';@@ -458,7 +459,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo? worktreeCommitGuidance({isTui,canTypeSlashCommands: false,- ownsPrWorkflow: false,+ rendersInlinePrLifecycle: false,isWorktreeOnExistingBranch,willOpenPR,discardWorktree,@@ -1020,7 +1021,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetproviderType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn,});- const ownsPrWorkflow = inlineSection !== null;+ const rendersInlinePrLifecycle = inlineSection !== null;// Slashdo already partitions reviewers. Plain-git completion prompts need the// same split spelled out: local CLIs/local LLMs inspect the committed branch// before it is public; Copilot and @login reviewers can only run after a PR.@@ -1102,7 +1103,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// --- Worktree / pipeline / JIRA context --------------------------------contractSections.push(...buildLightTaskContextSections({- task, worktreeInfo, isWorktreeOnExistingBranch, isTui, mode: completionMode, canTypeSlashCommands: canTypeSlash, ownsPrWorkflow,+ task, worktreeInfo, isWorktreeOnExistingBranch, isTui, mode: completionMode, canTypeSlashCommands: canTypeSlash, rendersInlinePrLifecycle,willOpenPR, discardWorktree, claimFlow, noChangeSuccess,}));@@ -1112,15 +1113,15 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// `mode` and adapts the workflow itself. Likewise the three commit/push// modes: `buildCliCompletionSection` already reads `worktreeInfo`/`willOpenPR`.const pushTuiCompletion = () => contractSections.push(buildTuiCompletionSection({- willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, mode: completionMode, ownsPrWorkflow, portosMergesBranch,+ willOpenPR, prCompletion, simplifyEnabled, noChangeSuccess, mode: completionMode, rendersInlinePrLifecycle, portosMergesBranch,sentinelPath: lightSentinelPath(),branchName: worktreeInfo?.branchName || null,baseBranch: worktreeInfo?.baseBranch || null,leavePrOpen: leavesPrForHuman(task),reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies,- forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null+ forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null}));- const pushCliCompletion = () => contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, mode: completionMode, canTypeSlashCommands: canTypeSlash, ownsPrWorkflow, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: ownsPrWorkflow ? runsPrSideReviewLoop : null }));+ const pushCliCompletion = () => contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, mode: completionMode, canTypeSlashCommands: canTypeSlash, rendersInlinePrLifecycle, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewers: lightReviewers, usernames: lightReviewerUsernames, optionalReviewers: lightOptionalReviewers, reviewerMaxRounds: lightReviewerMaxRounds, reviewerModels: lightReviewerModels, reviewerEfforts: lightReviewerEfforts, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null }));({[COMPLETION_MODES.TOOL_FREE]: () => contractSections.push(buildToolFreeReasoningCompletionSection()),@@ -1155,7 +1156,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet// 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) {+ if (rendersInlinePrLifecycle) {contractSections.push(buildInlineReviewLoopSection({taskId: task.id,branchName: worktreeInfo?.branchName || null,@@ -1196,7 +1197,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMet* `buildLightContextSections`.*/function buildLightTaskContextSections({- task, worktreeInfo, isWorktreeOnExistingBranch, isTui, mode, canTypeSlashCommands, ownsPrWorkflow,+ task, worktreeInfo, isWorktreeOnExistingBranch, isTui, mode, canTypeSlashCommands, rendersInlinePrLifecycle,willOpenPR, discardWorktree, claimFlow, noChangeSuccess,}) {const sections = [];@@ -1208,7 +1209,7 @@ function buildLightTaskContextSections({`- **Path**: \`${worktreeInfo.worktreePath}\``,worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\`` : null,'',- worktreeCommitGuidance({ isTui, mode, canTypeSlashCommands, ownsPrWorkflow, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess }),+ worktreeCommitGuidance({ isTui, mode, canTypeSlashCommands, rendersInlinePrLifecycle, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow, noChangeSuccess }),'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.diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 4d7fb073b4..2866702c7c 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -6,8 +6,9 @@* asked for?** Cleanup reports only what it TRIED and failed to do. The case this exists for- * is an agent that owns its own PR workflow (`ownsPrWorkflow`), merges the PR- * itself, and exits before deleting the branch — or exits with the PR still open.+ * is an agent that opens its own PR (`metadata.prOpenedBy` naming the agent),+ * merges it itself, and exits before deleting the branch — or exits with the PR+ * still open.* Cleanup stands down for exactly those runs, so nothing checked, and the branch* plus its worktree persist through every later sweep that treats "an agent owns* it" as a reason to skip. (`removeWorktree` also only `console.log`s a faileddiff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 67411aa5e9..bc4c0f8093 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -25,7 +25,7 @@ import { PTY_UNAVAILABLE_PREFIX } from '../lib/ptySpawnDiagnostics.js';import { finalizeAgentRunCommon, shouldAbandonAgentRun } from './agentRunFinalize.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';import { prClaimWasVerified, leavesPrForHuman } from '../lib/prDisposition.js';-import { resolvePrOwnership } from '../lib/slashdoInvocation.js';+import { resolvePrOwnership, PR_OPENED_BY } from '../lib/slashdoInvocation.js';import { mergeGateOwed, resolveMergeGateVerdict, buildMergeGateReprompt } from '../lib/mergeGateContract.js';import { probePrForBranch } from './prProbe.js';import * as git from './git.js';@@ -669,7 +669,7 @@ export async function spawnTuiAgent({executionId,laneName,isTruthyMetaFn,- ownsPrWorkflow,+ prOpenedBy,leanMode = false,useDurableRunner = false,// The public-content execution profile this run enforces (null for an@@ -707,26 +707,29 @@ export async function spawnTuiAgent({const doneSentinelPath = resolveDoneSentinelPath(cwd, agentId);// 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. Resolved once up front (rather- // than inside finish()) so the merge-gate contract check below and the- // completion dispatch finish() hands off to read the same answer.+ // the slashdo command (`prOpenedBy: 'agent-slashdo'`),+ // codex/antigravity/grok/OpenCode run the plain `git`/`gh` equivalent from+ // the same prompt (`'agent-inline'`). A lean `--bare` session, and any task+ // shape whose prompt says "do NOT open a PR", hands the lifecycle back to+ // PortOS (`'portos'`). Resolved once up front (rather than inside finish())+ // so the merge-gate contract check below and the completion dispatch+ // finish() hands off to read the same answer.const prOwnership = resolvePrOwnership({task,isTruthyMeta: isTruthyMetaFn,- persisted: ownsPrWorkflow,+ persistedPrOpenedBy: prOpenedBy,providerId: provider?.id,providerCommand: provider?.command,leanMode,});- // Does this run's own task shape say it owed a merge (#5876)? A run PortOS- // still backstops (no PR at all, or a lean session) or one whose prompt- // hands the PR to a human (JIRA, claim flow) never owed one, so the- // contract check below is inert for those — see mergeGateContract.js.+ // Does this run's own task shape say it owed a merge (#5876)? Only the inline+ // prompt carries a **Merge Gate** section to hold it to — a `/do:pr` run+ // merges inside that one command, and a run PortOS backstops or that hands+ // the PR to a human (JIRA, claim flow) never owed one. So the contract check+ // below is inert for all three — see mergeGateContract.js.const mergeGateIsOwed = mergeGateOwed({taskOpenPR: prOwnership.taskOpenPR,- ownsPrWorkflow: prOwnership.agentOwnsPR,+ rendersInlinePrLifecycle: prOwnership.prOpenedBy === PR_OPENED_BY.AGENT_INLINE,leaveOpen: leavesPrForHuman(task),});const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);@@ -1198,7 +1201,7 @@ export async function spawnTuiAgent({// `prOwnership` was resolved once, up front, near `doneSentinelPath`, so the// merge-gate contract check above and the completion dispatch below read the// same answer (#3733); see `resolvePrOwnership` for why finalize's- // `prClaimExpected` and cleanup's `agentOwnsPR` are two predicates (#3358).+ // `prClaimExpected` and cleanup's `agentOpensOwnPr` are two predicates (#3358).//// Whether finalize's check ACTUALLY produced a forge answer, filled in from// its return below. Deliberately not `prClaimExpected`: finalize substitutesdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 896083eda6..a8ce677240 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -248,6 +248,7 @@ import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgentLifecycle from './cosAgentLifecycle.js';import * as gitService from './git.js';import { probePrForBranch } from './prProbe.js';+import { promptOpensOwnPr } from './promptSections/completion.js';import { activeAgents, userTerminatedAgents, pausedAgents, consumePausedAgentExit } from './agentState.js';import {SELF_CLEARING_RESUBMIT_INTERVAL_MS,@@ -633,6 +634,23 @@ describe('spawnTuiAgent runtime', () => {promptDelayMs: 100,};+ // The stamp `agentLifecycle` would write for this run, derived through the+ // REAL predicate rather than hand-written. The old `!leanMode` default pinned+ // `true` for every non-lean host, a value the spawn path never produced for a+ // slashdo-capable one (#6869), so the suite agreed with itself and not with+ // production. A worktree is assumed unless a case says otherwise: a PR-opening+ // TUI run always has one.+ function stampPrOpenedBy(overrides, task, provider) {+ return promptOpensOwnPr(task, {+ providerType: provider?.type ?? 'tui',+ providerId: provider?.id ?? null,+ providerCommand: provider?.command ?? null,+ leanMode: overrides.leanMode ?? false,+ worktreeInfo: overrides.worktreeInfo ?? { branchName: 'agent/t', worktreePath: '/tmp/ws', baseBranch: 'main' },+ isTruthyMetaFn: (v) => v === true || v === 'true',+ });+ }+function runSpawn(overrides = {}) {const agentId = overrides.agentId ?? 'agent-1';const task = overrides.task ?? { id: 'task-1', description: 'do the thing', metadata: {} };@@ -658,7 +676,7 @@ describe('spawnTuiAgent runtime', () => {agentDir,executionId,laneName,- ownsPrWorkflow: overrides.ownsPrWorkflow ?? !overrides.leanMode,+ prOpenedBy: overrides.prOpenedBy ?? stampPrOpenedBy(overrides, task, provider),leanMode: overrides.leanMode ?? false,useDurableRunner: overrides.useDurableRunner ?? false,safetyProfile: overrides.safetyProfile ?? null,@@ -967,7 +985,7 @@ describe('spawnTuiAgent runtime', () => {agentId: 'agent-1',task,success: true,- prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: false },+ prOwnership: { taskOpenPR: true, prOpenedBy: 'agent-inline', agentOpensOwnPr: true, prClaimExpected: false },prClaimVerified: false,}));// …and finalize was told not to verify a claim this session cannot make —@@ -994,7 +1012,7 @@ describe('spawnTuiAgent runtime', () => {// Neither predicate holds for a `--bare` session, so the dispatch opens the// PR itself (`always`) and may auto-merge the branch.expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({- prOwnership: { taskOpenPR: true, agentOwnsPR: false, prClaimExpected: false },+ prOwnership: { taskOpenPR: true, prOpenedBy: 'portos', agentOpensOwnPr: false, prClaimExpected: false },}));});@@ -1038,7 +1056,7 @@ describe('spawnTuiAgent runtime', () => {// finalize ran `verifyPrClaim` for a slashdo-capable session and the verdict// reaches the dispatch as verified, so it never queries the forge again.expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({- prOwnership: { taskOpenPR: true, agentOwnsPR: true, prClaimExpected: true },+ prOwnership: { taskOpenPR: true, prOpenedBy: 'agent-slashdo', agentOpensOwnPr: true, prClaimExpected: true },prClaimVerified: true,}));expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ prExpected: true }));@@ -2853,7 +2871,6 @@ describe('spawnTuiAgent runtime', () => {withSentinel('## Summary\nFinished the analysis.');const spawnPromise = runSpawn({task: { ...openPrTask, metadata: { openPR: true, readOnly: true } },- ownsPrWorkflow: false,});await flushMicrotasks();sentinelExists = true;@@ -2863,7 +2880,7 @@ describe('spawnTuiAgent runtime', () => {expect(probePrForBranch).not.toHaveBeenCalled();expect(shellService.pasteToSession).not.toHaveBeenCalled();expect(runSpawnerCompletionCleanup).toHaveBeenCalledWith(expect.objectContaining({- prOwnership: expect.objectContaining({ taskOpenPR: true, agentOwnsPR: false }),+ prOwnership: expect.objectContaining({ taskOpenPR: true, prOpenedBy: 'portos', agentOpensOwnPr: false }),}));});diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 20ec45963d..f188bb06a5 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -6,7 +6,7 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizimport { isAuditTaskType } from '../../lib/auditCatalog.js';import { resolveTaskHookType } from '../taskTypeHooks.js';import { PROGRAMMATIC_OUTPUT_COMPLETION_HEADING } from '../../lib/agentSentinel.js';-import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../../lib/slashdoInvocation.js';+import { canTypeSlashCommands, agentOwnsPrWorkflow, PR_OPENED_BY } from '../../lib/slashdoInvocation.js';import { shellQuote } from '../../lib/shellQuote.js';import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../lib/prDisposition.js';@@ -470,7 +470,7 @@ export function buildAutoMergeCommitStep(baseBranch = null) {* `canTypeSlashCommands` alone (no separate `isTui` re-check) tells the two* apart from their non-slashdo equivalents.*/-export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommands = false, ownsPrWorkflow = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false, noChangeSuccess = false }) {+export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, isWorktreeOnExistingBranch, willOpenPR, discardWorktree, claimFlow = false, noChangeSuccess = false }) {if (discardWorktree) return DISCARD_WORKTREE_NOTE;if (claimFlow) return 'The claim workflow in the Completion section owns the push, PR/MR, review, merge or human-handoff, and cleanup steps.';if (isTui) return withNoChangeAuditGuidance('Commit your changes to this branch — see **Completion Workflow** below.', noChangeSuccess);@@ -485,7 +485,7 @@ export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommand// (portosMergesBranchOnExit) — nothing drives a push, so say so.return withNoChangeAuditGuidance('Commit your changes here — do NOT push. PortOS merges this branch back after you exit; the **Completion** section below has the exact step.', noChangeSuccess);}- if (ownsPrWorkflow && willOpenPR) {+ if (rendersInlinePrLifecycle && willOpenPR) {return withNoChangeAuditGuidance('Commit your changes here — the **Completion** section below drives the push, the PR, the review loop, and the merge.', noChangeSuccess);}if (willOpenPR) {@@ -617,14 +617,14 @@ function localReviewCompletionInstruction(localReviewRequired = true) {* this IS a Claude session, so `/simplify` and `/do:pr` are both safe to emit* without a second provider check.*/-export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, mode = COMPLETION_MODES.TUI, ownsPrWorkflow = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, mode = COMPLETION_MODES.TUI, rendersInlinePrLifecycle = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;if (mode === COMPLETION_MODES.TUI_SLASHDO_FREE) {// Plain `git`/`gh` instead of `/do:pr` — but still the whole lifecycle when- // the session is a real coding harness (`ownsPrWorkflow`); the reviewer+ // the session is a real coding harness (`rendersInlinePrLifecycle`); the reviewer// procedure it needs is inlined in the Review Loop section that follows.- return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, ownsPrWorkflow, forgeCli, noChangeSuccess, localReviewSection, localReviewRequired, postPrReview });+ return buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen, rendersInlinePrLifecycle, forgeCli, noChangeSuccess, localReviewSection, localReviewRequired, postPrReview });}const cmd = willOpenPR ? '/do:pr' : '/do:push';// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out@@ -811,27 +811,28 @@ function buildManualPrCreateStep(step, { branchName, baseBranch, forgeCli = 'gh'* 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.+ * When `rendersInlinePrLifecycle` 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 `promptOpensOwnPr`, whose+ * `agent-inline` answer this is. 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.+ * `rendersInlinePrLifecycle: 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, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, simplifyEnabled, sentinelPath, branchName = null, baseBranch = null, leavePrOpen = false, rendersInlinePrLifecycle = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);- // `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;+ // `rendersInlinePrLifecycle` 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 simplifyStep = simplifyEnabled? `1. Before committing, ${SIMPLIFY_INLINE_REVIEW} and fix any findings.`: '1. (simplify disabled — skip)';- const sentinelTail = drivesOwnPr+ const sentinelTail = rendersInlinePrLifecycle? (noChangeSuccess? ' ## PR\n <PR URL, or "No change needed; no PR opened." if the audit made no change>': ' ## PR\n <PR URL>')@@ -840,7 +841,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETconst lines = ['## Completion Workflow',...(noChangeSuccess ? ['', NO_CHANGE_AUDIT_GUIDANCE, ''] : []),- drivesOwnPr+ rendersInlinePrLifecycle? `This provider does NOT have slashdo (\`/do:*\`) commands, so drive the handoff with plain \`git\` and \`${forgeCli}\`. **You own this ${forgeCli === 'glab' ? 'MR' : '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:','',@@ -854,7 +855,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET];let step = 3;- if (drivesOwnPr) {+ if (rendersInlinePrLifecycle) {if (localReviewSection) {lines.push(`${step++}. ${localReviewCompletionInstruction(localReviewRequired)}`);lines.push('', localReviewSection, '');@@ -880,45 +881,91 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLET}/**- * Which inline PR-lifecycle section — if any — a run gets after its manual- * completion workflow: `'review-loop'`, `'merge-gate'` (no reviewer configured,- * so CI is the whole gate), or `null`.+ * WHO opens this run's pull request, per the prompt the sections above render+ * for it — a `PR_OPENED_BY` value, never null, so no caller has to invent a+ * meaning for "absent".*- * ONE definition, used by both the prompt assembly that renders the section and- * the `buildAgentPrompt` preload that decides whether to read + stage the ~56KB- * CLI-reviewer recipe for it. They were two conditions at opposite ends of the- * file, and the loose one paid for a 56KB read and an `atomicWrite` on every- * read-only / leave-open / merge-gate run whose section never rendered — while- * the strict one restated four branches of the completion if/else chain by hand,- * 130 lines away from the chain it mirrored.+ * This is the one gate; `inlinePrLifecycleSection` below is a projection of it.+ * They used to be the same predicate under a name that answered a narrower+ * question — `metadata.ownsPrWorkflow` meant "did the prompt render the INLINE+ * `git`/`gh` PR section", which is FALSE for a slashdo-capable Claude host,+ * because that host drives the whole lifecycle through `/do:pr` instead. Every+ * consumer read the name as "the agent opens its own PR" and got the opposite+ * answer for the host that most often does, so cleanup re-pushed the branch and+ * called `git.createPR` for a PR the agent had already opened (#6869).*- * @returns {'review-loop'|'merge-gate'|null}+ * The three answers, in the order the prompt decides them:+ * - `PORTOS` — the run is not a local harness, is a lean `--bare` session, or+ * its task shape hands the change request back to PortOS. Every exclusion+ * below is one of those completion contracts.+ * - `AGENT_SLASHDO` — the session can type `/do:pr`, and the completion section+ * emits it: `buildTuiCompletionSection`'s `cmd` for a TUI, the+ * `WORKTREE_NO_PUSH` arm of `buildCliCompletionSection` for a CLI. Both are+ * exactly "worktree + `openPR` + none of the exclusions below", which is what+ * this gate has already established by the time we ask.+ * - `AGENT_INLINE` — everything else that clears the gate: a real harness that+ * cannot type a slash command (codex / grok / agy / OpenCode), handed the+ * plain `git`/`gh` steps plus the inline Review Loop / Merge Gate section.+ *+ * Not re-checked here: the claim-flow contract, whose completion mode also+ * emits no `/do:pr`. Every claim task type pins `useWorktree: false,+ * openPR: false` (see `taskScheduleRegistry.js`, which also protects both keys+ * from override), so the worktree and `openPR` gates below already exclude it —+ * and a claim prompt that somehow reached here would be answered correctly+ * anyway, since it opens and merges its own PR from its own procedure.+ *+ * @returns {string} a `PR_OPENED_BY` value*/-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;+export function promptOpensOwnPr(task, { providerType, providerId, providerCommand, leanMode, worktreeInfo, isTruthyMetaFn = isTruthyMetaDefault }) {+ if (!LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) return PR_OPENED_BY.PORTOS;+ if (!agentOwnsPrWorkflow({ providerType, leanMode })) return PR_OPENED_BY.PORTOS;// 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;+ if (!worktreeInfo) return PR_OPENED_BY.PORTOS;const metadata = task?.metadata || {};- if (!isTruthyMetaFn(metadata.openPR)) return null;+ if (!isTruthyMetaFn(metadata.openPR)) return PR_OPENED_BY.PORTOS;// The completion branches that hand back a contract which never opens a PR.- if (isTruthyMetaFn(metadata.noCodeOutput) || metadata.creativeDirector) return null;- if (isTruthyMetaFn(metadata.discardWorktree)) return null;- if (isTruthyMetaFn(metadata.readOnly)) return null;- if (isTruthyMetaFn(metadata.reviewLoopFollowUp)) return null;+ if (isTruthyMetaFn(metadata.noCodeOutput) || metadata.creativeDirector) return PR_OPENED_BY.PORTOS;+ if (isTruthyMetaFn(metadata.discardWorktree)) return PR_OPENED_BY.PORTOS;+ if (isTruthyMetaFn(metadata.readOnly)) return PR_OPENED_BY.PORTOS;+ if (isTruthyMetaFn(metadata.reviewLoopFollowUp)) return PR_OPENED_BY.PORTOS;// A PR a human lands gets neither a review loop nor a merge gate.- const prCompletion = resolvePrCompletion(metadata);- if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task)) return null;+ if (resolvePrCompletion(metadata) === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task)) return PR_OPENED_BY.PORTOS;++ return canTypeSlashCommands({ providerId, providerCommand, leanMode })+ ? PR_OPENED_BY.AGENT_SLASHDO+ : PR_OPENED_BY.AGENT_INLINE;+}- return prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE ? 'review-loop' : 'merge-gate';+/**+ * Which inline PR-lifecycle section — if any — a run gets after its manual+ * completion workflow: `'review-loop'`, `'merge-gate'` (no reviewer configured,+ * so CI is the whole gate), or `null`.+ *+ * ONE definition, used by both the prompt assembly that renders the section and+ * the `buildAgentPrompt` preload that decides whether to read + stage the ~56KB+ * CLI-reviewer recipe for it. They were two conditions at opposite ends of the+ * file, and the loose one paid for a 56KB read and an `atomicWrite` on every+ * read-only / leave-open / merge-gate run whose section never rendered — while+ * the strict one restated four branches of the completion if/else chain by hand,+ * 130 lines away from the chain it mirrored.+ *+ * The section exists only on the inline path: a `/do:pr` run reviews and merges+ * inside that one command, so `promptOpensOwnPr` answering `AGENT_SLASHDO` is a+ * `null` here — which is exactly why the two questions need separate names.+ *+ * @returns {'review-loop'|'merge-gate'|null}+ */+export function inlinePrLifecycleSection(task, opts) {+ if (promptOpensOwnPr(task, opts) !== PR_OPENED_BY.AGENT_INLINE) return null;+ return resolvePrCompletion(task?.metadata || {}) === PR_COMPLETIONS.REVIEW_THEN_MERGE+ ? 'review-loop'+ : 'merge-gate';}/**@@ -976,7 +1023,7 @@ export function buildInlineReviewLoopSection({* (`lib/agentCompletionMode.js`) rather than re-testing `worktreeInfo` /* `willOpenPR` — the caller already resolved those into `mode`.*/-export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, mode = null, canTypeSlashCommands = false, ownsPrWorkflow = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);if (canTypeSlashCommands && mode === COMPLETION_MODES.WORKTREE_NO_PUSH) {@@ -1028,9 +1075,9 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleti// 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.- // `ownsPrWorkflow` already folds in `willOpenPR`, the worktree, and the+ // `rendersInlinePrLifecycle` already folds in `willOpenPR`, the worktree, and the// leave-open exclusions (it is `inlinePrLifecycleSection() !== null`).- if (ownsPrWorkflow) {+ if (rendersInlinePrLifecycle) {const lines = ['## Completion', ...(noChangeSuccess ? ['', NO_CHANGE_AUDIT_GUIDANCE, ''] : []), '**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