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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: resolve repo forge auth for app issue and pull request listings
Adam Eivyafa6d01e9da1
diff --git a/server/services/appIssues.js b/server/services/appIssues.jsindex 04a59913ab..bc48f9e408 100644--- a/server/services/appIssues.js+++ b/server/services/appIssues.js@@ -25,6 +25,7 @@import { execGh, ensureForgeReachable } from './github.js';import { execGlab, execGlabJson } from './gitlab.js';+import { resolveForgeForRepo } from './forgeAuth.js';import { resolveAppForgeTarget } from '../lib/workTracker.js';import { safeJSONParse } from '../lib/fileUtils.js';import { CONTRIBUTOR_LABELS } from '../lib/dispatchLabels.js';@@ -120,8 +121,18 @@ function toIssueResult(rows, normalize) {* stays deterministic. The reachability probe runs first: without it an* unreachable `gh` returns an empty page that reads as "no open issues".*/-async function fetchGithubIssues(repoSpec, apiHost) {- const forge = await ensureForgeReachable('app-issues', { hostname: apiHost });+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 forge = await ensureForgeReachable('app-issues', {+ hostname: apiHost,+ ...(customEnv ? { env: customEnv } : {}),+ });if (!forge.ok) {return { issues: [], reason: `gh-${forge.status}`, transient: true, remedy: forge.remedy || null };}@@ -131,7 +142,7 @@ async function fetchGithubIssues(repoSpec, apiHost) {'issue', 'list', '--repo', repoSpec, '--state', 'open','--limit', String(GH_LIST_LIMIT),'--json', 'number,title,body,labels,assignees,author,milestone,url,updatedAt,comments',- ]).catch((err) => {+ ], undefined, { cwd, env }).catch((err) => {console.error(`❌ app-issues: gh issue list failed for ${repoSpec}: ${err.message}`);return null;});@@ -216,7 +227,7 @@ export async function listAppIssues(app) {if (target.forge !== tracker) return { ...base, tracker, reason: 'tracker-forge-mismatch' };const result = tracker === 'github'- ? await fetchGithubIssues(target.repoSpec, target.apiHost)+ ? await fetchGithubIssues(target.repoSpec, target.apiHost, { repoPath: app.repoPath, forgeAccount: app.forgeAccount }): await fetchGitlabIssues(app.repoPath);return {@@ -240,9 +251,15 @@ 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 readLabels = async () => {const raw = tracker === 'github'- ? await execGh(['issue', 'view', issueNumber, '--repo', target.repoSpec, '--json', 'labels'])+ ? await execGh(['issue', 'view', issueNumber, '--repo', target.repoSpec, '--json', 'labels'], undefined, { cwd, env }): await execGlab(withGlabJson(['issue', 'view', issueNumber]), app.repoPath, undefined, { rejectOnError: true });const issue = safeJSONParse(raw, null);if (!Array.isArray(issue?.labels) || issue.labels.some(label => typeof label !== 'string' && typeof label?.name !== 'string')) {@@ -255,7 +272,7 @@ export async function prepareAppIssueClaim(app, issueNumber, tracker) {if (!labels.length) return;if (tracker === 'github') {await execGh(['issue', 'edit', issueNumber, '--repo', target.repoSpec,- ...labels.flatMap(label => ['--remove-label', label])]);+ ...labels.flatMap(label => ['--remove-label', label])], undefined, { cwd, env });} else {await execGlab(['issue', 'update', issueNumber, '--unlabel', labels.join(',')], app.repoPath, undefined, { rejectOnError: true });}diff --git a/server/services/appIssues.test.js b/server/services/appIssues.test.jsindex 23207aa582..40066aec2c 100644--- a/server/services/appIssues.test.js+++ b/server/services/appIssues.test.js@@ -1,10 +1,14 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));+const resolveForgeForRepoMock = vi.fn(async () => ({ cli: 'gh', env: process.env, account: null }));vi.mock('./github.js', () => ({execGh: vi.fn(async () => '[]'),ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),}));+vi.mock('./forgeAuth.js', () => ({+ resolveForgeForRepo: (...args) => resolveForgeForRepoMock(...args),+}));vi.mock('./gitlab.js', () => ({ execGlab: vi.fn(), execGlabJson: vi.fn(async () => ({ rows: [], reason: 'ok' })) }));// gitRemote is the only effectful dependency of the real forge classifier, so// mock IT and let `resolveRepoForgeTarget` run for real — the github-vs-gitlab@@ -35,6 +39,7 @@ function useGitlabOrigin() {beforeEach(() => {vi.clearAllMocks();ensureForgeReachableMock.mockResolvedValue({ ok: true, status: 'ok', detail: null, remedy: null });+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'gh', env: process.env, account: null });getOriginInfo.mockResolvedValue({ isGithub: true, host: 'github.com', fullName: 'acme/widget' });readOriginRemoteUrl.mockResolvedValue('[email protected]:acme/widget.git');execGh.mockResolvedValue('[]');@@ -142,6 +147,30 @@ describe('listAppIssues — GitHub', () => {expect(result.issues[0].body.length).toBeLessThan(9000);expect(result.issues[0].body).toMatch(/truncated/);});++ it('passes the app-pinned forge account token and repo cwd to gh and reachability check', async () => {+ resolveForgeForRepoMock.mockResolvedValue({+ cli: 'gh',+ env: { ...process.env, GH_TOKEN: 'other-user-token' },+ account: 'other-user',+ });+ execGh.mockResolvedValue('[]');+ await listAppIssues({ ...APP, forgeAccount: 'other-user' });++ expect(resolveForgeForRepoMock).toHaveBeenCalledWith('/repo', { forgeAccount: 'other-user' });+ expect(ensureForgeReachableMock).toHaveBeenCalledWith('app-issues', {+ hostname: 'github.com',+ env: expect.objectContaining({ GH_TOKEN: 'other-user-token' }),+ });+ expect(execGh).toHaveBeenCalledWith(+ expect.arrayContaining(['issue', 'list', '--repo', 'github.com/acme/widget']),+ undefined,+ expect.objectContaining({+ cwd: '/repo',+ env: expect.objectContaining({ GH_TOKEN: 'other-user-token' }),+ }),+ );+ });});describe('listAppIssues — GitLab', () => {@@ -345,4 +374,27 @@ describe('prepareAppIssueClaim', () => {execGh.mockResolvedValue('{"labels":["help wanted"]}');await expect(prepareAppIssueClaim(APP, '42', 'github')).rejects.toThrow('Contributor labels remain');});++ it('passes cwd and repo forge auth env when claiming on GitHub', async () => {+ resolveForgeForRepoMock.mockResolvedValue({+ cli: 'gh',+ env: { ...process.env, GH_TOKEN: 'other-user-token' },+ account: 'other-user',+ });+ execGh.mockResolvedValueOnce(JSON.stringify({ labels: [{ name: 'Help Wanted' }] }))+ .mockResolvedValueOnce('')+ .mockResolvedValueOnce(JSON.stringify({ labels: [] }));++ await prepareAppIssueClaim({ ...APP, forgeAccount: 'other-user' }, '42', 'github');++ expect(resolveForgeForRepoMock).toHaveBeenCalledWith('/repo', { forgeAccount: 'other-user' });+ expect(execGh).toHaveBeenCalledWith(+ ['issue', 'view', '42', '--repo', 'github.com/acme/widget', '--json', 'labels'],+ undefined,+ expect.objectContaining({+ cwd: '/repo',+ env: expect.objectContaining({ GH_TOKEN: 'other-user-token' }),+ }),+ );+ });});diff --git a/server/services/appPullRequests.js b/server/services/appPullRequests.jsindex 79731d2b84..590e03e762 100644--- a/server/services/appPullRequests.js+++ b/server/services/appPullRequests.js@@ -12,6 +12,7 @@import { execGh, ensureForgeReachable } from './github.js';import { execGlabJson } from './gitlab.js';+import { resolveForgeForRepo } from './forgeAuth.js';import { resolveAppForgeTarget } from '../lib/workTracker.js';import { safeJSONParse } from '../lib/fileUtils.js';import { forkHeadFromGithubPr } from '../lib/forkHead.js';@@ -151,8 +152,18 @@ function answeredResult(rows, normalize) {};}-async function fetchGithubPullRequests(repoSpec, apiHost) {- const forge = await ensureForgeReachable('app-pull-requests', { hostname: apiHost });+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 forge = await ensureForgeReachable('app-pull-requests', {+ hostname: apiHost,+ ...(customEnv ? { env: customEnv } : {}),+ });if (!forge.ok) {return {pullRequests: [],@@ -165,7 +176,7 @@ async function fetchGithubPullRequests(repoSpec, apiHost) {const raw = await execGh(['pr', 'list', '--repo', repoSpec, '--state', 'open','--limit', String(GH_LIST_LIMIT), '--json', GH_PR_FIELDS,- ]).catch(err => {+ ], undefined, { cwd, env }).catch(err => {console.error(`❌ app-pull-requests: gh pr list failed for ${repoSpec}: ${err.message}`);return null;});@@ -221,7 +232,7 @@ export async function listAppPullRequests(app) {if (!target) return { ...baseResult, tracker, reason: 'unsupported-forge' };const result = target.forge === 'github'- ? await fetchGithubPullRequests(target.repoSpec, target.apiHost)+ ? await fetchGithubPullRequests(target.repoSpec, target.apiHost, { repoPath: app.repoPath, forgeAccount: app.forgeAccount }): await fetchGitlabPullRequests(app.repoPath);return {diff --git a/server/services/appPullRequests.test.js b/server/services/appPullRequests.test.jsindex 757a8481aa..d39879cbfe 100644--- a/server/services/appPullRequests.test.js+++ b/server/services/appPullRequests.test.js@@ -4,6 +4,10 @@ vi.mock('./github.js', () => ({execGh: vi.fn(),ensureForgeReachable: vi.fn(),}));+const resolveForgeForRepoMock = vi.fn(async () => ({ cli: 'gh', env: process.env, account: null }));+vi.mock('./forgeAuth.js', () => ({+ resolveForgeForRepo: (...args) => resolveForgeForRepoMock(...args),+}));vi.mock('./gitlab.js', () => ({execGlabJson: vi.fn(),}));@@ -20,6 +24,7 @@ const APP = { id: 'app-001', name: 'Widget', repoPath: '/repo', workTracker: 'aubeforeEach(() => {vi.clearAllMocks();+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'gh', env: process.env, account: null });ensureForgeReachable.mockResolvedValue({ ok: true });resolveAppForgeTarget.mockResolvedValue({tracker: 'github',@@ -52,9 +57,13 @@ describe('listAppPullRequests', () => {const result = await listAppPullRequests(APP);expect(ensureForgeReachable).toHaveBeenCalledWith('app-pull-requests', { hostname: 'github.com' });- expect(execGh).toHaveBeenCalledWith(expect.arrayContaining([- 'pr', 'list', '--repo', 'github.com/acme/widget', '--state', 'open', '--limit', '200',- ]));+ expect(execGh).toHaveBeenCalledWith(+ expect.arrayContaining([+ 'pr', 'list', '--repo', 'github.com/acme/widget', '--state', 'open', '--limit', '200',+ ]),+ undefined,+ expect.objectContaining({ cwd: '/repo', env: expect.anything() }),+ );expect(result).toMatchObject({forge: 'github',tracker: 'github',@@ -177,6 +186,30 @@ describe('listAppPullRequests', () => {});});+ it('passes the app-pinned forge account token and repo cwd to gh and reachability check', async () => {+ resolveForgeForRepoMock.mockResolvedValue({+ cli: 'gh',+ env: { ...process.env, GH_TOKEN: 'other-user-token' },+ account: 'other-user',+ });+ execGh.mockResolvedValue('[]');+ await listAppPullRequests({ ...APP, forgeAccount: 'other-user' });++ expect(resolveForgeForRepoMock).toHaveBeenCalledWith('/repo', { forgeAccount: 'other-user' });+ expect(ensureForgeReachable).toHaveBeenCalledWith('app-pull-requests', {+ hostname: 'github.com',+ env: expect.objectContaining({ GH_TOKEN: 'other-user-token' }),+ });+ expect(execGh).toHaveBeenCalledWith(+ expect.arrayContaining(['pr', 'list', '--repo', 'github.com/acme/widget']),+ undefined,+ expect.objectContaining({+ cwd: '/repo',+ env: expect.objectContaining({ GH_TOKEN: 'other-user-token' }),+ }),+ );+ });+it('normalizes GitLab merge-request and pipeline state from the repo cwd', async () => {resolveAppForgeTarget.mockResolvedValue({tracker: 'plan',diff --git a/server/services/forgeAuth.js b/server/services/forgeAuth.jsindex 20e62ae35c..58577b4532 100644--- a/server/services/forgeAuth.js+++ b/server/services/forgeAuth.js@@ -156,7 +156,7 @@ async function getGhCommitIdentity(token, timeoutMs, signal) {* @returns {Promise<{cli: string, env: object, host: string|null, owner: string|null,* account: string|null, identity: {name: string, email: string}|null}>}*/-export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal } = {}) {+export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_TIMEOUT_MS, signal, forgeAccount = null } = {}) {const remote = await execGitSafe(['remote', 'get-url', 'origin'], dir);const parsed = parseGitRemote(remote.stdout?.trim());if (!parsed) {@@ -169,7 +169,8 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_Tif (cli !== 'gh' || signal?.aborted) return ambient;- const pinned = await resolveConfiguredAccount(dir);+ const explicitPin = (typeof forgeAccount === 'string' && forgeAccount.trim()) ? forgeAccount.trim() : null;+ const pinned = explicitPin || await resolveConfiguredAccount(dir);if (signal?.aborted) return ambient;// A pinned account skips the `gh auth status` listing entirely: the user named@@ -186,7 +187,11 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_Tconst identity = pinned ? await getGhCommitIdentity(token, timeoutMs, signal) : null;if (signal?.aborted) return { ...base, account };- return { ...base, env: { ...process.env, GH_TOKEN: token }, account, identity };+ const env = { ...process.env, GH_TOKEN: token };+ delete env.GITHUB_TOKEN;+ delete env.GH_ENTERPRISE_TOKEN;+ delete env.GITHUB_ENTERPRISE_TOKEN;+ return { ...base, env, account, identity };}/**@@ -218,7 +223,7 @@ export async function resolveForgeForRepo(dir, { timeoutMs = DEFAULT_SPAWN_CLI_T* @returns {Promise<{ GH_TOKEN?: string, GIT_AUTHOR_NAME?: string, GIT_AUTHOR_EMAIL?: string,* GIT_COMMITTER_NAME?: string, GIT_COMMITTER_EMAIL?: string }>}*/-export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {+export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000, forgeAccount = null } = {}) {// Keep the whole lookup inside the agent-spawn budget. The shared abort signal// kills whichever gh subprocess is active when the outer budget expires and// prevents a slow git lookup from starting a stale follow-on auth probe. Each@@ -226,7 +231,7 @@ export async function resolveForgeTokenEnv(dir, { timeoutMs = 10000 } = {}) {let timer;const controller = new AbortController();const resolved = await Promise.race([- resolveForgeForRepo(dir, { timeoutMs, signal: controller.signal }).catch(() => null),+ resolveForgeForRepo(dir, { timeoutMs, signal: controller.signal, forgeAccount }).catch(() => null),new Promise((r) => {timer = setTimeout(() => {controller.abort();diff --git a/server/services/forgeAuth.test.js b/server/services/forgeAuth.test.jsindex bcadd2e931..a1034c9309 100644--- a/server/services/forgeAuth.test.js+++ b/server/services/forgeAuth.test.js@@ -231,4 +231,19 @@ describe('per-app forge account pinning', () => {respond({ stdout: 'test-owner-token\n' });await expect(resolveForgeTokenEnv('/example/repo')).resolves.toEqual({ GH_TOKEN: 'test-owner-token' });});++ it('honors explicit forgeAccount option directly and strips conflicting env tokens', async () => {+ vi.stubEnv('GITHUB_TOKEN', 'ambient-github-token');+ vi.stubEnv('GH_ENTERPRISE_TOKEN', 'ambient-enterprise-token');+ respond({ stdout: '[email protected]:example-owner/project.git\n' });+ respond({ stdout: 'direct-account-token\n' });+ respond({ stdout: '9999\tdirect-bot\tDirect Bot\n' });++ const forge = await resolveForgeForRepo('/example/repo', { forgeAccount: 'direct-bot' });+ expect(forge.account).toBe('direct-bot');+ expect(forge.env.GH_TOKEN).toBe('direct-account-token');+ expect(forge.env.GITHUB_TOKEN).toBeUndefined();+ expect(forge.env.GH_ENTERPRISE_TOKEN).toBeUndefined();+ expect(listForgePinnedApps).not.toHaveBeenCalled();+ });});diff --git a/server/services/github.js b/server/services/github.jsindex 21e629f2ba..af55c4e113 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -656,7 +656,7 @@ export function ghRemedy(status) {// host-keying prWatcher's self-login cache already needs.const ghHealthCache = new Map();-function probeGh(timeoutMs, hostname) {+function probeGh(timeoutMs, hostname, env = null) {return new Promise((resolve) => {// `rate_limit` is authenticated, cheap, and — unlike every other endpoint —// does not itself consume quota, so polling this probe is free.@@ -664,7 +664,7 @@ function probeGh(timeoutMs, hostname) {// targets github.com regardless of cwd, so an enterprise repo would be// gated on a host it never talks to.const args = hostname ? ['api', 'rate_limit', '--hostname', hostname] : ['api', 'rate_limit'];- const child = spawn('gh', args, { shell: false });+ const child = spawn('gh', args, { shell: false, ...(env ? { env } : {}) });let stderr = '';let settled = false;const done = (result) => { if (!settled) { settled = true; clearTimeout(timer); resolve(result); } };@@ -685,18 +685,19 @@ function probeGh(timeoutMs, hostname) {* Result is cached per host for a minute — /api/system/health/details is polled,* and the probe spawns a process. Pass `{ force: true }` to bypass the cache.*- * @param {{ force?: boolean, timeoutMs?: number, hostname?: string|null }} [opts]+ * @param {{ force?: boolean, timeoutMs?: number, hostname?: string|null, env?: object|null }} [opts]* `hostname` targets a specific forge host (a GitHub Enterprise install);* omitted means gh's default host.* @returns {Promise<{ status: string, ok: boolean, detail: string|null, remedy: string|null, checkedAt: string }>}*/-export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOUT_MS, hostname = null } = {}) {+export async function checkGhHealth({ force = false, timeoutMs = GH_PROBE_TIMEOUT_MS, hostname = null, env = null } = {}) {const now = Date.now();- const key = hostname || '';+ const token = env?.GH_TOKEN || env?.GITHUB_TOKEN || '';+ const key = `${hostname || ''}#${token}`;const cached = ghHealthCache.get(key);if (!force && cached && (now - cached.at) < GH_HEALTH_TTL_MS) return cached.health;- const { status, detail } = classifyGhProbe(await probeGh(timeoutMs, hostname));+ const { status, detail } = classifyGhProbe(await probeGh(timeoutMs, hostname, env));const health = {status,ok: status === 'ok',@@ -803,8 +804,8 @@ export function __resetGhHealthCache() {* of a host it never contacts (and vice versa).* @returns {Promise<{ ok: boolean, status: string, detail: string|null, remedy: string|null }>}*/-export async function ensureForgeReachable(label, { hostname = null } = {}) {- const health = await checkGhHealth({ hostname }).catch(err => ({+export async function ensureForgeReachable(label, { hostname = null, env = null } = {}) {+ const health = await checkGhHealth({ hostname, env }).catch(err => ({status: 'error', ok: false, detail: err.message, remedy: ghRemedy('error')}));if (health.ok) return health;