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
settle a "resolve and merge PR #N" run from forge state, not from its diff
[._.]/ Adam Eivy44f0b62307f6
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex e2c06a3f99..3921848183 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -214,7 +214,11 @@ function GoalFidelityPanel({ review }) {<Target size={10} aria-hidden="true" />Goal fidelity: {tone.label}<span className="min-w-0 [overflow-wrap:anywhere] text-gray-500">- ({review.verdict}{review.model ? ` · ${review.model}` : ''}{review.diffTruncated ? ' · partial diff' : ''})+ {/* A forge-established verdict has no reviewer model and read no diff —+ say where it came from rather than leaving the reader to assume a+ local model produced it. */}+ ({review.verdict}{review.source === 'forge-outcome' ? ' · forge-verified' : ''}+ {review.model ? ` · ${review.model}` : ''}{review.diffTruncated ? ' · partial diff' : ''})</span></div>{review.missing?.length > 0 && (diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex c828c22a19..dbd3929e00 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -728,6 +728,17 @@ describe('AgentCard missing shell explanation', () => {describe('AgentCard goal fidelity', () => {const withReview = (goalFidelity) => ({ ...agent, result: { ...agent.result, goalFidelity } });+ // A merge-shaped objective is settled by forge state, not by a model reading a+ // diff — so the card must not leave a reader assuming a local model said so.+ it('names the forge as the source of a verdict no model produced', () => {+ render(<MemoryRouter><AgentCard agent={withReview({+ verdict: 'ship', source: 'forge-outcome', evidence: 'The forge reports #7653 MERGED', missing: [], unrequested: [],+ })} completed /></MemoryRouter>);+ expect(screen.getByText(/forge-verified/)).toBeInTheDocument();+ expect(screen.getByText('Goal fidelity:', { exact: false })).toHaveTextContent('Delivers the objective');+ expect(screen.queryByRole('button', { name: 'Investigate findings' })).not.toBeInTheDocument();+ });+it('queues an isolated investigation with the original prompt and app, then links to the task', async () => {api.getCosAgentPrompt.mockResolvedValue({ prompt: 'Resolve issue #123 acceptance criteria' });api.addCosTask.mockResolvedValue({ id: 'task-investigation', approvalRequired: false });diff --git a/server/lib/README.md b/server/lib/README.mdindex 0421802783..ac107a0104 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -527,7 +527,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `avatarStyles.js` | The CoS avatar-style vocabulary (#6253) — `AVATAR_STYLES` (`{id, label, webgl}`), `AVATAR_STYLE_IDS` (the `avatarStyle` zod enum in `cosStatusRoutes.js`), `AVATAR_STYLE_LABELS`, and `WEBGL_AVATAR_STYLE_IDS` (the three.js-stage set). `client/src/lib/avatarStyles.js` re-exports it for the picker and the lazy-load map. || `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. || `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |-| `goalFidelity.js` | Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. `GOAL_FIDELITY_VERDICTS` (`ship` / `fix-first` / `rethink`, only `rethink` gating a run via `goalFidelityHoldsRun`), `taskObjective(task)` (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), `resolveGoalFidelityConfig(codeReview, chain)` (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its `<backend>Model`/`Effort` scalars), `normalizeGoalFidelityVerdict(parsed)` (`null` = nothing judged the run, never collapsed into a `ship` pass or a `rethink` hold) and `formatGoalFidelitySummary(review)`. `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. |+| `goalFidelity.js` | Goal-fidelity review contract (#5994) — the value half of "does this diff deliver what was asked?", the question the quality-review chain structurally cannot answer because it never sees the request. `GOAL_FIDELITY_VERDICTS` (`ship` / `fix-first` / `rethink`, only `rethink` gating a run via `goalFidelityHoldsRun`), `taskObjective(task)` (the trusted operator-authored objective — the TASK's description + prompt block, never the agent's transcript, since a reviewer handed the transcript inherits the assumptions that produced the drift), `resolveGoalFidelityConfig(codeReview, chain)` (enabled/backend/model/effort, restricted to the local-LLM reviewers PortOS can call server-side and falling back to the quality chain's own local reviewer + its `<backend>Model`/`Effort` scalars), `normalizeGoalFidelityVerdict(parsed)` (`null` = nothing judged the run, never collapsed into a `ship` pass or a `rethink` hold) and `formatGoalFidelitySummary(review)`. `mergeOutcomeObjective(task)` / `mergeOutcomeReview({ number, prState })` / `GOAL_FIDELITY_SOURCE_FORGE` are the second answer shape: a review-loop follow-up is asked to LAND a change request, which no diff evidences, so its verdict is established from forge state (`MERGED` ⇒ `ship`, everything else ⇒ nothing). `MAX_OBJECTIVE_CHARS` / `MAX_FIDELITY_DIFF_CHARS` bound what crosses into a fixed-window local model. Pure. || `goalFidelityFollowUp.js` | Goal-fidelity FOLLOW-UP contract — what happens once the review HAS a finding, as opposed to what the finding is. `resolveGoalFidelityFollowUp(codeReview)` (`null` when neither action is configured; reads the RAW block, since a verdict already exists by the time this is asked), `normalizeGoalFidelityFollowUpTrigger` (shared with the settings projection so the form and the runtime cannot disagree), and `goalFidelityFollowUpApplies(review, trigger)` over `GOAL_FIDELITY_FOLLOW_UP_TRIGGERS` (`rethink` = only the verdict that holds a run, the default; `any-finding` also fires on the advisory `fix-first`). `goalFidelityFingerprint(task)` is the one dedup identity three parties share — the issue body marker (`goalFidelityIssueMarker` / `issueMatchesGoalFidelityMarker`), the tracker listing that reads it back, and the queued task fingerprint — keyed on taskType + app + objective slug so a perpetual task regenerating with a fresh id cannot re-file forever. `buildGoalFidelityIssue` / `buildGoalFidelityFollowUpTask` compose the bodies. Closure-free apart from `textUtils.js` (see the header); I/O lives in `services/goalFidelityFollowUp.js`. || `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. Also `getNavPageForPath(pathname)` → `{ label, section, breadcrumb }` for the most specific command that owns a route (`null` for one nothing declares) — how user-facing copy NAMES a page it links to, instead of typing "Models → LLMs" beside the link and stranding it on the next move (#7414). `expandPageToken(text, runtime)` expands a `{page}` token in `text` using `getNavPageForPath(runtime?.manageUrl)`, falling back to generic prose rather than shipping a literal `{page}` (#7419). || `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |diff --git a/server/lib/goalFidelity.js b/server/lib/goalFidelity.jsindex cd919615a2..917f2f576f 100644--- a/server/lib/goalFidelity.js+++ b/server/lib/goalFidelity.js@@ -200,3 +200,65 @@ export function formatGoalFidelitySummary(review) {? `Goal-fidelity verdict: ${review.verdict} (${counts.join(', ')})`: `Goal-fidelity verdict: ${review.verdict}`;}++/**+ * `review.source` for a verdict established from FORGE STATE rather than from a+ * model's read of a diff. Rendered in place of the reviewer model, so "this run+ * delivered" is never mistaken for a local model's opinion. Mirrored as a literal+ * in `client/src/components/cos/tabs/AgentCard.jsx`, alongside the verdict keys.+ */+export const GOAL_FIDELITY_SOURCE_FORGE = 'forge-outcome';++/**+ * The change request a task's objective is to LAND, or `null` when the task's+ * objective is ordinary code.+ *+ * A review-loop follow-up (`metadata.reviewLoopFollowUp`, queued by+ * `agentWorktreeCleanup.js` or the PR page's resolve button) is asked for a+ * STATE CHANGE on a change request — "resolve and merge PR #N" — not for a+ * feature. Nothing in `git diff` evidences a merge, so the diff-reading gate is+ * structurally unable to answer it, and it answers anyway: PR #7653 merged, and+ * its run was then graded `rethink` on the unrelated `main` commits the branch+ * had absorbed, failing the run and re-queueing the task against an+ * already-merged PR.+ *+ * `reviewLoopLeaveOpen` follow-ups are excluded on purpose: their objective is+ * to address review feedback and LEAVE the PR open, so a merge proves nothing+ * about them and their fix commits are ordinary diff the normal gate can read.+ */+export function mergeOutcomeObjective(task) {+ const metadata = task?.metadata;+ if (!metadata || typeof metadata !== 'object') return null;+ // Stored Markdown metadata may carry booleans as strings.+ const truthy = (value) => value === true || value === 'true';+ if (!truthy(metadata.reviewLoopFollowUp) || truthy(metadata.reviewLoopLeaveOpen)) return null;+ const number = Number(metadata.reviewLoopPRNumber);+ const branch = typeof metadata.reviewLoopPRBranch === 'string' ? metadata.reviewLoopPRBranch.trim() : '';+ // Both are required: the number is what the forge is asked about, and the+ // branch is what a forge without a cheap by-number state read is asked about.+ if (!Number.isSafeInteger(number) || number <= 0 || !branch) return null;+ return { number, branch };+}++/**+ * The verdict a probed change-request state establishes, or `null` for one that+ * establishes none.+ *+ * ONLY `MERGED` produces a verdict, and it is always `ship`. The polarity is+ * deliberate and matches the module's fail-open doctrine: a merge is positive+ * proof the objective landed, while `OPEN` and `CLOSED` are not proof it did+ * not. A review loop legitimately leaves a PR open when a required review is+ * blocked or CI never went green, and a PR closed as superseded can be a+ * correct resolution — both are owned by the merge-gate contract, the repo-state+ * audit, and pr-watcher, none of which this gate should second-guess.+ */+export function mergeOutcomeReview({ number, prState }) {+ if (String(prState || '').toUpperCase() !== 'MERGED') return null;+ return {+ verdict: 'ship',+ missing: [],+ unrequested: [],+ evidence: `The forge reports #${number} MERGED — this run's objective is established by forge state, not by reading a diff.`,+ source: GOAL_FIDELITY_SOURCE_FORGE,+ };+}diff --git a/server/lib/goalFidelity.test.js b/server/lib/goalFidelity.test.jsindex 7fadebb4dc..4834cfbc22 100644--- a/server/lib/goalFidelity.test.js+++ b/server/lib/goalFidelity.test.js@@ -4,6 +4,8 @@ import {MAX_OBJECTIVE_CHARS,formatGoalFidelitySummary,goalFidelityHoldsRun,+ mergeOutcomeObjective,+ mergeOutcomeReview,normalizeGoalFidelityVerdict,resolveGoalFidelityConfig,taskObjective,@@ -109,3 +111,50 @@ describe('formatGoalFidelitySummary', () => {.toBe('Goal-fidelity verdict: ship');});});++describe('mergeOutcomeObjective', () => {+ const followUp = (metadata) => ({ description: 'Resolve and merge PR #7653', metadata });++ it('recognizes a review-loop follow-up, tolerating Markdown-stored string booleans', () => {+ expect(mergeOutcomeObjective(followUp({+ reviewLoopFollowUp: true, reviewLoopPRNumber: 7653, reviewLoopPRBranch: 'claim/issue-7625',+ }))).toEqual({ number: 7653, branch: 'claim/issue-7625' });+ expect(mergeOutcomeObjective(followUp({+ reviewLoopFollowUp: 'true', reviewLoopPRNumber: '7653', reviewLoopPRBranch: 'claim/issue-7625',+ }))).toEqual({ number: 7653, branch: 'claim/issue-7625' });+ });++ it.each([+ ['an ordinary task', {}],+ ['a leave-open follow-up, whose deliverable IS a diff', { reviewLoopFollowUp: true, reviewLoopLeaveOpen: 'true', reviewLoopPRNumber: 7653, reviewLoopPRBranch: 'b' }],+ ['a follow-up missing its number', { reviewLoopFollowUp: true, reviewLoopPRBranch: 'b' }],+ ['a follow-up missing its branch', { reviewLoopFollowUp: true, reviewLoopPRNumber: 7653 }],+ ])('declines %s, leaving it to the ordinary diff review', (_label, metadata) => {+ expect(mergeOutcomeObjective(followUp(metadata))).toBeNull();+ });++ it('declines a task with no metadata at all', () => {+ expect(mergeOutcomeObjective(null)).toBeNull();+ expect(mergeOutcomeObjective({ description: 'Merge it' })).toBeNull();+ });+});++describe('mergeOutcomeReview', () => {+ it('establishes ship from a merge, naming the forge as the source', () => {+ expect(mergeOutcomeReview({ number: 7653, prState: 'MERGED' })).toEqual({+ verdict: 'ship',+ missing: [],+ unrequested: [],+ evidence: expect.stringContaining('#7653 MERGED'),+ source: 'forge-outcome',+ });+ expect(mergeOutcomeReview({ number: 7653, prState: 'merged' })?.verdict).toBe('ship');+ });++ // Only a merge is proof. An open PR is what a blocked review legitimately+ // leaves behind, and a PR closed as superseded can be a correct resolution —+ // turning either into a finding would hold runs that did nothing wrong.+ it.each(['OPEN', 'CLOSED', null])('establishes nothing from state %s', prState => {+ expect(mergeOutcomeReview({ number: 7653, prState })).toBeNull();+ });+});diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.jsindex bab4fffc1f..57ee5eb6d5 100644--- a/server/services/agentFinalization.goalFidelity.test.js+++ b/server/services/agentFinalization.goalFidelity.test.js@@ -21,6 +21,7 @@ vi.mock('./github.js', () => ({execGh: vi.fn(),findPullRequestForBranch: vi.fn(async () => ({ status: 'found', number: 7, url: 'https://example.com/pr/7', body: 'Closes #42' })),ensureForgeReachable: vi.fn(async () => ({ ok: true, status: 'ok' })),+ getPullRequestState: vi.fn(async () => ({ status: 'known', state: 'MERGED', detail: null })),}));vi.mock('./gitlab.js', () => ({ findMergeRequestForBranch: vi.fn(), execGlab: vi.fn() }));vi.mock('./git.js', () => ({ resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh' })) }));@@ -91,7 +92,7 @@ vi.mock('./codeReview.js', async (importOriginal) => ({}));import { execGit } from '../lib/execGit.js';-import { execGh, findPullRequestForBranch } from './github.js';+import { execGh, findPullRequestForBranch, getPullRequestState } from './github.js';import { execGlab } from './gitlab.js';import { resolveForgeForRepo } from './git.js';import { getAgentRecord } from './cosAgentLifecycle.js';@@ -450,6 +451,58 @@ describe('finalizeAgent — goal-fidelity gate', () => {});});+ // #7653 — see `mergeOutcomeObjective` (lib/goalFidelity.js) for the run this+ // gate wrongly held.+ describe('a merge-shaped objective is settled by the forge, not by a diff', () => {+ const mergeFollowUp = (metadata = {}) => ({+ id: 'task-1',+ taskType: 'internal',+ description: '[Review Loop] Resolve and merge PR #7653 for PortOS',+ metadata: {+ reviewLoopFollowUp: true,+ reviewLoopPRNumber: 7653,+ reviewLoopPRBranch: 'claim/issue-7625',+ ...metadata,+ },+ });++ it('records a forge-established ship without reading a diff or calling a model', async () => {+ runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'rethink', unrequested: ['Resolve and merge PR #7653'] }));+ await finalize({ task: mergeFollowUp() });++ expect(getPullRequestState).toHaveBeenCalledWith('7653', { cwd: '/example/worktree', env: { GH_TOKEN: 'synthetic-token' } });+ expect(runWindowDiffMock).not.toHaveBeenCalled();+ expect(runLocalGoalFidelityReviewMock).not.toHaveBeenCalled();+ expect(completion()).toMatchObject({ success: true });+ expect(completion().goalFidelity).toMatchObject({ verdict: 'ship', source: 'forge-outcome' });+ expect(completion().goalFidelity.model).toBeUndefined();+ expect(cosEvents.emit).not.toHaveBeenCalledWith(GOAL_FIDELITY_HOLD_EVENT, expect.anything());+ });++ it.each([+ ['an unmerged PR', { status: 'known', state: 'OPEN', detail: null }],+ ['an unreadable forge', { status: 'unavailable', state: null, detail: 'gh failed' }],+ ])('leaves the run untouched and the model uncalled for %s', async (_label, view) => {+ getPullRequestState.mockResolvedValue(view);+ runLocalGoalFidelityReviewMock.mockResolvedValue(verdict({ verdict: 'rethink' }));+ await finalize({ task: mergeFollowUp() });++ expect(runLocalGoalFidelityReviewMock).not.toHaveBeenCalled();+ expect(completion()).toMatchObject({ success: true });+ expect(completion().goalFidelity).toBeUndefined();+ });++ // A leave-open follow-up's objective is the review fixes, which ARE ordinary+ // diff — it must keep the model review a merge objective skips.+ it('does not divert a leave-open follow-up, whose deliverable is a diff', async () => {+ await finalize({ task: mergeFollowUp({ reviewLoopLeaveOpen: 'true' }) });++ expect(getPullRequestState).not.toHaveBeenCalled();+ expect(runLocalGoalFidelityReviewMock).toHaveBeenCalledOnce();+ expect(completion().goalFidelity).toMatchObject({ verdict: 'ship', model: 'example-model' });+ });+ });+it('never re-judges a run that already failed — the original diagnosis is the better one', async () => {await finalize({ success: false, errorAnalysis: { category: 'timeout', message: 'agent timed out' } });expect(runLocalGoalFidelityReviewMock).not.toHaveBeenCalled();diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 0f0f0fc74a..9621f247c2 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -47,6 +47,8 @@ import {MAX_OBJECTIVE_CHARS,formatGoalFidelitySummary,goalFidelityHoldsRun,+ mergeOutcomeObjective,+ mergeOutcomeReview,taskObjective,} from '../lib/goalFidelity.js';import { formatGoalFidelityFollowUpSummary, goalFidelityFollowUpApplies } from '../lib/goalFidelityFollowUp.js';@@ -646,6 +648,34 @@ ${JSON.stringify({ title: issue.title, body })}`;return objective.length <= MAX_OBJECTIVE_CHARS ? objective : null;}+/** The gate's no-verdict sentinel: nothing judged this run, so leave it alone. */+const noFidelityVerdict = (error = null) => ({ verdict: null, review: null, error });++/**+ * The goal-fidelity answer for a run whose objective is to LAND a change+ * request (`mergeOutcomeObjective`), established from forge state instead of+ * from a model's read of a diff.+ *+ * Fail-OPEN on everything but a merge, matching the gate it stands in for. A PR+ * still OPEN is what a blocked required review correctly leaves behind, and one+ * CLOSED as superseded can be a correct resolution — both decline SILENTLY, since+ * the caller warns on a reason and neither is a gate miss. Only an unreadable+ * forge is worth saying out loud: it means the check did not happen.+ *+ * @param {string} workspacePath - the run's worktree; supplies the forge remote+ * @param {{ number: number, branch: string }} mergeObjective+ */+async function verifyMergeOutcome(workspacePath, mergeObjective) {+ const { probeChangeRequestState } = await import('./prProbe.js');+ const probe = await probeChangeRequestState(workspacePath, mergeObjective).catch(() => null);+ if (!probe?.readable) {+ return noFidelityVerdict(`Could not read the state of #${mergeObjective.number}; a merge objective is not graded from a diff.`);+ }+ const review = mergeOutcomeReview({ number: mergeObjective.number, prState: probe.prState });+ if (!review) return noFidelityVerdict();+ return { verdict: review.verdict, review: { ...review, checkedAt: new Date().toISOString() }, error: null };+}+/*** Goal-fidelity completion gate (#5994).*@@ -673,7 +703,7 @@ ${JSON.stringify({ title: issue.title, body })}`;* @returns {Promise<{verdict: string|null, review: Object|null, error: string|null}>}*/async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {- const none = (error = null) => ({ verdict: null, review: null, error });+ const none = noFidelityVerdict;if (!workspacePath || !task?.id) return none();// A coordinator's run-window diff cannot represent work delegated across// worker branches. Judge individual tasks, not the aggregate swarm objective.@@ -681,8 +711,14 @@ async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {const workers = Number(task.metadata?.swarmCount);if ((Number.isSafeInteger(workers) && workers > 1)|| resolveTaskHookType(task) === 'branch-reconcile') return none();+ // Resolved before the merge diversion below so the gate's off-switch suppresses+ // BOTH paths — an install that turned the gate off gets no verdict of any kind.const config = await getGoalFidelityConfig().catch(() => null);if (!config) return none();+ // A merge-shaped objective is answered by the FORGE, never by a diff — see+ // `mergeOutcomeObjective` for the run this gate wrongly held.+ const mergeObjective = mergeOutcomeObjective(task);+ if (mergeObjective) return verifyMergeOutcome(workspacePath, mergeObjective);const claimFlow = task.metadata?.claimFlow === true || task.metadata?.claimFlow === 'true'|| CLAIM_FLOW_TASK_TYPES.has(resolveTaskHookType(task));const objective = claimFlowdiff --git a/server/services/prProbe.js b/server/services/prProbe.jsindex 48124d98d7..9ecb2a9340 100644--- a/server/services/prProbe.js+++ b/server/services/prProbe.js@@ -14,10 +14,23 @@ import * as git from './git.js';// 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)),-]);+// The timer is cleared once the race settles: an uncleared one keeps the event+// loop hot for its full duration after the forge has already answered, which on+// a teardown path delays the process that is trying to finish.+const withTimeout = (promise, ms, fallback) => {+ let timer = null;+ return Promise.race([+ promise,+ new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), ms); }),+ ]).finally(() => clearTimeout(timer));+};++/** The repo's forge CLI + credential overlay, or null when it cannot be resolved. */+const resolveForge = (sourceWorkspace) => withTimeout(+ git.resolveForgeForRepo(sourceWorkspace).catch(() => null),+ FORGE_RESOLVE_TIMEOUT_MS,+ null+);/*** Resolve the open (or merged/closed) pull/merge request for `branchName`.@@ -30,14 +43,12 @@ const withTimeout = (promise, ms, fallback) => Promise.race([* @param {string} sourceWorkspace - a git working directory with the remote* configured (a worktree qualifies — it shares its parent's git config).* @param {string} branchName+ * @param {{cli: string, env: object|null}|null} [resolvedForge] - a forge a+ * delegating caller already resolved, so the `gh auth` probe chain runs once.* @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- );+export async function probePrForBranch(sourceWorkspace, branchName, resolvedForge = null) {+ const forge = resolvedForge || await resolveForge(sourceWorkspace);if (!forge?.cli) return { prState: null, prUrl: null, prNumber: null, cli: null, readable: false };const { cli, env } = forge;const found = cli === 'glab'@@ -60,3 +71,43 @@ export async function probePrForBranch(sourceWorkspace, branchName) {readable: !!found.detail,};}++/**+ * Read ONE change request's state, by its forge-native number.+ *+ * The truth `probePrForBranch` cannot give a caller that already knows WHICH+ * change request it means: a branch lookup answers with the most recent PR on+ * that branch, and a reused branch makes that a different one. Same tri-state+ * discipline — `readable: false` is "we could not ask", never "not merged".+ *+ * GitHub answers by number directly. GitLab has no by-IID state read wired here,+ * so it goes through the branch lookup and the IID is CROSS-CHECKED: a mismatch+ * means the branch's newest MR is not the one asked about, which is unreadable+ * rather than an answer about the wrong MR.+ *+ * @param {string} sourceWorkspace - a git working directory with the remote configured+ * @param {{ number: number, branch: string }} target+ * @returns {Promise<{ prState: string|null, cli: string|null, readable: boolean }>}+ * `prState` is upper-cased (`MERGED` / `OPEN` / `CLOSED`) when `readable`, and+ * is named to match `probePrForBranch` so both results read the same way.+ */+export async function probeChangeRequestState(sourceWorkspace, { number, branch } = {}) {+ const unreadable = (cli = null) => ({ prState: null, cli, readable: false });+ // `Number(null)` is 0 and `Number.isSafeInteger(0)` is true, so the positivity+ // check is what keeps a missing number from being asked about as PR #0.+ const id = Number(number);+ if (!sourceWorkspace || !Number.isSafeInteger(id) || id <= 0) return unreadable();+ const forge = await resolveForge(sourceWorkspace);+ if (!forge?.cli) return unreadable();+ const { cli, env } = forge;+ if (cli === 'glab') {+ const probe = await probePrForBranch(sourceWorkspace, branch, forge);+ if (!probe.readable || Number(probe.prNumber) !== id) return unreadable(cli);+ return { prState: probe.prState, cli, readable: true };+ }+ const { getPullRequestState } = await import('./github.js');+ const view = await getPullRequestState(String(id), { cwd: sourceWorkspace, env: env || null })+ .catch(() => ({ status: 'unavailable', state: null }));+ if (view.status !== 'known' || !view.state) return unreadable(cli);+ return { prState: view.state, cli, readable: true };+}diff --git a/server/services/prProbe.test.js b/server/services/prProbe.test.jsindex 4d36c18594..18e0bb1593 100644--- a/server/services/prProbe.test.js+++ b/server/services/prProbe.test.js@@ -5,21 +5,23 @@ vi.mock('./git.js', () => ({}));vi.mock('./github.js', () => ({findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),+ getPullRequestState: vi.fn().mockResolvedValue({ status: 'unavailable', state: null, detail: null }),}));vi.mock('./gitlab.js', () => ({findMergeRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),}));import { resolveForgeForRepo } from './git.js';-import { findPullRequestForBranch } from './github.js';+import { findPullRequestForBranch, getPullRequestState } from './github.js';import { findMergeRequestForBranch } from './gitlab.js';-import { probePrForBranch } from './prProbe.js';+import { probeChangeRequestState, probePrForBranch } from './prProbe.js';beforeEach(() => {vi.clearAllMocks();resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: null });findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });findMergeRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });+ getPullRequestState.mockResolvedValue({ status: 'unavailable', state: null, detail: null });});describe('probePrForBranch', () => {@@ -74,3 +76,52 @@ describe('probePrForBranch', () => {expect(result).toEqual({ prState: 'MERGED', prUrl: 'https://gitlab.example.com/mr/4', prNumber: 4, cli: 'glab', readable: true });});});++// A caller that already knows WHICH change request it means (a review-loop+// follow-up carries the number) must not be answered about a different one: a+// reused branch makes the branch lookup's newest PR the wrong PR.+describe('probeChangeRequestState', () => {+ it('asks GitHub by number, bypassing the branch lookup entirely', async () => {+ getPullRequestState.mockResolvedValue({ status: 'known', state: 'MERGED', detail: null });++ const result = await probeChangeRequestState('/repo', { number: 7653, branch: 'claim/issue-7625' });++ expect(getPullRequestState).toHaveBeenCalledWith('7653', { cwd: '/repo', env: null });+ expect(findPullRequestForBranch).not.toHaveBeenCalled();+ expect(result).toEqual({ prState: 'MERGED', cli: 'gh', readable: true });+ });++ it.each([+ ['gh could not answer', { status: 'unavailable', state: null, detail: 'gh failed' }],+ ['gh answered without a state', { status: 'known', state: null, detail: null }],+ ])('reports unreadable — never "not merged" — when %s', async (_label, view) => {+ getPullRequestState.mockResolvedValue(view);+ expect(await probeChangeRequestState('/repo', { number: 7653, branch: 'b' }))+ .toEqual({ prState: null, cli: 'gh', readable: false });+ });++ it('cross-checks the IID on GitLab, where the state is only reachable by branch', async () => {+ resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });+ findMergeRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/mr/12', number: 12, detail: 'merged' });++ expect(await probeChangeRequestState('/repo', { number: 12, branch: 'feature' }))+ .toEqual({ prState: 'MERGED', cli: 'glab', readable: true });+ // The delegation reuses the forge it already resolved rather than paying for+ // the `gh auth` probe chain twice to answer one question.+ expect(resolveForgeForRepo).toHaveBeenCalledOnce();+ // A different MR on the same source branch answers about the wrong one.+ expect(await probeChangeRequestState('/repo', { number: 13, branch: 'feature' }))+ .toEqual({ prState: null, cli: 'glab', readable: false });+ });++ it('is unreadable with no forge CLI or no number, without calling either forge', async () => {+ resolveForgeForRepo.mockResolvedValue(null);+ expect(await probeChangeRequestState('/repo', { number: 7653, branch: 'b' }))+ .toEqual({ prState: null, cli: null, readable: false });+ resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: null });+ expect(await probeChangeRequestState('/repo', { number: null, branch: 'b' }))+ .toEqual({ prState: null, cli: null, readable: false });+ expect(getPullRequestState).not.toHaveBeenCalled();+ expect(findMergeRequestForBranch).not.toHaveBeenCalled();+ });+});