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

feat: give forge credentials a shared service owner

[._.]/ Adam Eivy3cfbaa113583
diff --git a/server/lib/README.md b/server/lib/README.md
index 3a308b8e58..5334e3323e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -338,7 +338,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
| `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)` utility imported by `git.js` + worktree manager. `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). |
+| `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. |
| `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`. |
diff --git a/server/lib/execGit.js b/server/lib/execGit.js
index 720543287f..962886fa5f 100644
--- a/server/lib/execGit.js
+++ b/server/lib/execGit.js
@@ -85,3 +85,10 @@ export function execGit(args, cwd, options = {}) {
});
});
}
+
+// Like execGit but catches rejections (e.g. timeout) into a failed-result shape.
+// Exported because every caller that wants `ignoreExitCode` semantics also has to
+// survive the two rejections `ignoreExitCode` does NOT suppress — a timeout and a
+// maxBuffer overflow — and each one hand-rolling that catch drops `stdout`.
+export const execGitSafe = (args, cwd, options) =>
+ execGit(args, cwd, options).catch(err => ({ exitCode: 1, stdout: '', stderr: err.message }));
diff --git a/server/lib/gitForge.js b/server/lib/gitForge.js
index 78f06c30f5..8b4fbe3102 100644
--- a/server/lib/gitForge.js
+++ b/server/lib/gitForge.js
@@ -1,8 +1,8 @@
// Pure helpers for resolving forge (GitHub/GitLab) identity from git remote
// and PR/MR URLs. No child-process or network access — these are string
// parsers and selectors. The orchestration that shells out to `gh`/`glab`
-// (resolveForgeForRepo, createPR, requestCopilotReview) lives in
-// server/services/git.js and composes these.
+// lives in server/services/forgeAuth.js (account/token resolution) and
+// server/services/git.js (PR operations); both compose these helpers.
/**
* Parse a git remote URL into `{ host, owner }`. Returns null for unparseable input.
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 00c60b989f..0fc45be59e 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -37,7 +37,7 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
// if-chain — see providerVendors.js for the vendor rows.
import { buildVendorSpawnConfig } from '../lib/providerVendors.js';
import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
-import { resolveForgeTokenEnv } from './git.js';
+import { resolveForgeTokenEnv } from './forgeAuth.js';
import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { prepareCliSpawn, killProcessTree, guardChildStdin, deliverChildStdin } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 33f8c4b391..c2d10c870f 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -48,10 +48,10 @@ const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () =>
vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));
vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn().mockResolvedValue(undefined) }));
-// Mock git.js directly so spawnDirectly's GH_TOKEN pinning is exercised without
+// Mock forgeAuth.js directly so spawnDirectly's GH_TOKEN pinning is exercised without
// pulling in the real worktreeManager → instances module graph. Default: no
// owner-matched account → empty overlay (ambient gh auth untouched).
-vi.mock('./git.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
vi.mock('./agentFinalization.js', () => ({
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn(),
@@ -1105,7 +1105,7 @@ describe('stream error containment', () => {
});
it('injects the repo-owner-pinned GH_TOKEN into the spawn env so the agent\'s own `gh` uses the right account', async () => {
- const { resolveForgeTokenEnv } = await import('./git.js');
+ const { resolveForgeTokenEnv } = await import('./forgeAuth.js');
vi.mocked(resolveForgeTokenEnv).mockResolvedValueOnce({ GH_TOKEN: 'ghp_pinned_owner_token' });
const spawnPromise = spawnDirectly(minimalArgs);
@@ -1147,7 +1147,7 @@ describe('stream error containment', () => {
});
it('leaves the spawn env\'s ambient GH_TOKEN untouched when there is no owner match', async () => {
- const { resolveForgeTokenEnv } = await import('./git.js');
+ const { resolveForgeTokenEnv } = await import('./forgeAuth.js');
vi.mocked(resolveForgeTokenEnv).mockResolvedValueOnce({});
const prev = process.env.GH_TOKEN;
process.env.GH_TOKEN = 'ghp_ambient';
@@ -1167,7 +1167,7 @@ describe('stream error containment', () => {
});
it('skips the owner-token probe when the provider supplies its own GITHUB_TOKEN', async () => {
- const { resolveForgeTokenEnv } = await import('./git.js');
+ const { resolveForgeTokenEnv } = await import('./forgeAuth.js');
vi.mocked(resolveForgeTokenEnv).mockClear();
vi.mocked(spawn).mockClear();
diff --git a/server/services/agentLifecycle.blockAndBail.test.js b/server/services/agentLifecycle.blockAndBail.test.js
index f806d0071a..22edada229 100644
--- a/server/services/agentLifecycle.blockAndBail.test.js
+++ b/server/services/agentLifecycle.blockAndBail.test.js
@@ -81,7 +81,7 @@ vi.mock('./cos.js', () => ({
getTaskById: vi.fn().mockResolvedValue(null),
getAgentRecord: vi.fn().mockResolvedValue(null),
}));
-vi.mock('./git.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
vi.mock('./agentCliSpawning.js', () => ({
buildCliSpawnConfig: vi.fn(),
isClaudeCliProvider: vi.fn().mockReturnValue(false),
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 06c2cfb2d6..68bad4e0a6 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -76,7 +76,7 @@ import { loadPublicReviewSpawnInput } from './publicReviewSpawnInput.js';
import { releaseAppReviewMarker } from './appActivity.js';
import { ensureInstanceId } from './instances.js';
import { isClaimableBy, buildClaim, buildRelease, getClaimOwner, getTargetInstance, isTargetedElsewhere } from './cosTaskClaim.js';
-import { resolveForgeTokenEnv } from './git.js';
+import { resolveForgeTokenEnv } from './forgeAuth.js';
import { runnerAgents, pausedAgents, consumePausedAgentExit, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
import { withSpawnDedupGuard, withMapEntryCleanup, withUpdateInProgressGuard, SPAWN_DEDUP_SKIP, SPAWN_UPDATE_SKIP } from './agentGuards.js';
import { isUpdateInProgress } from './updateChecker.js';
diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.js
index 2b911c11f0..6af21615af 100644
--- a/server/services/agentLifecycle.postureGate.test.js
+++ b/server/services/agentLifecycle.postureGate.test.js
@@ -82,7 +82,7 @@ vi.mock('./cos.js', () => ({
getTaskById: vi.fn().mockResolvedValue(null),
getAgentRecord: vi.fn().mockResolvedValue(null),
}));
-vi.mock('./git.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
vi.mock('./agentCliSpawning.js', () => ({
buildCliSpawnConfig: vi.fn(),
isClaudeCliProvider: vi.fn().mockReturnValue(false),
diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.js
index 2d7cc2c465..9cc8651498 100644
--- a/server/services/agentLifecycle.spawnViaRunner.test.js
+++ b/server/services/agentLifecycle.spawnViaRunner.test.js
@@ -67,7 +67,7 @@ vi.mock('./cos.js', () => ({
getAgentRecord: vi.fn().mockResolvedValue(null),
}));
-vi.mock('./git.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
+vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));
vi.mock('./agentCliSpawning.js', () => ({
buildCliSpawnConfig: vi.fn(),
diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.js
new file mode 100644
index 0000000000..cff840cf6f
--- /dev/null
+++ b/server/services/forgeAuth.js
@@ -0,0 +1,116 @@
+/**
+ * Repository-owner forge credentials shared by Git operations and agent launches.
+ * Keep account probing and token overlays here; repository mutations stay in git.js
+ * and pure remote/account parsing stays in lib/gitForge.js.
+ */
+import { spawn } from '../lib/childProcess.js';
+import { execGitSafe } from '../lib/execGit.js';
+import { parseGitRemote, detectForgeCli, pickGhAccountForOwner } from '../lib/gitForge.js';
+
+function spawnCli(cmd, args, options = {}) {
+ return new Promise((resolve) => {
+ const child = spawn(cmd, args, { shell: false, ...options });
+ let stdout = '', stderr = '';
+ 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: '' }));
+ });
+}
+
+async function listGhAccounts() {
+ const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com']);
+ // gh writes status to stderr in older versions, stdout in newer — search both.
+ const text = `${stdout}\n${stderr}`;
+ const accounts = [];
+ const re = /Logged in to github\.com account (\S+)/g;
+ let m;
+ while ((m = re.exec(text))) accounts.push(m[1]);
+ return accounts;
+}
+
+async function getGhTokenForAccount(login) {
+ const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com']);
+ return code === 0 ? stdout.trim() : null;
+}
+
+/**
+ * Resolve the forge CLI + auth env for a given repo directory.
+ * - For GitHub repos: auto-pins `GH_TOKEN` to the logged-in gh account whose login
+ * matches the repo owner, so PR creation doesn't depend on `hosts.yml`'s mutable
+ * `user:` field (avoids the multi-account "must be a collaborator" failure mode).
+ * - 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.
+ */
+export async function resolveForgeForRepo(dir) {
+ const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);
+ const parsed = parseGitRemote(remote.stdout?.trim());
+ if (!parsed) {
+ return { cli: 'gh', env: process.env, host: null, owner: null, account: null };
+ }
+
+ const cli = detectForgeCli(parsed.host);
+
+ if (cli !== 'gh') {
+ return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };
+ }
+
+ const accounts = await listGhAccounts();
+ 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);
+ 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 };
+}
+
+/**
+ * Resolve just the GitHub-token env overlay for a repo directory, so a spawned
+ * child that runs its own `gh pr create` — a CoS agent, most notably codex,
+ * which is otherwise blind to PortOS's account-pinning — authenticates as the
+ * gh account whose login matches the repo owner (the same pinning
+ * `resolveForgeForRepo` gives PortOS's own `createPR`). Two reasons a plain
+ * env inherit isn't enough: (1) TUI agents run under `buildSafeEnv`, which
+ * strips `GH_TOKEN` entirely, so the child would fall back to gh's mutable
+ * `hosts.yml` active user; (2) even when inherited, the ambient token can be
+ * the wrong account in a multi-login setup ("must be a collaborator").
+ *
+ * Returns `{ GH_TOKEN }` only when a github.com repo-owner-matched account and
+ * token were found; otherwise `{}` so the child keeps whatever gh auth it would
+ * have used. Best-effort and bounded: never throws, and a stalled `gh` probe
+ * times out to `{}` so a spawn is never blocked.
+ * @param {string} dir - Repo (or worktree) root
+ * @param {object} [opts]
+ * @param {number} [opts.timeoutMs=10000] - Cap on the git+gh probe before giving up
+ * @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.
+ let timer;
+ const resolved = await Promise.race([
+ resolveForgeForRepo(dir).catch(() => null),
+ new Promise((r) => { timer = setTimeout(() => r(null), timeoutMs); timer.unref?.(); }),
+ ]);
+ clearTimeout(timer);
+ // Overlay a token ONLY for a genuinely-minted github.com credential. Two gates:
+ // - host === 'github.com': detectForgeCli defaults an unrecognized/GHES host to
+ // `gh`, and resolveForgeForRepo's account/token probes are hardcoded to
+ // `-h github.com`. Without this gate, a Bitbucket/GHES repo whose owner segment
+ // happens to match a local github.com login would get that github.com token
+ // injected into every agent — the wrong (or a leaked) credential.
+ // - env !== process.env: resolveForgeForRepo returns a NEW env object
+ // (`{ ...process.env, GH_TOKEN }`) ONLY on a successful mint; every other
+ // branch (no match, token fetch failed) returns the ambient `process.env` by
+ // reference. Keying on `account` alone would re-emit the ambient GH_TOKEN when
+ // the account matched but the token fetch failed.
+ const minted = resolved && resolved.host === 'github.com' && resolved.env !== process.env;
+ const token = minted ? resolved.env.GH_TOKEN : null;
+ return token ? { GH_TOKEN: token } : {};
+}
diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.js
new file mode 100644
index 0000000000..c0b45681fb
--- /dev/null
+++ b/server/services/forgeAuth.test.js
@@ -0,0 +1,94 @@
+import { EventEmitter } from 'node:events';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../lib/childProcess.js', () => ({ spawn: vi.fn() }));
+
+import { spawn } from '../lib/childProcess.js';
+import { resolveForgeForRepo, resolveForgeTokenEnv } from './forgeAuth.js';
+
+// Exercise remote discovery and authentication without a real credential store.
+function respond({ stdout = '', stderr = '', code = 0 } = {}) {
+ spawn.mockImplementationOnce(() => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = vi.fn();
+ queueMicrotask(() => {
+ child.stdout.emit('data', stdout);
+ child.stderr.emit('data', stderr);
+ child.emit('close', code);
+ });
+ return child;
+ });
+}
+
+function githubAccount({ host = 'github.com', tokenCode = 0 } = {}) {
+ respond({ stdout: `git@${host}:example-owner/project.git\n` });
+ respond({ stderr: 'Logged in to github.com account other-account\nLogged in to github.com account example-owner\n' });
+ respond({ stdout: tokenCode === 0 ? 'test-owner-token\n' : '', code: tokenCode });
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.stubEnv('GH_TOKEN', 'test-ambient-token');
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+});
+
+describe('forge credential resolution', () => {
+ it('pins the repository owner for PR operations without mutating ambient auth', async () => {
+ githubAccount();
+ const forge = await resolveForgeForRepo('/example/repo');
+ expect(forge).toEqual({
+ cli: 'gh', host: 'github.com', owner: 'example-owner', account: 'example-owner',
+ env: { ...process.env, GH_TOKEN: 'test-owner-token' }
+ });
+ expect(spawn).toHaveBeenNthCalledWith(3, 'gh', ['auth', 'token', '-u', 'example-owner', '-h', 'github.com'], { shell: false });
+ expect(process.env.GH_TOKEN).toBe('test-ambient-token');
+ });
+
+ it('gives agent launches only the newly resolved token', async () => {
+ githubAccount();
+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });
+ });
+
+ it.each([
+ ['failed token lookup', { tokenCode: 1 }],
+ ['a non-github.com host', { host: 'github.example.com' }]
+ ])('does not overlay ambient or wrong-host credentials after %s', async (_label, options) => {
+ githubAccount(options);
+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({});
+ });
+
+ it('keeps GitLab host auth ambient and never probes GitHub accounts', async () => {
+ respond({ stdout: '[email protected]:group/project.git\n' });
+ const forge = await resolveForgeForRepo('/example/repo');
+ expect(forge).toEqual({ cli: 'glab', host: 'gitlab.example.com', owner: 'group', account: null, env: process.env });
+ expect(forge.env).toBe(process.env);
+ expect(spawn).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves auth untouched when origin cannot be read or no owner account matches', async () => {
+ respond({ code: 1, stderr: 'no origin' });
+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({});
+ respond({ stdout: '[email protected]:example-owner/project.git\n' });
+ respond({ stdout: 'Logged in to github.com account other-account\n' });
+ await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({});
+ expect(spawn).toHaveBeenCalledTimes(3);
+ });
+
+ it('bounds a stalled credential probe so an agent launch can continue', async () => {
+ vi.useFakeTimers();
+ respond({ stdout: '[email protected]:example-owner/project.git\n' });
+ const stalled = new EventEmitter();
+ stalled.stdout = new EventEmitter();
+ stalled.stderr = new EventEmitter();
+ spawn.mockImplementationOnce(() => stalled);
+ const pending = resolveForgeTokenEnv('/example/repo', { timeoutMs: 25 });
+ await vi.advanceTimersByTimeAsync(25);
+ await expect(pending).resolves.toEqual({});
+ stalled.emit('close', 1);
+ });
+});
diff --git a/server/services/git.js b/server/services/git.js
index 39be7da0d0..7820f49f21 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -3,7 +3,9 @@ import { existsSync } from 'fs';
import { join, resolve } from 'path';
import { safeJSONParse, PATHS, sleep } from '../lib/fileUtils.js';
import { isGitLockError, listWorktrees, reapMergedWorktrees } from './worktreeManager.js';
-import { execGit } from '../lib/execGit.js';
+import { execGit, execGitSafe } from '../lib/execGit.js';
+import { resolveForgeForRepo } from './forgeAuth.js';
+export { resolveForgeForRepo, resolveForgeTokenEnv } from './forgeAuth.js';
import {
parseStatus,
parseDiffStat,
@@ -23,7 +25,7 @@ import { PROTECTED_BRANCHES, validateFilePaths, toLiteralPathspec } from '../lib
import { ServerError } from '../lib/errorHandler.js';
// Re-export so callers that used to import from services/git.js keep working.
-export { execGit };
+export { execGit, execGitSafe };
// Re-export the extracted pure helpers so existing
// `import { … } from 'services/git.js'` call sites keep working.
export {
@@ -36,13 +38,6 @@ export {
extractAgentSummary
};
-// Like execGit but catches rejections (e.g. timeout) into a failed-result shape.
-// Exported because every caller that wants `ignoreExitCode` semantics also has to
-// survive the two rejections `ignoreExitCode` does NOT suppress — a timeout and a
-// maxBuffer overflow — and each one hand-rolling that catch drops `stdout`.
-export const execGitSafe = (args, cwd, options) =>
- execGit(args, cwd, options).catch(err => ({ exitCode: 1, stdout: '', stderr: err.message }));
-
/**
* Get git status for a directory
*/
@@ -364,114 +359,6 @@ export async function checkout(dir, branchName) {
return { success: true, branch: branchName };
}
-function spawnCli(cmd, args, options = {}) {
- return new Promise((resolve) => {
- const child = spawn(cmd, args, { shell: false, ...options });
- let stdout = '', stderr = '';
- 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: '' }));
- });
-}
-
-async function listGhAccounts() {
- const { stdout, stderr } = await spawnCli('gh', ['auth', 'status', '-h', 'github.com']);
- // gh writes status to stderr in older versions, stdout in newer — search both.
- const text = `${stdout}\n${stderr}`;
- const accounts = [];
- const re = /Logged in to github\.com account (\S+)/g;
- let m;
- while ((m = re.exec(text))) accounts.push(m[1]);
- return accounts;
-}
-
-async function getGhTokenForAccount(login) {
- const { code, stdout } = await spawnCli('gh', ['auth', 'token', '-u', login, '-h', 'github.com']);
- return code === 0 ? stdout.trim() : null;
-}
-
-/**
- * Resolve the forge CLI + auth env for a given repo directory.
- * - For GitHub repos: auto-pins `GH_TOKEN` to the logged-in gh account whose login
- * matches the repo owner, so PR creation doesn't depend on `hosts.yml`'s mutable
- * `user:` field (avoids the multi-account "must be a collaborator" failure mode).
- * - 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.
- */
-export async function resolveForgeForRepo(dir) {
- const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);
- const parsed = parseGitRemote(remote.stdout?.trim());
- if (!parsed) {
- return { cli: 'gh', env: process.env, host: null, owner: null, account: null };
- }
-
- const cli = detectForgeCli(parsed.host);
-
- if (cli !== 'gh') {
- return { cli, env: process.env, host: parsed.host, owner: parsed.owner, account: null };
- }
-
- const accounts = await listGhAccounts();
- 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);
- 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 };
-}
-
-/**
- * Resolve just the GitHub-token env overlay for a repo directory, so a spawned
- * child that runs its own `gh pr create` — a CoS agent, most notably codex,
- * which is otherwise blind to PortOS's account-pinning — authenticates as the
- * gh account whose login matches the repo owner (the same pinning
- * `resolveForgeForRepo` gives PortOS's own `createPR`). Two reasons a plain
- * env inherit isn't enough: (1) TUI agents run under `buildSafeEnv`, which
- * strips `GH_TOKEN` entirely, so the child would fall back to gh's mutable
- * `hosts.yml` active user; (2) even when inherited, the ambient token can be
- * the wrong account in a multi-login setup ("must be a collaborator").
- *
- * Returns `{ GH_TOKEN }` only when a github.com repo-owner-matched account and
- * token were found; otherwise `{}` so the child keeps whatever gh auth it would
- * have used. Best-effort and bounded: never throws, and a stalled `gh` probe
- * times out to `{}` so a spawn is never blocked.
- * @param {string} dir - Repo (or worktree) root
- * @param {object} [opts]
- * @param {number} [opts.timeoutMs=10000] - Cap on the git+gh probe before giving up
- * @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.
- let timer;
- const resolved = await Promise.race([
- resolveForgeForRepo(dir).catch(() => null),
- new Promise((r) => { timer = setTimeout(() => r(null), timeoutMs); timer.unref?.(); }),
- ]);
- clearTimeout(timer);
- // Overlay a token ONLY for a genuinely-minted github.com credential. Two gates:
- // - host === 'github.com': detectForgeCli defaults an unrecognized/GHES host to
- // `gh`, and resolveForgeForRepo's account/token probes are hardcoded to
- // `-h github.com`. Without this gate, a Bitbucket/GHES repo whose owner segment
- // happens to match a local github.com login would get that github.com token
- // injected into every agent — the wrong (or a leaked) credential.
- // - env !== process.env: resolveForgeForRepo returns a NEW env object
- // (`{ ...process.env, GH_TOKEN }`) ONLY on a successful mint; every other
- // branch (no match, token fetch failed) returns the ambient `process.env` by
- // reference. Keying on `account` alone would re-emit the ambient GH_TOKEN when
- // the account matched but the token fetch failed.
- const minted = resolved && resolved.host === 'github.com' && resolved.env !== process.env;
- const token = minted ? resolved.env.GH_TOKEN : null;
- return token ? { GH_TOKEN: token } : {};
-}
-
/**
* 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
diff --git a/server/services/git.test.js b/server/services/git.test.js
index 869543fdc1..77ce396e4c 100644
--- a/server/services/git.test.js
+++ b/server/services/git.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner, parseGitRemote, detectForgeCli, parsePullRequestUrl, requestCopilotReview, resolveForgeTokenEnv } from './git.js';
+import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner, parseGitRemote, detectForgeCli, parsePullRequestUrl, requestCopilotReview } from './git.js';
describe('parseGitRemote', () => {
it('parses GitHub SSH urls', () => {
@@ -211,15 +211,11 @@ describe('requestCopilotReview', () => {
// contract so the request never reaches a real network call.
});
-describe('resolveForgeTokenEnv', () => {
- it('returns {} for a non-existent dir so ambient gh auth is untouched (and never throws)', async () => {
- // A cwd that doesn't exist makes the git spawn fail → resolveForgeForRepo
- // sees no origin remote → account: null → no overlay. Deterministic and
- // network-free regardless of the host machine's gh logins. (A null/omitted
- // dir would fall back to the process cwd — a real repo — so we use an
- // explicitly bogus path to keep the assertion environment-independent.)
- await expect(resolveForgeTokenEnv('/nonexistent-path-for-test')).resolves.toEqual({});
- });
+it('preserves forge credential exports for existing Git service callers', async () => {
+ const auth = await import('./forgeAuth.js');
+ const git = await import('./git.js');
+ expect(git.resolveForgeTokenEnv).toBe(auth.resolveForgeTokenEnv);
+ expect(git.resolveForgeForRepo).toBe(auth.resolveForgeForRepo);
});
describe('extractAgentSummary', () => {
diff --git a/server/services/taskDataInputs.js b/server/services/taskDataInputs.js
index 433b4411aa..f57f21c7fc 100644
--- a/server/services/taskDataInputs.js
+++ b/server/services/taskDataInputs.js
@@ -12,7 +12,7 @@ import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { DISPATCH_HINT_READING_GUIDANCE } from '../lib/dispatchLabels.js';
import { TASK_DATA_INPUT_DEFINITIONS } from '../lib/taskDataInputCatalog.js';
import { githubApiHost, resolveAppWorkTracker } from '../lib/workTracker.js';
-import { resolveForgeTokenEnv } from './git.js';
+import { resolveForgeTokenEnv } from './forgeAuth.js';
import { execGh } from './github.js';
import { execGlabJson } from './gitlab.js';