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): pin the verification credential, bound glab, and probe LI's own host (#3358)

[._.]/ Adam Eivy05ce1a5d8c1d
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 6c7c805f63..b91cc4eb24 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -242,10 +242,14 @@ export async function verifyPrClaim({ task, workspacePath, success, prExpected }
}
const { resolveForgeForRepo } = await import('./git.js');
- const { cli } = await resolveForgeForRepo(workspacePath).catch(() => ({ cli: 'gh' }));
+ // `env` carries the repo-owner-pinned `GH_TOKEN` the agent's own `gh pr create`
+ // used. Dropping it would query as whatever ambient account `gh` happens to be
+ // on, which on a multi-login host may not even see the PR — reading as
+ // "no PR" for a run that opened one.
+ const { cli, env } = await resolveForgeForRepo(workspacePath).catch(() => ({ cli: 'gh', env: null }));
const found = cli === 'glab'
? await (await import('./gitlab.js')).findMergeRequestForBranch(branch, workspacePath)
- : await (await import('./github.js')).findPullRequestForBranch(branch, { cwd: workspacePath });
+ : await (await import('./github.js')).findPullRequestForBranch(branch, { cwd: workspacePath, env: env || null });
const noun = cli === 'glab' ? 'merge request' : 'pull request';
if (found.status === 'found') return { ok: true, branch };
diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.js
index 8274c95c9f..c40bc19a0c 100644
--- a/server/services/agentFinalization.prVerification.test.js
+++ b/server/services/agentFinalization.prVerification.test.js
@@ -107,7 +107,17 @@ describe('verifyPrClaim (#3358)', () => {
onBranch('claim/issue-1');
const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });
expect(verdict.ok).toBe(true);
- expect(findPullRequestForBranchMock).toHaveBeenCalledWith('claim/issue-1', { cwd: '/w' });
+ expect(findPullRequestForBranchMock).toHaveBeenCalledWith('claim/issue-1', { cwd: '/w', env: null });
+ });
+
+ it('threads the repo-pinned gh credential into the lookup', async () => {
+ // The agent opened its PR as the repo-owner-matched account; querying as the
+ // ambient one may not even see it on a multi-login host.
+ onBranch('claim/issue-1');
+ const env = { GH_TOKEN: 'pinned-token' };
+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'gh', env });
+ await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });
+ expect(findPullRequestForBranchMock).toHaveBeenCalledWith('claim/issue-1', { cwd: '/w', env });
});
it('fails with pr-missing when the forge answered and has no PR', async () => {
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index 909f8866d5..2345c9352e 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -300,8 +300,14 @@ export async function buildTaskInput({ app } = {}) {
// 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')
+ const [{ ensureForgeReachable }, { githubApiHost }] = await Promise.all([
+ import('../github.js'),
+ import('../../lib/workTracker.js')
+ ])
+ // Probed against the app's OWN forge host (`tracker.host`), not gh's
+ // default: a bare probe would skip a healthy GitHub Enterprise app whenever
+ // github.com is unreachable, and run one whose enterprise host is down.
+ const forge = await ensureForgeReachable('layered-intelligence', { hostname: githubApiHost(tracker.host) })
if (!forge.ok) return skip('skipped', 'forge-unreachable')
}
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index 7b187d4b91..f0e490a7fe 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -8,9 +8,15 @@ vi.mock('../apps.js', () => ({
updateAppLayeredIntelligence: vi.fn().mockResolvedValue(undefined)
}));
-vi.mock('../../lib/workTracker.js', () => ({
- resolveAppWorkTracker: vi.fn().mockResolvedValue({ resolved: 'github', forge: 'gh' })
-}));
+vi.mock('../../lib/workTracker.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ // Real pure host→API-host mapping so the forge gate is exercised through
+ // the exact enterprise-aware resolution production uses (#3358).
+ githubApiHost: actual.githubApiHost,
+ resolveAppWorkTracker: vi.fn().mockResolvedValue({ resolved: 'github', forge: 'gh', host: 'github.com' })
+ };
+});
vi.mock('../../lib/fileUtils.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null)
diff --git a/server/services/github.js b/server/services/github.js
index 296be568d9..66eed6560d 100644
--- a/server/services/github.js
+++ b/server/services/github.js
@@ -46,12 +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, { cwd = null } = {}) {
+export function execGh(args, timeoutMs = DEFAULT_EXEC_GH_TIMEOUT_MS, { cwd = null, env = null } = {}) {
return new Promise((resolve, reject) => {
+ const baseEnv = env || process.env;
const child = spawn('gh', args, {
shell: false,
windowsHide: true,
- ...(cwd ? { cwd, env: withSpawnCwdEnv(process.env, cwd) } : {})
+ ...(cwd ? { cwd, env: withSpawnCwdEnv(baseEnv, cwd) } : (env ? { env } : {}))
});
let stdout = '';
let stderr = '';
@@ -512,15 +513,19 @@ export async function ensureForgeReachable(label, { hostname = null } = {}) {
* 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
+ * @param {{ cwd?: string, env?: object|null }} [opts] - repo dir gh resolves the
+ * remote from, and the env overlay to run under. Pass the `env` from
+ * `resolveForgeForRepo` so the lookup authenticates as the SAME repo-owner-
+ * pinned account that opened the PR — on a multi-login host the ambient
+ * account may not even see it, which would read as "no PR".
* @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, detail: string|null }>}
*/
-export async function findPullRequestForBranch(branch, { cwd = null } = {}) {
+export async function findPullRequestForBranch(branch, { cwd = null, env = 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 }
+ { cwd, env }
).catch(err => err);
if (raw instanceof Error) {
return { status: 'unavailable', number: null, url: null, detail: raw.message };
diff --git a/server/services/gitlab.js b/server/services/gitlab.js
index da4282151b..ff46cec8d6 100644
--- a/server/services/gitlab.js
+++ b/server/services/gitlab.js
@@ -1,30 +1,47 @@
import { spawn } from 'child_process';
+// Mirrors execGh's DEFAULT_EXEC_GH_TIMEOUT_MS. `glab` hits the network, so a
+// stalled call (hung keychain prompt, dead VPN) would otherwise leave the
+// returned promise pending forever — wedging the scheduled job or, since #3358,
+// the agent finalization that awaits an MR lookup before completing the run.
+const DEFAULT_EXEC_GLAB_TIMEOUT_MS = 60000;
+
/**
* Execute a `glab` CLI command safely using spawn (no shell — injection-proof).
*
* Unlike `execGh` (github.js), this takes an explicit `cwd`: `glab` resolves the
* target project from the repo's git `origin` remote in the working directory, so
* it MUST run inside the repo checkout. Resolves to trimmed stdout on success and
- * `null` on ANY failure (non-zero exit, spawn error, glab not installed) — callers
- * treat null as "unavailable / transient", mirroring the `.catch(() => null)`
- * pattern used around `execGh`.
+ * `null` on ANY failure (non-zero exit, spawn error, glab not installed, timeout)
+ * — callers treat null as "unavailable / transient", mirroring the
+ * `.catch(() => null)` pattern used around `execGh`.
*
* @param {string[]} args - glab arguments (e.g. ['issue', 'list', '-F', 'json'])
* @param {string} cwd - repo root the glab command runs in
+ * @param {number} [timeoutMs] - kills the child and resolves null past this
* @returns {Promise<string|null>}
*/
-export function execGlab(args, cwd) {
+export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {
return new Promise((resolve) => {
const child = spawn('glab', args, { cwd, shell: false, windowsHide: true });
let stdout = '';
+ let settled = false;
+ // One settle path so the timeout can't resolve a promise `close` 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('SIGKILL'); } catch (err) { console.error(`❌ execGlab: failed to kill timed-out 'glab ${args.join(' ')}': ${err.message}`); }
+ console.error(`❌ execGlab: 'glab ${args.join(' ')}' timed out after ${timeoutMs}ms`);
+ done(null);
+ }, timeoutMs);
child.stdout.on('data', (d) => { stdout += d.toString(); });
// We never surface glab's stderr to the caller (a failed call resolves to null
// via the exit code), but stderr MUST still be drained — an unread pipe can
// fill its buffer and block the child on a chatty warning.
child.stderr.on('data', () => {});
- child.on('close', (code) => resolve(code === 0 ? stdout.trim() : null));
- child.on('error', () => resolve(null));
+ child.on('close', (code) => done(code === 0 ? stdout.trim() : null));
+ child.on('error', () => done(null));
});
}
diff --git a/server/services/gitlab.test.js b/server/services/gitlab.test.js
index db388aa1a4..59fdbada8a 100644
--- a/server/services/gitlab.test.js
+++ b/server/services/gitlab.test.js
@@ -68,3 +68,26 @@ describe('findMergeRequestForBranch (#3358)', () => {
expect(spawnMock).not.toHaveBeenCalled();
});
});
+
+describe('execGlab timeout (#3358)', () => {
+ it('kills a stalled glab and resolves null instead of hanging the caller', async () => {
+ // Without this bound, the agent PR-claim verification that awaits an MR
+ // lookup would strand a finishing run forever on a hung keychain/network.
+ vi.useFakeTimers();
+ const hung = new EventEmitter();
+ hung.stdout = new EventEmitter();
+ hung.stderr = new EventEmitter();
+ hung.kill = vi.fn();
+ spawnMock.mockImplementationOnce(() => hung);
+
+ const pending = findMergeRequestForBranch('claim/issue-1', '/repo');
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(hung.kill).toHaveBeenCalledWith('SIGKILL');
+ await expect(pending).resolves.toMatchObject({ status: 'unavailable' });
+
+ // A late close must not flip the already-settled result.
+ hung.emit('close', 0);
+ await expect(pending).resolves.toMatchObject({ status: 'unavailable' });
+ vi.useRealTimers();
+ });
+});