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

give spawned CoS agents the repo-owner-matched GH_TOKEN for their own gh calls

[._.]/ Adam Eivy455c0057c433
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cdb20a38db..e777d0dc5c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -43,6 +43,8 @@
## Fixed
+- **CoS agents (notably codex) now open their PR as the gh account that matches the repo owner, not gh's mutable active user.** PortOS's own `createPR` pins `GH_TOKEN` to the logged-in gh account whose login matches the repo owner (avoiding the multi-account "must be a collaborator" failure), but a spawned agent running its *own* `gh pr create` — a codex/Claude/CLI CoS agent finishing `/do:pr` — never received that pinning. TUI agents fared worst: `shell.js`'s `buildSafeEnv` strips `GH_TOKEN` from the inherited env entirely, so their `gh` fell back to whatever `hosts.yml` active user happened to be set. A new best-effort `resolveForgeTokenEnv(dir)` (in `server/services/git.js`) resolves just the owner-matched `GH_TOKEN` overlay and is injected into all three agent-spawn env paths — direct CLI (`spawnDirectly`), TUI shell session (`spawnTuiAgent`), and the CoS runner (`spawnViaRunner`). It's provider-agnostic (no codex special-case), returns `{}` when no owner-matched account exists (so single-account installs and GitLab repos are untouched), and is spread before `provider.envVars` so an explicit provider `GH_TOKEN` override still wins.
+
- **Read-only CoS agents (e.g. reference-watch) on a TUI provider now signal completion via the `.agent-done` sentinel.** The prompt builder's completion decision tree gave every other task shape (reasoning-only, TUI push+PR, CLI) an explicit sentinel instruction, but the `isReadOnly` branch emitted only the bare "Read-Only Task" notice with no sentinel — so a read-only TUI run (reference-watch records its proposals directly in the tracker, then just needs to signal done) never wrote `.agent-done`. The 2s sentinel poll in `spawnTuiAgent` — the primary finalize path and the channel that ingests the run summary — therefore never fired, and the run only completed via the idle-reaper / shell-exit fallback with no clean resolution summary captured. `agentPromptBuilder.js` now routes the read-only branch through a new `buildReadOnlyCompletionSection({ isTui, sentinelPath })` that keeps the do-not-modify guidance and, for TUI agents, appends the write-`.agent-done`-then-stop instruction. CLI/API read-only agents complete on process exit and never poll a sentinel, so they still get the bare notice.
- **Digital Twin Taste questionnaire no longer shows "Question 5 of 3" after follow-ups.** The progress header used total response count (core + follow-ups) as the current question number against a core-only total, so once branching follow-ups fired the counter overran the "of N". It now reports the 1-based index among core questions for that section, so the label stays "Question 2 of 3" even when follow-ups sit between cores.
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 7fa6f78e01..b81d66d2f9 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -29,6 +29,7 @@ import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/ant
import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../lib/grok.js';
import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
+import { resolveForgeTokenEnv } from './git.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
@@ -430,11 +431,15 @@ export async function spawnDirectly({
// Ensure workspacePath is valid
const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
- // For Claude CLI providers, inject ~/.claude/settings.json env vars so Bedrock config
- // (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.) is present even if PM2 lacks them
- const claudeSettingsEnv = isClaudeCliProvider(provider)
- ? await getClaudeSettingsEnv()
- : {};
+ // Two independent async env lookups, resolved together: Claude's
+ // ~/.claude/settings.json Bedrock config (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE,
+ // etc., present even if PM2 lacks them) and the repo-owner-pinned GH_TOKEN
+ // (so the agent's own `gh pr create` auths as the right account — see
+ // resolveForgeTokenEnv; `{}` when there's no owner match).
+ const [claudeSettingsEnv, forgeTokenEnv] = await Promise.all([
+ isClaudeCliProvider(provider) ? getClaudeSettingsEnv() : Promise.resolve({}),
+ resolveForgeTokenEnv(cwd),
+ ]);
// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with
// the models map so --model is accepted (the static env var lacked this).
@@ -443,8 +448,9 @@ export async function spawnDirectly({
// The pm2 shim must be prepended onto the FINAL PATH (after any
// provider.envVars override) so a `--dangerously-skip-permissions` agent
// can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override
- // the static OPENCODE_CONFIG_CONTENT in provider.envVars.
- const childEnv = (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })();
+ // the static OPENCODE_CONFIG_CONTENT in provider.envVars; forgeTokenEnv sits
+ // before provider.envVars so an explicit provider GH_TOKEN override still wins.
+ const childEnv = (() => { const e = { ...process.env, ...forgeTokenEnv, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })();
// Resolve a bare npm-installed CLI (a .cmd/.bat shim on Windows) to its real
// path and wrap a shim as `cmd.exe /c <path>` so spawn() under shell:false
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index cd4d7050dc..7d7c26b6b3 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -45,6 +45,10 @@ vi.mock('./toolStateMachine.js', () => ({
}));
vi.mock('./agentErrorAnalysis.js', () => ({ analyzeAgentFailure: vi.fn().mockResolvedValue(null) }));
vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn().mockResolvedValue(undefined) }));
+// Mock git.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('./agentLifecycle.js', () => ({
finalizeAgent: vi.fn().mockResolvedValue(undefined),
releaseAgentLane: vi.fn(),
@@ -478,6 +482,45 @@ describe('stream error containment', () => {
await spawnPromise.catch(() => {});
});
+ 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');
+ vi.mocked(resolveForgeTokenEnv).mockResolvedValueOnce({ GH_TOKEN: 'ghp_pinned_owner_token' });
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+ await new Promise((r) => setTimeout(r, 10)); // let the resolveForgeTokenEnv await settle
+
+ // Resolved against the workspace dir (the worktree the agent will PR from).
+ expect(resolveForgeTokenEnv).toHaveBeenCalledWith('/tmp');
+ expect(spawn).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ env: expect.objectContaining({ GH_TOKEN: 'ghp_pinned_owner_token' }) }),
+ );
+
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ });
+
+ it('leaves the spawn env\'s ambient GH_TOKEN untouched when there is no owner match', async () => {
+ const { resolveForgeTokenEnv } = await import('./git.js');
+ vi.mocked(resolveForgeTokenEnv).mockResolvedValueOnce({});
+ const prev = process.env.GH_TOKEN;
+ process.env.GH_TOKEN = 'ghp_ambient';
+
+ const spawnPromise = spawnDirectly(minimalArgs);
+ await new Promise((r) => setTimeout(r, 10));
+
+ expect(spawn).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ env: expect.objectContaining({ GH_TOKEN: 'ghp_ambient' }) }),
+ );
+
+ if (prev === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = prev;
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ });
+
describe('initialization timeout — 3-second phase transition', () => {
it('calls updateAgent with working phase after 3s when agent has not started working', async () => {
const { activeAgents } = await import('./agentState.js');
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 2eeab63839..82b0015548 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -32,6 +32,7 @@ import { processAgentCompletion } from './agentCompletion.js';
import { releaseAppReviewMarker } from './appActivity.js';
import { ensureInstanceId } from './instances.js';
import { isClaimableBy, buildClaim, buildRelease, getClaimOwner } from './cosTaskClaim.js';
+import { resolveForgeTokenEnv } from './git.js';
import { runnerAgents, pausedAgents, spawningTasks, useRunner, isTruthyMeta } from './agentState.js';
import { v4 as uuidv4 } from '../lib/uuid.js';
@@ -628,10 +629,14 @@ export async function spawnViaRunner(agentId, task, opts) {
}
}, 3000);
- // For Claude CLI providers, merge ~/.claude/settings.json env vars so Bedrock config is present
- const claudeSettingsEnv = isClaudeCliProvider(provider)
- ? await getClaudeSettingsEnv()
- : {};
+ // Two independent async env lookups, resolved together: Claude's
+ // ~/.claude/settings.json Bedrock config, and the repo-owner-pinned GH_TOKEN
+ // (so the runner-spawned agent's own `gh pr create` auths as the right
+ // account — see resolveForgeTokenEnv; `{}` when there's no owner match).
+ const [claudeSettingsEnv, forgeTokenEnv] = await Promise.all([
+ isClaudeCliProvider(provider) ? getClaudeSettingsEnv() : Promise.resolve({}),
+ resolveForgeTokenEnv(workspacePath),
+ ]);
// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with the
// models map so the injected `--model ollama/<id>` is accepted (empty/no-op
@@ -647,7 +652,8 @@ export async function spawnViaRunner(agentId, task, opts) {
prompt,
workspacePath,
model,
- envVars: { ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv },
+ // forgeTokenEnv before provider.envVars so an explicit provider override wins.
+ envVars: { ...forgeTokenEnv, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv },
cliCommand: cliConfig.command,
cliArgs: cliConfig.args
});
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index e4a0c01a7c..8acaebdb15 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -778,6 +778,20 @@ describe('agentLifecycle — runner OpenCode Ollama env (#2243 / #2190)', () =>
expect(fnBody.indexOf('...opencodeEnv'), 'opencodeEnv must be spread AFTER provider.envVars so it overrides the static config')
.toBeGreaterThan(fnBody.indexOf('...provider.envVars'));
});
+
+ it('source: spawnViaRunner pins GH_TOKEN via resolveForgeTokenEnv so the runner-spawned agent\'s `gh` uses the repo-owner account', () => {
+ // The direct and TUI spawn paths inject the owner-matched GH_TOKEN; the
+ // runner path must too, or a codex/CLI agent under the runner opens its PR
+ // as gh's mutable active-user (the multi-account "must be a collaborator"
+ // failure). Assert the resolve+spread exists inside spawnViaRunner.
+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnViaRunner');
+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 4000);
+ expect(fnBody).toContain('resolveForgeTokenEnv(workspacePath)');
+ expect(fnBody).toMatch(/envVars:\s*\{[^}]*\.\.\.forgeTokenEnv[^}]*\}/);
+ // forgeTokenEnv before provider.envVars so an explicit provider GH_TOKEN wins.
+ expect(fnBody.indexOf('...forgeTokenEnv'), 'forgeTokenEnv must be spread BEFORE provider.envVars')
+ .toBeLessThan(fnBody.indexOf('...provider.envVars'));
+ });
});
// ─── handleAgentCompletion error recovery ──────────────────────────────────
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index d34d761299..73b6d61ef2 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -180,7 +180,7 @@ const DONE_POLL_INTERVAL_MS = 2000;
* to create the session, `sessionId` is null and the caller is expected
* to bail out via its `finish` path.
*/
-export function createAgentTuiSession({ agentId, provider, model, tuiConfig, cwd, onData, onExit, onInitialCommandSent }) {
+export function createAgentTuiSession({ agentId, provider, model, tuiConfig, cwd, forgeTokenEnv = {}, onData, onExit, onInitialCommandSent }) {
// For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with
// the models map so --model is accepted (the static env var lacked this).
const opencodeEnv = buildOpencodeEnvVars(provider, model);
@@ -204,7 +204,9 @@ export function createAgentTuiSession({ agentId, provider, model, tuiConfig, cwd
// points it at the real pm2). Spread LAST so it wins over any provider PATH.
// Only AI agent sessions get this — the user's own Shell page does not.
// opencodeEnv comes after provider.envVars to override the static config.
- env: { ...(provider.envVars || {}), ...opencodeEnv, ...agentGuardEnv() },
+ // forgeTokenEnv is threaded in explicitly because buildSafeEnv strips
+ // GH_TOKEN from the inherited env (see resolveForgeTokenEnv).
+ env: { ...(provider.envVars || {}), ...opencodeEnv, ...forgeTokenEnv, ...agentGuardEnv() },
onData,
onExit,
});
@@ -798,12 +800,17 @@ export async function spawnTuiAgent({
});
};
+ // Repo-owner-pinned GH_TOKEN for the agent's own `gh pr create` (see
+ // resolveForgeTokenEnv). Resolved here since createAgentTuiSession is sync.
+ const forgeTokenEnv = await git.resolveForgeTokenEnv(cwd);
+
const session = createAgentTuiSession({
agentId,
provider,
model,
tuiConfig,
cwd,
+ forgeTokenEnv,
onData: handleData,
onExit: handleExit,
onInitialCommandSent: () => { commandInjected = true; },
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 0334b2c79b..a6c44646f5 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -75,6 +75,8 @@ vi.mock('./git.js', () => ({
// to exercise the idle-no-changes failure path override via mockResolvedValueOnce.
getStatus: vi.fn().mockResolvedValue({ clean: false, files: [{ path: 'file.txt', status: 'M' }] }),
getDiff: vi.fn().mockResolvedValue('diff content here'),
+ // No owner-matched gh account by default → empty overlay (ambient auth kept).
+ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}),
}));
vi.mock('fs', () => ({
@@ -422,6 +424,28 @@ describe('spawnTuiAgent runtime', () => {
// arguments handed to `finalizeAgent`, not the downstream individual
// calls — those are covered by agentLifecycle.test.js.
+ // ── GH_TOKEN pinning: the agent's own `gh pr create` must auth as the repo owner ─
+ it('passes the repo-owner-pinned GH_TOKEN into the TUI session env (buildSafeEnv would otherwise strip it)', async () => {
+ let resolveComplete;
+ const completeDone = new Promise((r) => { resolveComplete = r; });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
+ vi.mocked(gitService.resolveForgeTokenEnv).mockResolvedValueOnce({ GH_TOKEN: 'ghp_pinned_owner_token' });
+
+ runSpawn({ workspacePath: '/tmp/ws' });
+ await flushMicrotasks();
+
+ // Resolved against the agent's workspace and folded into the session env.
+ expect(gitService.resolveForgeTokenEnv).toHaveBeenCalledWith('/tmp/ws');
+ expect(shellService.createShellSession).toHaveBeenCalledWith(
+ null,
+ expect.objectContaining({ env: expect.objectContaining({ GH_TOKEN: 'ghp_pinned_owner_token' }) }),
+ );
+
+ // Drive the shell-exit path so the completion chain settles and no timer leaks.
+ await capturedOnExit({ exitCode: 0, killed: false });
+ await completeDone;
+ });
+
// ── 1. Successful idle-complete path ────────────────────────────────────────
it('idle-complete: calls finalizeAgent(success:true) with completionReason=idle-complete when idle fires after enough output and runtime', async () => {
// Wire finalizeAgent to resolve a promise we can await, so we can detect
diff --git a/server/services/git.js b/server/services/git.js
index cb788aa737..27ac10443f 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -353,6 +353,32 @@ export async function resolveForgeForRepo(dir) {
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 repo-owner-matched account and token were
+ * found; otherwise `{}` so the child keeps whatever gh auth it would have used.
+ * Best-effort: never throws, so a spawn is never blocked by remote/auth probes.
+ * @param {string} dir - Repo (or worktree) root
+ * @returns {Promise<{ GH_TOKEN?: string }>}
+ */
+export async function resolveForgeTokenEnv(dir) {
+ const resolved = await resolveForgeForRepo(dir).catch(() => null);
+ // Only overlay when an owner-matched account was actually picked — the
+ // no-match branches of resolveForgeForRepo return the ambient env verbatim,
+ // and re-setting the ambient GH_TOKEN would be a meaningless no-op.
+ const token = resolved?.account ? 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 83a3859188..eb092d6ef0 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 } from './git.js';
+import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner, parseGitRemote, detectForgeCli, parsePullRequestUrl, requestCopilotReview, resolveForgeTokenEnv } from './git.js';
describe('parseGitRemote', () => {
it('parses GitHub SSH urls', () => {
@@ -210,6 +210,17 @@ 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({});
+ });
+});
+
describe('extractAgentSummary', () => {
it('returns null for short output', () => {
expect(extractAgentSummary(null)).toBeNull();