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
feat: verify the merge-gate contract before a completing agent tears down (#5876)
Adam Eivy1dd12a767685
diff --git a/server/lib/README.md b/server/lib/README.mdindex 22b80f4c0b..49c7c9ad3d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -475,6 +475,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `openapiDowngrade.js` | `OPENAPI_VERSION` plus `toOpenApi30Schema` / `toOpenApi30Operation`, which rewrite Zod's draft-2020-12 output (null unions, numeric exclusive bounds, `const`, tuples, `propertyNames`) into the OpenAPI 3.0.3 dialect. Apply ONLY at the OpenAPI document boundary — the AsyncAPI payloads, CoS provider tool definitions, and tool resource read the same schemas as plain JSON Schema, where these rewrites silently widen bounds and drop null branches. || `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`. || `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, 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`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex cab611c94a..0978235428 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -452,6 +452,7 @@ export * from './objects.js';export * from './openapiSpec.js';export * from './openapiDowngrade.js';export * from './apiToolResource.js';+export * from './mergeGateContract.js';export * from './prDisposition.js';export * from './prReviewReport.js';export * from './repoStateExpectations.js';diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.jsnew file mode 100644index 0000000000..d56d0c1743--- /dev/null+++ b/server/lib/mergeGateContract.js@@ -0,0 +1,104 @@+/**+ * 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 —+ * 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+ * finish a 30-second merge.+ *+ * This module is the pure decision logic for a cheaper first line of+ * defense: while the agent's session is still attached, check whether its+ * own sentinel and the PR it opened agree that the Merge Gate is done, and+ * — for exactly one nudge — re-prompt instead of tearing the session down.+ * The PR lookup itself lives in `../services/prProbe.js`, and the re-prompt+ * delivery (pasting into the live PTY) lives in `agentTuiSpawning.js` — kept+ * out of here so this stays testable without either.+ */++/**+ * Did this run's own task shape ask it to own the merge?+ *+ * 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`).+ *+ * @param {{taskOpenPR: boolean, ownsPrWorkflow: boolean, leaveOpen: boolean}} params+ * @returns {boolean}+ */+export function mergeGateOwed({ taskOpenPR, ownsPrWorkflow, leaveOpen }) {+ return !!taskOpenPR && !!ownsPrWorkflow && !leaveOpen;+}++// What the Merge Gate's own step 4 asks the agent to say when it deliberately+// doesn't merge ("Do NOT exit until state is MERGED (or you have explicitly+// decided not to merge per the rule above)") — a STATED decision, not+// something inferred from the PR being open. Matches the shapes an agent's+// own prose actually uses for that decision, not every possible phrasing.+const LEAVE_OPEN_PATTERNS = [+ /\bleav(?:e|ing)\b[^.\n]{0,40}\bopen\b/i,+ /\bleft\b[^.\n]{0,40}\b(?:pr|pull request|merge request|mr)\b[^.\n]{0,20}\bopen\b/i,+ /\b(?:not merg(?:e|ed|ing)|did(?:n'?t| not) merge)\b/i,+ /\breview[- ]blocked\b/i,+];++/**+ * Does the agent's own completion summary say it decided not to merge?+ *+ * @param {string|null|undefined} summary+ * @returns {boolean}+ */+export function summaryStatesLeaveOpen(summary) {+ if (!summary) return false;+ return LEAVE_OPEN_PATTERNS.some((pattern) => pattern.test(summary));+}++/**+ * Resolve what a completing run that owed a merge should do next.+ *+ * - `merged` — the PR landed; finalize normally.+ * - `unreadable` — no PR found, or the forge lookup itself failed; there is+ * nothing here to act on, so finalize normally and let the post-teardown+ * audit (`agentRepoStateVerification.js`) be the backstop, as today.+ * - `leave-open-stated` — the agent said, in its own words, that it is+ * deliberately leaving the PR open; that is a correct terminal state.+ * - `needs-reprompt` — the PR is open, the summary names no blocker, and no+ * nudge has gone out yet this run: send exactly one corrective re-prompt.+ * - `reprompt-exhausted` — the nudge already fired once and the PR is STILL+ * open with no blocker stated; stop nudging and let the audit's recovery+ * task take over, per the "re-prompt once, not N times" decision.+ *+ * @param {object} params+ * @param {{prState: string|null, readable: boolean}|null} params.prProbe+ * @param {string|null|undefined} params.summary+ * @param {boolean} params.alreadyReprompted+ * @returns {'merged'|'unreadable'|'leave-open-stated'|'needs-reprompt'|'reprompt-exhausted'}+ */+export function resolveMergeGateVerdict({ prProbe, summary, alreadyReprompted }) {+ if (!prProbe || prProbe.readable === false) return 'unreadable';+ if (prProbe.prState === 'MERGED') return 'merged';+ if (prProbe.prState !== 'OPEN') return 'unreadable';+ if (summaryStatesLeaveOpen(summary)) return 'leave-open-stated';+ return alreadyReprompted ? 'reprompt-exhausted' : 'needs-reprompt';+}++/**+ * The corrective prompt re-pasted into the still-attached session. Names the+ * PR and points back at the Merge Gate's own numbered steps rather than+ * re-explaining the procedure — the agent already has it in context.+ *+ * @param {string} prUrl+ * @returns {string}+ */+export function buildMergeGateReprompt(prUrl) {+ return [+ `Your Merge Gate is not finished: ${prUrl} is still OPEN and your last summary did not say you were leaving it open.`,+ 'Work through the Merge Gate steps from your original instructions now: watch required CI to green, merge with `gh pr merge "<PR_URL>" --merge --delete-branch`, and confirm `gh pr view "<PR_URL>" --json state -q .state` returns `MERGED` before exiting.',+ 'If it truly cannot merge (a required check is red after a genuine fix attempt, or there is a conflict only a human can resolve), say so explicitly and leave it open.',+ ].join('\n');+}diff --git a/server/lib/mergeGateContract.test.js b/server/lib/mergeGateContract.test.jsnew file mode 100644index 0000000000..eca810acbb--- /dev/null+++ b/server/lib/mergeGateContract.test.js@@ -0,0 +1,100 @@+import { describe, it, expect } from 'vitest';+import { mergeGateOwed, summaryStatesLeaveOpen, resolveMergeGateVerdict, buildMergeGateReprompt } from './mergeGateContract.js';++describe('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);+ });++ 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);+ });++ 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);+ });++ 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);+ });++ 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);+ });+});++describe('summaryStatesLeaveOpen', () => {+ it('is false for an empty or missing summary', () => {+ expect(summaryStatesLeaveOpen(null)).toBe(false);+ expect(summaryStatesLeaveOpen(undefined)).toBe(false);+ expect(summaryStatesLeaveOpen('')).toBe(false);+ });++ it('is false for a plain shipped-it summary', () => {+ expect(summaryStatesLeaveOpen('Shipped the fix and opened the PR.')).toBe(false);+ });++ it.each([+ 'A required check is still red after two fix attempts — leaving the PR open for a human.',+ 'Left the merge request open because of an unresolved conflict.',+ 'I did not merge because branch protection blocked it.',+ 'Required review is review-blocked, so the PR stays open.',+ ])('recognizes a stated leave-open decision: %s', (summary) => {+ expect(summaryStatesLeaveOpen(summary)).toBe(true);+ });+});++describe('resolveMergeGateVerdict', () => {+ const summary = 'Shipped the fix and opened the PR.';++ it('is "merged" when the PR landed', () => {+ expect(resolveMergeGateVerdict({+ prProbe: { prState: 'MERGED', readable: true }, summary, alreadyReprompted: false,+ })).toBe('merged');+ });++ it('is "unreadable" when the forge lookup itself failed', () => {+ expect(resolveMergeGateVerdict({+ prProbe: { prState: null, readable: false }, summary, alreadyReprompted: false,+ })).toBe('unreadable');+ });++ it('is "unreadable" when there is no probe result at all', () => {+ expect(resolveMergeGateVerdict({ prProbe: null, summary, alreadyReprompted: false })).toBe('unreadable');+ });++ it('is "unreadable" when the forge found no PR for the branch', () => {+ expect(resolveMergeGateVerdict({+ prProbe: { prState: null, readable: true }, summary, alreadyReprompted: false,+ })).toBe('unreadable');+ });++ it('is "leave-open-stated" when the PR is open and the summary says so', () => {+ expect(resolveMergeGateVerdict({+ prProbe: { prState: 'OPEN', readable: true },+ summary: 'Leaving the PR open — CI is still red.',+ alreadyReprompted: false,+ })).toBe('leave-open-stated');+ });++ it('is "needs-reprompt" when the PR is open, no blocker is stated, and no nudge has gone out yet', () => {+ expect(resolveMergeGateVerdict({+ prProbe: { prState: 'OPEN', readable: true }, summary, alreadyReprompted: false,+ })).toBe('needs-reprompt');+ });++ it('is "reprompt-exhausted" when the PR is STILL open after the one allowed nudge', () => {+ expect(resolveMergeGateVerdict({+ prProbe: { prState: 'OPEN', readable: true }, summary, alreadyReprompted: true,+ })).toBe('reprompt-exhausted');+ });+});++describe('buildMergeGateReprompt', () => {+ it('names the PR URL and points back at the Merge Gate steps', () => {+ const text = buildMergeGateReprompt('https://example.com/pr/1');+ expect(text).toContain('https://example.com/pr/1');+ expect(text).toContain('Merge Gate');+ expect(text.toLowerCase()).toContain('merged');+ });+});diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 96dc3af1ef..f16ece14c8 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -43,6 +43,7 @@ import { isTruthyMeta } from './agentState.js';import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';import { leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';+import { probePrForBranch } from './prProbe.js';import {REPO_STATE_ISSUES,REPO_STATE_SKIPS,@@ -51,23 +52,12 @@ import {resolveRepoStateExpectation,} from '../lib/repoStateExpectations.js';-// `resolveForgeForRepo` spawns `git remote get-url` + `gh auth status` + `gh auth-// token` with no internal timeout; git.js races the same call on the agent-SPAWN-// path for exactly this reason. The completion path has the same property — a-// stalled gh (network / keychain hang) must not hold an agent lane open.-const FORGE_RESOLVE_TIMEOUT_MS = 10000;-// A task in any of these still HOLDS its branch and will resume on it, so a// branch one of them targets is owned, not leaked. `challenged` is the easy one// to miss: it is a parked-for-dispute status, not a terminal one, and its task// keeps its resume pointer (`cosTaskStore.js` `challengeTask`).const PENDING_OWNER_STATUSES = new Set(['pending', 'in_progress', 'blocked', 'challenged']);-const withTimeout = (promise, ms, fallback) => Promise.race([- promise,- new Promise(resolve => setTimeout(() => resolve(fallback), ms)),-]);-/*** Is something ALREADY queued to land this branch?*@@ -175,37 +165,13 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, brancreturn heads ? heads.has(branchName) : null;};- // Ask whichever forge this remote actually lives on. Both lookups share the- // same tri-state contract and both return the change request's state in- // `detail`, so no second round trip is needed to read it.+ // Ask whichever forge this remote actually lives on, via the shared probe+ // (`prProbe.js`) — `verifyPrClaim` already owns "the agent never opened+ // one", so there is nothing here to report and nothing missing on a `none`+ // answer.const probePr = async () => {if (!prExpected || !branchShouldBeGone) return { prState: null, prUrl: null, prNumber: null, cli: null, readable: true };- const forge = await withTimeout(- git.resolveForgeForRepo(sourceWorkspace).catch(() => null),- FORGE_RESOLVE_TIMEOUT_MS,- null- );- if (!forge?.cli) return { prState: null, prUrl: null, prNumber: null, cli: null, readable: false };- const { cli, env } = forge;- const found = cli === 'glab'- ? await (await import('./gitlab.js')).findMergeRequestForBranch(branchName, sourceWorkspace)- .catch(() => ({ status: 'unavailable' }))- : await (await import('./github.js')).findPullRequestForBranch(branchName, { cwd: sourceWorkspace, env: env || null })- .catch(() => ({ status: 'unavailable' }));- if (found.status === 'unavailable') return { prState: null, prUrl: null, prNumber: null, cli, readable: false };- // `none` is a real answer, not a gap — `verifyPrClaim` already owns "the agent- // never opened one", so there is nothing here to report and nothing missing.- if (found.status !== 'found') return { prState: null, prUrl: null, prNumber: null, cli, readable: true };- return {- prState: found.detail ? String(found.detail).toUpperCase() : null,- prUrl: found.url || null,- // The forge's own identifier for the change request — a GitLab `glab mr- // merge` line needs the IID, and emitting a literal `<iid>` placeholder- // hands the recovery agent a command it cannot run.- prNumber: found.number ?? null,- cli,- readable: !!found.detail,- };+ return probePrForBranch(sourceWorkspace, branchName);};// `allowRemote: false` — a bookkeeping question must not block on `git remotediff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 69736c19e5..ade1e3aa8d 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -21,8 +21,10 @@ import { resolveAgentCliCwd } from '../lib/spawnCwd.js';import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';-import { PR_CREATION, prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';+import { PR_CREATION, prClaimWasVerified, resolvePrCompletion, resolvePrCreation, leavesPrForHuman } from '../lib/prDisposition.js';import { canTypeSlashCommands, agentOwnsPrWorkflow } from '../lib/slashdoInvocation.js';+import { mergeGateOwed, resolveMergeGateVerdict, buildMergeGateReprompt } from '../lib/mergeGateContract.js';+import { probePrForBranch } from './prProbe.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { normalizeReviewers } from '../lib/validation.js';import * as git from './git.js';@@ -576,9 +578,31 @@ export async function spawnTuiAgent({// Resolved from the shared helper, so this is byte-identical to the path the// prompt told the agent to write (see resolveSentinelPath).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. Computed once up front (rather+ // than inside finish()) so the merge-gate contract check below and finish()+ // itself read the same answer.+ const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const agentOwnsPR = taskOpenPR && agentOwnsPrWorkflow({ providerType: PROVIDER_TYPES.TUI, 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.+ const mergeGateIsOwed = mergeGateOwed({ taskOpenPR, ownsPrWorkflow: agentOwnsPR, leaveOpen: leavesPrForHuman(task) });const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);const commandName = tuiConfig.command.split('/').pop();let finalized = false;+ // Synchronous re-entrancy guard for finish() — see its own comment for why+ // `finalized` alone isn't enough once the merge-gate check adds awaits+ // before it (#5876).+ let finishing = false;+ // Caps the merge-gate re-prompt (#5876) at once per run — a local closure+ // counter is enough: the check only ever runs from this same live process,+ // and a fresh spawn (a real retry) starts a fresh closure with its own flag.+ let mergeGateReprompted = false;let immediateFallbackAnalysis = null;const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();// Holds the wait-it-out window for a provider signal carrying a `graceMs`@@ -709,9 +733,12 @@ export async function spawnTuiAgent({// different things in two places.const sentinelPresent = () => !!doneSentinelPath && existsSync(doneSentinelPath);+ // Returns the sentinel's `summary` text (or null on a second call / no+ // sentinel / an empty summary) — the merge-gate contract check below reads+ // this same return value rather than re-reading the file a second time.const ingestDoneSentinel = async () => {- if (sentinelIngested) return;- if (!sentinelPresent()) return;+ if (sentinelIngested) return null;+ if (!sentinelPresent()) return null;sentinelIngested = true;const contents = await readFile(doneSentinelPath, 'utf8').catch(err => {console.error(`❌ ingestDoneSentinel readFile failed: ${err.message}`);@@ -723,13 +750,70 @@ export async function spawnTuiAgent({// read mode-agnostically in finalizeAgent). A legacy plain-markdown sentinel// parses back as its own text, so this is a no-op change for existing types.const { summary } = parseSentinelPayload(contents);- if (!summary) return;+ if (!summary) return null;// Shared constant, not a literal: `extractAgentSummary` anchors the PR-body// extraction on this exact line to tell the agent's summary apart from the// lifecycle telemetry above it. Reword it here only, and the noise returns.appendLine(SENTINEL_COMPLETION_MARKER);const truncated = summary.length > 4096 ? `${summary.slice(0, 4096)}\n…[truncated]` : summary;for (const line of truncated.split('\n')) appendLine(line);+ return summary;+ };++ // Sentinel-file watcher. The agent's prompt instructs it to write+ // .agent-done in the workspace after running /simplify + /do:pr and then+ // stop (it does NOT `/quit` — that is a UI command it can't invoke). This+ // watcher is the PRIMARY finalize path: it fires finish() shortly after the+ // sentinel appears, and finish()'s own cleanup kills the still-running TUI+ // session. The actual sentinel READ happens in finish() (via+ // ingestDoneSentinel) so the resolution is captured no matter which path+ // finalizes. A normal shell exit or explicit provider failure handles+ // agents that do not write the sentinel.+ //+ // `watchForFile` is one-shot (it detects, closes itself, then calls back) —+ // so a run whose merge-gate check re-prompts and deletes the sentinel to+ // await a SECOND completion needs a brand-new watcher, not a re-trigger of+ // this one. Factored out so both call sites build the exact same watcher.+ const armSentinelWatcher = () => (doneSentinelPath ? watchForFile(doneSentinelPath, async () => {+ if (finalized) return;+ await finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });+ }) : null);++ /**+ * Merge Gate contract check (#5876) — runs on a successful sentinel, before+ * ANY teardown, for a run whose own task shape said it owed a merge. Asks+ * the forge whether the PR this run opened actually landed and, if it is+ * still open with no blocker stated in the agent's own summary, re-pastes+ * one corrective nudge into the still-attached session instead of paying+ * for a cold recovery agent (`agentRepoStateVerification.js`) to do the+ * same merge later. See mergeGateContract.js for the decision table.+ *+ * @returns {Promise<boolean>} true when a re-prompt went out — the caller+ * must NOT finalize this call; false means finalize normally.+ */+ const checkMergeGateCompliance = async (summary) => {+ if (!mergeGateIsOwed || mergeGateReprompted) return false;+ const branchName = await git.getBranch(cwd).catch(() => null);+ if (!branchName) return false;+ const prProbe = await probePrForBranch(cwd, branchName).catch(() => null);+ const verdict = resolveMergeGateVerdict({ prProbe, summary, alreadyReprompted: mergeGateReprompted });+ if (verdict !== 'needs-reprompt') return false;+ if (!pasteController?.resubmit({ text: buildMergeGateReprompt(prProbe.prUrl || '<PR_URL>'), label: 'merge-gate contract nudge' })) {+ // Session is already gone — nothing to nudge; fall through to finalize.+ return false;+ }+ mergeGateReprompted = true;+ // Reopen the completion window: a fresh `.agent-done` write after the+ // nudge must be re-ingested (not silently skipped by the once-only guard)+ // and needs a brand-new watcher — the original already closed itself on+ // its first (this) detection.+ sentinelIngested = false;+ if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});+ const agentData = activeAgents.get(agentId);+ if (agentData) agentData.doneSentinelWatcher = armSentinelWatcher();+ appendLine(`🔁 Merge Gate not finished (PR still OPEN, no blocker stated) — re-prompted the session (1 nudge only)`);+ emitLog('warn', `🔁 Merge-gate contract nudge sent for ${agentId} — PR still OPEN with no stated blocker`, { agentId });+ return true;};/**@@ -758,7 +842,18 @@ export async function spawnTuiAgent({};const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {- if (finalized) return;+ // `finalized` alone used to be the whole re-entrancy guard, safe because it+ // was set SYNCHRONOUSLY as this function's first act. The merge-gate check+ // below needs `ingestDoneSentinel`'s summary before it can decide whether+ // to finalize at all, which pushes `finalized = true` past several awaits —+ // wide enough for a second trigger (the shell exiting right after the+ // sentinel appears) to also pass the `if (finalized)` gate before the first+ // call sets it, double-firing `finalizeAgent`. `finishing` closes that+ // window synchronously; `finalized` still means "truly done" and is what+ // `pasteController.resubmit()` reads, so it must stay false while a+ // re-prompt is still possible.+ if (finalized || finishing) return;+ finishing = true;// PortOS is going down. Whatever path got here — the PTY exiting under// TreeKill, a provider-signal failure, a paste that failed because the shell died —// the cause is the host restart, not the agent, so there is no outcome to@@ -781,19 +876,32 @@ export async function spawnTuiAgent({await abandonForHostShutdown();return;}++ // Ingest the .agent-done sentinel BEFORE any teardown decision, so its+ // markdown summary lands in outputBuffer/output.txt regardless of WHICH+ // path finalized the agent, AND so the merge-gate contract check right+ // below reads the same text without a second file read. The completion+ // workflow writes the sentinel and stops; the 2s doneSentinelWatcher is+ // what normally calls finish(). Idempotent via `sentinelIngested`.+ const sentinelSummary = await ingestDoneSentinel();++ // Merge Gate contract check (#5876): only for a run that actually+ // succeeded — a failed/killed run never reached its own Merge Gate steps,+ // and re-prompting it would paste a corrective nudge over a dead or+ // errored session. Returns true (and this call does NOT finalize) exactly+ // once, when the run owed a merge, the PR is open, and the summary names+ // no blocker — see mergeGateContract.js for the full decision table.+ if (success && await checkMergeGateCompliance(sentinelSummary)) {+ // Not finalizing — reopen the re-entrancy gate for the next completion+ // signal the re-prompt is expected to produce.+ finishing = false;+ return;+ }+finalized = true;const agentData = stopRunMachinery();- // Ingest the .agent-done sentinel BEFORE draining, so its markdown summary- // lands in outputBuffer/output.txt regardless of WHICH path finalized the- // agent. The completion workflow writes the sentinel and stops; the 2s- // doneSentinelWatcher is what normally calls finish(). Reading it here- // (not just in the watcher) keeps the resolution captured even when shell exit- // finalizes first. Idempotent- // via `sentinelIngested`.- await ingestDoneSentinel();-// Drain pending parsed lines AND raw chunks before the final state// writes so completion events don't beat the last output batch to disk.await drainLines();@@ -852,15 +960,11 @@ export async function spawnTuiAgent({completionError: finalError,});- // Every TUI that is a real coding harness drives its own push → PR → review- // → merge, whether or not it can type `/do:pr` (#3733) — a Claude TUI runs- // the slashdo command, codex/antigravity/grok/OpenCode run the plain- // `git`/`gh` equivalent from the same prompt. Only a lean `--bare` session- // still hands the lifecycle back to PortOS. Derived from the same predicate- // the prompt builder used so neither side can believe the other owns the PR.- const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ // `taskOpenPR` / `agentOwnsPR` are computed once, up front, near+ // `doneSentinelPath` — the merge-gate contract check above reads the same+ // answer this cleanup path does, so neither side can believe the other+ // owns the PR (#3733).const taskReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);- const agentOwnsPR = taskOpenPR && agentOwnsPrWorkflow({ providerType: PROVIDER_TYPES.TUI, leanMode });// …but PR-claim verification (#3358) stays keyed on the SLASH-command// predicate. A run PortOS still backstops (it re-checks the forge at cleanup// and opens the PR itself when the agent skipped it) must not be failed here@@ -1614,19 +1718,7 @@ export async function spawnTuiAgent({}}, PROVIDER_SIGNAL_POLL_MS);- // Sentinel-file watcher. The agent's prompt instructs it to write- // .agent-done in the workspace after running /simplify + /do:pr and then- // stop (it does NOT `/quit` — that is a UI command it can't invoke). This- // watcher is the PRIMARY finalize path: it fires finish() shortly after the- // sentinel appears, and finish()'s own cleanup kills- // the still-running TUI session. The actual sentinel READ happens in finish()- // (via ingestDoneSentinel) so the resolution is captured no matter which path- // finalizes. A normal shell exit or explicit provider failure handles agents- // that do not write the sentinel.- const doneSentinelWatcher = doneSentinelPath ? watchForFile(doneSentinelPath, async () => {- if (finalized) return;- await finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' });- }) : null;+ const doneSentinelWatcher = armSentinelWatcher();activeAgents.set(agentId, {process: ptyProcess || { kill: () => shellService.killSession(sessionId) },diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 0eacfe043c..eccb4d4475 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -110,6 +110,16 @@ vi.mock('./git.js', () => ({getDiff: vi.fn().mockResolvedValue('diff content here'),// No owner-matched gh account by default → empty overlay (ambient auth kept).resolveForgeTokenEnv: vi.fn().mockResolvedValue({}),+ // Read by the merge-gate contract check (#5876) to name the branch it+ // probes the forge for.+ getBranch: vi.fn().mockResolvedValue('claim/issue-5876'),+}));++// The forge lookup itself (`resolveForgeForRepo` + gitlab.js/github.js) is+// exercised on its own in prProbe.test.js — this suite only needs to drive+// the merge-gate contract check's branching on the tri-state result.+vi.mock('./prProbe.js', () => ({+ probePrForBranch: vi.fn().mockResolvedValue({ prState: null, prUrl: null, prNumber: null, cli: null, readable: true }),}));// Lazily imported by finish()'s cleanup block to record a failed run's resume@@ -227,6 +237,7 @@ import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgentLifecycle from './cosAgentLifecycle.js';import * as gitService from './git.js';+import { probePrForBranch } from './prProbe.js';import { activeAgents, userTerminatedAgents } from './agentState.js';import {SELF_CLEARING_RESUBMIT_INTERVAL_MS,@@ -2425,4 +2436,127 @@ describe('spawnTuiAgent runtime', () => {});});++ // ── Merge Gate contract check (#5876) ────────────────────────────────────+ // A run that owns its own PR lifecycle (`openPR: true`, a TUI/CLI provider,+ // not leaned/handed-to-a-human) is told to merge its own PR before exiting.+ // These tests drive `finish()` via the shell-exit path (same as the+ // completion-sentinel suite above) with a `.agent-done` sentinel already on+ // disk, and assert on the re-prompt delivery (`shellService.pasteToSession`)+ // and on whether `finalizeAgent` — the point of no return — was reached.+ describe('merge-gate contract check (#5876)', () => {+ const openPrTask = { id: 'task-1', description: 'ship the fix', metadata: { openPR: true } };++ const withSentinel = (summary) => {+ vi.mocked(existsSync).mockReturnValue(true);+ vi.mocked(readFile).mockImplementation(async (p) =>+ typeof p === 'string' && p.endsWith('.agent-done-agent-1') ? summary : ''+ );+ };++ // The merge-gate check adds real await hops (ingestDoneSentinel's readFile,+ // git.getBranch, probePrForBranch) before finish() reaches finalizeAgent —+ // more than the module-level `flushMicrotasks`'s fixed 3 hops reliably+ // drains. Loop it rather than deepen the shared helper for every caller.+ const settle = async () => {+ for (let i = 0; i < 8; i += 1) await flushMicrotasks();+ };++ it('re-prompts exactly once when the PR is open and the summary names no blocker, then finalizes on the next completion even if it is still open', async () => {+ vi.mocked(shellService.pasteToSession).mockReturnValue(999);+ vi.mocked(probePrForBranch).mockResolvedValue({+ prState: 'OPEN', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true,+ });+ withSentinel('## Summary\nShipped the fix and opened the PR.');++ const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();++ // Round 1: nudged, not finalized.+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);+ expect(shellService.pasteToSession.mock.calls[0][1]).toContain('still OPEN');+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();++ // Round 2 (a fresh completion after the nudge): still OPEN, still no+ // blocker stated — but the cap is one nudge per run, so this finalizes.+ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();+ await spawnPromise;++ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);+ });++ it('finalizes on the first sentinel with no re-prompt when the PR is already merged', async () => {+ vi.mocked(probePrForBranch).mockResolvedValue({+ prState: 'MERGED', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true,+ });+ withSentinel('## Summary\nMerged the PR.');++ const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();+ await spawnPromise;++ expect(shellService.pasteToSession).not.toHaveBeenCalled();+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);+ });++ it('finalizes on the first sentinel with no re-prompt when the summary states it is deliberately leaving the PR open', async () => {+ vi.mocked(probePrForBranch).mockResolvedValue({+ prState: 'OPEN', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true,+ });+ withSentinel('## Summary\nA required check is still red after two fix attempts — leaving the PR open for a human.');++ const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();+ await spawnPromise;++ expect(shellService.pasteToSession).not.toHaveBeenCalled();+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);+ });++ it('finalizes on the first sentinel with no re-prompt when the forge lookup is unreadable', async () => {+ vi.mocked(probePrForBranch).mockResolvedValue({+ prState: null, prUrl: null, prNumber: null, cli: null, readable: false,+ });+ withSentinel('## Summary\nShipped the fix and opened the PR.');++ const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();+ await spawnPromise;++ expect(shellService.pasteToSession).not.toHaveBeenCalled();+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);+ });++ it('never probes the forge or re-prompts for a run that never asked for a PR', async () => {+ withSentinel('## Summary\nDid the audit, no PR needed.');++ const spawnPromise = runSpawn({+ task: { id: 'task-1', description: 'audit only', metadata: {} },+ workspacePath: '/tmp/ws',+ });+ await flushMicrotasks();++ await capturedOnExit({ exitCode: 0, killed: false });+ await settle();+ await spawnPromise;++ expect(probePrForBranch).not.toHaveBeenCalled();+ expect(shellService.pasteToSession).not.toHaveBeenCalled();+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/server/services/prProbe.js b/server/services/prProbe.jsnew file mode 100644index 0000000000..48124d98d7--- /dev/null+++ b/server/services/prProbe.js@@ -0,0 +1,62 @@+/**+ * Forge-agnostic "what change request exists for this branch" lookup.+ *+ * Extracted out of `agentRepoStateVerification.js`'s `probePr` (#5876) so a+ * second caller — the merge-gate contract check in `agentTuiSpawning.js`,+ * which asks the same question BEFORE that module's post-teardown audit runs+ * — shares one definition instead of re-deriving the tri-state contract.+ */++import * as git from './git.js';++// `resolveForgeForRepo` spawns `git remote get-url` + `gh auth status` + `gh+// auth token` with no internal timeout, so a stalled `gh` (network / keychain+// hang) must not hold a caller open indefinitely.+const FORGE_RESOLVE_TIMEOUT_MS = 10000;++const withTimeout = (promise, ms, fallback) => Promise.race([+ promise,+ new Promise((resolve) => setTimeout(() => resolve(fallback), ms)),+]);++/**+ * Resolve the open (or merged/closed) pull/merge request for `branchName`.+ *+ * Every field is tri-state: `readable: false` means the lookup itself could+ * not be completed (no forge CLI resolvable, or the forge call failed) — not+ * "no PR exists". `prState: null` with `readable: true` means the forge was+ * asked and answered "none" for this branch.+ *+ * @param {string} sourceWorkspace - a git working directory with the remote+ * configured (a worktree qualifies — it shares its parent's git config).+ * @param {string} branchName+ * @returns {Promise<{prState: string|null, prUrl: string|null, prNumber: number|string|null, cli: string|null, readable: boolean}>}+ */+export async function probePrForBranch(sourceWorkspace, branchName) {+ const forge = await withTimeout(+ git.resolveForgeForRepo(sourceWorkspace).catch(() => null),+ FORGE_RESOLVE_TIMEOUT_MS,+ null+ );+ if (!forge?.cli) return { prState: null, prUrl: null, prNumber: null, cli: null, readable: false };+ const { cli, env } = forge;+ const found = cli === 'glab'+ ? await (await import('./gitlab.js')).findMergeRequestForBranch(branchName, sourceWorkspace)+ .catch(() => ({ status: 'unavailable' }))+ : await (await import('./github.js')).findPullRequestForBranch(branchName, { cwd: sourceWorkspace, env: env || null })+ .catch(() => ({ status: 'unavailable' }));+ if (found.status === 'unavailable') return { prState: null, prUrl: null, prNumber: null, cli, readable: false };+ // `none` is a real answer, not a gap — callers that need "the agent never+ // opened one" distinguished from "we couldn't ask" read `readable` for that.+ if (found.status !== 'found') return { prState: null, prUrl: null, prNumber: null, cli, readable: true };+ return {+ prState: found.detail ? String(found.detail).toUpperCase() : null,+ prUrl: found.url || null,+ // The forge's own identifier for the change request — a GitLab `glab mr+ // merge` line needs the IID, and emitting a literal `<iid>` placeholder+ // hands a caller a command it cannot run.+ prNumber: found.number ?? null,+ cli,+ readable: !!found.detail,+ };+}