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: bound forge PR subprocesses (#6938)

[._.]/ Adam Eivyff375c10c660
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index cc27c0f3be..dbe6840f1f 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -269,7 +269,6 @@ describe('every cwd-passing spawn pins PWD', () => {
// a tool that resolves paths from its real cwd, never from PWD" — git, gh,
// glab, pm2, psql, npm, xcodegen, python.
const EXEMPT = new Map([
- ['services/git.js', 'git/gh resolve from real cwd (and -C), never PWD'],
['lib/execGit.js', 'git only'],
['lib/planIds.js', 'git only'],
['services/repoCloner.js', 'git clone/fetch only'],
diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.js
index f84e956855..d586a81fd5 100644
--- a/server/services/forgeAuth.js
+++ b/server/services/forgeAuth.js
@@ -7,19 +7,33 @@ import { spawn } from '../lib/childProcess.js';
import { execGitSafe } from '../lib/execGit.js';
import { parseGitRemote, detectForgeCli, pickGhAccountForOwner } from '../lib/gitForge.js';
-function spawnCli(cmd, args) {
+const DEFAULT_SPAWN_CLI_TIMEOUT_MS = 10000;
+
+function spawnCli(cmd, args, timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS) {
return new Promise((resolve) => {
const child = spawn(cmd, args, { shell: false });
let stdout = '', stderr = '';
+ let settled = false;
+ const done = (result) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(result);
+ };
+ const timer = setTimeout(() => {
+ try { child.kill('SIGKILL'); } catch { /* best-effort process cleanup */ }
+ done({ code: -1, stdout: '', stderr: 'timed out' });
+ }, timeoutMs);
+ timer.unref?.();
child.stdout.on('data', (d) => { stdout += d.toString(); });
child.stderr.on('data', (d) => { stderr += d.toString(); });
- child.on('close', (code) => resolve({ code, stdout, stderr }));
- child.on('error', () => resolve({ code: -1, stdout: '', stderr: '' }));
+ child.on('close', (code) => done({ code, stdout, stderr }));
+ child.on('error', () => done({ code: -1, stdout: '', stderr: '' }));
});
}
-async function listGhAccounts() {
- const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com']);
+async function listGhAccounts(timeoutMs) {
+ const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com'], timeoutMs);
// gh writes status to stderr in older versions, stdout in newer — search both.
const text = `${stdout}\n${stderr}`;
const accounts = [];
@@ -29,8 +43,8 @@ async function listGhAccounts() {
return accounts;
}
-async function getGhTokenForAccount(login) {
- const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com']);
+async function getGhTokenForAccount(login, timeoutMs) {
+ const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com'], timeoutMs);
return code === 0 ? stdout.trim() : null;
}
@@ -42,8 +56,11 @@ async function getGhTokenForAccount(login) {
* - For GitLab repos: uses glab as-is. glab is single-user-per-host, so its keyring
* already disambiguates by host without the mutable-active-user pitfall.
* Falls back to ambient env when no match is possible.
+ * @param {string} dir - Repository root
+ * @param {object} [opts]
+ * @param {number} [opts.timeoutMs=10000] - Per-process bound for gh auth probes
*/
-export async function resolveForgeForRepo(dir) {
+export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS } = {}) {
const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);
const parsed = parseGitRemote(remote.stdout?.trim());
if (!parsed) {
@@ -56,11 +73,11 @@ export async function resolveForgeForRepo(dir) {
return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };
}
- const accounts = await listGhAccounts();
+ const accounts = await listGhAccounts(timeoutMs);
const account = pickGhAccountForOwner(parsed.owner, accounts);
if (!account) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };
- const token = await getGhTokenForAccount(account);
+ const token = await getGhTokenForAccount(account, timeoutMs);
if (!token) return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account };
return { cli, env: { ...process.env, GH_TOKEN: token }, host: parsed.host, owner: parsed.owner, account };
@@ -87,15 +104,14 @@ export async function resolveForgeForRepo(dir) {
* @returns {Promise<{ GH_TOKEN?: string }>}
*/
export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {
- // resolveForgeForRepo shells out to git + `gh auth status` + `gh auth token`
- // with no internal timeout, and this runs on the critical agent-spawn path.
- // Race it against a timer so a stalled gh (network/keychain hang) can't leave
- // a task marked in-progress forever with no child process — a timeout falls
- // through to `{}` (ambient auth) exactly like any other miss. The timer is
- // unref'd so it never itself keeps the event loop alive.
+ // Keep the whole lookup inside the agent-spawn budget. Each gh subprocess has
+ // the same bound and kills itself on timeout, so losing this race cannot leak
+ // the auth child that was still pending. A timeout falls through to `{}`
+ // (ambient auth) exactly like any other miss. The timer is unref'd so it never
+ // itself keeps the event loop alive.
let timer;
const resolved = await Promise.race([
- resolveForgeForRepo(dir).catch(() => null),
+ resolveForgeForRepo(dir, { timeoutMs }).catch(() => null),
new Promise((r) => { timer = setTimeout(() => r(null), timeoutMs); timer.unref?.(); }),
]);
clearTimeout(timer);
diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.js
index c0b45681fb..6070bc9c53 100644
--- a/server/services/forgeAuth.test.js
+++ b/server/services/forgeAuth.test.js
@@ -85,10 +85,15 @@ describe('forge credential resolution', () => {
const stalled = new EventEmitter();
stalled.stdout = new EventEmitter();
stalled.stderr = new EventEmitter();
+ stalled.kill = vi.fn();
spawn.mockImplementationOnce(() => stalled);
const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 25 });
await vi.advanceTimersByTimeAsync(25);
await expect(pending).resolves.toEqual({});
+ expect(stalled.kill).toHaveBeenCalledWith('SIGKILL');
+
+ // A close emitted after the timeout must not change the settled result.
stalled.emit('close', 1);
+ await expect(pending).resolves.toEqual({});
});
});
diff --git a/server/services/git.forgeTimeout.test.js b/server/services/git.forgeTimeout.test.js
new file mode 100644
index 0000000000..e4f4b885ea
--- /dev/null
+++ b/server/services/git.forgeTimeout.test.js
@@ -0,0 +1,115 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ resolveForgeForRepo: vi.fn(),
+}));
+
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: mocks.spawn,
+}));
+
+vi.mock('./forgeAuth.js', () => ({
+ resolveForgeForRepo: mocks.resolveForgeForRepo,
+ resolveForgeTokenEnv: vi.fn(),
+}));
+
+import { createPR, mergePR, requestCopilotReview } from './git.js';
+
+const pinnedEnv = { GH_TOKEN: 'test-owner-token' };
+
+function hungChild() {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = new EventEmitter();
+ child.kill = vi.fn();
+ return child;
+}
+
+describe('bounded forge mutations', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ mocks.resolveForgeForRepo.mockResolvedValue({
+ cli: 'gh',
+ env: pinnedEnv,
+ host: 'github.com',
+ owner: 'example-owner',
+ account: 'example-owner',
+ });
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it.each([
+ ['createPR', () => createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' })],
+ ['mergePR', () => mergePR('/repo', 42)],
+ ['requestCopilotReview', () => requestCopilotReview('/repo', 'https://github.com/example-owner/repo/pull/42')],
+ ])('kills a stalled gh process and returns a structured timeout from %s', async (_name, invoke) => {
+ const child = hungChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const pending = invoke();
+ await vi.dynamicImportSettled();
+ await vi.advanceTimersByTimeAsync(60000);
+
+ await expect(pending).resolves.toMatchObject({
+ success: false,
+ error: expect.stringContaining('timed out after 60000ms'),
+ });
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+ expect(mocks.spawn).toHaveBeenCalledWith(
+ 'gh',
+ expect.any(Array),
+ expect.objectContaining({ cwd: '/repo', env: expect.objectContaining({ GH_TOKEN: 'test-owner-token', PWD: '/repo' }) }),
+ );
+ });
+
+ it('bounds GitLab MR creation with the resolved forge environment', async () => {
+ mocks.resolveForgeForRepo.mockResolvedValue({
+ cli: 'glab',
+ env: { GITLAB_TOKEN: 'test-token' },
+ host: 'gitlab.example.com',
+ owner: 'example-owner',
+ account: null,
+ });
+ const child = hungChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const pending = createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' });
+ await vi.dynamicImportSettled();
+ await vi.advanceTimersByTimeAsync(60000);
+
+ await expect(pending).resolves.toMatchObject({
+ success: false,
+ error: expect.stringContaining('timed out'),
+ cli: 'glab',
+ });
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');
+ expect(mocks.spawn).toHaveBeenCalledWith(
+ 'glab',
+ expect.arrayContaining(['mr', 'create']),
+ { cwd: '/repo', shell: false, env: { GITLAB_TOKEN: 'test-token', PWD: '/repo' } },
+ );
+ });
+
+ it('preserves gh stderr so no-commit cleanup still recognizes its contract', async () => {
+ const child = hungChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const pending = createPR('/repo', { title: 'Title', body: 'Body', base: 'main', head: 'topic' });
+ await vi.dynamicImportSettled();
+ child.stderr.emit('data', Buffer.from('GraphQL: No commits between main and topic'));
+ child.emit('close', 1);
+
+ await expect(pending).resolves.toMatchObject({
+ success: false,
+ error: 'GraphQL: No commits between main and topic',
+ });
+ });
+});
diff --git a/server/services/git.js b/server/services/git.js
index 639de46752..bca28b426a 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -359,6 +359,15 @@ export async function checkout(dir, branchName) {
return { success: true, branch: branchName };
}
+async function execForgeCli(cli, args, dir, env) {
+ if (cli === 'glab') {
+ const { execGlab } = await import('./gitlab.js');
+ return execGlab(args, dir, undefined, { env });
+ }
+ const { execGh } = await import('./github.js');
+ return execGh(args, undefined, { cwd: dir, env });
+}
+
/**
* Create a pull request (GitHub) or merge request (GitLab) using `gh` / `glab`.
* Forge is auto-detected from the repo's `origin` URL; gh identity is auto-pinned
@@ -381,31 +390,19 @@ export async function createPR(dir, { title, body, base, head }) {
const meta = { cli, account, owner, host };
- return new Promise((resolve) => {
- const child = spawn(cli, args, { cwd: dir, env, shell: false });
-
- let stdout = '';
- let stderr = '';
-
- child.stdout.on('data', (data) => { stdout += data.toString(); });
- child.stderr.on('data', (data) => { stderr += data.toString(); });
-
- child.on('close', (code) => {
- if (code === 0) {
- // Both gh and glab print the resulting URL on stdout (gh: just the URL;
- // glab: a couple lines ending in the URL — extract the last http(s)-looking line).
- const urlMatch = stdout.trim().match(/(https?:\/\/\S+)\s*$/);
- const url = urlMatch ? urlMatch[1] : stdout.trim();
- resolve({ success: true, url, ...meta });
- } else {
- resolve({ success: false, error: stderr || `${cli} exited with code ${code}`, ...meta });
- }
- });
-
- child.on('error', (err) => {
- resolve({ success: false, error: `${cli} not available: ${err.message}`, ...meta });
- });
- });
+ try {
+ const stdout = await execForgeCli(cli, args, dir, env);
+ if (stdout === null) {
+ return { success: false, error: 'glab command failed or timed out', ...meta };
+ }
+ // Both gh and glab print the resulting URL on stdout (gh: just the URL;
+ // glab: a couple lines ending in the URL — extract the last http(s)-looking line).
+ const urlMatch = stdout.trim().match(/(https?:\/\/\S+)\s*$/);
+ const url = urlMatch ? urlMatch[1] : stdout.trim();
+ return { success: true, url, ...meta };
+ } catch (err) {
+ return { success: false, error: err.message || `${cli} command failed`, ...meta };
+ }
}
/**
@@ -424,20 +421,12 @@ export async function mergePR(dir, prNumber) {
return { success: false, error: `Merge-only PR automation requires gh, not ${cli}`, ...meta };
}
- return new Promise((resolve) => {
- const child = spawn('gh', ['pr', 'merge', String(prNumber), '--merge', '--delete-branch'], {
- cwd: dir, env, shell: false
- });
- let stderr = '';
- child.stderr.on('data', (data) => { stderr += data.toString(); });
- child.on('close', (code) => {
- if (code === 0) resolve({ success: true, ...meta });
- else resolve({ success: false, error: stderr.trim() || `gh exited with code ${code}`, ...meta });
- });
- child.on('error', (err) => {
- resolve({ success: false, error: `gh not available: ${err.message}`, ...meta });
- });
- });
+ try {
+ await execForgeCli('gh', ['pr', 'merge', String(prNumber), '--merge', '--delete-branch'], dir, env);
+ return { success: true, ...meta };
+ } catch (err) {
+ return { success: false, error: err.message || 'gh command failed', ...meta };
+ }
}
/**
@@ -484,18 +473,12 @@ export async function requestCopilotReview(dir, prUrl) {
'-f', 'reviewers[]=copilot-pull-request-reviewer[bot]'
);
- return new Promise((resolve) => {
- const child = spawn(cli, args, { cwd: dir, env, shell: false });
- let stderr = '';
- child.stderr.on('data', (data) => { stderr += data.toString(); });
- child.on('close', (code) => {
- if (code === 0) resolve({ success: true });
- else resolve({ success: false, error: stderr.trim() || `gh exited with code ${code}` });
- });
- child.on('error', (err) => {
- resolve({ success: false, error: `gh not available: ${err.message}` });
- });
- });
+ try {
+ await execForgeCli('gh', args, dir, env);
+ return { success: true };
+ } catch (err) {
+ return { success: false, error: err.message || 'gh command failed' };
+ }
}
/**
diff --git a/server/services/gitlab.js b/server/services/gitlab.js
index ef812c8ec5..904a783ea4 100644
--- a/server/services/gitlab.js
+++ b/server/services/gitlab.js
@@ -1,6 +1,7 @@
import { spawn } from '../lib/childProcess.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { withGlabJson } from '../lib/glabArgs.js';
+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
// 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
@@ -26,11 +27,13 @@ const DEFAULT_EXEC_GLAB_TIMEOUT_MS = 60000;
* @param {string[]} args - glab arguments (e.g. ['issue', 'list', '--output', 'json'])
* @param {string} cwd - repo root the glab command runs in
* @param {number} [timeoutMs] - kills the child and resolves null past this
+ * @param {object} [options]
+ * @param {NodeJS.ProcessEnv} [options.env] - Explicit forge credentials/environment
* @returns {Promise<string|null>}
*/
-export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS) {
+export function execGlab(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIMEOUT_MS, { env = null } = {}) {
return new Promise((resolve) => {
- const child = spawn('glab', args, { cwd, shell: false });
+ const child = spawn('glab', args, { cwd, shell: false, env: withSpawnCwdEnv(env || process.env, cwd) });
let stdout = '';
let settled = false;
// One settle path so the timeout can't resolve a promise `close` already