Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: verify an agent's PR exists before recording the run a success (#3358)
[._.]/ Adam Eivyaef7aac1ce2d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0362951ffe..caa2855cf7 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -158,6 +158,7 @@- **[issue-3335] Deleting a prompt stage now checks the source, not a hand-written list of ten.** `DELETE /api/prompts/:stage` force-guarded exactly the ten curated CoS/Brain/Memory stages, so removing `pipeline-series-concept-judge` (or roughly a hundred others PortOS resolves by literal key) succeeded with no warning and left the feature naming it throwing `Stage <key> not found` on its next run. Adding them all to the curated table was the wrong fix — the same table drives the Prompt Manager's `SYSTEM` badge and its "System only" filter, and badging ~100 of 127 rows makes both meaningless. Deletion protection is now a second, generated set: a checked-in manifest indexes every stage key a `server/` source names, including the ones reached only through an interpolated prefix like `pipeline-panel-${personaId}`, and a drift test fails until a new call site is regenerated into it. The badge and the filter still show the same ten stages; the delete dialog now names the files that reference the one you're about to remove.- **[issue-3288] Video render submission is no longer a 717-line route handler — and a failed lookup mid-request stops orphaning your upload.** `POST /api/video-gen` did request validation, backend-pin resolution, model checks, durable staging for four upload kinds with rollback bookkeeping, IC-LoRA/keyframe/a2v validation, render-history lookups, LoRA normalization and chunk resolution inline, with twenty-plus throw sites sharing mutable cleanup state — so every new video-gen parameter meant editing the monolith and risking an unrelated validation branch. That whole region now lives in `services/videoGen/prepareParams.js`, mirroring what `imageGen` already did, and the route is a thin parse → prepare → enqueue → respond shell. Validation order and the exact cleanup-on-throw unwind are preserved verbatim, pinned by the existing route suite plus a new service suite. The extraction also closed a real leak (#3326): every *explicit* throw released the staged uploads, but a plain rejected `await` — a music-video project or track lookup, a render-history read, or the enqueue itself — bubbled straight past them, orphaning up to 100MB per request under `data/uploads` with no job to ever clean it up. One rollback guard now covers every rejection point at once and stays correct as new awaits are added, rethrowing the original error untouched.- **[issue-3353] Client tests that type into a field and then submit no longer race the keystrokes.** A Stacker News save test failed on CI for a pull request whose entire diff was a dependency config file, and passed on the rerun. The cause is a shape that suite had in six places: `user.type` enters `20` as two separate events, and nothing between the last keystroke and the Save click asserted that the controlled input had actually reached `20` — so under load the click could send a payload built from the intermediate `2`, or from the post-clear empty string that `Number('')` turns into `0`. Waiting on the assertion cannot recover from that, because the call has already happened with the wrong argument and re-waiting never produces a second one. A shared `src/test/settledInput.js` helper now pins the settled input value between the keystrokes and whatever depends on them, and every instance of the shape now uses it — all six in the Stacker News suite plus ten more found by auditing the rest of the client tests, across the CoS agent card and reviewer picker, the sprite reference workflow, the media jobs queue, the duplicate-universe merge tab, and Media Collections. Two of those submitted with Enter typed as part of the same keystroke run, where a partially-typed `bad token!` would have been a *valid* username and quietly emitted; the Enter is now a separate press after the draft is pinned. One more asserted only the navigation that followed its submit, so a half-typed collection name could not have failed it — it now asserts the request it sent. The failure mode it replaces is an honest one — an input that never settles now fails saying so, rather than silently asserting against a half-typed value.+- **[issue-3358] An unreachable `gh` no longer looks like a quiet repo — and an agent can no longer report success having filed no PR.** Around thirty call sites ran `gh` and turned *any* failure into an empty result, so a firewalled or unauthenticated CLI was indistinguishable from a repo with nothing going on: the PR watcher saw no PRs, the branch reconciler classified every pushed branch as "needs a PR" (and would have had an agent open duplicates on top of the ones already open), the issue reconciler saw nothing to reconcile, and none of it logged a distinguishable error. Those reads now answer with three states instead of two — the forge said nothing, the forge said nothing *exists*, or we could not ask — and every forge-dependent scheduled job (`pr-watcher`, `branch-reconcile`, `issue-reconcile`, layered intelligence, self-diagnostics) probes `gh` first and skips the cycle with one clear line rather than executing against a forge it cannot read. Separately, a run whose task shape promised a pull request is now verified against the forge before it is recorded complete: an agent that commits, pushes over SSH (unaffected by an outbound block) and then fails to create the PR is recorded as needing attention with the branch named, not as "Completed successfully" — and "we could not confirm the PR" is kept distinct from "there is no PR", so a network outage is treated as environmental instead of denting the task type's measured success rate.## Three.js Modelsdiff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 329c059d80..a771e8590d 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -859,6 +859,15 @@ export async function spawnDirectly({const analysisBuffer = rawStreamBuffer || outputBuffer;const errorAnalysis = finalSuccess ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));+ // Claude Code CLI agents run `/simplify` + `/do:pr` themselves (see+ // buildCliCompletionSection in agentPromptBuilder.js) — mirror the TUI+ // cleanup contract so PortOS doesn't double-fire push+PR creation. Resolved+ // BEFORE finalizeAgent because it also gates the PR-claim verification+ // (#3358): a PortOS-owned PR is created by the cleanup below, i.e. AFTER+ // finalize, so only an agent-owned PR can be verified there.+ const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');+// try/finally so a throw from finalizeAgent still runs the local// cleanup (worktree, pid unregister, activeAgents delete). Mirrors the// TUI path's pattern.@@ -878,16 +887,11 @@ export async function spawnDirectly({error: finalError || undefined,completionReason: terminatedByUser ? 'user-terminated' : undefined,workspacePath,+ prExpected: directAgentOwnsPR,});} finally {- // Clean up worktree if agent was using one. Claude Code CLI agents run- // `/simplify` + `/do:pr` themselves (see buildCliCompletionSection in- // agentPromptBuilder.js) — mirror the TUI cleanup contract so PortOS- // doesn't double-fire push+PR creation.- const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);const directPrCompletion = resolvePrCompletion(task.metadata);const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);- const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');const reviewOptions = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn });await cleanupWorktreeFn(agentId, finalSuccess, {openPR: directAgentOwnsPR ? false : directOpenPR,diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 6565dba0f0..7340cf1adb 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -18,6 +18,7 @@*/import { join } from 'path';+import { execGit } from '../lib/execGit.js';import { emitLog } from './cosEvents.js';import { getAgent, updateAgent, completeAgent } from './cosAgents.js';import { updateTask } from './cos.js';@@ -177,6 +178,100 @@ export function resolveProgrammaticIoVerdict({ success, hookResult }) {// output at all" — distinct from both a rejection and an acceptance.const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);+/**+ * Error categories for the two ways a PR-shaped run can finish without a PR+ * (#3358). Distinct from each other AND from a generic failure, because the+ * remedies are opposite: `pr-missing` is the agent's miss, `forge-unreachable`+ * is the machine's — the run may have been perfect and simply had no way to+ * reach the forge. `forge-unreachable` is registered in+ * `taskLearning/store.js#ENVIRONMENTAL_ERROR_CATEGORIES` so a firewalled `gh`+ * can't drag a task type's measured success rate down (or auto-park it).+ */+export const PR_MISSING_CATEGORY = 'pr-missing';+export const FORGE_UNREACHABLE_CATEGORY = 'forge-unreachable';++/**+ * The branch a finished agent's workspace is sitting on, or null when the+ * workspace is gone / not a repo / detached. Read at finalize time, while the+ * worktree still exists (cleanup runs after finalizeAgent in every spawn path).+ */+async function resolveWorkspaceBranch(workspacePath) {+ if (!workspacePath) return null;+ const result = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], workspacePath, { ignoreExitCode: true })+ .catch(() => null);+ const branch = (result?.stdout || '').trim();+ return branch && branch !== 'HEAD' ? branch : null;+}++/**+ * Verify that a run whose task shape PROMISED a pull request actually produced+ * one (#3358).+ *+ * The failure this closes: an agent that owns its own `/do:pr` step commits,+ * pushes over SSH (unaffected by an outbound block on `gh`), fails to create the+ * PR, writes its `.agent-done` sentinel anyway, and PortOS records "Completed+ * successfully" against a branch no one will ever review. Nothing else in the+ * completion path asks the forge whether the PR exists — `agentWorktreeCleanup`+ * only composes advisory prose SUGGESTING `gh pr list --head <branch>`.+ *+ * Only runs when `prExpected` — i.e. the AGENT owned PR creation. When PortOS+ * owns it (slashdo-free TUIs, runner mode) the PR is created by+ * `cleanupAgentWorktree` AFTER finalize, so checking here would report every+ * correct run as missing.+ *+ * Three outcomes, never collapsed:+ * - `ok: true` — a PR exists, or there was nothing to check+ * - `ok: false, category: 'pr-missing'` — the forge answered: no PR+ * - `ok: false, category: 'forge-unreachable'` — we could not ask+ *+ * @returns {Promise<{ ok: boolean, category?: string, message?: string, branch?: string|null }>}+ */+export async function verifyPrClaim({ task, workspacePath, success, prExpected }) {+ // Only a run that CLAIMED success has a claim to verify; a failed run is+ // already recorded as failed.+ if (!prExpected || !success || !workspacePath) return { ok: true };+ const branch = await resolveWorkspaceBranch(workspacePath);+ if (!branch) {+ // No branch to ask about (detached HEAD, non-repo workspace). Nothing was+ // verified — say nothing rather than invent a failure.+ return { ok: true, branch: null };+ }+ const { findPullRequestForBranch } = await import('./github.js');+ const found = await findPullRequestForBranch(branch, { cwd: workspacePath });+ if (found.status === 'found') return { ok: true, branch };+ if (found.status === 'none') {+ return {+ ok: false,+ branch,+ category: PR_MISSING_CATEGORY,+ message: `Agent reported success but no pull request exists for branch ${branch}`+ };+ }+ return {+ ok: false,+ branch,+ category: FORGE_UNREACHABLE_CATEGORY,+ message: `Could not confirm a pull request for branch ${branch} — the forge is unreachable${found.detail ? ` (${String(found.detail).split('\n')[0].slice(0, 120)})` : ''}`+ };+}++/**+ * The `errorAnalysis` shape for a failed PR verification. Non-actionable so the+ * task RETRIES (a re-run can open the missing PR, or find the forge back) rather+ * than blocking on a first miss — `resolveFailedTaskDecision` still blocks it+ * once it has burned its retry budget.+ */+function prVerificationAnalysis(verdict) {+ return {+ category: verdict.category,+ message: verdict.message,+ actionable: false,+ suggestedFix: verdict.category === PR_MISSING_CATEGORY+ ? `The branch ${verdict.branch} is pushed but has no pull request. Re-run the task, or open the PR by hand with \`gh pr create --head ${verdict.branch}\`.`+ : 'Check the forge probe on the System Health page — `gh` could not reach the forge, so the run\'s PR could not be confirmed.'+ };+}+/*** Hard bound on output-hook dispatch (#2727). The hook is only awaited BEFORE* `completeAgent` so its verdict can be recorded — but `status: 'running'` is what@@ -372,17 +467,40 @@ export async function finalizeAgent({task,runId,providerId,- success,+ success: reportedSuccess,exitCode,duration,outputBuffer,- errorAnalysis,+ errorAnalysis: reportedErrorAnalysis,terminatedByUser = false,isTruthyMetaFn,error,completionReason,workspacePath = null,+ prExpected = false,}) {+ // #3358: a run whose task shape promised a PR is not successful until the+ // forge confirms one exists. Runs BEFORE the completion verdict is derived so+ // every downstream write (task status, learning telemetry, the "Completed+ // successfully" the UI renders off `result.success`) sees the corrected value.+ // A THROW here is not a verdict — fall back to the reported outcome rather+ // than manufacturing a failure out of a check that never ran.+ const prVerdict = terminatedByUser+ ? { ok: true }+ : await verifyPrClaim({ task, workspacePath, success: reportedSuccess, prExpected })+ .catch(err => {+ emitLog('warn', `⚠️ PR verification failed for ${agentId}: ${err.message}`, { agentId });+ return { ok: true };+ });++ const success = reportedSuccess && prVerdict.ok;+ const errorAnalysis = prVerdict.ok ? reportedErrorAnalysis : prVerificationAnalysis(prVerdict);+ if (!prVerdict.ok) {+ emitLog('warn', `⚠️ ${prVerdict.message} — recording ${agentId} as needs-attention (${prVerdict.category}) rather than complete`, {+ agentId, taskId: task?.id, branch: prVerdict.branch, category: prVerdict.category+ });+ }+if (success && isTruthyMetaFn) {await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);}@@ -443,6 +561,12 @@ export async function finalizeAgent({// completeAgentRun writes its own runs/<id>/metadata.json (separate lock),// so its place in the chain is purely about progress reporting on partial// failure.+ // A PR-verification downgrade carries its own error text + reason: without+ // them the agent card would render a bare "Failed" for a run that actually+ // did everything but land its PR (or simply couldn't reach the forge).+ const finalError = prVerdict.ok ? error : prVerdict.message;+ const finalCompletionReason = prVerdict.ok ? completionReason : prVerdict.category;+await completeAgent(agentId, {success,validationPassed,@@ -450,12 +574,15 @@ export async function finalizeAgent({duration,outputLength: outputBuffer?.length ?? 0,errorAnalysis,- ...(error !== undefined ? { error } : {}),- ...(completionReason !== undefined ? { completionReason } : {}),+ ...(finalError !== undefined ? { error: finalError } : {}),+ ...(finalCompletionReason !== undefined ? { completionReason: finalCompletionReason } : {}),});if (runId) {- await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);+ // Pass the downgrade explicitly: this run exited 0, so the run record would+ // otherwise keep saying "success" for the one run we just concluded did not+ // land its PR (#3358).+ await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis, prVerdict.ok ? null : false);}// LI hand-off execution verdict (#2779): stamp the per-proposal execution outcome intodiff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsnew file mode 100644index 0000000000..57141c53b1--- /dev/null+++ b/server/services/agentFinalization.prVerification.test.js@@ -0,0 +1,232 @@+/**+ * Tests for the PR-claim verification finalizeAgent runs before it records a+ * completion (#3358).+ *+ * The bug: an agent that owns its own `/do:pr` step commits, pushes over SSH+ * (unaffected by an outbound block on `gh`), fails to create the pull request,+ * writes its `.agent-done` sentinel anyway — and PortOS records "Completed+ * successfully" against a branch nobody will ever review. Nothing in the+ * completion path asked the forge whether the PR exists.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const execGitMock = vi.fn();+vi.mock('../lib/execGit.js', () => ({+ execGit: (...args) => execGitMock(...args),+}));++const findPullRequestForBranchMock = vi.fn();+vi.mock('./github.js', () => ({+ findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args),+ ensureForgeReachable: vi.fn(async () => ({ ok: true, status: 'ok' })),+}));++vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));++const completeAgentMock = vi.fn();+vi.mock('./cosAgents.js', () => ({+ getAgent: vi.fn(async () => null),+ updateAgent: vi.fn(async () => null),+ completeAgent: (...args) => completeAgentMock(...args),+}));++const updateTaskMock = vi.fn(async () => ({}));+vi.mock('./cos.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));+vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => null) }));+vi.mock('./providerStatus.js', () => ({+ markProviderUsageLimit: vi.fn(async () => null),+ markProviderRateLimited: vi.fn(async () => null),+}));+vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));+vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));++const resolveFailedTaskUpdateMock = vi.fn(async (_task, analysis) => ({+ status: 'pending',+ metadata: { lastErrorCategory: analysis?.category || null },+}));+vi.mock('./agentErrorAnalysis.js', () => ({+ resolveFailedTaskUpdate: (...args) => resolveFailedTaskUpdateMock(...args),+ resolveTypeFailureSignal: vi.fn(() => ({ record: 'skip' })),+}));++const completeAgentRunMock = vi.fn(async () => null);+vi.mock('./agentRunTracking.js', () => ({+ checkForTaskCommit: vi.fn(async () => true),+ createAgentRun: vi.fn(),+ completeAgentRun: (...args) => completeAgentRunMock(...args),+}));++vi.mock('./taskTypeHooks.js', () => ({+ canRunTaskOutputHookWithoutPayload: vi.fn(() => false),+ isProgrammaticIoTaskType: vi.fn(() => false),+ resolveTaskHookType: vi.fn(() => null),+ declaresNoCommitCriterion: vi.fn(() => false),+ getTaskOutputHook: vi.fn(async () => null),+}));++vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));+vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));++import {+ verifyPrClaim,+ finalizeAgent,+ PR_MISSING_CATEGORY,+ FORGE_UNREACHABLE_CATEGORY,+} from './agentFinalization.js';++const onBranch = (name) => execGitMock.mockResolvedValue({ stdout: `${name}\n`, stderr: '', exitCode: 0 });++const prTask = () => ({+ id: 'task-1',+ taskType: 'internal',+ description: 'ship something',+ metadata: { openPR: true },+});++beforeEach(() => {+ vi.clearAllMocks();+ execGitMock.mockResolvedValue({ stdout: 'claim/issue-1\n', stderr: '', exitCode: 0 });+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7' });+});++describe('verifyPrClaim (#3358)', () => {+ it('passes when the forge confirms a PR for the branch', async () => {+ onBranch('claim/issue-1');+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(true);+ expect(findPullRequestForBranchMock).toHaveBeenCalledWith('claim/issue-1', { cwd: '/w' });+ });++ it('fails with pr-missing when the forge answered and has no PR', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ expect(verdict.branch).toBe('claim/issue-1');+ });++ it('fails with forge-unreachable — NOT pr-missing — when we could not ask', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({+ status: 'unavailable', number: null, url: null, detail: 'connect: bad file descriptor'+ });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(FORGE_UNREACHABLE_CATEGORY);+ // The two are deliberately distinct: one is the agent's miss, the other the+ // machine's, and only the latter is treated as environmental by learning.+ expect(verdict.category).not.toBe(PR_MISSING_CATEGORY);+ });++ it('does not check when PortOS (not the agent) owns PR creation', async () => {+ // The PR is created by cleanupAgentWorktree AFTER finalize, so a check here+ // would report every correct slashdo-free TUI / runner-mode run as missing.+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: false });+ expect(verdict.ok).toBe(true);+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();+ });++ it('does not check a run that already failed — there is no success claim to verify', async () => {+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: false, prExpected: true });+ expect(verdict.ok).toBe(true);+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();+ });++ it('passes (verifies nothing) when the workspace has no resolvable branch', async () => {+ execGitMock.mockResolvedValue({ stdout: 'HEAD\n', stderr: '', exitCode: 0 });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict.ok).toBe(true);+ expect(verdict.branch).toBeNull();+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();+ });+});++describe('finalizeAgent — a PR-shaped run with no PR is not a success (#3358)', () => {+ const finalize = (overrides = {}) => finalizeAgent({+ agentId: 'agent-1',+ task: prTask(),+ runId: null,+ providerId: 'claude-code',+ success: true,+ exitCode: 0,+ duration: 1000,+ outputBuffer: 'done',+ errorAnalysis: null,+ workspacePath: '/w',+ prExpected: true,+ ...overrides,+ });++ it('records success when the PR exists', async () => {+ onBranch('claim/issue-1');+ await finalize();+ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');+ });++ it('does NOT record "completed" when the forge says no PR exists', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await finalize();++ const [, result] = completeAgentMock.mock.calls[0];+ expect(result.success).toBe(false);+ expect(result.completionReason).toBe(PR_MISSING_CATEGORY);+ expect(result.error).toMatch(/no pull request exists for branch claim\/issue-1/i);+ // The task must not be marked completed — it goes back through the failure+ // path so it can retry and actually open the PR.+ expect(updateTaskMock).not.toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');+ });++ it('marks the RUN record failed too, even though the process exited 0', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await finalize({ runId: 'run-1' });+ // 6th arg is the explicit success override — without it the run history+ // would keep reporting success off `exitCode === 0`.+ expect(completeAgentRunMock).toHaveBeenCalledWith('run-1', 'done', 0, 1000, expect.anything(), false);+ });++ it('leaves the run record alone when the PR is confirmed', async () => {+ onBranch('claim/issue-1');+ await finalize({ runId: 'run-1' });+ expect(completeAgentRunMock).toHaveBeenCalledWith('run-1', 'done', 0, 1000, null, null);+ });++ it('records forge-unreachable (not a generic failure) when gh cannot be reached', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({+ status: 'unavailable', number: null, url: null, detail: 'connect: bad file descriptor'+ });+ await finalize();++ const [, result] = completeAgentMock.mock.calls[0];+ expect(result.success).toBe(false);+ expect(result.completionReason).toBe(FORGE_UNREACHABLE_CATEGORY);+ expect(result.errorAnalysis.category).toBe(FORGE_UNREACHABLE_CATEGORY);+ expect(result.errorAnalysis.actionable).toBe(false);+ expect(resolveFailedTaskUpdateMock).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'task-1' }),+ expect.objectContaining({ category: FORGE_UNREACHABLE_CATEGORY }),+ 'agent-1'+ );+ });++ it('leaves a user-terminated run alone — it is already recorded as terminated', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await finalize({ success: false, terminatedByUser: true });+ expect(findPullRequestForBranchMock).not.toHaveBeenCalled();+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'blocked' }), 'internal');+ });++ it('falls back to the reported outcome when the verification itself throws', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockRejectedValue(new Error('boom'));+ await finalize();+ // A check that never ran is not a verdict — it must not manufacture a failure.+ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));+ });+});diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex d2f17ee11d..537f8e1ba7 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -100,8 +100,13 @@ export async function checkForTaskCommit(taskId, workspacePath) {/*** Complete a run entry with final results.+ *+ * `successOverride` (#3358) lets finalizeAgent record a run that exited 0 but+ * failed its PR-claim verification as the failure it is. Without it the run+ * history would keep saying "success" for exactly the run the agent record and+ * the task status now agree did NOT land its deliverable.*/-export async function completeAgentRun(runId, output, exitCode, duration, errorAnalysis = null) {+export async function completeAgentRun(runId, output, exitCode, duration, errorAnalysis = null, successOverride = null) {if (!runId) return; // Skip if no runId (e.g., agent recovered after restart)const runDir = join(RUNS_DIR, runId);@@ -124,6 +129,9 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorAsuccess = true;}}+ // An explicit false from the caller is authoritative and outranks both the+ // exit code and the commit rescue above; null (the default) means "no opinion".+ if (successOverride === false) success = false;metadata.success = success;metadata.outputSize = Buffer.byteLength(output || '');diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex fdc6c97bc9..10c841e379 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -624,6 +624,22 @@ export async function spawnTuiAgent({completionError: finalError,});+ // A slashdo-capable Claude TUI owns /do:pr itself. Slashdo-free TUIs+ // (Codex, Antigravity, OpenCode, lean Claude) only commit and signal;+ // PortOS must own their push + PR + reviewer/merge follow-up. Derive this+ // from the same predicate used by the prompt builder so neither side can+ // believe the other owns the PR.+ //+ // Resolved BEFORE finalizeAgent (not just in the cleanup below) because it is+ // also the gate for the PR-claim verification (#3358): only a run that owned+ // its own PR creation can be expected to have produced one by finalize time.+ const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);+ const agentOwnsPR = taskOpenPR && canTypeSlashCommands({+ providerId: provider?.id,+ providerCommand: provider?.command,+ leanMode,+ });+// try/finally so a throw from finalizeAgent (e.g. processAgentCompletion// hook crash) still runs the local cleanup — sentinel removal, worktree// cleanup, pid unregister, activeAgents delete, session kill. Without@@ -645,21 +661,11 @@ export async function spawnTuiAgent({error: finalError || undefined,completionReason: reason,workspacePath,+ prExpected: agentOwnsPR,});} finally {if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});- // A slashdo-capable Claude TUI owns /do:pr itself. Slashdo-free TUIs- // (Codex, Antigravity, OpenCode, lean Claude) only commit and signal;- // PortOS must own their push + PR + reviewer/merge follow-up. Derive this- // from the same predicate used by the prompt builder so neither side can- // believe the other owns the PR.- const taskOpenPR = isTruthyMetaFn(task.metadata?.openPR);- const agentOwnsPR = taskOpenPR && canTypeSlashCommands({- providerId: provider?.id,- providerCommand: provider?.command,- leanMode,- });const reviewOptions = finalSuccess && taskOpenPR && !agentOwnsPR? await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn }).catch(err => {diff --git a/server/services/taskLearning/metrics.test.js b/server/services/taskLearning/metrics.test.jsindex aca0fb312f..9ce0ee0c59 100644--- a/server/services/taskLearning/metrics.test.js+++ b/server/services/taskLearning/metrics.test.js@@ -469,6 +469,9 @@ describe('ENVIRONMENTAL_ERROR_CATEGORIES (issue #2618)', () => {'claude-error','connection','forbidden',+ // #3358: a PR-shaped run we could not verify because `gh` couldn't reach+ // the forge. The agent's own miss (`pr-missing`) is deliberately NOT here.+ 'forge-unreachable','model-not-available','model-not-found','model-not-supported',diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.jsindex d7532cedee..dd56213862 100644--- a/server/services/taskLearning/store.js+++ b/server/services/taskLearning/store.js@@ -226,6 +226,11 @@ export const ENVIRONMENTAL_ERROR_CATEGORIES = new Set(['billing-error','connection','network-error',+ // #3358: a PR-shaped run finalized while `gh` could not reach the forge. The+ // run itself may have been perfect — we simply could not confirm its PR — so+ // it must not dent the type's success rate the way `pr-missing` (the agent's+ // own miss, deliberately NOT listed here) should.+ 'forge-unreachable','claude-error','startup-failure','model-not-available',