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

address review (codex): propagate the PR verdict to cleanup, and probe the repo's own forge host (#3358)

[._.]/ Adam Eivy4f0112557680
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index a771e8590d..72e4211dfc 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -29,11 +29,12 @@ import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/ant
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
import { isKimiCommand, ensureKimiHeadlessArgs } from '../lib/kimi.js';
-import { resolveCliModel, buildEffortArgs, buildCodexStartupArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
+import { resolveCliModel, buildEffortArgs, buildCodexStartupArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
import { resolveForgeTokenEnv } from './git.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { resolvePrCompletion } from '../lib/prDisposition.js';
+import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
import { DONE_SENTINEL_NAME } from '../lib/agentSentinel.js';
import { isHostShuttingDown, shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
@@ -859,20 +860,34 @@ export async function spawnDirectly({
const analysisBuffer = rawStreamBuffer || outputBuffer;
const errorAnalysis = finalSuccess ? null : (immediateFallbackAnalysis || analyzeAgentFailure(analysisBuffer, task, model));
- // Claude Code CLI agents run `/simplify` + `/do:pr` themselves (see
+ // Slashdo-capable CLI agents run `/simplify` + `/do:pr` themselves (see
// buildCliCompletionSection in agentPromptBuilder.js) — mirror the TUI
// cleanup contract so PortOS doesn't double-fire push+PR creation. Resolved
// BEFORE finalizeAgent because it also gates the PR-claim verification
// (#3358): a PortOS-owned PR is created by the cleanup below, i.e. AFTER
// finalize, so only an agent-owned PR can be verified there.
+ //
+ // Uses the SAME `canTypeSlashCommands` predicate the prompt builder and the
+ // runner-mode cleanup already use, not a provider-id allowlist: an allowlist
+ // misses a path-configured `claude` under a custom provider id (told to run
+ // `/do:pr`, then PortOS opens a second PR) and wrongly claims a lean `--bare`
+ // session owns a PR it was never told to open. Whoever the prompt told to
+ // open the PR must be who cleanup and verification believe opened it.
const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');
+ const directAgentOwnsPR = directOpenPR && canTypeSlashCommands({
+ providerId: provider?.id,
+ providerCommand: provider?.command,
+ leanMode: isOllamaClaudeProvider(provider),
+ });
// try/finally so a throw from finalizeAgent still runs the local
// cleanup (worktree, pid unregister, activeAgents delete). Mirrors the
// TUI path's pattern.
+ // See the TUI path: a PR-claim downgrade must reach cleanup, or a run that
+ // opened no PR is cleaned up as a success and loses its retry state (#3358).
+ let cleanupSuccess = finalSuccess;
try {
- await finalizeAgent({
+ const finalized = await finalizeAgent({
agentId,
task,
runId: agentData?.runId || runId,
@@ -889,11 +904,12 @@ export async function spawnDirectly({
workspacePath,
prExpected: directAgentOwnsPR,
});
+ if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;
} finally {
const directPrCompletion = resolvePrCompletion(task.metadata);
const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
const reviewOptions = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn });
- await cleanupWorktreeFn(agentId, finalSuccess, {
+ await cleanupWorktreeFn(agentId, cleanupSuccess, {
openPR: directAgentOwnsPR ? false : directOpenPR,
prCompletion: directPrCompletion,
...reviewOptions,
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 7340cf1adb..adb4fe04f9 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -648,6 +648,13 @@ export async function finalizeAgent({
}
await processAgentCompletion(agentId, task, success, outputBuffer);
+
+ // Hand the CORRECTED verdict back so the caller's worktree cleanup runs on the
+ // same answer this function just persisted (#3358). Without it, a run
+ // downgraded to `pr-missing` would still be cleaned up as a success — worktree
+ // removed, local branch deleted, and no resume pointer recorded — destroying
+ // the state the retry needs to open the PR that is missing.
+ return { success, prVerdict };
}
/**
diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.js
index 57141c53b1..e2f60b7b4d 100644
--- a/server/services/agentFinalization.prVerification.test.js
+++ b/server/services/agentFinalization.prVerification.test.js
@@ -222,6 +222,17 @@ describe('finalizeAgent — a PR-shaped run with no PR is not a success (#3358)'
expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'blocked' }), 'internal');
});
+ it('hands the corrected verdict back so worktree cleanup runs on the same answer', async () => {
+ // Cleaning up as a success removes the worktree and deletes the local
+ // branch — the exact state a retry needs to open the PR that is missing.
+ onBranch('claim/issue-1');
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });
+ await expect(finalize()).resolves.toMatchObject({ success: false });
+
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'u' });
+ await expect(finalize()).resolves.toMatchObject({ success: true });
+ });
+
it('falls back to the reported outcome when the verification itself throws', async () => {
onBranch('claim/issue-1');
findPullRequestForBranchMock.mockRejectedValue(new Error('boom'));
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 07b9d3147b..aa67f5bf73 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -38,6 +38,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { createAgentRun, checkForTaskCommit } from './agentRunTracking.js';
import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
+import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';
import { composeProviderEnv } from '../lib/cliChildEnv.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
@@ -891,6 +892,18 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// Analyze failure if applicable
const errorAnalysis = effectiveSuccess ? null : analyzeAgentFailure(outputBuffer, task, model);
+ // Whether the AGENT (not PortOS) owned PR creation — the gate for
+ // finalizeAgent's PR-claim verification (#3358). Derived from the same
+ // `canTypeSlashCommands` predicate `runAgentCompletionCleanup` uses below, so
+ // the run that was told to open its own PR is exactly the run we check for
+ // one. When PortOS owns it the PR is created by that cleanup, i.e. AFTER
+ // finalize, so verifying here would fail every correct run.
+ const runnerAgentOwnsPR = isTruthyMeta(task?.metadata?.openPR) && canTypeSlashCommands({
+ providerId: agent.providerId,
+ providerCommand: agent.providerCommand,
+ leanMode: agent.leanMode === true,
+ });
+
// Extract pipeline output summary before completion writes metadata to disk
if (task?.metadata?.pipeline && effectiveSuccess) {
const workspacePath = agent.workspacePath || ROOT_DIR;
@@ -917,8 +930,12 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// it (#2727) but both carry their own .catch, so neither throws out —
// the partial-state cases are best-effort by design).
let finalizeError = null;
+ // The verdict finalizeAgent persisted — a PR-claim downgrade (#3358) has to
+ // reach the cleanup below, which otherwise removes the worktree, deletes the
+ // local branch, and skips the resume pointer for a run it believes succeeded.
+ let cleanupSuccess = effectiveSuccess;
try {
- await finalizeAgent({
+ const finalized = await finalizeAgent({
agentId,
task,
runId,
@@ -930,7 +947,9 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
errorAnalysis,
isTruthyMetaFn: isTruthyMeta,
workspacePath: agent.workspacePath || null,
+ prExpected: runnerAgentOwnsPR,
});
+ if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;
} catch (err) {
finalizeError = err;
emitLog('error', `finalizeAgent threw for ${agentId} (continuing cleanup): ${err.message}`, { agentId, error: err.message });
@@ -940,7 +959,7 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// pipeline progression, the Creative Director chain hook, and worktree
// cleanup (+ cleanup-warning notification and merge-recovery task). Runs
// inside this try so a throw still hits the finally below.
- await runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess, outputBuffer });
+ await runAgentCompletionCleanup({ agentId, task, agent, effectiveSuccess: cleanupSuccess, outputBuffer });
// Surface a finalizeAgent throw to the caller after best-effort
// cleanup completed — without this the runner harness would never see
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 537f8e1ba7..f47e0dbb87 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -136,8 +136,10 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
metadata.success = success;
metadata.outputSize = Buffer.byteLength(output || '');
- // Store error details - extract from output if no analysis provided
- if (exitCode !== 0) {
+ // Store error details - extract from output if no analysis provided. A clean
+ // exit that was overridden to failure (#3358) also needs its diagnostic
+ // recorded, or the run reads `success: false` with nothing saying why.
+ if (exitCode !== 0 || !success) {
const errorInfo = errorAnalysis || extractErrorFromOutput(output, exitCode);
metadata.error = errorInfo.message || `Process exited with code ${exitCode}`;
metadata.errorDetails = errorInfo.details || metadata.error;
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 10c841e379..e5a413f841 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -645,8 +645,14 @@ export async function spawnTuiAgent({
// cleanup, pid unregister, activeAgents delete, session kill. Without
// this, a memory-extraction crash would strand the worktree and the
// shell session on disk.
+ // The verdict finalizeAgent actually persisted. A PR-claim downgrade (#3358)
+ // must reach cleanup too — cleaning up as a success removes the worktree and
+ // deletes the local branch, destroying the state the retry needs. Left at
+ // `finalSuccess` if finalize threw before returning (the pre-existing
+ // best-effort posture).
+ let cleanupSuccess = finalSuccess;
try {
- await finalizeAgent({
+ const finalized = await finalizeAgent({
agentId,
task,
runId,
@@ -663,17 +669,18 @@ export async function spawnTuiAgent({
workspacePath,
prExpected: agentOwnsPR,
});
+ if (finalized && typeof finalized.success === 'boolean') cleanupSuccess = finalized.success;
} finally {
if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});
- const reviewOptions = finalSuccess && taskOpenPR && !agentOwnsPR
+ const reviewOptions = cleanupSuccess && taskOpenPR && !agentOwnsPR
? await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn })
.catch(err => {
emitLog('warn', `TUI review options unavailable for ${agentId}: ${err.message}`, { agentId });
return {};
})
: {};
- await cleanupWorktreeFn(agentId, finalSuccess, {
+ await cleanupWorktreeFn(agentId, cleanupSuccess, {
openPR: agentOwnsPR ? false : taskOpenPR,
prCompletion: resolvePrCompletion(task.metadata),
...reviewOptions,
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 54278bd25a..88be8a0e90 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -22,7 +22,7 @@ import { execGit } from '../lib/execGit.js';
import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, isHumanClaimWorktree } from './worktreeManager.js';
import { execGh, ensureForgeReachable } from './github.js';
import { getOriginInfo } from '../lib/gitRemote.js';
-import { githubRepoSpec } from '../lib/workTracker.js';
+import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';
@@ -492,20 +492,31 @@ 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}[], 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).
+ * @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}
+ * `forgeUnavailable: true` means the cycle was SKIPPED before it started because
+ * the `gh` probe failed; `prStateUnavailable: true` means it ran but a gh read
+ * failed mid-cycle. Either way an empty `inFlight` says nothing about the repo
+ * and the caller must retry rather than park on it (#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');
+ // Probed against THIS repo's API host (enterprise-correct) — a bare probe
+ // would gate an enterprise checkout on github.com's health. A non-GitHub
+ // origin has no host to probe and falls through to gh's default, which is the
+ // pre-existing behavior for the `new Map()` no-PR-state path below.
+ const origin = await getOriginInfo(repoPath).catch(() => null);
+ const forge = await ensureForgeReachable('branch-reconcile', { hostname: githubApiHost(origin?.host) });
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 });
+ // A gh failure AFTER a passing probe (a blip mid-cycle, or an unparseable
+ // page) is still "we could not ask" — surface it so the caller retries next
+ // tick instead of parking on an in-flight set built from unknown PR state.
+ const prStateUnavailable = inputs.some((i) => i.prStateUnavailable);
const classified = classifyBranches(inputs);
const merged = classified.filter((c) => c.state === 'MERGED');
@@ -521,7 +532,7 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, activeA
? await cleanupMerged(repoPath, defaultBranch, merged, { activeAgentIds })
: { cleaned: [], skipped: merged.map((m) => ({ branch: m.branch, reason: 'cleanup-disabled' })) };
- return { defaultBranch, cleaned, inFlight, wip, skipped };
+ return { defaultBranch, cleaned, inFlight, wip, skipped, prStateUnavailable };
}
// ============================================================
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index d195e296d8..d78c92ee63 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -459,6 +459,40 @@ describe('unreachable forge (#3358)', () => {
expect(classifyBranches(inputs)[0].state).toBe('NEEDS_PR');
});
+ it('surfaces a mid-cycle gh failure as prStateUnavailable so the caller retries instead of parking', 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 res = await reconcile('/repo');
+ // The probe passed, so the cycle ran — but the in-flight set is empty for a
+ // reason that says nothing about the repo, and parking on it would sit out a
+ // full recheck cadence.
+ expect(res.forgeUnavailable).toBeUndefined();
+ expect(res.prStateUnavailable).toBe(true);
+ expect(res.inFlight).toEqual([]);
+ });
+
+ it('leaves prStateUnavailable false on a clean cycle', 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);
+ expect((await reconcile('/repo')).prStateUnavailable).toBe(false);
+ });
+
+ it('probes THIS repo\'s API host so an enterprise checkout is not gated on github.com', async () => {
+ getOriginInfo.mockResolvedValue({ hasOrigin: true, isGithub: false, host: 'github.acme-corp.example', fullName: 'o/r' });
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'not-authenticated', detail: null });
+ await reconcile('/repo');
+ expect(ensureForgeReachableMock).toHaveBeenCalledWith('branch-reconcile', { hostname: 'github.acme-corp.example' });
+ });
+
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');
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index d6ad30bf5d..f745258dde 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -2066,6 +2066,15 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
emitLog('info', `🔀 branch-reconcile skipped for ${app.name}: forge unreachable (gh ${result.forgeStatus || 'error'})`, { appId: app.id, analysisType: taskType });
return { skip: true };
}
+ // A gh read that failed AFTER the probe passed leaves PR state unknown, so
+ // every un-merged branch classified WIP and the actionable set below would be
+ // empty for a reason that has nothing to do with the repo. Retry next tick
+ // rather than parking. Merged branches were still cleaned (git truth), so log
+ // that before bailing.
+ if (result.prStateUnavailable) {
+ emitLog('info', `🔀 branch-reconcile deferred for ${app.name}: PR state unreadable this cycle (cleaned ${result.cleaned.length} merged branch(es))`, { 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 ac91a7c4af..0dacff44b6 100644
--- a/server/services/github.ghHealth.test.js
+++ b/server/services/github.ghHealth.test.js
@@ -254,3 +254,29 @@ describe('findPullRequestForBranch (#3358)', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
});
+
+describe('checkGhHealth host keying (#3358)', () => {
+ beforeEach(() => { __resetGhHealthCache(); spawnMock.mockReset(); });
+
+ it('targets a named host with --hostname', async () => {
+ spawnMock.mockImplementation(() => fakeChild({ code: 0 }));
+ await checkGhHealth({ hostname: 'github.acme-corp.example' });
+ expect(spawnMock).toHaveBeenCalledWith('gh', ['api', 'rate_limit', '--hostname', 'github.acme-corp.example'], expect.any(Object));
+ });
+
+ it('caches per host — a healthy github.com does not vouch for an enterprise host', async () => {
+ spawnMock.mockImplementation((_cmd, args) => fakeChild(
+ args.includes('github.acme-corp.example')
+ ? { code: 1, stderr: 'HTTP 401: Bad credentials' }
+ : { code: 0 }
+ ));
+ await expect(checkGhHealth()).resolves.toMatchObject({ ok: true });
+ await expect(checkGhHealth({ hostname: 'github.acme-corp.example' }))
+ .resolves.toMatchObject({ ok: false, status: 'not-authenticated' });
+ // Both are memoized independently.
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ await checkGhHealth();
+ await checkGhHealth({ hostname: 'github.acme-corp.example' });
+ expect(spawnMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/server/services/github.js b/server/services/github.js
index 6bffa05d68..296be568d9 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -411,14 +411,21 @@ export function ghRemedy(status) {
}
}
-let ghHealthCache = null;
-let ghHealthCheckedAt = 0;
+// Keyed by hostname (`''` = gh's default host). An operator commonly has a
+// working github.com credential and a broken enterprise one (or the reverse), so
+// one process-wide verdict would report the wrong forge's health — the same
+// host-keying prWatcher's self-login cache already needs.
+const ghHealthCache = new Map();
-function probeGh(timeoutMs) {
+function probeGh(timeoutMs, hostname) {
return new Promise((resolve) => {
// `rate_limit` is authenticated, cheap, and — unlike every other endpoint —
// does not itself consume quota, so polling this probe is free.
- const child = spawn('gh', ['api', 'rate_limit'], { shell: false, windowsHide: true });
+ // `--hostname` is required for an enterprise host: without it `gh api`
+ // targets github.com regardless of cwd, so an enterprise repo would be
+ // gated on a host it never talks to.
+ const args = hostname ? ['api', 'rate_limit', '--hostname', hostname] : ['api', 'rate_limit'];
+ const child = spawn('gh', args, { shell: false, windowsHide: true });
let stderr = '';
let settled = false;
const done = (result) => { if (!settled) { settled = true; clearTimeout(timer); resolve(result); } };
@@ -436,31 +443,35 @@ function probeGh(timeoutMs) {
/**
* Probe whether `gh` can actually talk to the forge right now.
*
- * Result is cached for a minute — /api/system/health/details is polled, and the
- * probe spawns a process. Pass `{ force: true }` to bypass the cache.
+ * Result is cached per host for a minute — /api/system/health/details is polled,
+ * and the probe spawns a process. Pass `{ force: true }` to bypass the cache.
*
+ * @param {{ force?: boolean, timeoutMs?: number, hostname?: string|null }} [opts]
+ * `hostname` targets a specific forge host (a GitHub Enterprise install);
+ * omitted means gh's default host.
* @returns {Promise<{ status: string, ok: boolean, detail: string|null, remedy: string|null, checkedAt: string }>}
*/
-export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOUT_MS } = {}) {
+export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOUT_MS, hostname = null } = {}) {
const now = Date.now();
- if (!force && ghHealthCache && (now - ghHealthCheckedAt) < GH_HEALTH_TTL_MS) return ghHealthCache;
+ const key = hostname || '';
+ const cached = ghHealthCache.get(key);
+ if (!force && cached && (now - cached.at) < GH_HEALTH_TTL_MS) return cached.health;
- const { status, detail } = classifyGhProbe(await probeGh(timeoutMs));
- ghHealthCache = {
+ const { status, detail } = classifyGhProbe(await probeGh(timeoutMs, hostname));
+ const health = {
status,
ok: status === 'ok',
detail,
remedy: ghRemedy(status),
checkedAt: new Date(now).toISOString()
};
- ghHealthCheckedAt = now;
- return ghHealthCache;
+ ghHealthCache.set(key, { health, at: now });
+ return health;
}
-/** Test seam — drops the memoized probe result. */
+/** Test seam — drops the memoized probe results. */
export function __resetGhHealthCache() {
- ghHealthCache = null;
- ghHealthCheckedAt = 0;
+ ghHealthCache.clear();
}
/**
@@ -473,15 +484,20 @@ export function __resetGhHealthCache() {
* 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')
+ * @param {{ hostname?: string|null }} [opts] - the forge host this job actually
+ * talks to. Pass it whenever the caller knows the repo's host: a bare probe
+ * hits github.com, so an enterprise job would otherwise be gated on the health
+ * of a host it never contacts (and vice versa).
* @returns {Promise<{ ok: boolean, status: string, detail: string|null, remedy: string|null }>}
*/
-export async function ensureForgeReachable(label) {
- const health = await checkGhHealth().catch(err => ({
+export async function ensureForgeReachable(label, { hostname = null } = {}) {
+ const health = await checkGhHealth({ hostname }).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}`);
+ const where = hostname ? ` on ${hostname}` : '';
+ console.error(`❌ ${label}: skipping this cycle, gh is ${health.status}${where}${detail}`);
return health;
}
diff --git a/server/services/issueReconcile.js b/server/services/issueReconcile.js
index 7e95b04d22..cb4050ea53 100644
--- a/server/services/issueReconcile.js
+++ b/server/services/issueReconcile.js
@@ -55,7 +55,7 @@ import { execGh, ensureForgeReachable } from './github.js';
import { execGlab } from './gitlab.js';
import { fetchMyCurrentSprintTickets } from './jira.js';
import { getOriginInfo, readOriginRemoteUrl } from '../lib/gitRemote.js';
-import { hostToWorkTracker, hostFromOriginUrl, githubRepoSpec } from '../lib/workTracker.js';
+import { hostToWorkTracker, hostFromOriginUrl, githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
// Bound the forge queries (single-user repos never realistically truncate at 200).
@@ -266,10 +266,10 @@ function normalizeGithubIssue(issue) {
* @param {string} fullName - plain `OWNER/REPO`, returned for display/logging
* @returns {Promise<{forge:'github', fullName:string, inProgress:object[], mergedPrs:object[], openPrs:object[]}|null>}
*/
-async function getGithubState(repoSpec, fullName) {
+async function getGithubState(repoSpec, fullName, apiHost = null) {
// 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');
+ const forge = await ensureForgeReachable('issue-reconcile', { hostname: apiHost });
if (!forge.ok) return null;
const ghList = (args, what) => execGh(args).catch((err) => {
@@ -422,7 +422,7 @@ async function getForgeState(repoPath) {
// `HOST/OWNER/REPO` --repo selector (deterministic on fork+upstream checkouts),
// or null when the origin isn't a resolvable GitHub repo.
const githubSpec = githubRepoSpec(origin);
- if (githubSpec) return getGithubState(githubSpec, origin.fullName);
+ if (githubSpec) return getGithubState(githubSpec, origin.fullName, githubApiHost(origin.host));
// GitLab: classify off the host (subgroup-safe). `glab` is cwd-based, so a
// display path is best-effort — prefer getOriginInfo's fullName, else derive the
diff --git a/server/services/issueReconcile.test.js b/server/services/issueReconcile.test.js
index 0fdbbf419d..55e5ecc2a4 100644
--- a/server/services/issueReconcile.test.js
+++ b/server/services/issueReconcile.test.js
@@ -37,6 +37,7 @@ vi.mock('../lib/workTracker.js', async (importActual) => {
hostToWorkTracker: actual.hostToWorkTracker,
hostFromOriginUrl: actual.hostFromOriginUrl,
githubRepoSpec: actual.githubRepoSpec,
+ githubApiHost: actual.githubApiHost,
};
});
vi.mock('../lib/fileUtils.js', () => ({
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index c71e7a72ac..cf925e0545 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -306,14 +306,14 @@ 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' };
+ // Skip rather than poll every pending PR into an `errors` count we can't act on.
+ const forge = await ensureForgeReachable('pr-watcher pending-merge', { hostname: githubApiHost(origin.host) });
+ if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status };
+
const outcomes = new Map();
const result = { ok: true, checked: 0, merged: 0, escalated: 0, timedOut: 0, errors: 0 };
@@ -410,12 +410,6 @@ 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
@@ -429,6 +423,14 @@ export async function checkPullRequests(app, { authorFilter = 'any' } = {}) {
}
const repoFullName = origin.fullName;
+ // Probe before any gh read (#3358). Without this an unreachable gh returns an
+ // empty PR page, the high-water mark stays put, and the watcher reports a
+ // quiet repo forever with nothing in the log naming the real cause. Probed
+ // against THIS repo's API host, not gh's default — an enterprise app must not
+ // be gated on github.com's health (and vice versa).
+ const forge = await ensureForgeReachable('pr-watcher', { hostname: githubApiHost(origin.host) });
+ if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status, repoFullName };
+
const defaultBranch = await getDefaultBranch(repoSpec);
if (!defaultBranch) {
return { ok: false, reason: 'default-branch-unresolved', repoFullName };
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index 89e0f4fa39..9d53cea4a2 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -330,12 +330,20 @@ describe('checkPullRequests', () => {
// 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 () => {
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
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(r).toMatchObject({ ok: false, reason: 'forge-unreachable', forgeStatus: 'unreachable' });
expect(execGhMock).not.toHaveBeenCalled();
});
+ it('probes THIS repo\'s API host, not gh\'s default (enterprise-correct)', async () => {
+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: false, host: 'github.acme-corp.example', fullName: 'o/r' });
+ ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'not-authenticated', detail: null });
+ await checkPullRequests(app, { authorFilter: 'any' });
+ expect(ensureForgeReachableMock).toHaveBeenCalledWith('pr-watcher', { hostname: 'github.acme-corp.example' });
+ });
+
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