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: poll branch-reconcile and pr-watcher with each repo's own gh credential (#7540)

[._.]/ Adam Eivy58bf5cc30a51
diff --git a/server/lib/README.md b/server/lib/README.md
index ebd9543182..39d38c6410 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -365,6 +365,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `execGit.js` | `execGit(args, cwd, options)` and `execGitSafe(args, cwd, options)` shared process boundary for Git operations, worktrees, and `services/forgeAuth.js` credential resolution. The safe variant converts rejections into `{ exitCode: 1, stdout: '', stderr }`; `services/git.js` re-exports both for compatibility. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. `installEncodedVideo(tmpPath, targetPath, label)` is the shared in-place install: move the original aside to a `.bak` on Windows (where `fs.rename` refuses an existing destination), rename the new file over it, and restore the backup — plus unlink the temp — on any failure, returning `{ok:true,outPath}` / `{ok:false,reason}` so the worst case is "skipped", never "the video is gone". Use it for EVERY replace-a-video-with-its-re-encode path; `pipeline/audioMux.js` is the out-of-module caller. |
+| `forgeAccessErrors.js` | `isForgeNoAccessError(err)` / `isForgeNoAccessMessage(text)` / `logForgeNoAccessOnce(scope, repoSpec, detail)` / `forgeNoAccessRemedy(repoSpec)` — tells a PERMANENT `gh` no-access 404 (`Could not resolve to a Repository`, `HTTP 404`) apart from a transient blip. `execGh` stamps `ghNoAccess` on the rejection and keeps it OUT of the consecutive-failure backoff (which caps at 15 min and then re-fires forever), and the polling jobs (`branchReconcile`, `prWatcher`) narrate it exactly once per scope+repo per process with a remedy line instead of once per tick. `__resetForgeNoAccessLog()` is the test seam. |
| `forkHead.js` | `normalizeForkHead(value)` / `forkRemoteName(ownerLogin)` / `resolveTaskForkHead(metadata)` — the validated `{remoteUrl, ownerLogin}` address of a cross-repository PR's head branch, which has no `origin/<branch>` to attach to. Fail-closed: anything that isn't a usable pair (or that starts with `-`, which git would read as an option) is `null`, so every caller falls back to origin-only behavior instead of guessing. `forkRemoteName` is the deterministic `fork-<owner>` remote name that makes a re-attach reuse the remote it already added. Shared by `appPullRequests.js` (produces), `agentWorktreeCleanup.js`/`prRemediationFollowUp.js` (persist in task metadata), `agentWorkspacePrep.js` (threads), and `worktreeManager.js` (consumes — it has no forge client of its own). `resolveTaskForkHead` is the single reader of the generic `forkHead` task-metadata key, the fork-side counterpart to `taskTargetBranch.js`. |
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
diff --git a/server/lib/forgeAccessErrors.js b/server/lib/forgeAccessErrors.js
new file mode 100644
index 0000000000..4c16081aa2
--- /dev/null
+++ b/server/lib/forgeAccessErrors.js
@@ -0,0 +1,86 @@
+/**
+ * Tell a PERMANENT `gh` no-access failure apart from a transient one, and log it
+ * at most once per scope+repo.
+ *
+ * `Could not resolve to a Repository` is GitHub's 404-for-no-access: the repo
+ * exists, the credential in use cannot see it. That does not heal on its own the
+ * way a network blip or a rate limit does — it stays broken until the credential
+ * changes — so it must NOT ride `execGh`'s consecutive-failure backoff (which
+ * caps at 15 minutes and then re-fires and re-logs forever), and the polling
+ * jobs must not narrate it once per tick.
+ *
+ * Pure except for the process-lifetime de-dup set behind `logForgeNoAccessOnce`.
+ * Once per process (rather than a re-log window) is deliberate: the remedy is a
+ * credential change, which on this install means a `gh auth login` or an edit to
+ * the app record — both user actions that carry their own feedback.
+ */
+
+// `gh pr list` / `gh repo view` answer a no-access repo through GraphQL, which
+// reports it as an unresolvable node rather than an HTTP status; `gh api` and
+// the REST-backed subcommands answer with the status line instead. Match both,
+// plus gh's bare `Not Found` phrasing for a resource the token cannot read.
+const NO_ACCESS_PATTERNS = [
+ /could not resolve to a (?:repository|pullrequest|issue|user|organization)/i,
+ /\bHTTP 404\b/i,
+ /^gh: not found\b/im,
+];
+
+/**
+ * True when `text` is `gh` stderr describing a no-access/404, not a transient
+ * failure.
+ * @param {string|null|undefined} text
+ * @returns {boolean}
+ */
+export function isForgeNoAccessMessage(text) {
+ if (typeof text !== 'string' || !text.trim()) return false;
+ return NO_ACCESS_PATTERNS.some((pattern) => pattern.test(text));
+}
+
+/**
+ * True when an `execGh` rejection is a no-access/404. Prefers the `ghNoAccess`
+ * flag `execGh` stamps on, and falls back to re-reading the stderr/message for a
+ * caller that received the error through a wrapper that dropped the flag.
+ * @param {unknown} err
+ * @returns {boolean}
+ */
+export function isForgeNoAccessError(err) {
+ if (!err || typeof err !== 'object') return false;
+ if (err.ghNoAccess === true) return true;
+ return isForgeNoAccessMessage(err.ghStderr) || isForgeNoAccessMessage(err.message);
+}
+
+/**
+ * The one actionable line a no-access repo gets. Names the fix rather than the
+ * symptom: an owner-match against a locally logged-in account already covers the
+ * common multi-account case, so what is left to say is "pin the account".
+ * @param {string} repoSpec
+ * @returns {string}
+ */
+export function forgeNoAccessRemedy(repoSpec) {
+ return `${repoSpec} is not visible to the gh account PortOS resolved for it — `
+ + 'log in to the owning account (`gh auth login`) or pin it on the app record\'s Forge account field';
+}
+
+const loggedNoAccess = new Set();
+
+/**
+ * Log a no-access failure ONCE per scope+repo for this process. Returns true
+ * when it logged, so a caller can branch on "first time seen".
+ * @param {string} scope - The polling job's log prefix, e.g. `branch-reconcile`
+ * @param {string} repoSpec
+ * @param {string} [detail] - gh's own message, appended when present
+ * @returns {boolean}
+ */
+export function logForgeNoAccessOnce(scope, repoSpec, detail = '') {
+ const key = `${scope} :: ${repoSpec}`;
+ if (loggedNoAccess.has(key)) return false;
+ loggedNoAccess.add(key);
+ const because = detail ? ` (${String(detail).split('\n')[0].slice(0, 160)})` : '';
+ console.error(`❌ ${scope}: ${forgeNoAccessRemedy(repoSpec)}${because}`);
+ return true;
+}
+
+/** Test seam — drops the once-per-process de-dup set between runs. */
+export function __resetForgeNoAccessLog() {
+ loggedNoAccess.clear();
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index 1cdae23086..93410fd5e5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -347,6 +347,7 @@ export * from './setupScriptRunner.js';
export * from './hostShutdown.js';
export * from './execGit.js';
export * from './ffmpeg.js';
+export * from './forgeAccessErrors.js';
export * from './forkHead.js';
export * from './ffmpegRenderGuard.js';
export * from './frameQuality.js';
diff --git a/server/services/appIssues.js b/server/services/appIssues.js
index 1c1c90b381..a4cb3d2d3c 100644
--- a/server/services/appIssues.js
+++ b/server/services/appIssues.js
@@ -25,7 +25,7 @@
import { execGh, ensureForgeReachable } from './github.js';
import { execGlab, execGlabJson } from './gitlab.js';
-import { resolveForgeForRepo } from './forgeAuth.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
import { resolveAppForgeTarget } from '../lib/workTracker.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { CONTRIBUTOR_LABELS } from '../lib/dispatchLabels.js';
@@ -156,12 +156,7 @@ function toIssueResult(rows, normalize) {
* unreachable `gh` returns an empty page that reads as "no open issues".
*/
async function fetchGithubIssues(repoSpec, apiHost, { repoPath = null, forgeAccount = null } = {}) {
- const forgeAuth = repoPath
- ? await resolveForgeForRepo(repoPath, { forgeAccount }).catch(() => null)
- : null;
- const customEnv = forgeAuth?.env && forgeAuth.env !== process.env ? forgeAuth.env : null;
- const env = customEnv || process.env;
- const cwd = repoPath || undefined;
+ const { cwd, env, customEnv } = await resolveForgeExecOptions(repoPath, { forgeAccount });
const forge = await ensureForgeReachable('app-issues', {
hostname: apiHost,
@@ -293,11 +288,10 @@ export async function prepareAppIssueClaim(app, issueNumber, tracker) {
if (!target || resolvedTracker !== tracker || target.forge !== tracker) {
throw new ServerError('Could not resolve the issue tracker for this claim', { status: 400, code: 'CLAIM_TRACKER_MISMATCH' });
}
- const forgeAuth = (tracker === 'github' && app?.repoPath)
- ? await resolveForgeForRepo(app.repoPath, { forgeAccount: app.forgeAccount }).catch(() => null)
- : null;
- const env = forgeAuth?.env || process.env;
- const cwd = app?.repoPath || undefined;
+ const { cwd, env } = await resolveForgeExecOptions(
+ tracker === 'github' ? app?.repoPath : null,
+ { forgeAccount: app?.forgeAccount }
+ );
const readLabels = async () => {
const raw = tracker === 'github'
diff --git a/server/services/appPullRequests.js b/server/services/appPullRequests.js
index 590e03e762..4060047c27 100644
--- a/server/services/appPullRequests.js
+++ b/server/services/appPullRequests.js
@@ -12,7 +12,7 @@
import { execGh, ensureForgeReachable } from './github.js';
import { execGlabJson } from './gitlab.js';
-import { resolveForgeForRepo } from './forgeAuth.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
import { resolveAppForgeTarget } from '../lib/workTracker.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { forkHeadFromGithubPr } from '../lib/forkHead.js';
@@ -153,12 +153,7 @@ function answeredResult(rows, normalize) {
}
async function fetchGithubPullRequests(repoSpec, apiHost, { repoPath = null, forgeAccount = null } = {}) {
- const forgeAuth = repoPath
- ? await resolveForgeForRepo(repoPath, { forgeAccount }).catch(() => null)
- : null;
- const customEnv = forgeAuth?.env && forgeAuth.env !== process.env ? forgeAuth.env : null;
- const env = customEnv || process.env;
- const cwd = repoPath || undefined;
+ const { cwd, env, customEnv } = await resolveForgeExecOptions(repoPath, { forgeAccount });
const forge = await ensureForgeReachable('app-pull-requests', {
hostname: apiHost,
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 36e41385e7..a567252ac8 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -29,6 +29,8 @@ import { execGit } from '../lib/execGit.js';
import { listWorktrees, forceRemoveWorktreeDir, classifyWorktreeDirt, reapMergedWorktrees } from './worktreeManager.js';
import { isAgentWorktreeId, worktreeOwnershipReason, worktreeHoldExpiresAt } from '../lib/worktreeOwnership.js';
import { execGh, ensureForgeReachable, getIssueDispatchHint } from './github.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
+import { isForgeNoAccessError, logForgeNoAccessOnce } from '../lib/forgeAccessErrors.js';
import { issueNumberFromRef } from './issueReconcile.js';
import { getOriginInfo } from '../lib/gitRemote.js';
import { githubRepoSpec, githubApiHost } from '../lib/workTracker.js';
@@ -227,9 +229,15 @@ export function classifyBranches(inputs) {
* @param {object|null} [providedOrigin] - `getOriginInfo`'s answer when the caller
* already resolved it (gatherBranchState needs the same record for `hasOrigin`);
* omitted, this reads it itself so a standalone call still works.
+ * @param {object} [opts]
+ * @param {{cwd?:string, env?:object}|null} [opts.forgeExec] - The per-repo gh
+ * credential overlay `reconcile` already resolved; omitted, this resolves it
+ * itself so a standalone call still authenticates correctly.
+ * @param {string|null} [opts.forgeAccount] - The app record's explicit gh pin,
+ * used only when `forgeExec` was not supplied.
* @returns {Promise<Map<string, {number:number, mergeable:string, isDraft:boolean, url:string}>|null>}
*/
-async function getOpenPrsByHead(repoPath, providedOrigin) {
+async function getOpenPrsByHead(repoPath, providedOrigin, { forgeExec = null, forgeAccount = null } = {}) {
const origin = providedOrigin === undefined
? await getOriginInfo(repoPath).catch(() => null)
: providedOrigin;
@@ -239,17 +247,27 @@ async function getOpenPrsByHead(repoPath, providedOrigin) {
// the host-qualified `HOST/OWNER/REPO` selector (null for a non-GitHub origin).
const repoSpec = githubRepoSpec(origin);
if (!repoSpec) return new Map();
+ // Run gh with the credential THIS repo needs, not gh's ambient active login
+ // (#7540) — an app whose repo belongs to another GitHub account otherwise 404s
+ // on every tick forever. Mirrors appPullRequests.fetchGithubPullRequests.
+ const { cwd, env } = forgeExec || await resolveForgeExecOptions(repoPath, { forgeAccount });
// `backoffKey: repoSpec` opts this polling read into execGh's consecutive-
// failure backoff — this call is retried on every scheduler tick with no
// parking cooldown (resolveBranchReconcileBlock treats `prStateUnavailable`
// as transient), so a `gh` blip must not turn into every managed repo
- // re-firing this same expensive call on its very next tick.
+ // re-firing this same expensive call on its very next tick. A no-access 404 is
+ // deliberately exempted inside execGh: it is permanent, so backing off on it
+ // would park the shared key for every other caller of this repo.
const raw = await execGh([
'pr', 'list', '--repo', repoSpec, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,headRefName,mergeable,isDraft,url'
- ], undefined, { backoffKey: repoSpec }).catch((err) => {
- if (!isHostShuttingDown() && err.name !== 'AbortError') {
+ ], undefined, { cwd, env, backoffKey: repoSpec }).catch((err) => {
+ if (isForgeNoAccessError(err)) {
+ // Permanent until credentials change — one actionable line naming the
+ // remedy, not one per scheduler tick.
+ logForgeNoAccessOnce('branch-reconcile', repoSpec, err.message);
+ } else if (!isHostShuttingDown() && err.name !== 'AbortError') {
console.error(`❌ branch-reconcile: gh pr list failed for ${repoSpec}: ${err.message}`);
}
return null;
@@ -709,11 +727,14 @@ async function worktreeAgeMs(worktreePath) {
* `hasOrigin` is `getOriginInfo`'s verdict when the caller already has it (same
* rationale); omitted, this reads it itself, so a standalone caller still gets a
* truthful answer rather than the fail-closed default.
+ * `forgeExec` is the per-repo gh credential overlay (`{cwd, env}`) when the
+ * caller already resolved it; `forgeAccount` is the app record's explicit gh
+ * pin for the standalone case. Both feed `getOpenPrsByHead` — see #7540.
* @returns {Promise<object[]>} one entry per candidate branch:
* { branch, tip, hasUpstream, hasOrigin, tracking, upstreamGone, isMerged, hasWorktree, worktreePath,
* worktreeDirty, dirtyPaths, behind, ahead, collisionPaths, abandonedAgentWorktree, openPr }
*/
-export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, remoteHeads: providedRemoteHeads, hasOrigin: providedHasOrigin, origin: providedOrigin } = {}) {
+export async function gatherBranchState(repoPath, { defaultBranch, activeAgentIds = null, remoteHeads: providedRemoteHeads, hasOrigin: providedHasOrigin, origin: providedOrigin, forgeExec = null, forgeAccount = null } = {}) {
const protectedSet = new Set([...PROTECTED_BRANCHES, defaultBranch]);
// Read origin ONCE and use it for both facts below — `hasOrigin` (the gate on
// classifyBranch's ahead-based NEEDS_PR arm, so an origin-less repo's local work
@@ -739,7 +760,7 @@ export async function gatherBranchState(repoPath, { defaultBranch, activeAgentId
const [branches, worktrees, prsByHeadOrNull, remoteHeads] = await Promise.all([
getBranches(repoPath),
listWorktrees(repoPath).catch(() => []),
- getOpenPrsByHead(repoPath, origin),
+ getOpenPrsByHead(repoPath, origin, { forgeExec, forgeAccount }),
providedRemoteHeads !== undefined ? providedRemoteHeads
: hasOrigin ? listRemoteHeads(repoPath)
: null
@@ -1081,7 +1102,10 @@ async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClai
* explicitly. `reapRemotes` (default false) additionally deletes merged
* branches left on `origin` that nothing local points at; off, they are only
* reported — see `reapOrphanedRemotes`. `activeAgentIds` protects in-use CoS
- * agent worktrees.
+ * agent worktrees. `forgeAccount` is the managed app record's explicit gh
+ * account pin, so an app whose repo belongs to another GitHub account is
+ * polled with a credential that can actually see it (#7540); unset, the
+ * owner-match in `forgeAuth.resolveForgeForRepo` still applies.
* @returns {Promise<{ defaultBranch:string, cleaned:string[], inFlight:object[], wip:object[], skipped:{branch:string,reason:string}[], orphanRemotes:{reaped:string[],reported:object[]}, forgeUnavailable?:boolean, prStateUnavailable?:boolean }>}
* A `wip` entry with a `liveOwnerReason` is held because a live agent/claim/lock
* owns it — the "leave it alone, this reconcile IS done" case. `superseded` holds
@@ -1093,7 +1117,7 @@ async function retireBranch(repoPath, b, { activeAgentIds = new Set(), staleClai
* 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, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set() } = {}) {
+export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSuperseded = cleanup, reapRemotes = false, activeAgentIds = new Set(), forgeAccount = null } = {}) {
// Worktree cleanup is the first reconcile step, before any forge probe. It
// only removes a tree after proving both that it is completely clean and
// that every branch commit is already in the default branch (including
@@ -1117,8 +1141,17 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSup
// and gating it on a `gh` probe that will never pass would permanently block
// the git-only merged-branch cleanup those repos still benefit from.
const origin = await getOriginInfo(repoPath).catch(() => null);
- if (githubRepoSpec(origin)) {
- const forge = await ensureForgeReachable('branch-reconcile', { hostname: githubApiHost(origin.host) });
+ // Resolve the per-repo gh credential ONCE per cycle and reuse it for the
+ // reachability probe and the PR read — a second resolve would re-run the same
+ // bounded git+gh probes for an answer that cannot have changed mid-cycle.
+ const forgeExec = githubRepoSpec(origin)
+ ? await resolveForgeExecOptions(repoPath, { forgeAccount })
+ : null;
+ if (forgeExec) {
+ const forge = await ensureForgeReachable('branch-reconcile', {
+ hostname: githubApiHost(origin.host),
+ ...(forgeExec?.customEnv ? { env: forgeExec.customEnv } : {}),
+ });
if (!forge.ok) {
return { defaultBranch: null, cleaned: cleanedWorktrees, inFlight: [], wip: [], skipped: [], forgeUnavailable: true, forgeStatus: forge.status };
}
@@ -1137,7 +1170,8 @@ export async function reconcile(repoPath = PATHS.root, { cleanup = true, reapSup
// per cycle is the cost of each destructive step reading the remote itself.
const remoteHeads = origin?.hasOrigin ? await listRemoteHeads(repoPath) : null;
const inputs = await gatherBranchState(repoPath, {
- defaultBranch, activeAgentIds, remoteHeads, hasOrigin: Boolean(origin?.hasOrigin), origin
+ defaultBranch, activeAgentIds, remoteHeads, hasOrigin: Boolean(origin?.hasOrigin), origin,
+ forgeExec, forgeAccount
});
// 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
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 9ab8797015..7bfdbe969d 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -55,6 +55,17 @@ vi.mock('./github.js', () => ({
ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),
getIssueDispatchHint: (...args) => getIssueDispatchHintMock(...args),
}));
+// The per-repo gh credential overlay (#7540). Mocked rather than real so the
+// suite asserts what execGh RECEIVED without spawning git/gh probes.
+const PINNED_ENV = { GH_TOKEN: 'token-for-other-account' };
+const resolveForgeExecOptionsMock = vi.fn(async (repoPath) => ({
+ cwd: repoPath || undefined,
+ env: PINNED_ENV,
+ customEnv: PINNED_ENV,
+}));
+vi.mock('./forgeExecOptions.js', () => ({
+ resolveForgeExecOptions: (...args) => resolveForgeExecOptionsMock(...args),
+}));
vi.mock('../lib/gitRemote.js', () => ({
getOriginInfo: vi.fn(async () => ({
hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'
@@ -102,6 +113,7 @@ import { execGit } from '../lib/execGit.js';
import { execGh } from './github.js';
import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';
import { getOriginInfo } from '../lib/gitRemote.js';
+import { __resetForgeNoAccessLog } from '../lib/forgeAccessErrors.js';
beforeEach(() => {
vi.clearAllMocks();
@@ -111,6 +123,10 @@ beforeEach(() => {
// clearAllMocks keeps implementations, so restore the default GitHub origin —
// a case that swaps in a GitLab/origin-less remote would otherwise leak into
// every test after it.
+ // mockReset, not just the clearAllMocks above: a case that queued an unused
+ // mockResolvedValueOnce/mockRejectedValueOnce leaves it at the head of the
+ // queue, where it outranks this default and leaks into the NEXT test.
+ getOriginInfo.mockReset();
getOriginInfo.mockResolvedValue({
hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'atomantic/PortOS'
});
@@ -812,6 +828,54 @@ describe('unreachable forge (#3358)', () => {
expect(getOriginInfo).toHaveBeenCalledOnce();
});
+ it('runs `gh pr list` with the per-repo credential, honouring the app\'s forgeAccount pin', async () => {
+ // #7540: without this the poll used gh's ambient active login and 404'd
+ // forever on a private repo owned by another GitHub account.
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ git.hasBranchMergeEvidence.mockResolvedValue(false);
+ execGh.mockResolvedValue('[]');
+
+ await reconcile('/repo', { forgeAccount: 'other-account' });
+
+ expect(resolveForgeExecOptionsMock).toHaveBeenCalledWith('/repo', { forgeAccount: 'other-account' });
+ const [, , options] = execGh.mock.calls.find(([callArgs]) => callArgs[0] === 'pr' && callArgs[1] === 'list');
+ expect(options).toMatchObject({ cwd: '/repo', env: PINNED_ENV });
+ // One resolve per cycle, shared by the reachability probe and the PR read.
+ expect(resolveForgeExecOptionsMock).toHaveBeenCalledOnce();
+ });
+
+ it('logs a no-access 404 ONCE per repo instead of once per cycle', async () => {
+ // #7540: `Could not resolve to a Repository` is permanent until credentials
+ // change, so re-narrating it every scheduler tick is pure noise.
+ __resetForgeNoAccessLog();
+ git.getBranches.mockResolvedValue([
+ { name: 'claim/issue-1', isDefault: false, current: false, tracking: 'origin/claim/issue-1', merged: false }
+ ]);
+ wt.listWorktrees.mockResolvedValue([]);
+ git.hasBranchMergeEvidence.mockResolvedValue(false);
+ const noAccess = Object.assign(new Error("GraphQL: Could not resolve to a Repository with the name 'o/r'. (repository)"), {
+ ghExitCode: 1, ghNoAccess: true,
+ });
+ execGh.mockRejectedValue(noAccess);
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const first = await reconcile('/repo');
+ const second = await reconcile('/repo');
+
+ // The cycle is still reported unreadable both times — only the LOG is deduped.
+ expect(first.prStateUnavailable).toBe(true);
+ expect(second.prStateUnavailable).toBe(true);
+ const noAccessLines = errors.mock.calls
+ .map(([line]) => String(line))
+ .filter((line) => line.includes('not visible to the gh account'));
+ expect(noAccessLines).toHaveLength(1);
+ expect(noAccessLines[0]).toContain('Forge account');
+ errors.mockRestore();
+ });
+
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 }
@@ -826,7 +890,10 @@ describe('unreachable forge (#3358)', () => {
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' });
+ expect(ensureForgeReachableMock).toHaveBeenCalledWith('branch-reconcile', {
+ hostname: 'github.acme-corp.example',
+ env: PINNED_ENV,
+ });
});
it('does not gate a non-GitHub repo on the gh probe — it has no gh PR state to lose', async () => {
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index c4c8898016..c3eae2abb3 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -397,7 +397,10 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
};
const result = await reconcile(app.repoPath, {
cleanup: actions.cleanupMerged !== false,
- activeAgentIds: new Set(getActiveAgentIds())
+ activeAgentIds: new Set(getActiveAgentIds()),
+ // The app's gh account pin, so a repo owned by another GitHub account is
+ // polled with a credential that can see it (#7540).
+ forgeAccount: app.forgeAccount || null
}).catch((err) => {
emitLog('warn', `branch-reconcile pre-step failed for ${app.name}: ${err.message}`, { appId: app.id });
return null;
diff --git a/server/services/forgeExecOptions.js b/server/services/forgeExecOptions.js
new file mode 100644
index 0000000000..eb82fc9e52
--- /dev/null
+++ b/server/services/forgeExecOptions.js
@@ -0,0 +1,42 @@
+/**
+ * One concern: turn a managed app's repo path (+ optional gh account pin) into
+ * the `{ cwd, env }` a `gh` invocation needs to authenticate as the account
+ * that repo actually belongs to.
+ *
+ * Separate from `forgeAuth.js` (which it composes over) on purpose: the suites
+ * that exercise the polling jobs mock `forgeAuth.js` wholesale, so a helper
+ * living INSIDE it could only be tested against a re-implementation of itself.
+ * Here, a suite mocks whichever of the two layers it is not exercising.
+ */
+import { resolveForgeForRepo } from './forgeAuth.js';
+
+/**
+ * The `{ cwd, env }` overlay for running `gh` against `repoPath` as the account
+ * that repo actually needs, rather than whichever login gh's mutable `hosts.yml`
+ * currently calls active.
+ *
+ * This is the shape every polling job that reads a MANAGED APP's repo must use.
+ * Without it, an app whose repo lives under a different GitHub account than the
+ * ambient login permanently 404s on a private repo (`Could not resolve to a
+ * Repository` is GitHub's no-access 404), once per scheduler tick, forever —
+ * #7540. It bites even with no `forgeAccount` pinned, because
+ * `resolveForgeForRepo` already owner-matches against the locally logged-in
+ * accounts; the explicit pin then covers the rest.
+ *
+ * Never throws: an unresolvable repo degrades to the ambient env, which is
+ * exactly the behavior every caller had before threading this through.
+ * `customEnv` is null when nothing was overlaid, so a caller can pass the
+ * overlay to `ensureForgeReachable` only when there is one.
+ *
+ * @param {string|null} repoPath - Repo (or worktree) root; null/absent = ambient
+ * @param {object} [opts]
+ * @param {string|null} [opts.forgeAccount] - The app record's explicit pin
+ * @returns {Promise<{cwd: string|undefined, env: object, customEnv: object|null}>}
+ */
+export async function resolveForgeExecOptions(repoPath, { forgeAccount = null } = {}) {
+ const forgeAuth = repoPath
+ ? await resolveForgeForRepo(repoPath, { forgeAccount }).catch(() => null)
+ : null;
+ const customEnv = forgeAuth?.env && forgeAuth.env !== process.env ? forgeAuth.env : null;
+ return { cwd: repoPath || undefined, env: customEnv || process.env, customEnv };
+}
diff --git a/server/services/github.js b/server/services/github.js
index af55c4e113..39f0004b63 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -7,6 +7,7 @@ import { ServerError } from '../lib/errorHandler.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createMutex } from '../lib/asyncMutex.js';
import { dispatchHintFromLabels } from '../lib/dispatchLabels.js';
+import { isForgeNoAccessMessage } from '../lib/forgeAccessErrors.js';
const DATA_DIR = PATHS.data;
const REPOS_FILE = join(DATA_DIR, 'github-repos.json');
@@ -171,10 +172,18 @@ export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = nul
name: 'AbortError', signal, terminated: Boolean(signal)
}));
} else if (code !== 0) {
- settle(false);
- const error = new Error(stderr.trim() || `gh exited with ${signal ? `signal ${signal}` : `code ${code}`}`);
+ const detail = stderr.trim();
+ // A no-access 404 is PERMANENT until credentials change, so it must not
+ // feed the consecutive-failure backoff: that would park the shared
+ // `repoSpec` key for every other caller over a condition retrying can
+ // never clear. `settle(null)` preserves whatever backoff a genuinely
+ // transient failure already recorded. See lib/forgeAccessErrors.js.
+ const noAccess = isForgeNoAccessMessage(detail);
+ settle(noAccess ? null : false);
+ const error = new Error(detail || `gh exited with ${signal ? `signal ${signal}` : `code ${code}`}`);
error.ghExitCode = code;
- error.ghStderr = stderr.trim();
+ error.ghStderr = detail;
+ if (noAccess) error.ghNoAccess = true;
reject(error);
} else {
settle(true);
diff --git a/server/services/github.test.js b/server/services/github.test.js
index 4671ebf975..65bbf47856 100644
--- a/server/services/github.test.js
+++ b/server/services/github.test.js
@@ -192,6 +192,46 @@ describe('execGh backoffKey', () => {
expect(spawn).toHaveBeenCalledTimes(1); // second call never spawned a child
});
+ it('exempts a no-access 404 from the backoff and flags it ghNoAccess', async () => {
+ // #7540: `Could not resolve to a Repository` is GitHub's 404-for-no-access —
+ // permanent until credentials change, so parking the SHARED repoSpec key on
+ // it would starve every other caller of that repo over a condition retrying
+ // can never clear. The caller de-dups the LOG instead.
+ const failing = makeChild();
+ spawn.mockReturnValue(failing);
+ const first = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ first.catch(() => {});
+ failing.stderr.emit('data', Buffer.from(
+ "GraphQL: Could not resolve to a Repository with the name 'o/r'. (repository)"
+ ));
+ failing.emit('close', 1);
+ await expect(first).rejects.toMatchObject({ ghNoAccess: true, ghExitCode: 1 });
+
+ // The very next call still SPAWNS — no cooldown was armed.
+ const second = execGh(['pr', 'list'], 5000, { backoffKey: 'github.com/o/r' });
+ second.catch(() => {});
+ failing.emit('close', 1);
+ // A real second attempt (gh's own exit), never the backoff short-circuit.
+ await expect(second).rejects.toThrow(/exited with code 1/);
+ expect(spawn).toHaveBeenCalledTimes(2);
+ });
+
+ it('leaves an existing cooldown intact when a no-access failure follows a transient one', async () => {
+ // `settle(null)` preserves prior backoff rather than clearing it: a repo that
+ // blipped and then answered 404 must still serve out the transient cooldown.
+ const blip = makeChild();
+ spawn.mockReturnValueOnce(blip);
+ const first = execGh(['pr', 'list'], 5000, { backoffKey: 'mixed-repo' });
+ first.catch(() => {});
+ blip.stderr.emit('data', Buffer.from('connect: connection reset'));
+ blip.emit('close', 1);
+ await expect(first).rejects.toThrow(/connection reset/);
+
+ await expect(execGh(['pr', 'list'], 5000, { backoffKey: 'mixed-repo' }))
+ .rejects.toThrow(/backing off/);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
it('records a child error only once when close follows it', async () => {
const failing = makeChild();
spawn.mockReturnValueOnce(failing);
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 03d95077e9..0305d9e91a 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -11,6 +11,8 @@
*/
import { execGh, ensureForgeReachable } from './github.js';
+import { resolveForgeExecOptions } from './forgeExecOptions.js';
+import { isForgeNoAccessError, logForgeNoAccessOnce } from '../lib/forgeAccessErrors.js';
import { getAppById, updateApp, getActiveApps } from './apps.js';
import * as git from './git.js';
import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
@@ -98,16 +100,23 @@ export function __resetSelfLoginCache() {
* `HOST/OWNER/REPO` selector (see checkPullRequests) — pinning the host makes
* this work on GitHub Enterprise (a bare `OWNER/REPO` defaults to github.com)
* while staying deterministic on a multi-remote (fork + upstream) checkout that
- * cwd-based auto-detection would resolve ambiguously. Returns null on failure.
+ * cwd-based auto-detection would resolve ambiguously. `forgeExec` is the
+ * per-repo gh credential overlay (`{cwd, env}`) — without it this runs as gh's
+ * ambient active login and permanently 404s on a private repo owned by another
+ * account (#7540). Returns null on failure.
*/
-async function getDefaultBranch(repoSpec) {
+async function getDefaultBranch(repoSpec, { cwd, env } = {}) {
const name = await execGh(
['repo', 'view', repoSpec, '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name'],
undefined,
- { backoffKey: repoSpec }
+ { cwd, env, backoffKey: repoSpec }
)
.catch((err) => {
- console.error(`❌ pr-watcher: could not resolve the default branch for ${repoSpec}: ${err.message}`);
+ if (isForgeNoAccessError(err)) {
+ logForgeNoAccessOnce('pr-watcher', repoSpec, err.message);
+ } else {
+ console.error(`❌ pr-watcher: could not resolve the default branch for ${repoSpec}: ${err.message}`);
+ }
return null;
});
return name ? name.trim() : null;
@@ -119,14 +128,18 @@ async function getDefaultBranch(repoSpec) {
* and fork-safe — see getDefaultBranch. Returns an array of normalized PR
* objects, or null on failure.
*/
-async function listOpenPullRequests(repoSpec, baseBranch) {
+async function listOpenPullRequests(repoSpec, baseBranch, { cwd, env } = {}) {
const raw = await execGh([
'pr', 'list', '--repo', repoSpec,
'--base', baseBranch, '--state', 'open',
'--limit', String(PR_LIST_LIMIT),
'--json', 'number,title,author,url,createdAt,updatedAt,isDraft,headRefName,headRefOid,mergeStateStatus,statusCheckRollup'
- ], undefined, { backoffKey: repoSpec }).catch((err) => {
- console.error(`❌ pr-watcher: gh pr list failed for ${repoSpec}: ${err.message}`);
+ ], undefined, { cwd, env, backoffKey: repoSpec }).catch((err) => {
+ if (isForgeNoAccessError(err)) {
+ logForgeNoAccessOnce('pr-watcher', repoSpec, err.message);
+ } else {
+ console.error(`❌ pr-watcher: gh pr list failed for ${repoSpec}: ${err.message}`);
+ }
return null;
});
if (raw === null) return null;
@@ -285,11 +298,11 @@ export function isPendingMergeReady(prView) {
});
}
-async function readPendingPullRequest(repoSpec, prNumber) {
+async function readPendingPullRequest(repoSpec, prNumber, { cwd, env } = {}) {
const raw = await execGh([
'pr', 'view', String(prNumber), '--repo', repoSpec,
'--json', 'state,mergeStateStatus,statusCheckRollup'
- ], undefined, { backoffKey: repoSpec }).catch(() => null);
+ ], undefined, { cwd, env, backoffKey: repoSpec }).catch(() => null);
const parsed = raw === null ? null : safeJSONParse(raw, null);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
}
@@ -321,8 +334,15 @@ export async function processPendingMergePrs(app) {
const repoSpec = githubRepoSpec(origin);
if (!repoSpec) return { ok: false, reason: 'not-a-github-repo' };
+ // Run gh as the account THIS app's repo needs, not gh's ambient active login
+ // (#7540) — mirrors appPullRequests.fetchGithubPullRequests.
+ const forgeExec = await resolveForgeExecOptions(app?.repoPath, { forgeAccount: app?.forgeAccount });
+
// 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) });
+ const forge = await ensureForgeReachable('pr-watcher pending-merge', {
+ hostname: githubApiHost(origin.host),
+ ...(forgeExec.customEnv ? { env: forgeExec.customEnv } : {}),
+ });
if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status };
const outcomes = new Map();
@@ -330,7 +350,7 @@ export async function processPendingMergePrs(app) {
for (const entry of pending) {
const key = pendingMergeKey(entry);
- const prView = await readPendingPullRequest(repoSpec, entry.prNumber);
+ const prView = await readPendingPullRequest(repoSpec, entry.prNumber, forgeExec);
if (!prView) {
// An unreadable PR is still a cycle this entry spent pending, so it has to
// tick. A PR whose `gh pr view` fails PERMANENTLY (deleted PR, renamed
@@ -492,28 +512,40 @@ export async function checkPullRequests(app, { authorFilter = 'trusted' } = {})
}
const repoFullName = origin.fullName;
+ // Same per-repo credential resolution as the pending-merge sweep above — an
+ // app whose repo belongs to another GitHub account is invisible to the ambient
+ // login, and every gh read below would 404 forever (#7540).
+ const forgeExec = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount });
+
// 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) });
+ const forge = await ensureForgeReachable('pr-watcher', {
+ hostname: githubApiHost(origin.host),
+ ...(forgeExec.customEnv ? { env: forgeExec.customEnv } : {}),
+ });
if (!forge.ok) return { ok: false, reason: 'forge-unreachable', forgeStatus: forge.status, repoFullName };
- const defaultBranch = await getDefaultBranch(repoSpec);
+ const defaultBranch = await getDefaultBranch(repoSpec, forgeExec);
if (!defaultBranch) {
return { ok: false, reason: 'default-branch-unresolved', repoFullName };
}
const trust = await createGithubActorTrust({
- runGh: execGh, host: githubApiHost(origin.host), repoFullName,
+ // Bound to the same overlay: the collaborator-permission reads below are
+ // `gh api` calls against this repo, so they need its credential too.
+ runGh: (args, timeoutMs) => execGh(args, timeoutMs, { cwd: forgeExec.cwd, env: forgeExec.env }),
+ host: githubApiHost(origin.host),
+ repoFullName,
});
const selfLogin = trust.currentUser;
if (filter === 'self' && !selfLogin) {
return { ok: false, reason: 'self-login-unavailable', repoFullName, defaultBranch };
}
- const prs = await listOpenPullRequests(repoSpec, defaultBranch);
+ const prs = await listOpenPullRequests(repoSpec, defaultBranch, forgeExec);
if (prs === null) {
return { ok: false, reason: 'pr-list-failed', repoFullName, defaultBranch };
}
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index bacd967714..c47c8933d3 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -9,6 +9,18 @@ vi.mock('./github.js', () => ({
ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),
}));
+// The per-repo gh credential overlay (#7540). Mocked rather than real so the
+// suite asserts what execGh RECEIVED without spawning git/gh probes.
+const PINNED_ENV = { GH_TOKEN: 'token-for-other-account' };
+const resolveForgeExecOptionsMock = vi.fn(async (repoPath) => ({
+ cwd: repoPath || undefined,
+ env: PINNED_ENV,
+ customEnv: PINNED_ENV,
+}));
+vi.mock('./forgeExecOptions.js', () => ({
+ resolveForgeExecOptions: (...args) => resolveForgeExecOptionsMock(...args),
+}));
+
const mergePrMock = vi.fn();
vi.mock('./git.js', () => ({
mergePR: (...args) => mergePrMock(...args),
@@ -43,6 +55,7 @@ vi.mock('../lib/gitRemote.js', () => ({
getOriginInfo: (...args) => getOriginInfoMock(...args),
}));
+import { __resetForgeNoAccessLog } from '../lib/forgeAccessErrors.js';
import {
matchesAuthorFilter,
computePrCheck,
@@ -216,7 +229,7 @@ describe('merge-only PR watcher', () => {
expect(execGhMock).toHaveBeenCalledWith([
'pr', 'view', '88', '--repo', 'github.com/o/r',
'--json', 'state,mergeStateStatus,statusCheckRollup'
- ], undefined, { backoffKey: 'github.com/o/r' });
+ ], undefined, { cwd: '/repos/app1', env: PINNED_ENV, backoffKey: 'github.com/o/r' });
});
it.each([
@@ -450,6 +463,53 @@ describe('checkPullRequests trusted maintenance boundary', () => {
expect((await checkPullRequests({ ...tracked, prWatcherState: { lastSeenPrNumber: 3, activityByPr: failureSeen.activityByPr } })).newPrs.map(pr => pr.number)).toEqual([3]);
});
+ it('runs every gh read with the per-repo credential, honouring the app\'s forgeAccount pin', async () => {
+ // #7540: `gh repo view`, `gh pr list` and the collaborator `gh api` probes all
+ // used gh's ambient active login, so an app whose repo belongs to another
+ // GitHub account 404'd on every tick forever.
+ forge([rawPr(10, 'collaborator')]);
+ const pinned = { ...app, forgeAccount: 'other-account' };
+
+ expect((await checkPullRequests(pinned)).newPrs).toHaveLength(1);
+
+ expect(resolveForgeExecOptionsMock).toHaveBeenCalledWith('/repos/example', { forgeAccount: 'other-account' });
+ // Not just the PR list — the default-branch read and the actor-trust probes
+ // are against the same private repo and need the same credential.
+ const kinds = new Set(execGhMock.mock.calls.map(([args]) => args[0]));
+ expect(kinds).toEqual(new Set(['repo', 'pr', 'api']));
+ for (const [, , options] of execGhMock.mock.calls) {
+ expect(options).toMatchObject({ cwd: '/repos/example', env: PINNED_ENV });
+ }
+ expect(ensureForgeReachableMock).toHaveBeenCalledWith('pr-watcher', {
+ hostname: 'github.com',
+ env: PINNED_ENV,
+ });
+ });
+
+ it('logs a no-access 404 ONCE per repo instead of once per poll', async () => {
+ // #7540: permanent until credentials change, so the watcher must not narrate
+ // it every scheduler tick — and must still report the poll as failed.
+ __resetForgeNoAccessLog();
+ getOriginInfoMock.mockResolvedValue({ host: 'github.com', fullName: 'example/project', hasOrigin: true });
+ execGhMock.mockRejectedValue(Object.assign(
+ new Error("GraphQL: Could not resolve to a Repository with the name 'example/project'. (repository)"),
+ { ghExitCode: 1, ghNoAccess: true }
+ ));
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const first = await checkPullRequests(app);
+ const second = await checkPullRequests(app);
+
+ expect(first).toMatchObject({ ok: false, reason: 'default-branch-unresolved' });
+ expect(second).toMatchObject({ ok: false, reason: 'default-branch-unresolved' });
+ const noAccessLines = errors.mock.calls
+ .map(([line]) => String(line))
+ .filter((line) => line.includes('not visible to the gh account'));
+ expect(noAccessLines).toHaveLength(1);
+ expect(noAccessLines[0]).toContain('Forge account');
+ errors.mockRestore();
+ });
+
it('refreshes authority every poll and pins repository and permission queries to the enterprise host', async () => {
forge([rawPr(10, 'collaborator')], { host: 'github.enterprise.example' });
expect((await checkPullRequests(app)).newPrs).toHaveLength(1);
diff --git a/server/services/repoSync.js b/server/services/repoSync.js
index 81aca1dffd..905bb6fb31 100644
--- a/server/services/repoSync.js
+++ b/server/services/repoSync.js
@@ -747,12 +747,12 @@ export function describeStep(step) {
* or an agent. Never throws; a scan that blows up is reported as a `scan-failed`
* escalation so the sweep continues.
*
- * @param {{repoPath:string, appId?:string, name?:string, actions?:object}} repo
+ * @param {{repoPath:string, appId?:string, name?:string, actions?:object, forgeAccount?:string|null}} repo
* @param {{activeAgentIds?:Set<string>}} [deps]
* @returns {Promise<object>} per-repo result
*/
export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
- const { repoPath, appId = null, name = repoPath, actions = {} } = repo;
+ const { repoPath, appId = null, name = repoPath, actions = {}, forgeAccount = null } = repo;
const base = { appId, name, repoPath, performed: [], escalations: [] };
if (!repoPath || !existsSync(repoPath)) {
@@ -805,7 +805,8 @@ export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
const result = await reconcile(repoPath, {
cleanup: true,
reapRemotes: actions.reapRemotes === true,
- activeAgentIds
+ activeAgentIds,
+ forgeAccount
}).catch((err) => {
escalations.push({ kind: ESCALATION_KINDS.SCAN_FAILED, detail: `branch cleanup failed: ${err.message}` });
return null;
@@ -847,7 +848,7 @@ export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
* parallel sweep interleaves push output and git index locks across repos that
* may share a worktree parent.
*
- * @param {{repoPath:string, appId?:string, name?:string, actions?:object}[]} repos
+ * @param {{repoPath:string, appId?:string, name?:string, actions?:object, forgeAccount?:string|null}[]} repos
* @param {{activeAgentIds?:Set<string>}} [deps]
* @returns {Promise<object[]>}
*/
@@ -1012,6 +1013,9 @@ export function resolveSyncTargets(apps, actions = {}) {
repoPath,
appId: app.id,
name: app.name || app.id,
+ // Carried so the delegated branch-reconcile runs gh as the account this
+ // repo needs rather than gh's ambient active login (#7540).
+ forgeAccount: app.forgeAccount || null,
// A per-app override may switch an individual action off for one repo
// (e.g. leave one checkout's stashes alone) without opting the repo out.
actions: { ...actions, ...override }