Skip to content

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

fix: address local review findings on the merge-gate contract check (#5876)

Adam Eivya09dbf07c3f3
diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.js
index d56d0c1743..83e3eabc89 100644
--- a/server/lib/mergeGateContract.js
+++ b/server/lib/mergeGateContract.js
@@ -61,30 +61,33 @@ export function summaryStatesLeaveOpen(summary) {
/**
* Resolve what a completing run that owed a merge should do next.
*
+ * The "send at most one nudge" decision is NOT this function's job — it lives
+ * entirely in the caller (`agentTuiSpawning.js`'s `checkMergeGateCompliance`,
+ * which short-circuits before ever calling this a second time this run), so
+ * there is exactly one place that answer can drift out of sync with itself.
+ *
* - `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.
+ * - `no-pr-action` — the forge lookup itself failed (`readable: false`), or it
+ * succeeded but found nothing actionable for this branch (no PR at all, or
+ * one that's CLOSED rather than merged). Either way there is nothing here
+ * to act on: 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.
+ * - `needs-reprompt` — the PR is open and the summary names no blocker: send
+ * one corrective re-prompt.
*
* @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'}
+ * @returns {'merged'|'no-pr-action'|'leave-open-stated'|'needs-reprompt'}
*/
-export function resolveMergeGateVerdict({ prProbe, summary, alreadyReprompted }) {
- if (!prProbe || prProbe.readable === false) return 'unreadable';
+export function resolveMergeGateVerdict({ prProbe, summary }) {
+ if (!prProbe || prProbe.readable === false) return 'no-pr-action';
if (prProbe.prState === 'MERGED') return 'merged';
- if (prProbe.prState !== 'OPEN') return 'unreadable';
+ if (prProbe.prState !== 'OPEN') return 'no-pr-action';
if (summaryStatesLeaveOpen(summary)) return 'leave-open-stated';
- return alreadyReprompted ? 'reprompt-exhausted' : 'needs-reprompt';
+ return 'needs-reprompt';
}
/**
diff --git a/server/lib/mergeGateContract.test.js b/server/lib/mergeGateContract.test.js
index eca810acbb..ca42e897ec 100644
--- a/server/lib/mergeGateContract.test.js
+++ b/server/lib/mergeGateContract.test.js
@@ -49,45 +49,44 @@ describe('resolveMergeGateVerdict', () => {
it('is "merged" when the PR landed', () => {
expect(resolveMergeGateVerdict({
- prProbe: { prState: 'MERGED', readable: true }, summary, alreadyReprompted: false,
+ prProbe: { prState: 'MERGED', readable: true }, summary,
})).toBe('merged');
});
- it('is "unreadable" when the forge lookup itself failed', () => {
+ it('is "no-pr-action" when the forge lookup itself failed', () => {
expect(resolveMergeGateVerdict({
- prProbe: { prState: null, readable: false }, summary, alreadyReprompted: false,
- })).toBe('unreadable');
+ prProbe: { prState: null, readable: false }, summary,
+ })).toBe('no-pr-action');
});
- it('is "unreadable" when there is no probe result at all', () => {
- expect(resolveMergeGateVerdict({ prProbe: null, summary, alreadyReprompted: false })).toBe('unreadable');
+ it('is "no-pr-action" when there is no probe result at all', () => {
+ expect(resolveMergeGateVerdict({ prProbe: null, summary })).toBe('no-pr-action');
});
- it('is "unreadable" when the forge found no PR for the branch', () => {
+ it('is "no-pr-action" when the forge found no PR for the branch', () => {
expect(resolveMergeGateVerdict({
- prProbe: { prState: null, readable: true }, summary, alreadyReprompted: false,
- })).toBe('unreadable');
+ prProbe: { prState: null, readable: true }, summary,
+ })).toBe('no-pr-action');
+ });
+
+ it('is "no-pr-action" when the PR is closed rather than merged', () => {
+ expect(resolveMergeGateVerdict({
+ prProbe: { prState: 'CLOSED', readable: true }, summary,
+ })).toBe('no-pr-action');
});
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', () => {
+ it('is "needs-reprompt" when the PR is open and no blocker is stated', () => {
expect(resolveMergeGateVerdict({
- prProbe: { prState: 'OPEN', readable: true }, summary, alreadyReprompted: false,
+ prProbe: { prState: 'OPEN', readable: true }, summary,
})).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', () => {
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index ade1e3aa8d..600d368160 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -599,6 +599,10 @@ export async function spawnTuiAgent({
// `finalized` alone isn't enough once the merge-gate check adds awaits
// before it (#5876).
let finishing = false;
+ // A finish() call's args, dropped by the `finishing` guard while an earlier
+ // call was still deciding whether to finalize — replayed if that call ends
+ // up NOT finalizing (see finish()'s own comments on both).
+ let pendingFinish = null;
// 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.
@@ -796,7 +800,7 @@ export async function spawnTuiAgent({
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 });
+ const verdict = resolveMergeGateVerdict({ prProbe, summary });
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.
@@ -809,8 +813,14 @@ export async function spawnTuiAgent({
// its first (this) detection.
sentinelIngested = false;
if (doneSentinelPath) await rm(doneSentinelPath).catch(() => {});
+ // Armed unconditionally — the sentinel is already gone, so a missing
+ // `activeAgents` entry (an anomaly this code doesn't otherwise expect)
+ // must not also leave the run with no watcher at all. `stopRunMachinery`
+ // reads it back off the map to tear it down at real finalize; if the
+ // entry is missing there too, the watcher self-closes on its next fire.
+ const newWatcher = armSentinelWatcher();
const agentData = activeAgents.get(agentId);
- if (agentData) agentData.doneSentinelWatcher = armSentinelWatcher();
+ if (agentData) agentData.doneSentinelWatcher = newWatcher;
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;
@@ -852,7 +862,16 @@ export async function spawnTuiAgent({
// 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;
+ //
+ // A trigger dropped here while the first call is mid-decision is not
+ // discarded: it's the one call that could carry news the first call
+ // doesn't have (the shell exiting right in this window), so it's replayed
+ // once that call settles on "not finalizing after all" — see below.
+ if (finalized) return;
+ if (finishing) {
+ pendingFinish = { success, exitCode, error, reason };
+ 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 —
@@ -886,15 +905,27 @@ export async function spawnTuiAgent({
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)) {
+ // succeeded AND signaled that success via a real `.agent-done` summary —
+ // an ordinary clean exit with no sentinel (or one with an empty summary)
+ // is not the "the agent believes its Merge Gate is done" signal this
+ // reads; re-prompting THAT would paste into a shell whose TUI child may
+ // already be gone, parking the run on a nudge that can never land.
+ // 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 && sentinelSummary !== null && await checkMergeGateCompliance(sentinelSummary)) {
// Not finalizing — reopen the re-entrancy gate for the next completion
- // signal the re-prompt is expected to produce.
+ // signal the re-prompt is expected to produce. A trigger that arrived
+ // WHILE this call was deciding (dropped by the `finishing` guard above)
+ // is the only thing that could tell us the session actually died during
+ // that window, so replay it now rather than losing it — otherwise the
+ // run would sit waiting for a nudge with nothing left alive to receive it.
finishing = false;
+ if (pendingFinish) {
+ const replay = pendingFinish;
+ pendingFinish = null;
+ return finish(replay);
+ }
return;
}
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index eccb4d4475..5f95d5a01d 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -226,7 +226,7 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {
});
import { existsSync } from 'fs';
-import { readFile } from 'fs/promises';
+import { readFile, rm } from 'fs/promises';
import { execFile } from '../lib/childProcess.js';
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import { releaseRetryHold } from './agentWorktreeCleanup.js';
@@ -2447,11 +2447,21 @@ describe('spawnTuiAgent runtime', () => {
describe('merge-gate contract check (#5876)', () => {
const openPrTask = { id: 'task-1', description: 'ship the fix', metadata: { openPR: true } };
+ // Stateful (not a blanket `true`): `watchForFile`'s `detect()` also runs
+ // SYNCHRONOUSLY at watcher-creation time, so if the sentinel already
+ // "existed" when spawnTuiAgent creates its initial watcher, that watcher
+ // self-fires before the test ever drives an explicit trigger — and a
+ // re-prompt's `rm(doneSentinelPath)` needs to actually clear presence for
+ // the re-armed watcher's OWN creation-time check to stay quiet too.
+ // `withSentinel` therefore only wires the mocks; every test flips
+ // `sentinelExists = true` itself, only once its trigger is ready to fire.
+ let sentinelExists = false;
const withSentinel = (summary) => {
- vi.mocked(existsSync).mockReturnValue(true);
+ vi.mocked(existsSync).mockImplementation(() => sentinelExists);
vi.mocked(readFile).mockImplementation(async (p) =>
- typeof p === 'string' && p.endsWith('.agent-done-agent-1') ? summary : ''
+ (typeof p === 'string' && p.endsWith('.agent-done-agent-1') && sentinelExists) ? summary : ''
);
+ vi.mocked(rm).mockImplementation(async () => { sentinelExists = false; });
};
// The merge-gate check adds real await hops (ingestDoneSentinel's readFile,
@@ -2462,7 +2472,9 @@ describe('spawnTuiAgent runtime', () => {
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 () => {
+ beforeEach(() => { sentinelExists = false; });
+
+ it('re-prompts exactly once when the PR is open and the summary names no blocker, then finalizes on the RE-ARMED watcher even if 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,
@@ -2470,18 +2482,71 @@ describe('spawnTuiAgent runtime', () => {
withSentinel('## Summary\nShipped the fix and opened the PR.');
const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });
- await flushMicrotasks();
+ await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+ sentinelExists = true; // the agent writes .agent-done
await capturedOnExit({ exitCode: 0, killed: false });
await settle();
- // Round 1: nudged, not finalized.
+ // Round 1: nudged, not finalized. The reprompt path deletes the
+ // sentinel (`rm` flips `sentinelExists` false, see withSentinel) and
+ // arms a brand-new watcher — the original is one-shot and already
+ // closed itself on this same detection.
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.
+ // Round 2: the agent writes a fresh sentinel (still OPEN, still no
+ // blocker) and the RE-ARMED watcher's fallback poll picks it up —
+ // proving the re-arm itself works, not just a second exit event.
+ sentinelExists = true;
+ // Past the 5000ms poll AND the 50ms settle delay `watchForFile` applies
+ // after a `detect()` — a bare 5000ms advance lands exactly on the poll
+ // tick but not the settle timer it then schedules.
+ await vi.advanceTimersByTimeAsync(5100);
+ await settle();
+ await spawnPromise;
+
+ // One nudge per run: round 2 finalizes instead of nudging again.
+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('never nudges a clean exit that carries no real .agent-done summary, even for a run that owed a merge', async () => {
+ // success:true with nothing on disk — an ordinary quit, not the agent
+ // signaling its Merge Gate is done. Must fall straight through to a
+ // normal finalize, never probe the forge or paste into the session.
+ vi.mocked(existsSync).mockReturnValue(false);
+ vi.mocked(readFile).mockResolvedValue('');
+
+ const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });
+ await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+
+ sentinelExists = true; // the agent writes .agent-done
+ await capturedOnExit({ exitCode: 0, killed: false });
+ await settle();
+ await spawnPromise;
+
+ expect(probePrForBranch).not.toHaveBeenCalled();
+ expect(shellService.pasteToSession).not.toHaveBeenCalled();
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls through to a normal finalize when the session is already gone (resubmit fails)', async () => {
+ // pasteToSession returns nothing → resubmit() reports it couldn't nudge.
+ // `clearAllMocks()` doesn't reset a return value set by an earlier test
+ // (only call history), so this is explicit rather than relying on the
+ // vi.fn() factory default.
+ vi.mocked(shellService.pasteToSession).mockReturnValue(undefined);
+ 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(); // initial watcher arms while quiet — must not self-fire
+
+ sentinelExists = true; // the agent writes .agent-done
await capturedOnExit({ exitCode: 0, killed: false });
await settle();
await spawnPromise;
@@ -2490,6 +2555,36 @@ describe('spawnTuiAgent runtime', () => {
expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);
});
+ it('replays a finish() trigger dropped while the merge-gate check was deciding, instead of losing it', 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(); // initial watcher arms while quiet — must not self-fire
+
+ sentinelExists = true; // the agent writes .agent-done
+ // Two triggers fire back-to-back with no await between them: the first
+ // (a clean exit) starts the merge-gate decision; the second (a kill
+ // signal racing in right after) is dropped by the `finishing` guard
+ // while the first is still deciding. It must be replayed — not lost —
+ // once the first settles on "not finalizing after all", or the run
+ // would sit forever waiting for a nudge into a session that already died.
+ const p1 = capturedOnExit({ exitCode: 0, killed: false });
+ const p2 = capturedOnExit({ exitCode: 1, killed: true });
+ await settle();
+ await Promise.all([p1, p2]);
+ await spawnPromise;
+
+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ success: false })
+ );
+ });
+
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,
@@ -2497,8 +2592,9 @@ describe('spawnTuiAgent runtime', () => {
withSentinel('## Summary\nMerged the PR.');
const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });
- await flushMicrotasks();
+ await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+ sentinelExists = true; // the agent writes .agent-done
await capturedOnExit({ exitCode: 0, killed: false });
await settle();
await spawnPromise;
@@ -2514,8 +2610,9 @@ describe('spawnTuiAgent runtime', () => {
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 flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+ sentinelExists = true; // the agent writes .agent-done
await capturedOnExit({ exitCode: 0, killed: false });
await settle();
await spawnPromise;
@@ -2531,8 +2628,9 @@ describe('spawnTuiAgent runtime', () => {
withSentinel('## Summary\nShipped the fix and opened the PR.');
const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });
- await flushMicrotasks();
+ await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+ sentinelExists = true; // the agent writes .agent-done
await capturedOnExit({ exitCode: 0, killed: false });
await settle();
await spawnPromise;
diff --git a/server/services/prProbe.test.js b/server/services/prProbe.test.js
new file mode 100644
index 0000000000..4d36c18594
--- /dev/null
+++ b/server/services/prProbe.test.js
@@ -0,0 +1,76 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./git.js', () => ({
+ resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: null }),
+}));
+vi.mock('./github.js', () => ({
+ findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: 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 { findMergeRequestForBranch } from './gitlab.js';
+import { 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 });
+});
+
+describe('probePrForBranch', () => {
+ it('reports readable:true with a live prState when GitHub finds the PR', async () => {
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1, detail: 'MERGED' });
+
+ const result = await probePrForBranch('/repo', 'my-branch');
+
+ expect(findPullRequestForBranch).toHaveBeenCalledWith('my-branch', { cwd: '/repo', env: null });
+ expect(findMergeRequestForBranch).not.toHaveBeenCalled();
+ expect(result).toEqual({ prState: 'MERGED', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true });
+ });
+
+ it('uppercases whatever case the forge returned for prState', async () => {
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', number: 1, detail: 'open' });
+ const result = await probePrForBranch('/repo', 'my-branch');
+ expect(result.prState).toBe('OPEN');
+ });
+
+ it('is readable:true with a null prState when the forge found no PR for the branch', async () => {
+ const result = await probePrForBranch('/repo', 'my-branch');
+ expect(result).toEqual({ prState: null, prUrl: null, prNumber: null, cli: 'gh', readable: true });
+ });
+
+ it('is readable:false when the forge call itself fails', async () => {
+ findPullRequestForBranch.mockResolvedValue({ status: 'unavailable' });
+ const result = await probePrForBranch('/repo', 'my-branch');
+ expect(result).toEqual({ prState: null, prUrl: null, prNumber: null, cli: 'gh', readable: false });
+ });
+
+ it('is readable:false when no forge CLI could be resolved for the repo', async () => {
+ resolveForgeForRepo.mockResolvedValue({ cli: null, env: null });
+ const result = await probePrForBranch('/repo', 'my-branch');
+ expect(result).toEqual({ prState: null, prUrl: null, prNumber: null, cli: null, readable: false });
+ expect(findPullRequestForBranch).not.toHaveBeenCalled();
+ });
+
+ it('is readable:false when resolving the forge itself throws', async () => {
+ resolveForgeForRepo.mockRejectedValue(new Error('no git remote'));
+ const result = await probePrForBranch('/repo', 'my-branch');
+ expect(result.readable).toBe(false);
+ });
+
+ it('routes to GitLab, with the IID, when the forge is glab', async () => {
+ resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });
+ findMergeRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://gitlab.example.com/mr/4', number: 4, detail: 'merged' });
+
+ const result = await probePrForBranch('/repo', 'my-branch');
+
+ expect(findMergeRequestForBranch).toHaveBeenCalledWith('my-branch', '/repo');
+ expect(findPullRequestForBranch).not.toHaveBeenCalled();
+ expect(result).toEqual({ prState: 'MERGED', prUrl: 'https://gitlab.example.com/mr/4', prNumber: 4, cli: 'glab', readable: true });
+ });
+});