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: stop gh failures collapsing into empty results across the forge readers (#3358)

[._.]/ Adam Eivyf0a3ddebe007
diff --git a/server/lib/planIds.js b/server/lib/planIds.js
index d7c020b051..0b22d93057 100644
--- a/server/lib/planIds.js
+++ b/server/lib/planIds.js
@@ -238,9 +238,15 @@ export function pickFirstAvailable(items, takenIds = new Set(), options = {}) {
/**
* Promise-wrapped `gh pr list` — separated from execGit because `gh` is
- * not always installed on every host. Returns an empty array on any failure.
+ * not always installed on every host.
+ *
+ * Sentinel discipline (#3358): `[]` means "gh answered and there are no open
+ * PRs"; `null` means "we could not ask" (gh missing, unauthenticated, network
+ * blocked, timed out). The caller must not read the second as the first.
+ *
+ * @returns {Promise<string[]|null>}
*/
-function listOpenPullRequestHeadRefs(repoPath) {
+export function listOpenPullRequestHeadRefs(repoPath) {
return new Promise(resolve => {
const child = spawn('gh', ['pr', 'list', '--state', 'open', '--json', 'headRefName', '-q', '.[].headRefName'], {
cwd: repoPath,
@@ -248,15 +254,21 @@ function listOpenPullRequestHeadRefs(repoPath) {
windowsHide: true
});
let out = '';
- let errored = false;
- child.on('error', () => { errored = true; resolve([]); });
+ let settled = false;
+ // One settle path so the 15s backstop can't resolve a promise the close
+ // handler already settled, and so the timer is always cleared.
+ const done = (value) => { if (!settled) { settled = true; clearTimeout(timer); resolve(value); } };
+ const timer = setTimeout(() => {
+ // setTimeout callback boundary — a kill() throw here would be uncaught.
+ try { child.kill(); } catch { /* already exited */ }
+ done(null);
+ }, 15000);
+ child.on('error', () => done(null));
child.stdout.on('data', chunk => { out += chunk.toString(); });
child.on('close', code => {
- if (errored) return;
- if (code !== 0) return resolve([]);
- resolve(out.split('\n').map(s => s.trim()).filter(Boolean));
+ if (code !== 0) return done(null);
+ done(out.split('\n').map(s => s.trim()).filter(Boolean));
});
- setTimeout(() => { try { child.kill(); } catch { /* noop */ } resolve([]); }, 15000);
});
}
@@ -290,8 +302,13 @@ export function extractSlugFromRef(ref) {
* git branch (local or remote) or open PR with the slug encoded into a
* documented claim ref pattern (`claim/<slug>` or `cos/<task>/<slug>/<agent>`).
*
- * `repoPath` is the repository to query. Best-effort: missing git, missing gh,
- * or fetch failure all degrade silently and return what evidence is available.
+ * `repoPath` is the repository to query. Git refs (local + freshly fetched
+ * `origin/*`) are the primary evidence and cover every documented claim pattern;
+ * the open-PR head refs are a secondary net for a claim whose branch was pruned.
+ *
+ * When `gh` cannot be reached the PR net is UNAVAILABLE, not empty (#3358) — the
+ * degradation is logged once so a run that later double-claims an item has a
+ * visible cause, rather than the forge outage passing as "no PRs are open".
*
* @param {string} repoPath
* @param {string[]|Set<string>} knownIds
@@ -313,9 +330,13 @@ export async function findInProgressIds(repoPath, knownIds) {
listOpenPullRequestHeadRefs(repoPath)
]);
+ if (prHeadRefs === null) {
+ console.error(`❌ plan claim scan: could not read open PRs from the forge — in-flight detection is running on git refs alone for ${repoPath}`);
+ }
+
const refs = [
...branchOutput.split('\n'),
- ...prHeadRefs
+ ...(prHeadRefs || [])
].map(s => s.trim()).filter(Boolean);
const inFlight = new Set();
diff --git a/server/lib/planIds.prScan.test.js b/server/lib/planIds.prScan.test.js
new file mode 100644
index 0000000000..534a0c6d51
--- /dev/null
+++ b/server/lib/planIds.prScan.test.js
@@ -0,0 +1,80 @@
+/**
+ * `listOpenPullRequestHeadRefs` sentinel discipline (#3358).
+ *
+ * The claim scan uses open-PR head refs as a secondary net for detecting an
+ * already-claimed PLAN item. Before this, ANY `gh` failure resolved to `[]` —
+ * indistinguishable from "the repo has no open PRs" — so a firewalled `gh`
+ * silently removed the net with nothing in the log to say so.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { EventEmitter } from 'events';
+
+const spawnMock = vi.fn();
+vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));
+
+const { listOpenPullRequestHeadRefs } = await import('./planIds.js');
+
+/** A fake `gh pr list` child that writes `stdout` then exits with `code`. */
+const ghChild = ({ code = 0, stdout = '', spawnError = null } = {}) => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.kill = vi.fn();
+ setImmediate(() => {
+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));
+ if (spawnError) child.emit('error', spawnError);
+ else child.emit('close', code);
+ });
+ return child;
+};
+
+// A benign DEFAULT (exits 0 with no output) with each case layered on via
+// `mockImplementationOnce`: the child_process mock is process-wide for this
+// file's graph, so leaving a spawn-error implementation installed would hand a
+// synthetic ENOENT to any unrelated spawn that fires during teardown.
+beforeEach(() => {
+ spawnMock.mockReset();
+ spawnMock.mockImplementation(() => ghChild({ code: 0, stdout: '' }));
+});
+
+describe('listOpenPullRequestHeadRefs (#3358)', () => {
+ it('returns the head refs gh reported', async () => {
+ spawnMock.mockImplementationOnce(() => ghChild({ stdout: 'claim/issue-1\ncos/task/slug/agent\n' }));
+ await expect(listOpenPullRequestHeadRefs('/repo')).resolves.toEqual(['claim/issue-1', 'cos/task/slug/agent']);
+ });
+
+ it('returns [] — an ANSWER — when gh reports no open PRs', async () => {
+ spawnMock.mockImplementationOnce(() => ghChild({ stdout: '' }));
+ await expect(listOpenPullRequestHeadRefs('/repo')).resolves.toEqual([]);
+ });
+
+ it('returns null (not []) when gh exits non-zero', async () => {
+ spawnMock.mockImplementationOnce(() => ghChild({ code: 1 }));
+ await expect(listOpenPullRequestHeadRefs('/repo')).resolves.toBeNull();
+ });
+
+ it('returns null (not []) when gh is missing entirely', async () => {
+ spawnMock.mockImplementationOnce(() => ghChild({
+ spawnError: Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' })
+ }));
+ await expect(listOpenPullRequestHeadRefs('/repo')).resolves.toBeNull();
+ });
+
+ it('returns null when the call times out, and the close handler cannot re-settle it', async () => {
+ vi.useFakeTimers();
+ const hung = new EventEmitter();
+ hung.stdout = new EventEmitter();
+ hung.kill = vi.fn();
+ spawnMock.mockImplementationOnce(() => hung);
+
+ const pending = listOpenPullRequestHeadRefs('/repo');
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(hung.kill).toHaveBeenCalled();
+ await expect(pending).resolves.toBeNull();
+
+ // A late close must not flip the already-settled promise.
+ hung.emit('close', 0);
+ await expect(pending).resolves.toBeNull();
+ vi.useRealTimers();
+ });
+});
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index b14ebd5764..909f8866d5 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -295,6 +295,16 @@ export async function buildTaskInput({ app } = {}) {
// burning an agent on a result we couldn't land.
if (filer === 'jira' && !jira) return skip('skipped', 'jira-not-configured')
+ // Same reasoning for an unreachable `gh` (#3358): every downstream guard here
+ // (park check, dedup against existing issues, and the filing itself) reads the
+ // forge, so running the reasoner now would burn a provider call on a proposal
+ // we could neither dedup nor file. Skip with the probe's single log line.
+ if (filer === 'forge' && forgeCli === 'gh') {
+ const { ensureForgeReachable } = await import('../github.js')
+ const forge = await ensureForgeReachable('layered-intelligence')
+ if (!forge.ok) return skip('skipped', 'forge-unreachable')
+ }
+
// Park check (forge + jira; plan has no issue to block on). A FAILED read is not
// "no blocking issues" — skip rather than resume work the user parked.
if (trackerSupportsPause(tracker.resolved)) {
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index eac557838c..7b187d4b91 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -23,6 +23,14 @@ vi.mock('../providers.js', () => ({
getProviderById: vi.fn(async (id) => ({ id, type: 'cli' }))
}));
+// The forge-reachability gate (#3358) — the gh probe LI runs before it burns a
+// provider call on a proposal it could neither dedup nor file. Reachable by
+// default; individual cases override it.
+const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
+vi.mock('../github.js', () => ({
+ ensureForgeReachable: (...args) => ensureForgeReachableMock(...args)
+}));
+
// When no per-app provider is pinned, the guard falls back to the global LI
// schedule provider via getTaskInterval. Default to no global pin so the
// no-provider path stays inert.
@@ -164,6 +172,16 @@ describe('buildTaskInput', () => {
expect(await buildTaskInput({ app: APP })).toEqual({ skip: { reason: 'blocking-read-failed' } });
});
+ it('skips before spawning a reasoner when the gh probe is not ok (#3358)', async () => {
+ // Every downstream guard reads the forge (park check, dedup, filing), so a
+ // run started here would burn a provider call on a proposal it could neither
+ // dedup nor file — and an unreadable tracker would look like "no duplicates".
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
+ expect(await buildTaskInput({ app: APP })).toEqual({ skip: { reason: 'forge-unreachable' } });
+ expect(li.listBlockingIssues).not.toHaveBeenCalled();
+ expect(li.gatherSources).not.toHaveBeenCalled();
+ });
+
it('skips when the pinned provider is an api-only (harnessless) provider', async () => {
getProviderById.mockResolvedValue({ id: 'ollama', type: 'api' });
const res = await buildTaskInput({ app: APP });
diff --git a/server/services/autonomousJobs/selfDiagnostics.js b/server/services/autonomousJobs/selfDiagnostics.js
index b5def8a42a..039dbcfb98 100644
--- a/server/services/autonomousJobs/selfDiagnostics.js
+++ b/server/services/autonomousJobs/selfDiagnostics.js
@@ -230,13 +230,15 @@ export async function ensureDiagnosticsLabels({ cwd = PATHS.root, exec = runCli
* @param {(cmd,args,opts)=>Promise<{code,stdout,stderr}>} [deps.exec] - CLI runner
* @param {string} [deps.cwd] - repo root for `gh`
* @param {() => string} [deps.now] - ISO clock (test seam)
- * @returns {Promise<{ failingCount, categories, issue }>}
+ * @param {() => Promise<{ok:boolean,status:string}>} [deps.forgeGate] - gh probe (test seam)
+ * @returns {Promise<{ failingCount, categories, issue, forgeUnavailable? }>}
*/
export async function runSelfDiagnostics({
loadLearning = loadLearningData,
exec = runCli,
cwd = PATHS.root,
- now = () => new Date().toISOString()
+ now = () => new Date().toISOString(),
+ forgeGate = null
} = {}) {
const data = await loadLearning()
// Window against the injected clock so tests are deterministic (issue #2617).
@@ -249,6 +251,18 @@ export async function runSelfDiagnostics({
for (const c of failing) console.log(formatCategoryLogLine(c))
}
+ // The metrics half above is local and always worth logging; everything below
+ // reads or writes the forge. Probe once and skip that half rather than issuing
+ // four `gh` calls that each fail into an ambiguous empty result (#3358).
+ const gate = forgeGate || (async () => {
+ const { ensureForgeReachable } = await import('../github.js')
+ return ensureForgeReachable('self-diagnostics')
+ })
+ const forge = await gate()
+ if (!forge?.ok) {
+ return { failingCount: failing.length, categories: failing, issue: null, forgeUnavailable: true }
+ }
+
const generatedAt = now()
const title = buildDiagnosticsIssueTitle()
const body = buildDiagnosticsIssueBody(failing, { generatedAt })
diff --git a/server/services/autonomousJobs/selfDiagnostics.test.js b/server/services/autonomousJobs/selfDiagnostics.test.js
index ee29556edc..12e9281093 100644
--- a/server/services/autonomousJobs/selfDiagnostics.test.js
+++ b/server/services/autonomousJobs/selfDiagnostics.test.js
@@ -172,6 +172,11 @@ function makeExec(routes) {
const argsHave = (...needles) => (args) => needles.every(n => args.includes(n))
+// The forge-reachability gate (#3358), injected so the suite never spawns the
+// real `gh api rate_limit` probe — a machine whose gh IS blocked (exactly the
+// case this issue is about) would otherwise fail the whole describe block.
+const okForge = async () => ({ ok: true, status: 'ok', detail: null, remedy: null })
+
describe('findMonitoringIssue', () => {
it('prefers the issue carrying the diagnostics slug marker', async () => {
const exec = makeExec([{
@@ -231,13 +236,28 @@ describe('findMonitoringIssue', () => {
describe('runSelfDiagnostics', () => {
const loadLearning = async () => ({ byTaskType: sampleMetrics })
+ it('skips the forge half entirely when the gh probe is not ok (#3358)', async () => {
+ // The metrics half is local and still runs; the four `gh` calls below it do
+ // not, so a firewalled gh produces one clear skip instead of an ambiguous
+ // "could not read monitoring issues" per cycle.
+ const exec = makeExec([])
+ const res = await runSelfDiagnostics({
+ forgeGate: async () => ({ ok: false, status: 'unreachable' }),
+ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z'
+ })
+ expect(res.forgeUnavailable).toBe(true)
+ expect(res.failingCount).toBe(3)
+ expect(res.issue).toBeNull()
+ expect(exec).not.toHaveBeenCalled()
+ })
+
it('creates a new monitoring issue with both labels when none exists and there are failures', async () => {
const exec = makeExec([
{ match: argsHave('issue', 'list'), result: { code: 0, stdout: '[]' } },
{ match: argsHave('label', 'create'), result: { code: 0, stdout: '' } },
{ match: argsHave('issue', 'create'), result: { code: 0, stdout: 'https://github.com/acme/repo/issues/99\n' } }
])
- const res = await runSelfDiagnostics({ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ const res = await runSelfDiagnostics({ forgeGate: okForge, loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
expect(res.failingCount).toBe(3)
expect(res.issue).toMatchObject({ number: 99, created: true })
const createCall = exec.mock.calls.find(c => c[1].includes('create') && c[1].includes('issue'))
@@ -254,7 +274,7 @@ describe('runSelfDiagnostics', () => {
{ match: argsHave('label', 'create'), result: { code: 0, stdout: '' } },
{ match: argsHave('issue', 'edit'), result: { code: 0, stdout: '' } }
])
- const res = await runSelfDiagnostics({ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ const res = await runSelfDiagnostics({ forgeGate: okForge, loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
expect(res.issue).toMatchObject({ number: 7, created: false })
// No create call happened.
expect(exec.mock.calls.find(c => c[1].includes('issue') && c[1].includes('create'))).toBeUndefined()
@@ -266,7 +286,7 @@ describe('runSelfDiagnostics', () => {
it('does NOT file when the issue read failed (avoids duplicate on a transient gh blip)', async () => {
const exec = makeExec([{ match: argsHave('issue', 'list'), result: { code: 1, stdout: '', stderr: 'boom' } }])
- const res = await runSelfDiagnostics({ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ const res = await runSelfDiagnostics({ forgeGate: okForge, loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
expect(res.issue).toBeNull()
expect(exec.mock.calls.find(c => c[1].includes('create'))).toBeUndefined()
})
@@ -276,7 +296,7 @@ describe('runSelfDiagnostics', () => {
// counts (#2617), so this is "passing" despite the lifetime counter.
const allGood = async () => ({ byTaskType: { 'self-improve:update': sampleMetrics['self-improve:update'] } })
const exec = makeExec([{ match: argsHave('issue', 'list'), result: { code: 0, stdout: '[]' } }])
- const res = await runSelfDiagnostics({ loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ const res = await runSelfDiagnostics({ forgeGate: okForge, loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
expect(res.failingCount).toBe(0)
expect(res.issue).toBeNull()
expect(exec.mock.calls.find(c => c[1].includes('create') && c[1].includes('issue'))).toBeUndefined()
@@ -293,7 +313,7 @@ describe('runSelfDiagnostics', () => {
{ match: argsHave('label', 'create'), result: { code: 0, stdout: '' } },
{ match: argsHave('issue', 'edit'), result: { code: 0, stdout: '' } }
])
- await runSelfDiagnostics({ loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ await runSelfDiagnostics({ forgeGate: okForge, loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
const editCall = exec.mock.calls.find(c => c[1].includes('edit'))
expect(editCall[1]).toContain('--remove-label')
expect(editCall[1]).toContain(NEEDS_ATTENTION_LABEL)
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index ddcea3de0b..54278bd25a 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -20,7 +20,7 @@ import { stat } from 'node:fs/promises';
import { getBranches, getDefaultBranch, isBranchMergedInto, deleteBranch } from './git.js';
import { execGit } from '../lib/execGit.js';
import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, isHumanClaimWorktree } from './worktreeManager.js';
-import { execGh } from './github.js';
+import { execGh, ensureForgeReachable } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import { githubRepoSpec } from '../lib/workTracker.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
@@ -104,10 +104,12 @@ const PR_LIST_LIMIT = 200;
* NEEDS_PR — pushed, not merged, no PR, clean → agent verifies + opens PR
* WIP — local-only or dirty worktree → skip + report (never touch)
*
- * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, abandonedAgentWorktree?:boolean, openPr:({mergeable?:string}|null) }} input
+ * @param {{ hasUpstream:boolean, isMerged:boolean, worktreeDirty:boolean, abandonedAgentWorktree?:boolean, openPr:({mergeable?:string}|null), prStateUnavailable?:boolean }} input
+ * `prStateUnavailable` means the forge could not be READ this cycle — distinct
+ * from `openPr: null` ("the forge answered: no open PR").
* @returns {'ABANDONED_WIP'|'MERGED'|'CONFLICTED'|'IN_REVIEW'|'NEEDS_PR'|'WIP'}
*/
-export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandonedAgentWorktree, openPr }) {
+export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandonedAgentWorktree, openPr, prStateUnavailable = false }) {
// A dead agent's worktree that still holds uncommitted work is the ONE dirty
// case that must be driven rather than skipped — and it must be caught BEFORE
// the `isMerged` test, because an agent that exited without committing leaves
@@ -126,6 +128,11 @@ export function classifyBranch({ hasUpstream, isMerged, worktreeDirty, abandoned
// of PR state; the `cleanupMerged` path applies the same guard for MERGED.
if (worktreeDirty) return 'WIP';
if (openPr) return openPr.mergeable === 'CONFLICTING' ? 'CONFLICTED' : 'IN_REVIEW';
+ // The forge was unreadable this cycle, so "no open PR" is not something we
+ // learned — it is something we failed to ask (#3358). Report the branch as WIP
+ // (skip + never touch) rather than dispatching an agent to open a PR that may
+ // already exist. MERGED above is unaffected: that verdict is pure git truth.
+ if (prStateUnavailable) return 'WIP';
if (hasUpstream) return 'NEEDS_PR';
return 'WIP';
}
@@ -141,9 +148,18 @@ export function classifyBranches(inputs) {
/**
* Resolve the open PRs for a repo, keyed by head branch name.
- * Returns an empty Map on any gh failure (degrade: treat as "no PR").
+ *
+ * Three answers, never two (#3358):
+ * - a Map (possibly empty) — the forge answered
+ * - an EMPTY Map for a non-GitHub origin — there is no GitHub PR state to have
+ * - `null` — we could NOT ask (gh transport/auth failure, unparseable output)
+ *
+ * `null` must never be read as "this branch has no PR": that is what made an
+ * unreachable forge classify every pushed branch as NEEDS_PR and hand the
+ * coordinator agent a list of PRs to re-open on top of the ones that exist.
+ *
* @param {string} repoPath
- * @returns {Promise<Map<string, {number:number, mergeable:string, isDraft:boolean, url:string}>>}
+ * @returns {Promise<Map<string, {number:number, mergeable:string, isDraft:boolean, url:string}>|null>}
*/
async function getOpenPrsByHead(repoPath) {
const origin = await getOriginInfo(repoPath).catch(() => null);
@@ -157,9 +173,16 @@ async function getOpenPrsByHead(repoPath) {
'pr', 'list', '--repo', repoSpec, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,headRefName,mergeable,isDraft,url'
- ]).catch(() => null);
+ ]).catch((err) => {
+ console.error(`❌ branch-reconcile: gh pr list failed for ${repoSpec}: ${err.message}`);
+ return null;
+ });
+ if (raw === null) return null;
const parsed = safeJSONParse(raw, null);
- if (!Array.isArray(parsed)) return new Map();
+ if (!Array.isArray(parsed)) {
+ console.error(`❌ branch-reconcile: gh pr list returned unparseable output for ${repoSpec} — PR state unknown this cycle`);
+ return null;
+ }
const byHead = new Map();
for (const pr of parsed) {
if (pr?.headRefName) {
@@ -350,11 +373,15 @@ async function worktreeAgeMs(worktreePath) {
export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null }) {
const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);
- const [branches, worktrees, prsByHead] = await Promise.all([
+ const [branches, worktrees, prsByHeadOrNull] = await Promise.all([
getBranches(repoPath),
listWorktrees(repoPath).catch(() => []),
getOpenPrsByHead(repoPath)
]);
+ // null = the forge could not be read (see getOpenPrsByHead). Carried onto every
+ // input so the classifier can refuse to conclude "no PR" from an unread forge.
+ const prStateUnavailable = prsByHeadOrNull === null;
+ const prsByHead = prsByHeadOrNull || new Map();
// Map local branch name -> worktree record (strip the refs/heads/ prefix).
const worktreeByBranch = new Map();
@@ -394,7 +421,8 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
ahead: divergence.ahead,
collisionPaths: divergence.collisionPaths,
abandonedAgentWorktree: isAbandonedAgentWorktree({ path: worktreePath, locked: worktreeLocked, activeAgentIds }),
- openPr: prsByHead.get(b.name) || null
+ openPr: prsByHead.get(b.name) || null,
+ prStateUnavailable
});
}
return inputs;
@@ -464,9 +492,18 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
* @param {{ cleanup?: boolean, activeAgentIds?: Set<string> }} [opts] - when cleanup
* is false, merged branches are reported (in `skipped`, reason `cleanup-disabled`)
* but not deleted. `activeAgentIds` protects in-use CoS agent worktrees.
- * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[] }>}
+ * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], forgeUnavailable?:boolean }>}
+ * `forgeUnavailable: true` means the cycle was SKIPPED because `gh` could not be
+ * read — an empty `inFlight` there says nothing about the repo (#3358).
*/
export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeAgentIds = new Set() } = {}) {
+ // Every classification below depends on PR state, so an unreadable forge makes
+ // the whole pass a guess. Skip with one line rather than report a quiet repo.
+ const forge = await ensureForgeReachable('branch-reconcile');
+ if (!forge.ok) {
+ return { defaultBranch: null, cleaned: [], inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
+ }
+
const defaultBranch = await getDefaultBranch(repoPath).catch(() => 'main') || 'main';
const inputs = await gatherBranchState(repoPath, { defaultBranch, activeAgentIds });
const classified = classifyBranches(inputs);
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index cc5f8c5ca3..d195e296d8 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -35,7 +35,11 @@ vi.mock('./worktreeManager.js', () => ({
}),
isHumanClaimWorktree: vi.fn((id) => typeof id === 'string' && id.startsWith('claim-'))
}));
-vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));
+const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
+vi.mock('./github.js', () => ({
+ execGh: vi.fn(async () => '[]'),
+ ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),
+}));
vi.mock('../lib/gitRemote.js', () => ({
getOriginInfo: vi.fn(async () => ({
hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'
@@ -414,6 +418,61 @@ describe('branchPriorityRank / prioritizeBranches', () => {
});
});
+// #3358 — an unreachable forge must read as "we could not ask", never as
+// "this branch has no PR". Concluding the latter is what turned a firewalled
+// `gh` into a NEEDS_PR list the coordinator would act on by opening duplicate
+// PRs on top of the ones that already exist.
+describe('unreachable forge (#3358)', () => {
+ it('classifies a pushed branch as WIP — never NEEDS_PR — when PR state is unknown', () => {
+ const branch = { isMerged: false, worktreeDirty: false, hasUpstream: true, openPr: null };
+ expect(classifyBranch(branch)).toBe('NEEDS_PR');
+ expect(classifyBranch({ ...branch, prStateUnavailable: true })).toBe('WIP');
+ });
+
+ it('still reports MERGED when PR state is unknown — that verdict is pure git truth', () => {
+ expect(classifyBranch({ isMerged: true, hasUpstream: true, openPr: null, prStateUnavailable: true })).toBe('MERGED');
+ });
+
+ it('marks every gathered branch prStateUnavailable when gh pr list fails', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ execGh.mockRejectedValue(new Error('connect: bad file descriptor'));
+ git.isBranchMergedInto.mockResolvedValue(false);
+
+ const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });
+ expect(inputs[0].prStateUnavailable).toBe(true);
+ expect(classifyBranches(inputs)[0].state).toBe('WIP');
+ });
+
+ it('leaves prStateUnavailable false when gh answers with an empty list', async () => {
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ execGh.mockResolvedValue('[]');
+ git.isBranchMergedInto.mockResolvedValue(false);
+
+ const inputs = await gatherBranchState('/repo', { defaultBranch: 'main' });
+ expect(inputs[0].prStateUnavailable).toBe(false);
+ expect(classifyBranches(inputs)[0].state).toBe('NEEDS_PR');
+ });
+
+ it('skips the whole cycle (never touches git) when the gh probe is not ok', async () => {
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
+ const res = await reconcile('/repo');
+ expect(res.forgeUnavailable).toBe(true);
+ expect(res.forgeStatus).toBe('unreachable');
+ expect(res.inFlight).toEqual([]);
+ expect(res.cleaned).toEqual([]);
+ // Crucially: no branch enumeration and no deletion happened, so the empty
+ // result can't be mistaken for "the repo is clean".
+ expect(git.getBranches).not.toHaveBeenCalled();
+ expect(git.deleteBranch).not.toHaveBeenCalled();
+ });
+});
+
describe('reconcile', () => {
it('orders in-flight branches by work-branch priority', async () => {
// A plain unrecognized branch, a feature branch, and a claim branch — all
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 68613c399f..d6ad30bf5d 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2059,6 +2059,13 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
// A failed scan is treated as transient (git/gh blip) — skip WITHOUT parking
// so the next tick retries instead of waiting out a full recheck cadence.
if (!result) return { skip: true };
+ // Same treatment for a cycle the reconciler skipped because `gh` was unreadable
+ // (#3358): its empty in-flight set is "we could not ask", not "nothing to do",
+ // so parking on it would sit out a full recheck cadence over a network blip.
+ if (result.forgeUnavailable) {
+ emitLog('info', `🔀 branch-reconcile skipped for ${app.name}: forge unreachable (gh ${result.forgeStatus || 'error'})`, { appId: app.id, analysisType: taskType });
+ return { skip: true };
+ }
if (result.cleaned.length) {
emitLog('info', `🔀 branch-reconcile ${app.name}: cleaned ${result.cleaned.length} merged branch(es)`, { appId: app.id, analysisType: taskType });
}
diff --git a/server/services/github.ghHealth.test.js b/server/services/github.ghHealth.test.js
index fbaf205151..ac91a7c4af 100644
--- a/server/services/github.ghHealth.test.js
+++ b/server/services/github.ghHealth.test.js
@@ -6,7 +6,8 @@ vi.mock('../lib/fileUtils.js', () => ({
PATHS: { root: '/mock', data: '/mock/data' },
readJSONFile: vi.fn().mockResolvedValue({ repos: {}, secrets: {} }),
atomicWrite: vi.fn().mockResolvedValue(undefined),
- ensureDir: vi.fn().mockResolvedValue(undefined)
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ safeJSONParse: (raw, fallback) => { try { return JSON.parse(raw); } catch { return fallback; } }
}));
vi.mock('./settings.js', () => ({
@@ -17,7 +18,10 @@ vi.mock('./settings.js', () => ({
const spawnMock = vi.fn();
vi.mock('child_process', () => ({ spawn: (...args) => spawnMock(...args) }));
-const { classifyGhProbe, ghRemedy, checkGhHealth, __resetGhHealthCache } = await import('./github.js');
+const {
+ classifyGhProbe, ghRemedy, checkGhHealth, __resetGhHealthCache,
+ ensureForgeReachable, findPullRequestForBranch
+} = await import('./github.js');
/** A fake `gh` child that emits the given outcome on the next tick. */
function fakeChild({ code = 0, stderr = '', spawnError = null } = {}) {
@@ -180,3 +184,73 @@ describe('checkGhHealth', () => {
vi.useRealTimers();
});
});
+
+/**
+ * The two helpers the #3358 sweep hangs off: a job-level gate that logs once and
+ * a PR lookup with THREE answers instead of two.
+ */
+describe('ensureForgeReachable (#3358)', () => {
+ beforeEach(() => { __resetGhHealthCache(); spawnMock.mockReset(); });
+
+ it('passes silently when the probe is ok', async () => {
+ spawnMock.mockImplementation(() => fakeChild({ code: 0 }));
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {});
+ await expect(ensureForgeReachable('some-job')).resolves.toMatchObject({ ok: true, status: 'ok' });
+ expect(err).not.toHaveBeenCalled();
+ err.mockRestore();
+ });
+
+ it('logs exactly one line naming the job and the probe status when it is not', async () => {
+ spawnMock.mockImplementation(() => fakeChild({ code: 1, stderr: 'dial tcp: lookup api.github.com' }));
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const health = await ensureForgeReachable('pr-watcher');
+ expect(health.ok).toBe(false);
+ expect(err).toHaveBeenCalledTimes(1);
+ expect(err.mock.calls[0][0]).toContain('pr-watcher');
+ expect(err.mock.calls[0][0]).toContain('unreachable');
+ err.mockRestore();
+ });
+});
+
+describe('findPullRequestForBranch (#3358)', () => {
+ beforeEach(() => { spawnMock.mockReset(); });
+
+ /** A fake `gh` child that writes `stdout` then exits with `code`. */
+ const ghChild = ({ code = 0, stdout = '' } = {}) => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ setImmediate(() => {
+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));
+ child.emit('close', code);
+ });
+ return child;
+ };
+
+ it('reports `found` with the PR number', async () => {
+ spawnMock.mockImplementation(() => ghChild({ stdout: '[{"number":7,"url":"https://example.com/pr/7","state":"OPEN"}]' }));
+ await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'found', number: 7 });
+ });
+
+ it('reports `none` for an ANSWERED empty list', async () => {
+ spawnMock.mockImplementation(() => ghChild({ stdout: '[]' }));
+ await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'none', number: null });
+ });
+
+ it('reports `unavailable` — never `none` — when gh fails', async () => {
+ spawnMock.mockImplementation(() => ghChild({ code: 1 }));
+ const result = await findPullRequestForBranch('claim/issue-1');
+ expect(result.status).toBe('unavailable');
+ });
+
+ it('reports `unavailable` when a zero-exit gh emits unparseable output', async () => {
+ spawnMock.mockImplementation(() => ghChild({ stdout: 'not json' }));
+ await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'unavailable' });
+ });
+
+ it('reports `unavailable` with no branch to ask about', async () => {
+ await expect(findPullRequestForBranch('')).resolves.toMatchObject({ status: 'unavailable' });
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/github.js b/server/services/github.js
index a18fd275df..6bffa05d68 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -1,6 +1,7 @@
import { spawn } from 'child_process';
import { join } from 'path';
-import { atomicWrite, readJSONFile, PATHS, ensureDir } from '../lib/fileUtils.js';
+import { atomicWrite, readJSONFile, PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
import { ServerError } from '../lib/errorHandler.js';
import { getSettings, updateSettings } from './settings.js';
@@ -45,9 +46,13 @@ const DEFAULT_EXEC_GH_TIMEOUT_MS = 60000;
* process. `timeoutMs` kills the child and rejects with a clear error; it's
* cleared on normal exit so it never fires for a completed run.
*/
-export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS) {
+export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = null } = {}) {
return new Promise((resolve, reject) => {
- const child = spawn('gh', args, { shell: false, windowsHide: true });
+ const child = spawn('gh', args, {
+ shell: false,
+ windowsHide: true,
+ ...(cwd ? { cwd, env: withSpawnCwdEnv(process.env, cwd) } : {})
+ });
let stdout = '';
let stderr = '';
let timedOut = false;
@@ -457,3 +462,60 @@ export function __resetGhHealthCache() {
ghHealthCache = null;
ghHealthCheckedAt = 0;
}
+
+/**
+ * Gate for a forge-dependent scheduled job (#3358). Runs the probe and, when the
+ * forge is NOT usable, emits ONE single-line error naming the job and the probe
+ * status — then the caller skips the cycle instead of executing against a forge
+ * it cannot read and concluding "everything is quiet".
+ *
+ * A probe that itself blows up is reported as `error` rather than silently
+ * passing: "we could not even ask whether we can ask" is still not `ok`.
+ *
+ * @param {string} label - job name for the log line (e.g. 'pr-watcher')
+ * @returns {Promise<{ ok: boolean, status: string, detail: string|null, remedy: string|null }>}
+ */
+export async function ensureForgeReachable(label) {
+ const health = await checkGhHealth().catch(err => ({
+ status: 'error', ok: false, detail: err.message, remedy: ghRemedy('error')
+ }));
+ if (health.ok) return health;
+ const detail = health.detail ? ` — ${String(health.detail).split('\n')[0].slice(0, 160)}` : '';
+ console.error(`❌ ${label}: skipping this cycle, gh is ${health.status}${detail}`);
+ return health;
+}
+
+/**
+ * Does a pull request exist for `branch`? Three answers, never collapsed to two
+ * (#3358): `found` (the forge has one), `none` (the forge answered and has
+ * none), `unavailable` (we could not ask). A caller must never read
+ * `unavailable` as `none` — that is how a run that opened no PR gets recorded as
+ * a success while `gh` is firewalled.
+ *
+ * `--state all` deliberately: a PR that was opened and then closed still proves
+ * the agent DID reach the forge, which is the question being asked.
+ *
+ * @param {string} branch - head branch name
+ * @param {{ cwd?: string }} [opts] - repo dir gh resolves the remote from
+ * @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, detail: string|null }>}
+ */
+export async function findPullRequestForBranch(branch, { cwd = null } = {}) {
+ if (!branch) return { status: 'unavailable', number: null, url: null, detail: 'no branch name' };
+ const raw = await execGh(
+ ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,state'],
+ DEFAULT_EXEC_GH_TIMEOUT_MS,
+ { cwd }
+ ).catch(err => err);
+ if (raw instanceof Error) {
+ return { status: 'unavailable', number: null, url: null, detail: raw.message };
+ }
+ const parsed = safeJSONParse(raw, null);
+ // A zero-exit gh that emitted nothing parseable told us nothing — that is
+ // "could not ask", not "no PR".
+ if (!Array.isArray(parsed)) {
+ return { status: 'unavailable', number: null, url: null, detail: 'gh returned unparseable output' };
+ }
+ const pr = parsed[0];
+ if (!pr) return { status: 'none', number: null, url: null, detail: null };
+ return { status: 'found', number: pr.number ?? null, url: pr.url || null, detail: pr.state || null };
+}
diff --git a/server/services/issueReconcile.js b/server/services/issueReconcile.js
index b76b7eae38..7e95b04d22 100644
--- a/server/services/issueReconcile.js
+++ b/server/services/issueReconcile.js
@@ -51,7 +51,7 @@
*/
import { execGit } from '../lib/execGit.js';
-import { execGh } from './github.js';
+import { execGh, ensureForgeReachable } from './github.js';
import { execGlab } from './gitlab.js';
import { fetchMyCurrentSprintTickets } from './jira.js';
import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';
@@ -267,16 +267,26 @@ function normalizeGithubIssue(issue) {
* @returns {Promise<{forge:'github', fullName:string, inProgress:object[], mergedPrs:object[], openPrs:object[]}|null>}
*/
async function getGithubState(repoSpec, fullName) {
+ // Probe before the three list calls (#3358): without it an unreachable gh
+ // returns three empty pages that read as "nothing to reconcile" forever.
+ const forge = await ensureForgeReachable('issue-reconcile');
+ if (!forge.ok) return null;
+
+ const ghList = (args, what) => execGh(args).catch((err) => {
+ console.error(`❌ issue-reconcile: ${what} failed for ${fullName}: ${err.message}`);
+ return null;
+ });
+
const [issuesRaw, mergedRaw, openRaw] = await Promise.all([
- execGh(['issue', 'list', '--repo', repoSpec, '--state', 'open',
+ ghList(['issue', 'list', '--repo', repoSpec, '--state', 'open',
'--label', IN_PROGRESS_LABEL, '--limit', String(GH_LIST_LIMIT),
- '--json', 'number,title,labels,assignees,url']).catch(() => null),
- execGh(['pr', 'list', '--repo', repoSpec, '--state', 'merged',
+ '--json', 'number,title,labels,assignees,url'], 'gh issue list'),
+ ghList(['pr', 'list', '--repo', repoSpec, '--state', 'merged',
'--limit', String(GH_LIST_LIMIT),
- '--json', 'number,headRefName,body,url,mergedAt']).catch(() => null),
- execGh(['pr', 'list', '--repo', repoSpec, '--state', 'open',
+ '--json', 'number,headRefName,body,url,mergedAt'], 'gh pr list --state merged'),
+ ghList(['pr', 'list', '--repo', repoSpec, '--state', 'open',
'--limit', String(GH_LIST_LIMIT),
- '--json', 'number,headRefName,body']).catch(() => null),
+ '--json', 'number,headRefName,body'], 'gh pr list --state open'),
]);
const inProgressRaw = safeJSONParse(issuesRaw, null);
@@ -284,12 +294,20 @@ async function getGithubState(repoSpec, fullName) {
// transient blip (return null → skip without parking). Empty is a valid,
// different answer (no in-progress issues) and returns [].
if (!Array.isArray(inProgressRaw)) return null;
+ // The PR lists are load-bearing too (#3358): `mergedPrs` is what proves an
+ // issue shipped and `openPrs` is what proves a claim is still live on a peer.
+ // Degrading either to [] would classify a live claim as a zombie and unlabel a
+ // PR that is open right now — so a failure here fails the whole scan, and only
+ // an ANSWERED-but-empty list falls through as [].
+ const mergedPrs = safeJSONParse(mergedRaw, null);
+ const openPrs = safeJSONParse(openRaw, null);
+ if (!Array.isArray(mergedPrs) || !Array.isArray(openPrs)) return null;
return {
forge: 'github',
fullName,
inProgress: inProgressRaw.map(normalizeGithubIssue),
- mergedPrs: safeJSONParse(mergedRaw, []) || [],
- openPrs: safeJSONParse(openRaw, []) || [],
+ mergedPrs,
+ openPrs,
};
}
@@ -349,12 +367,20 @@ async function getGitlabState(repoPath, fullName) {
const inProgressRaw = safeJSONParse(issuesRaw, null);
if (!Array.isArray(inProgressRaw)) return null;
+ // Same load-bearing treatment as the GitHub path (#3358): a `glab` blip on the
+ // MR lists must fail the scan, not degrade to "no MRs exist".
+ const mergedRows = safeJSONParse(mergedRaw, null);
+ const openRows = safeJSONParse(openRaw, null);
+ if (!Array.isArray(mergedRows) || !Array.isArray(openRows)) {
+ console.error(`❌ issue-reconcile: glab mr list unavailable for ${fullName} — skipping this cycle`);
+ return null;
+ }
return {
forge: 'gitlab',
fullName,
inProgress: inProgressRaw.map(normalizeGitlabIssue),
- mergedPrs: (safeJSONParse(mergedRaw, []) || []).map(normalizeGitlabMr),
- openPrs: (safeJSONParse(openRaw, []) || []).map(normalizeGitlabMr),
+ mergedPrs: mergedRows.map(normalizeGitlabMr),
+ openPrs: openRows.map(normalizeGitlabMr),
};
}
diff --git a/server/services/issueReconcile.test.js b/server/services/issueReconcile.test.js
index 24232941c6..0fdbbf419d 100644
--- a/server/services/issueReconcile.test.js
+++ b/server/services/issueReconcile.test.js
@@ -17,7 +17,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../lib/execGit.js', () => ({
execGit: vi.fn(async () => ({ stdout: '', exitCode: 0 })),
}));
-vi.mock('./github.js', () => ({ execGh: vi.fn(async () => '[]') }));
+const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
+vi.mock('./github.js', () => ({
+ execGh: vi.fn(async () => '[]'),
+ ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),
+}));
vi.mock('./gitlab.js', () => ({ execGlab: vi.fn(async () => '[]') }));
vi.mock('./jira.js', () => ({ fetchMyCurrentSprintTickets: vi.fn(async () => []) }));
vi.mock('../lib/gitRemote.js', () => ({
@@ -546,6 +550,44 @@ describe('gatherIssueState carries labels/assignees for the follow-up', () => {
});
});
+// #3358 — "the forge said there is nothing" vs "we could not ask the forge".
+// Collapsing the two here is worse than elsewhere: this reconciler CLOSES issues
+// and strips their `in-progress` label, so an empty answer it never got would
+// unlabel a claim that is live on a peer right now.
+describe('unreachable forge (#3358)', () => {
+ it('skips the scan when the gh probe is not ok, without issuing a single gh call', async () => {
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
+ const gathered = await gatherIssueState('/repo');
+ expect(gathered).toBeNull();
+ expect(execGh).not.toHaveBeenCalled();
+ });
+
+ it('fails the scan when the merged-PR list is unavailable (never treats it as "nothing shipped")', async () => {
+ execGh.mockImplementation(async (argv) => {
+ if (argv[0] === 'issue') return JSON.stringify([{ number: 1, title: 't', labels: [], assignees: [], url: 'u' }]);
+ if (argv.includes('merged')) throw new Error('connect: bad file descriptor');
+ return '[]';
+ });
+ expect(await gatherIssueState('/repo')).toBeNull();
+ });
+
+ it('fails the scan when the OPEN-PR list is unavailable — an open PR is what proves a claim is live', async () => {
+ execGh.mockImplementation(async (argv) => {
+ if (argv[0] === 'issue') return JSON.stringify([{ number: 1, title: 't', labels: [], assignees: [], url: 'u' }]);
+ if (argv.includes('open')) throw new Error('connect: bad file descriptor');
+ return '[]';
+ });
+ expect(await gatherIssueState('/repo')).toBeNull();
+ });
+
+ it('still scans when every list is ANSWERED but empty', async () => {
+ mockGh({ issues: [], merged: [], open: [] });
+ const gathered = await gatherIssueState('/repo');
+ expect(gathered).not.toBeNull();
+ expect(gathered.issues).toEqual([]);
+ });
+});
+
describe('zombieSignature', () => {
it('is order-independent and keys on issue+merged PR', () => {
const a = zombieSignature([{ number: 2, mergedPr: { number: 20 } }, { number: 1, mergedPr: { number: 10 } }]);
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 2de930e231..c71e7a72ac 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -24,7 +24,7 @@
* failure on one app.
*/
-import { execGh } from './github.js';
+import { execGh, ensureForgeReachable } from './github.js';
import { getAppById, updateApp } from './apps.js';
import * as git from './git.js';
import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
@@ -77,7 +77,13 @@ export async function getSelfLogin(host) {
if (_selfLoginCache.has(host)) return _selfLoginCache.get(host);
// `--hostname` is required: without it `gh api` targets github.com regardless
// of cwd, resolving the wrong identity for an enterprise repo.
- const login = await execGh(['api', 'user', '--hostname', host, '--jq', '.login']).catch(() => null);
+ const login = await execGh(['api', 'user', '--hostname', host, '--jq', '.login']).catch((err) => {
+ // Log rather than swallow (#3358): without this a firewalled/unauthenticated
+ // gh is indistinguishable from "this host has no login", and every self/others
+ // gate silently stops firing with nothing in the log to explain it.
+ console.error(`❌ pr-watcher: could not resolve the gh login on ${host}: ${err.message}`);
+ return null;
+ });
// Only memoize a SUCCESSFUL lookup. Caching a null from a transient gh/auth
// failure (keychain locked mid-tick, gh re-auth in progress) would wedge every
// later self/others gate on this host into 'self-login-unavailable' until
@@ -101,7 +107,10 @@ export function __resetSelfLoginCache() {
*/
async function getDefaultBranch(repoSpec) {
const name = await execGh(['repo', 'view', repoSpec, '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name'])
- .catch(() => null);
+ .catch((err) => {
+ console.error(`❌ pr-watcher: could not resolve the default branch for ${repoSpec}: ${err.message}`);
+ return null;
+ });
return name ? name.trim() : null;
}
@@ -117,7 +126,10 @@ async function listOpenPullRequests(repoSpec, baseBranch) {
'--base', baseBranch, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,title,author,url,createdAt,isDraft,headRefName'
- ]).catch(() => null);
+ ]).catch((err) => {
+ console.error(`❌ pr-watcher: gh pr list failed for ${repoSpec}: ${err.message}`);
+ return null;
+ });
if (raw === null) return null;
// Guard the parse: a success-exit gh that emits empty/malformed stdout would
// otherwise throw a SyntaxError, breaking this module's "never throws"
@@ -294,6 +306,10 @@ export async function processPendingMergePrs(app) {
const pending = readPendingMergePrs(app).map(normalizePendingMerge).filter(Boolean);
if (pending.length === 0) return { ok: true, checked: 0, merged: 0, escalated: 0, timedOut: 0 };
+ // Skip rather than poll every pending PR into an `errors` count we can't act on.
+ const forge = await ensureForgeReachable('pr-watcher pending-merge');
+ if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status };
+
const origin = await getOriginInfo(app?.repoPath).catch(() => null);
const repoSpec = githubRepoSpec(origin);
if (!repoSpec) return { ok: false, reason: 'not-a-github-repo' };
@@ -394,6 +410,12 @@ export async function persistPrWatcherState(appId, patch) {
export async function checkPullRequests(app, { authorFilter = 'any' } = {}) {
const filter = PR_AUTHOR_FILTERS.includes(authorFilter) ? authorFilter : 'any';
+ // Probe first (#3358). Without this an unreachable gh reads as "no open PRs",
+ // the high-water mark stays put, and the watcher reports a quiet repo forever
+ // with nothing in the log naming the real cause.
+ const forge = await ensureForgeReachable('pr-watcher');
+ if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status };
+
const origin = await getOriginInfo(app.repoPath).catch(() => null);
// Accept any GitHub-family host — github.com AND self-hosted GitHub Enterprise
// (github.*) — not just github.com. `origin.isGithub` is github.com-only (it
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 1c7def8cfb..89e0f4fa39 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -3,8 +3,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// ─── mocks (must precede the import under test) ──────────────────────────────
const execGhMock = vi.fn();
+const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
vi.mock('./github.js', () => ({
execGh: (...args) => execGhMock(...args),
+ ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),
}));
const mergePrMock = vi.fn();
@@ -68,6 +70,8 @@ const pr = (number, login, extra = {}) => ({
beforeEach(() => {
execGhMock.mockReset();
+ ensureForgeReachableMock.mockReset();
+ ensureForgeReachableMock.mockResolvedValue({ ok: true, status: 'ok', detail: null, remedy: null });
mergePrMock.mockReset();
addNotificationMock.mockReset();
spawnReviewLoopFollowUpMock.mockReset();
@@ -322,6 +326,26 @@ describe('checkPullRequests', () => {
expect(r).toEqual({ ok: false, reason: 'not-a-github-repo' });
});
+ // #3358 — before this gate, an unreachable gh returned an empty PR page, the
+ // high-water mark stayed put, and the watcher reported a permanently quiet
+ // repo with nothing in the log naming the cause.
+ it('skips the cycle when the gh probe is not ok, without asking gh anything', async () => {
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable', detail: 'dial tcp' });
+ const r = await checkPullRequests(app, { authorFilter: 'any' });
+ expect(r).toEqual({ ok: false, reason: 'forge-unreachable', forgeStatus: 'unreachable' });
+ expect(execGhMock).not.toHaveBeenCalled();
+ });
+
+ it('reports pr-list-failed (not "no open PRs") when gh pr list rejects', async () => {
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
+ execGhMock
+ .mockResolvedValueOnce('main') // repo view → default branch
+ .mockRejectedValueOnce(new Error('connect: bad file descriptor'));
+ const r = await checkPullRequests(app, { authorFilter: 'any' });
+ expect(r.ok).toBe(false);
+ expect(r.reason).toBe('pr-list-failed');
+ });
+
it('bails when the default branch cannot be resolved', async () => {
getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
execGhMock.mockResolvedValueOnce(''); // repo view → empty