The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness Team account: its own gh, and commits by the app's bot account
bitcoinbuilder05f44dfffbd1
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.tsindex 8288937ef..ca1df91af 100644--- a/backend/integration/superTabGithub.test.ts+++ b/backend/integration/superTabGithub.test.ts@@ -62,7 +62,9 @@ async function fresh(options: { github?: boolean; approveAll?: boolean; signIn?:app.addHook('onRequest', async (request, reply) => {// GitHub sends a person back here without a Harness token, as the server's own gate lets it (authMiddleware.ts).if (request.url.startsWith('/api/github/callback')) return- const user = users.find(u => `Bearer ${u.sub}` === request.headers.authorization)+ // `x-test-team` signs in as that person's Harness Team account, where one is listed.+ const team = request.headers['x-test-team'] === '1'+ const user = users.find(u => `Bearer ${u.sub}` === request.headers.authorization && (u.harnessSessionKind === 'team') === team)if (!user) return reply.code(401).send({ success: false })request.user = user})@@ -118,6 +120,8 @@ describe('the GitHub token endpoint', () => {const minted = env.github.calls.find(c => c.path === '/app/installations/91/access_tokens')!expect(minted.body).toEqual({ repositories: ['app'],permissions: { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read' } })+ // A person's machine keeps its owner's git identity: the app's is for a Harness Team account.+ expect(data).not.toHaveProperty('commitAs')// The same task gets the same token back.expect((await ask(env, tab, worker)).json().data.token).toBe('ghs_fixture_1')// The tab tells a Lead's start that this server has the app.@@ -125,6 +129,30 @@ describe('the GitHub token endpoint', () => {expect(read.json().data.githubApp).toBe(true)})+ // A Harness Team account has no git identity of its own (PR #1934, 2026-10-28): its commits are the app's bot account's.+ it('names the app\'s bot account as who a Harness Team account\'s commits are by', async () => {+ const env = await fresh()+ const { tab, worker } = await working(env)+ const computerId = createHash('sha256').update('gh-host').digest('hex').slice(0, 32)+ await db.machine.update({ where: { machineId: 'gh-host' }, data: { computerId, sessionKind: 'team' } })+ onTestFinished(async () => { await db.machine.update({ where: { machineId: 'gh-host' }, data: { computerId: null, sessionKind: null } }) })+ const team: AuthUser = { ...host, sub: host.sub, harnessSessionId: 'team-gh-host', harnessSessionKind: 'team', harnessComputerId: computerId }+ users.push(team)+ onTestFinished(() => { users.splice(users.indexOf(team), 1) })+ const response = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/github-token?asAgentId=${worker}`,+ headers: { authorization: `Bearer ${host.sub}`, 'x-test-team': '1' }, payload: { machineId: 'gh-host' } })+ expect(response.statusCode, response.body).toBe(200)+ expect(response.json().data.commitAs).toEqual({ name: 'harness-fixture[bot]', email: '4242+harness-fixture[bot]@users.noreply.github.com' })+ // GitHub not saying who the bot is leaves it out, and the token is still given.+ const other = await fresh()+ other.github.control.botId = null+ const second = await working(other)+ const again = await other.app.inject({ method: 'POST', url: `/api/super-tabs/${second.tab}/github-token?asAgentId=${second.worker}`,+ headers: { authorization: `Bearer ${host.sub}`, 'x-test-team': '1' }, payload: { machineId: 'gh-host' } })+ expect(again.json().data).toMatchObject({ token: expect.any(String) })+ expect(again.json().data).not.toHaveProperty('commitAs')+ })+it('warns, but still gives the token, when the default branch does not require a pull request; and says when it does', async () => {const env = await fresh()const { tab, worker } = await working(env)diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.tsindex 3de612778..51eeb4341 100644--- a/backend/src/github/app.test.ts+++ b/backend/src/github/app.test.ts@@ -150,6 +150,33 @@ describe('installation tokens', () => {expect(app.notInstalled(repo).message).toBe('The Harness GitHub App is not installed on acme/app. Ask an owner of acme to install it.')})+ // A Harness Team account's commits are the app's (PR #1934): its bot account, as GitHub names it.+ it('names the app\'s bot account as its commit identity, reading the bot\'s id once', async () => {+ const { app, github } = setup()+ expect(await app.commitIdentity()).toEqual({ name: 'harness-fixture[bot]', email: '4242+harness-fixture[bot]@users.noreply.github.com' })+ expect(await app.commitIdentity()).toEqual({ name: 'harness-fixture[bot]', email: '4242+harness-fixture[bot]@users.noreply.github.com' })+ const asked = github.calls.filter(c => c.path.startsWith('/users/'))+ expect(asked).toEqual([expect.objectContaining({ method: 'GET', path: '/users/harness-fixture%5Bbot%5D', auth: '' })])+ // With no app name configured, the app's own answer names it.+ const unnamed = setup({ slug: null })+ expect(await unnamed.app.commitIdentity()).toMatchObject({ name: 'harness-fixture[bot]' })+ expect(unnamed.github.calls.map(c => c.path)).toEqual(['/app', '/users/harness-fixture%5Bbot%5D'])+ })++ it('has no commit identity while GitHub cannot say, and asks again ten minutes later', async () => {+ const { app, github, time } = setup()+ github.control.botId = null+ expect(await app.commitIdentity()).toBeNull()+ github.control.botId = 4242+ expect(await app.commitIdentity()).toBeNull()+ time.advance(10 * 60_000)+ github.control.down = true+ expect(await app.commitIdentity()).toBeNull()+ github.control.down = false+ time.advance(10 * 60_000)+ expect(await app.commitIdentity()).toMatchObject({ email: '4242+harness-fixture[bot]@users.noreply.github.com' })+ })+it('revokes a token with the token itself, takes one already ended as done, and reports any other failure', async () => {const { app, github } = setup()const { token } = await app.createToken(77, repo)diff --git a/backend/src/github/app.ts b/backend/src/github/app.tsindex 90c433c7e..9034f4f93 100644--- a/backend/src/github/app.ts+++ b/backend/src/github/app.ts@@ -74,6 +74,10 @@ const NOT_INSTALLED_TTL_MS = 60_000const REFRESH_MS = 15_000const BRANCH_TTL_MS = 10 * 60_000const REQUEST_TIMEOUT_MS = 10_000+const IDENTITY_RETRY_MS = 10 * 60_000++/** A git author and committer. */+export interface CommitIdentity { name: string; email: string }export interface GitHubAppOptions {fetch?: typeof fetch@@ -87,6 +91,8 @@ export class GitHubApp {private readonly now: () => numberprivate readonly apiUrl: stringprivate signed: { jwt: string; until: number } | null = null+ /** The app's commit identity once read; a failed read is asked again after [IDENTITY_RETRY_MS]. */+ private identity: { value: CommitIdentity | null; until: number } | null = nullprivate readonly installations = new Map<string, { id: number | null; until: number }>()private readonly branches = new Map<string, { value: DefaultBranch; until: number }>()/** A repository's name now, by the name asked for (lower case): null when it was not renamed. */@@ -105,6 +111,38 @@ export class GitHubApp {return this.config.slug ? `https://github.com/apps/${this.config.slug}/installations/new` : null}+ /**+ * Who the app's commits are by: its bot account as GitHub names it (`<slug>[bot]`, `<id>+<slug>[bot]@users.noreply.github.com`),+ * so a commit made with the app's token shows the app, not the made-up address of the machine account that ran git. A Harness+ * Team account has no git identity of its own, so its commits read "Harness Team <harnessteam@<host>.local>", unverified and+ * linked to nobody (PR #1934, 2026-10-28). Read once and kept; null while GitHub cannot say, asked again ten minutes later.+ */+ async commitIdentity(): Promise<CommitIdentity | null> {+ if (this.identity && (this.identity.value || this.identity.until > this.now())) return this.identity.value+ let value: CommitIdentity | null = null+ try {+ let slug = this.config.slug+ if (!slug) {+ const app = await this.call('GET', '/app', `Bearer ${this.jwt()}`)+ const named = (app.body as { slug?: unknown }).slug+ slug = app.status === 200 && typeof named === 'string' && /^[a-z0-9-]{1,100}$/.test(named) ? named : null+ }+ if (slug) {+ const login = `${slug}[bot]`+ // Public: the app's own JWT is not accepted here, and the bot's id is no secret.+ const user = await this.call('GET', `/users/${encodeURIComponent(login)}`, null)+ const id = (user.body as { id?: unknown }).id+ if (user.status === 200 && typeof id === 'number' && Number.isSafeInteger(id) && id > 0) {+ value = { name: login, email: `${id}+${login}@users.noreply.github.com` }+ }+ }+ } catch (error) {+ if (!(error instanceof GitHubAppError)) throw error+ }+ this.identity = { value, until: this.now() + IDENTITY_RETRY_MS }+ return value+ }+/** The app's own JWT (RS256, ten minutes at most): issued a minute back against clock drift, valid nine minutes, and* reused until a minute before it ends. */jwt(): string {@@ -118,13 +156,13 @@ export class GitHubApp {return jwt}- private async call(method: string, path: string, auth: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> | unknown[] }> {+ private async call(method: string, path: string, auth: string | null, body?: unknown): Promise<{ status: number; body: Record<string, unknown> | unknown[] }> {let response: Responsetry {response = await this.fetch(`${this.apiUrl}${path}`, {method, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),headers: { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'harness-backend',- Authorization: auth, ...(body ? { 'Content-Type': 'application/json' } : {}) },+ ...(auth ? { Authorization: auth } : {}), ...(body ? { 'Content-Type': 'application/json' } : {}) },...(body ? { body: JSON.stringify(body) } : {}),})} catch {diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.tsindex ec4dc4690..137648abb 100644--- a/backend/src/github/fakeGitHub.ts+++ b/backend/src/github/fakeGitHub.ts@@ -28,7 +28,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const issued = new Set<string>()const revoked: string[] = []let minted = 0- const control = { revokeStatus: 204, tokenStatus: 201 as number, tokenMessage: '', down: false }+ const control = { revokeStatus: 204, tokenStatus: 201 as number, tokenMessage: '', down: false, botId: 4242 as number | null }const json = (status: number, body?: unknown) => new Response(body === undefined ? null : JSON.stringify(body), { status })const jwtValid = (auth: string) => {const jwt = auth.replace(/^Bearer /, '')@@ -57,6 +57,14 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:const id = owners.get(match[1]!.toLowerCase())return id === undefined ? json(404, { message: 'Not Found' }) : json(200, { id })}+ if (method === 'GET' && url.pathname === '/app') {+ if (!jwtValid(auth)) return json(401, { message: 'Bad credentials' })+ return json(200, { slug: 'harness-fixture' })+ }+ if (method === 'GET' && (match = /^\/users\/([^/]+)$/.exec(url.pathname))) {+ const login = decodeURIComponent(match[1]!)+ return control.botId && login.endsWith('[bot]') ? json(200, { login, id: control.botId }) : json(404, { message: 'Not Found' })+ }if (method === 'POST' && (match = /^\/app\/installations\/(\d+)\/access_tokens$/.exec(url.pathname))) {if (!jwtValid(auth)) return json(401, { message: 'Bad credentials' })if (control.tokenStatus !== 201) return json(control.tokenStatus, { message: control.tokenMessage })diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 21a8cc8b2..f9e9d33c6 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -346,7 +346,10 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su}await requireApproval(req.user!, grant, repository)const issued = await github.issue({ tabId: grant.tabId, agentId: grant.agentId, assignmentId: grant.assignmentId, repository })- return { ...issued, ...attribution(grant) }+ // A Harness Team account has no git identity of its own: its commits are the app's, as its pull requests are+ // (github/app.ts commitIdentity). A person's machine keeps its owner's, as before.+ const commitAs = isTeamSession(req.user) ? await github.app.commitIdentity() : null+ return { ...issued, ...attribution(grant), ...(commitAs ? { commitAs } : {}) }}))app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof operation> }>('/api/super-tabs/:tabId/commands',{ preHandler: [validateParams(tabParams), validateBody(operation, { named: true })] },diff --git a/cli/src/lib/swarmGitHub.spec.ts b/cli/src/lib/swarmGitHub.spec.tsindex 6e50f4b1d..8a7754b6d 100644--- a/cli/src/lib/swarmGitHub.spec.ts+++ b/cli/src/lib/swarmGitHub.spec.ts@@ -186,6 +186,33 @@ describe('a session\'s gh login and trailers', () => {writeSessionGitHub(dir, 'not a token\n oauth_token: other')expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')})++ // A Harness Team account has no git identity: its commits read "Harness Team <harnessteam@<host>.local>" (PR #1934).+ it('makes the session\'s commits the app\'s when the server names its bot account, and git\'s own otherwise', () => {+ const dir = fresh('identity')+ // git as the session runs it: no identity in the environment, only what its config says.+ const env = { PATH: process.env.PATH!, HOME: home, GIT_CONFIG_NOSYSTEM: '1',+ GIT_CONFIG_PARAMETERS: gitConfigParameters('/no/helper', join(dir, 'hooks'), join(dir, 'gitconfig')) }+ const vars = (name: string) => spawnSync('git', ['var', name], { cwd: dir, encoding: 'utf8', env }).stdout+ writeFileSync(join(home, '.gitconfig'), '[user]\n\tname = Owner\n\temail = [email protected]\n')+ const ident = () => vars('GIT_AUTHOR_IDENT')+ expect(ident()).toMatch(/^Owner <owner@example\.com> /)+ const bot = { name: 'harness-for-autonomous[bot]', email: '245891234+harness-for-autonomous[bot]@users.noreply.github.com' }+ writeSessionGitHub(dir, 'ghs_fixtureToken0000001', [], bot)+ expect(statSync(join(dir, 'gitconfig')).mode & 0o777).toBe(0o600)+ expect(ident()).toMatch(/^harness-for-autonomous\[bot\] <245891234\+harness-for-autonomous\[bot\]@users\.noreply\.github\.com> /)+ expect(vars('GIT_COMMITTER_IDENT')).toMatch(/^harness-for-autonomous\[bot\] </)+ // A refusal keeps it; an answer without one (an older server, a person's machine) or with anything else drops it.+ writeSessionGitHub(dir, null)+ expect(ident()).toMatch(/^harness-for-autonomous\[bot\] </)+ for (const other of [null, { name: 'Mallory', email: '[email protected]' }, { ...bot, name: 'x[bot]\n[core]' }, 'bot']) {+ writeSessionGitHub(dir, 'ghs_fixtureToken0000001', [], bot)+ writeSessionGitHub(dir, 'ghs_fixtureToken0000001', [], other)+ expect(existsSync(join(dir, 'gitconfig'))).toBe(false)+ expect(ident()).toMatch(/^Owner </)+ }+ rmSync(join(home, '.gitconfig'))+ })})describe('a Swarm session\'s launch', () => {@@ -194,7 +221,7 @@ describe('a Swarm session\'s launch', () => {const launch = swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'linux')!const dir = swarmGitHubSessionDir(dataDir, 'harness-codex-abc')!expect(launch.env).toEqual({- GIT_CONFIG_PARAMETERS: gitConfigParameters(join(dataDir, 'swarm-github', 'bin', 'git-credential'), join(dataDir, 'swarm-github', 'hooks')),+ GIT_CONFIG_PARAMETERS: gitConfigParameters(join(dataDir, 'swarm-github', 'bin', 'git-credential'), join(dataDir, 'swarm-github', 'hooks'), join(dir, 'gitconfig')),GIT_TERMINAL_PROMPT: '0', GH_CONFIG_DIR: join(dir, 'gh'), GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', HARNESS_SWARM_GITHUB_DIR: dir,})expect(launch.clearEnv).toEqual(['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'])diff --git a/cli/src/lib/swarmGitHub.ts b/cli/src/lib/swarmGitHub.tsindex ca5125e31..f8114e885 100644--- a/cli/src/lib/swarmGitHub.ts+++ b/cli/src/lib/swarmGitHub.ts@@ -16,7 +16,7 @@** The variable `GIT_CONFIG_KEY_n` is not used: Codex leaves out of its commands every variable whose name contains KEY.*/-import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { env } from '../config/env.js'import { daemonCommand } from './daemonCommand.js'@@ -42,8 +42,9 @@ export function swarmGitHubSessionDir(dataDir: string, key: string): string | nureturn SESSION_KEY.test(key) ? join(swarmGitHubRoot(dataDir), 'sessions', key) : null}-/** What git reads for the session (see the file comment). */-export function gitConfigParameters(helper: string, hooks: string): string {+/** What git reads for the session (see the file comment). [identity]: the session's own config file, which names who its+ * commits are by once the server says (writeSessionGitHub); git skips an include whose file is not there. */+export function gitConfigParameters(helper: string, hooks: string, identity?: string): string {const entries: Array<[string, string]> = [// An empty helper empties the list of helpers read so far, from every config file: only Harness's is left.['credential.https://github.com.helper', ''],@@ -53,6 +54,7 @@ export function gitConfigParameters(helper: string, hooks: string): string {['url.https://github.com/.insteadof', '[email protected]:'],['url.https://github.com/.insteadof', 'ssh://[email protected]/'],['core.hookspath', hooks],+ ...(identity ? [['include.path', identity] as [string, string]] : []),]return entries.map(([key, value]) => `${shellWord(key)}=${shellWord(value)}`).join(' ')}@@ -164,8 +166,14 @@ const GH_CONFIG = 'version: "1"\n'* among them, and nothing that could break out of the YAML around it or a shell. */const TOKEN = /^[A-Za-z0-9_][A-Za-z0-9_.-]{19,4095}$/-/** The session's gh login: [token] for github.com, or none. And, when given, the trailers its commits get. */-export function writeSessionGitHub(dir: string, token: string | null, trailers?: readonly string[]): void {+/** Who a session's commits are by, as the server names the Harness GitHub App's bot account; nothing else is written. */+const COMMIT_NAME = /^[a-z0-9][a-z0-9-]{0,99}\[bot\]$/+const COMMIT_EMAIL = /^[0-9]{1,20}\+[a-z0-9][a-z0-9-]{0,99}\[bot\]@users\.noreply\.github\.com$/++/** The session's gh login: [token] for github.com, or none. And, when given, the trailers its commits get and who they are+ * by ([commitAs]: the app's bot account, which the server gives a Harness Team account, as it has no git identity of its+ * own: its commits read "Harness Team <harnessteam@<host>.local>" before, PR #1934). Without one, git's own stands. */+export function writeSessionGitHub(dir: string, token: string | null, trailers?: readonly string[], commitAs?: unknown): void {const gh = join(dir, 'gh')mkdirSync(gh, { recursive: true, mode: 0o700 })if (!existsSync(join(gh, 'config.yml'))) writeIfChanged(join(gh, 'config.yml'), GH_CONFIG, 0o600)@@ -177,6 +185,13 @@ export function writeSessionGitHub(dir: string, token: string | null, trailers?:const lines = trailers.filter(line => /^[A-Za-z][A-Za-z0-9-]*: [^\r\n]+$/.test(line) && line.length <= 300)writeIfChanged(join(dir, 'trailers'), lines.map(line => `${line}\n`).join(''), 0o600)}+ if (commitAs !== undefined) {+ const { name, email } = (commitAs && typeof commitAs === 'object' ? commitAs : {}) as { name?: unknown; email?: unknown }+ const file = join(dir, 'gitconfig')+ if (typeof name === 'string' && COMMIT_NAME.test(name) && typeof email === 'string' && COMMIT_EMAIL.test(email)) {+ writeIfChanged(file, `[user]\n\tname = ${name}\n\temail = ${email}\n`, 0o600)+ } else rmSync(file, { force: true })+ }}/**@@ -192,7 +207,7 @@ export function swarmGitHubLaunch(key: string, tools: SwarmGitHubTools = defaultif (!existsSync(join(dir, 'gh', 'hosts.yml'))) writeSessionGitHub(dir, null)return {env: {- GIT_CONFIG_PARAMETERS: gitConfigParameters(helper, hooks),+ GIT_CONFIG_PARAMETERS: gitConfigParameters(helper, hooks, join(dir, 'gitconfig')),// A credential the helper cannot give fails at once instead of waiting on a prompt nobody answers in an agent's pane.GIT_TERMINAL_PROMPT: '0',GH_CONFIG_DIR: join(dir, 'gh'),diff --git a/cli/src/superTabs/github.ts b/cli/src/superTabs/github.tsindex 85c29275a..c9913889e 100644--- a/cli/src/superTabs/github.ts+++ b/cli/src/superTabs/github.ts@@ -53,7 +53,7 @@ export async function githubToken(core: CoreApi, harnessId: string, sources: Swaif (typeof value.token !== 'string' || typeof value.repository !== 'string') {throw new SuperTabHostError('GITHUB_UNAVAILABLE', 'The Harness server answered without a token.', 502)}- if (dir) writeSessionGitHub(dir, value.token, Array.isArray(value.trailers) ? value.trailers.filter(t => typeof t === 'string') : [])+ if (dir) writeSessionGitHub(dir, value.token, Array.isArray(value.trailers) ? value.trailers.filter(t => typeof t === 'string') : [], value.commitAs ?? null)return { ok: true, value: { ...value, tabId, agentId } }} catch (error) {if (!(error instanceof SuperTabHostError)) throw errordiff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 4a9a140fa..60494b8ed 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -24,6 +24,7 @@ import { readTeamStatus } from '../team/privacy.js'import { ensureTeamTmux, TMUX_MANIFEST_URL, tmuxRunsAt, untarGz, type TeamTmuxDeps, type TeamTmuxOutcome } from '../team/tmux.js'import { downloadVerified } from '../lib/selfUpdate.js'import { managedTmuxPath, tmuxInstallDirectories } from '../lib/tmuxOnPath.js'+import { ensureTeamGh, ghRunsAt, unzipArchive, type TeamGhDeps, type TeamGhOutcome } from '../team/gh.js'import { env as appEnv } from '../config/env.js'import { homedir, userInfo } from 'node:os'import { delimiter, isAbsolute, join } from 'node:path'@@ -205,6 +206,8 @@ export interface SuperTabServiceOptions {team?: () => boolean/** The Harness Team account's own tmux (team/tmux.ts), for a spec. */teamTmux?: () => Promise<TeamTmuxOutcome>+ /** What installs the Harness Team account's own gh (team/gh.ts), for a spec. */+ teamGh?: () => Promise<TeamGhOutcome>/** The owner's subscriptions for the Harness Team account (team/relay.ts), for a spec. */teamRelay?: () => Pick<TeamRelayPublisher, 'start' | 'stop'>}@@ -257,14 +260,21 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =// A team account still on a build that cannot use the relay is updated from here (team/refresh.ts).(publishedAt) => refreshTeamAccount(realTeamRefreshDeps(core, publishedAt)))))()let autoSetup: Promise<Pick<TeamAutoSetup, 'offer' | 'decline'>> | null = null- // In the Harness Team account: a tmux of its own when it has none it can run (team/tmux.ts). Looked at as it connects,- // and a failed install again half an hour later.- let tmuxCheckedAt = -Infinity+ // In the Harness Team account: a tmux and a gh of its own when it has none it can run (team/tmux.ts, team/gh.ts). Looked+ // at as it connects, and a failed install again half an hour later.+ const settled = (outcome: string) => outcome === 'present' || outcome === 'installed' || outcome === 'not-team'+ let tmuxCheckedAt = -Infinity, ghCheckedAt = -Infinityconst ensureTmux = options.teamTmux ?? (() => ensureTeamTmux(realTeamTmuxDeps()))+ const ensureGh = options.teamGh ?? (() => ensureTeamGh(realTeamGhDeps()))const checkTmux = () => {- if (Date.now() - tmuxCheckedAt < 30 * 60_000) return- tmuxCheckedAt = Date.now()- void ensureTmux().then(outcome => { if (outcome === 'present' || outcome === 'installed' || outcome === 'not-team') tmuxCheckedAt = Infinity })+ if (Date.now() - tmuxCheckedAt >= 30 * 60_000) {+ tmuxCheckedAt = Date.now()+ void ensureTmux().then(outcome => { if (settled(outcome)) tmuxCheckedAt = Infinity })+ }+ if (Date.now() - ghCheckedAt >= 30 * 60_000) {+ ghCheckedAt = Date.now()+ void ensureGh().then(outcome => { if (settled(outcome)) ghCheckedAt = Infinity })+ }}const disconnect = () => { preparations.clear(); host?.stop(); host = null; held = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null; tokens.stop(); engines.stop() }const port = {@@ -545,6 +555,24 @@ function realTeamTmuxDeps(): TeamTmuxDeps {}}+/** The team daemon's own, as for its tmux: its account, its PATH and Homebrew's places (team/gh.ts). */+function realTeamGhDeps(): TeamGhDeps {+ const binDir = join(homedir(), '.local', 'bin')+ return {+ team: () => { try { return readTeamConfig()?.user === userInfo().username } catch { return false } },+ platform: process.platform,+ arch: process.arch,+ candidates: () => [binDir, ...(process.env.PATH ?? '').split(delimiter).filter(isAbsolute), '/opt/homebrew/bin', '/usr/local/bin']+ .map(dir => join(dir, 'gh')).filter(path => existsSync(path)),+ runs: ghRunsAt,+ download: (build) => downloadVerified({ url: build.url, sha256: build.sha256, size: build.size }),+ unzip: unzipArchive,+ runtimeDir: appEnv.ADAPTER_RUNTIME_DIR,+ binDir,+ log: (line) => console.log(`[team] ${line}`),+ }+}+/** The owner's daemon's own: its account's machine list, and the link to its Mac's team account (team/refresh.ts). */function realTeamRefreshDeps(core: CoreApi, publishedAt: number | null): TeamRefreshDeps {const file = teamRefreshFile(core.dataDir)diff --git a/cli/src/team/gh.spec.ts b/cli/src/team/gh.spec.tsnew file mode 100644index 000000000..a2fce12ae--- /dev/null+++ b/cli/src/team/gh.spec.ts@@ -0,0 +1,77 @@+import { execFileSync } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { ensureTeamGh, GH_BUILDS, ghRunsAt, unzipArchive, type TeamGhDeps } from './gh.js'++const cleanup: string[] = []+afterEach(() => { for (const dir of cleanup.splice(0)) rmSync(dir, { recursive: true, force: true }) })+const temp = (prefix: string) => { const dir = mkdtempSync(join(tmpdir(), prefix)); cleanup.push(dir); return dir }++/** A .zip holding [root]/bin/gh, as GitHub's release is laid out, made with the system's ditto. */+function archive(root: string, withBinary = true): Buffer {+ const dir = temp('gh-archive-')+ mkdirSync(join(dir, root, 'bin'), { recursive: true })+ if (withBinary) writeFileSync(join(dir, root, 'bin', 'gh'), '#!/bin/sh\necho gh version 2.103.3 \\(2026-10-26\\)\n', { mode: 0o755 })+ execFileSync('/usr/bin/ditto', ['-c', '-k', '--keepParent', join(dir, root), join(dir, 'out.zip')])+ return readFileSync(join(dir, 'out.zip'))+}++function deps(over: Partial<TeamGhDeps> = {}) {+ const home = temp('team-gh-')+ const d: TeamGhDeps = {+ team: () => true, platform: 'darwin', arch: 'arm64', candidates: () => ['/opt/homebrew/bin/gh'],+ runs: vi.fn(async (binary: string) => binary.startsWith(home)),+ download: vi.fn(async () => archive(GH_BUILDS.arm64!.archiveRoot)), unzip: unzipArchive,+ runtimeDir: join(home, '.harness', 'runtime'), binDir: join(home, '.local', 'bin'), log: vi.fn(), ...over,+ }+ return { d, home }+}++describe.runIf(process.platform === 'darwin')('the Harness Team account\'s own gh', () => {+ it('pins GitHub\'s own macOS builds, by checksum', () => {+ for (const [arch, name] of [['arm64', 'arm64'], ['x64', 'amd64']]) {+ expect(GH_BUILDS[arch]).toMatchObject({ archiveRoot: `gh_2.103.3_macOS_${name}`,+ url: `https://github.com/cli/cli/releases/download/v2.103.3/gh_2.103.3_macOS_${name}.zip`, sha256: expect.stringMatching(/^[0-9a-f]{64}$/) })+ }+ })++ // PR #1934 (2026-10-28): Homebrew's gh behind /opt/homebrew/bin, mode 770, answered "permission denied".+ it('installs gh in its own home when it has none it can run, on its agents\' PATH', async () => {+ const { d, home } = deps()+ expect(await ensureTeamGh(d)).toBe('installed')+ const binary = join(home, '.harness', 'runtime', 'gh_2.103.3_macOS_arm64', 'bin', 'gh')+ expect(readlinkSync(join(home, '.local', 'bin', 'gh'))).toBe(binary)+ expect(await ghRunsAt(join(home, '.local', 'bin', 'gh'))).toBe(true)+ expect(d.download).toHaveBeenCalledWith(GH_BUILDS.arm64)+ expect(d.log).toHaveBeenCalledWith(expect.stringContaining('installed gh 2.103.3'))+ // Already there: nothing downloaded again, and no staging left behind.+ expect(await ensureTeamGh({ ...d, candidates: () => [] })).toBe('installed')+ expect(d.download).toHaveBeenCalledOnce()+ expect(existsSync(join(home, '.harness', 'runtime', `.gh-staging-${process.pid}`))).toBe(false)+ })++ it('leaves alone a gh that runs, an account that is not a team account, and a Mac it has no build for', async () => {+ const { d } = deps({ runs: async () => true })+ expect(await ensureTeamGh(d)).toBe('present')+ expect(await ensureTeamGh({ ...d, team: () => false })).toBe('not-team')+ expect(await ensureTeamGh({ ...d, runs: async () => false, arch: 'ia32' })).toBe('unsupported')+ expect(await ensureTeamGh({ ...d, runs: async () => false, platform: 'linux' })).toBe('unsupported')+ expect(d.download).not.toHaveBeenCalled()+ })++ it('fails, saying why, on a download that fails, an archive without gh, or a gh that does not run', async () => {+ const failed = deps({ download: async () => { throw new Error('sha256 mismatch') } })+ expect(await ensureTeamGh(failed.d)).toBe('failed')+ expect(failed.d.log).toHaveBeenCalledWith(expect.stringContaining('sha256 mismatch'))+ const empty = deps({ download: async () => archive(GH_BUILDS.arm64!.archiveRoot, false) })+ expect(await ensureTeamGh(empty.d)).toBe('failed')+ expect(empty.d.log).toHaveBeenCalledWith(expect.stringContaining('has no gh_2.103.3_macOS_arm64/bin/gh'))+ const dead = deps({ runs: async () => false })+ expect(await ensureTeamGh(dead.d)).toBe('failed')+ expect(dead.d.log).toHaveBeenCalledWith(expect.stringContaining('does not run here'))+ expect(await ghRunsAt('/nonexistent/gh')).toBe(false)+ await expect(unzipArchive('/nonexistent.zip', temp('gh-into-'))).rejects.toThrow('could not unpack')+ })+})diff --git a/cli/src/team/gh.ts b/cli/src/team/gh.tsnew file mode 100644index 000000000..cd6ac05b9--- /dev/null+++ b/cli/src/team/gh.ts@@ -0,0 +1,99 @@+/**+ * The Harness Team account's own gh, installed by its own daemon, in its own home.+ *+ * A teammate's agent opens its pull request with gh, signed in as the Harness GitHub App for that session alone+ * (lib/swarmGitHub.ts `GH_CONFIG_DIR`). The team account had only its owner's Homebrew to find gh in, and a Homebrew+ * another account cannot read (/opt/homebrew/bin mode 770 on 2026-10-28) answered "permission denied": the Builder of+ * PR #1934 fell back to GitHub's API by hand. So the team daemon installs gh itself when it has none it can run, as it does+ * tmux (team/tmux.ts): GitHub's own release of it, checked against the checksum pinned here, in its own home. No password.+ *+ * A newer gh is a new version and checksums here, from the release's `gh_<version>_checksums.txt`.+ */+import { execFile } from 'node:child_process'+import { existsSync, mkdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'++export interface GhBuild { version: string; url: string; sha256: string; size: number; archiveRoot: string }++const GH_VERSION = '2.103.3'+const release = (arch: string, sha256: string, size: number): GhBuild => ({+ version: GH_VERSION, sha256, size, archiveRoot: `gh_${GH_VERSION}_macOS_${arch}`,+ url: `https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_macOS_${arch}.zip`,+})+/** GitHub's macOS builds of gh, by `process.arch`. */+export const GH_BUILDS: Readonly<Record<string, GhBuild>> = {+ arm64: release('arm64', 'd700207eae9ae98fe2b89535c2c087c07823d4628c56364695a5a07ef311c062', 14_106_091),+ x64: release('amd64', 'a2f86418f4350ae6e9ec60d5000bdf7665728436946a97fc27fe50e6ae752682', 15_702_601),+}++export type TeamGhOutcome = 'not-team' | 'present' | 'installed' | 'unsupported' | 'failed'++export interface TeamGhDeps {+ /** Whether this daemon is a Mac's Harness Team account. */+ team(): boolean+ platform: NodeJS.Platform+ arch: string+ /** The gh binaries an agent here would find (its own, on PATH, Homebrew's): any that runs is enough. */+ candidates(): string[]+ runs(binary: string): Promise<boolean>+ /** The archive's bytes, checked against its sha256 (lib/selfUpdate.ts `downloadVerified`). */+ download(build: GhBuild): Promise<Buffer>+ /** Unpacks a .zip into a folder. */+ unzip(archive: string, into: string): Promise<void>+ /** `~/.harness/runtime` and `~/.local/bin` of this account. */+ runtimeDir: string+ binDir: string+ log(line: string): void+}++/** Installs gh in the team account when it has none it can run. Never throws. */+export async function ensureTeamGh(deps: TeamGhDeps): Promise<TeamGhOutcome> {+ try {+ if (!deps.team()) return 'not-team'+ for (const binary of deps.candidates()) if (await deps.runs(binary)) return 'present'+ const build = deps.platform === 'darwin' ? GH_BUILDS[deps.arch] : undefined+ if (!build) {+ deps.log(`team: no gh build is pinned for ${deps.platform}-${deps.arch}; teammates' agents open pull requests through GitHub's API`)+ return 'unsupported'+ }+ const target = join(deps.runtimeDir, build.archiveRoot)+ const binary = join(target, 'bin', 'gh')+ if (!existsSync(binary)) {+ mkdirSync(deps.runtimeDir, { recursive: true, mode: 0o700 })+ const staging = join(deps.runtimeDir, `.gh-staging-${process.pid}`)+ rmSync(staging, { recursive: true, force: true })+ mkdirSync(staging, { recursive: true, mode: 0o700 })+ try {+ const archive = join(staging, 'gh.zip')+ writeFileSync(archive, await deps.download(build), { mode: 0o600 })+ await deps.unzip(archive, staging)+ if (!existsSync(join(staging, build.archiveRoot, 'bin', 'gh'))) throw new Error(`the gh archive has no ${build.archiveRoot}/bin/gh`)+ rmSync(target, { recursive: true, force: true })+ renameSync(join(staging, build.archiveRoot), target)+ } finally {+ rmSync(staging, { recursive: true, force: true })+ }+ }+ if (!await deps.runs(binary)) throw new Error(`the installed gh does not run here: ${binary}`)+ // On the PATH the team daemon gives its agents, and last on a login shell's: an unreadable Homebrew before it is skipped.+ mkdirSync(deps.binDir, { recursive: true })+ rmSync(join(deps.binDir, 'gh'), { force: true })+ symlinkSync(binary, join(deps.binDir, 'gh'))+ deps.log(`team: installed gh ${build.version} for the Harness Team account → ${target}`)+ return 'installed'+ } catch (error) {+ deps.log(`team: could not install gh for the Harness Team account: ${error instanceof Error ? error.message : String(error)}`)+ return 'failed'+ }+}++/** Whether [binary] runs and says it is gh. */+export const ghRunsAt = (binary: string) => new Promise<boolean>((resolve) => {+ execFile(binary, ['--version'], { timeout: 5_000, env: { ...process.env, GH_NO_UPDATE_NOTIFIER: '1' } },+ (error, stdout) => resolve(!error && /^gh version \S+/.test(String(stdout).trim())))+})++/** Unpacks with the system's ditto, which every Mac has. */+export const unzipArchive = (archive: string, into: string) => new Promise<void>((resolve, reject) => {+ execFile('/usr/bin/ditto', ['-x', '-k', archive, into], { timeout: 60_000 }, (error) => error ? reject(new Error(`could not unpack ${archive}`)) : resolve())+})diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.mdindex d2fccc720..5800e4310 100644--- a/docs/swarm-github-app.md+++ b/docs/swarm-github-app.md@@ -214,6 +214,13 @@ address. The `commit-msg` hook adds any missing trailers to a message written ineditor. Trailers already in the message are not added again, so an amend keeps oneof each. An empty message still aborts the commit.+In a Harness Team account, the commits themselves are by the app's bot account+(`<app>[bot] <id+<app>[bot]@users.noreply.github.com>`), as its pull requests are: the+account has no git identity of its own, and its commits read `Harness Team+<harnessteam@<host>.local>` before. The token response names it as `commitAs` for a+team account only; the daemon writes it to the session's `gitconfig`, which the+session's git includes. A person's machine keeps its owner's git identity.+The `prepare-commit-msg` hook runs even with `--no-verify`. Two things leave a commitwithout trailers: plumbing such as `git commit-tree`, and a command that sets its own`-c core.hooksPath`.@@ -283,6 +290,9 @@ The server never logs a token.- On a personal computer, startup files that export `GITHUB_TOKEN` reach ClaudeCode's and Codex's commands again. gh then uses that token. The team account hasno such files.+- The team account has gh of its own: a Homebrew it cannot read leaves it none, so its+ daemon installs GitHub's release of gh (pinned by checksum in `cli/src/team/gh.ts`)+ in its home and links it from `~/.local/bin`.- If Redis is unavailable, Harness still issues tokens but cannot revoke them whenthe task ends. They expire within the hour.- In the first minute of a task, gh can be without a token until the daemon's next