Skip to content

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.

Swarm agents push with a Harness GitHub App token for their task's repository (#1690)

Dee300ee670e6b9
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.ts
new file mode 100644
index 000000000..c692c4f0a
--- /dev/null
+++ b/backend/integration/superTabGithub.test.ts
@@ -0,0 +1,240 @@
+import { randomBytes, randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import Fastify, { type FastifyInstance } from 'fastify'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { superTabRoutes } from '../src/routes/superTabs.js'
+import { errorHandler } from '../src/middlewares/errorHandler.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { GitHubTokens, MemoryTokenCache } from '../src/github/tokens.js'
+import { fakeApp, fakeGitHub, throwawayKey } from '../src/github/fakeGitHub.js'
+
+// The Harness GitHub App's token endpoint on the real control API: a fresh loopback MongoDB and a fake GitHub. This suite
+// never reads DATABASE_URL, an existing database or github.com.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '200000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const host: AuthUser = { sub: '200000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const key = throwawayKey()
+const users = [owner, host]
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`super_tab_github_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: 'prod', name: 'Olive Owner' } })
+ await db.user.create({ data: { id: host.sub, externalId: `fixture-${host.sub}`, email: host.email, autonomousEnv: 'prod' } })
+ for (const [machineId, userId, name] of [['gh-host', host.sub, 'Fixture Mac'], ['gh-host-mini', host.sub, 'Fixture Mini'], ['owner-mac', owner.sub, 'Owner Mac']]) {
+ await db.machine.create({ data: { machineId: machineId!, userId: userId!, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod',
+ authMode: 'remote', name } })
+ }
+ await db.machineShare.create({ data: { machineId: 'gh-host', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email] } })
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** One control API with the app configured against a fresh fake GitHub, its store revoking as tasks end. */
+async function fresh(options: { github?: boolean } = {}) {
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242' })
+ github.installed.set('example/app', 91)
+ const log = { warn: vi.fn() }
+ const tokens = new GitHubTokens(fakeApp(key.privateKey, github), new MemoryTokenCache(), { log, secret: randomBytes(32) })
+ const releases: Promise<void>[] = []
+ const store = new SuperTabStore(db, Date.now, null, { workEnded: (tab, ended) => { releases.push(tokens.release(tab, ended)) } })
+ const app: FastifyInstance = Fastify()
+ app.setErrorHandler(errorHandler)
+ app.addHook('onRequest', async (request, reply) => {
+ const user = users.find(u => `Bearer ${u.sub}` === request.headers.authorization)
+ if (!user) return reply.code(401).send({ success: false })
+ request.user = user
+ })
+ await app.register(superTabRoutes, { store, github: options.github === false ? null : tokens })
+ await app.ready()
+ const run = (tab: string, command: Command, user = owner, asAgentId?: string) =>
+ store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId)
+ const settled = async () => { await Promise.all(releases.splice(0)) }
+ return { github, log, tokens, store, app, run, settled }
+}
+
+type Env = Awaited<ReturnType<typeof fresh>>
+/** A tab whose project is on [repositoryUrl], with a Builder on the host's machine working on a task. */
+async function working(env: Env, repositoryUrl: string | null = 'https://github.com/example/app.git') {
+ const tab = (await env.store.create(owner, randomUUID(), 'Pilot')).id
+ await env.run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'gh-host', harnessId: randomUUID(), name: 'Lead',
+ configuration: config, lead: true, project: { cwd: '/work/app', repositoryUrl } } as Command)
+ const group = String((await env.run(tab, { type: 'conversation.create', title: 'Add search', brief: 'Add a search field',
+ checks: [{ description: 'Search works', independent: false }] } as Command)).result.conversationId)
+ const worker = String((await env.run(tab, { type: 'agent.add', conversationId: group, machineId: 'gh-host', harnessId: randomUUID(),
+ name: 'Builder', configuration: config, lead: false } as Command)).result.agentId)
+ const assignmentId = String((await env.run(tab, { type: 'work.assign', conversationId: group, agentId: worker } as Command)).result.assignmentId)
+ return { tab, group, worker, assignmentId }
+}
+const ask = (env: Env, tab: string, agentId: string | null, machineId = 'gh-host', user = host) => env.app.inject({ method: 'POST',
+ url: `/api/super-tabs/${tab}/github-token${agentId ? `?asAgentId=${agentId}` : ''}`, headers: { authorization: `Bearer ${user.sub}` }, payload: { machineId } })
+
+describe('the GitHub token endpoint', () => {
+ it('gives the working agent\'s host a token for its project\'s repository, with who the work is for', async () => {
+ const env = await fresh()
+ const { tab, worker } = await working(env)
+ const response = await ask(env, tab, worker)
+ expect(response.statusCode, response.body).toBe(200)
+ const data = response.json().data
+ expect(data).toMatchObject({ token: 'ghs_fixture_1', repository: 'example/app', defaultBranch: 'main', defaultBranchProtected: false,
+ defaultBranchProtection: 'none', requestedBy: { name: 'Olive Owner', email: owner.email }, agent: expect.any(String), machine: 'Fixture Mac',
+ pullRequestLine: `Requested by Olive Owner (${owner.email}) through Harness.` })
+ expect(data.trailers).toEqual([`Co-authored-by: Olive Owner <${owner.email}>`, `Harness-Agent: ${data.agent}`, 'Harness-Machine: Fixture Mac'])
+ expect(Date.parse(data.expiresAt)).toBeGreaterThan(Date.now() + 50 * 60_000)
+ 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' } })
+ // 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.
+ const read = await env.app.inject({ method: 'GET', url: `/api/super-tabs/${tab}`, headers: { authorization: `Bearer ${owner.sub}` } })
+ expect(read.json().data.githubApp).toBe(true)
+ })
+
+ 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)
+ env.github.protection.set('example/app', { protected: true })
+ expect((await ask(env, tab, worker)).json().data).toMatchObject({ defaultBranchProtected: false, defaultBranchProtection: 'classic' })
+ const other = await fresh()
+ const second = await working(other)
+ other.github.protection.set('example/app', { rules: [{ type: 'pull_request' }] })
+ expect((await ask(other, second.tab, second.worker)).json().data).toMatchObject({ defaultBranchProtected: true, defaultBranchProtection: 'pull_request' })
+ })
+
+ it('refuses another account\'s agent, its own agent on another machine, and a request with no agent', async () => {
+ const env = await fresh()
+ const { tab, worker } = await working(env)
+ const ownAgent = String((await env.run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: randomUUID(),
+ name: 'Owner agent', configuration: config, lead: false } as Command)).result.agentId)
+ expect((await ask(env, tab, ownAgent, 'owner-mac')).json().error).toMatchObject({ code: 'FORBIDDEN' })
+ expect((await ask(env, tab, worker, 'gh-host', owner)).json().error).toMatchObject({ code: 'FORBIDDEN' })
+ const elsewhere = await ask(env, tab, worker, 'gh-host-mini')
+ expect(elsewhere.statusCode).toBe(403)
+ expect(elsewhere.json().error).toMatchObject({ code: 'FORBIDDEN', message: 'Only the machine running this agent can ask for its GitHub token.' })
+ const none = await ask(env, tab, null)
+ expect(none.statusCode).toBe(400)
+ expect(none.json().error.code).toBe('AGENT_REQUIRED')
+ expect(env.github.calls).toEqual([])
+ })
+
+ it('refuses an agent with no task in progress', async () => {
+ const env = await fresh()
+ const { tab } = await working(env)
+ const idle = String((await env.run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'gh-host', harnessId: randomUUID(),
+ name: 'Idle', configuration: config, lead: false } as Command)).result.agentId)
+ const response = await ask(env, tab, idle)
+ expect(response.statusCode).toBe(409)
+ expect(response.json().error.code).toBe('NO_ASSIGNMENT')
+ })
+
+ it('refuses a project whose repository is not on GitHub or has no address', async () => {
+ for (const url of ['https://gitlab.com/example/app.git', null]) {
+ const env = await fresh()
+ const { tab, worker } = await working(env, url)
+ const response = await ask(env, tab, worker)
+ expect(response.statusCode).toBe(409)
+ expect(response.json().error.code).toBe('REPOSITORY_NOT_GITHUB')
+ expect(env.github.calls).toEqual([])
+ }
+ })
+
+ it('refuses a repository the app is not installed on, with the install link', async () => {
+ const env = await fresh()
+ env.github.installed.clear()
+ const { tab, worker } = await working(env)
+ const response = await ask(env, tab, worker)
+ expect(response.statusCode).toBe(409)
+ expect(response.json().error).toEqual({ code: 'GITHUB_APP_NOT_INSTALLED', installUrl: 'https://github.com/apps/harness-fixture/installations/new',
+ message: 'The Harness GitHub App is not installed on example/app. Ask an owner of example to install it: https://github.com/apps/harness-fixture/installations/new.' })
+ })
+
+ it('answers not configured when the server has no app, and says nothing about it on the tab', async () => {
+ const env = await fresh({ github: false })
+ const { tab, worker } = await working(env)
+ const response = await ask(env, tab, worker)
+ expect(response.statusCode).toBe(503)
+ expect(response.json().error.code).toBe('GITHUB_APP_NOT_CONFIGURED')
+ const read = await env.app.inject({ method: 'GET', url: `/api/super-tabs/${tab}`, headers: { authorization: `Bearer ${owner.sub}` } })
+ expect(read.json().data).not.toHaveProperty('githubApp')
+ })
+})
+
+describe('revoking the token when the task ends', () => {
+ const issued = async (env: Env) => {
+ const work = await working(env)
+ const token = (await ask(env, work.tab, work.worker)).json().data.token as string
+ return { ...work, token }
+ }
+
+ it('revokes on done', async () => {
+ const env = await fresh()
+ const { tab, group, worker, assignmentId, token } = await issued(env)
+ const checkId = (await env.store.read(owner, tab)).state.conversations.find(c => c.id === group)!.checks[0]!.id
+ await env.run(tab, { type: 'work.check', conversationId: group, assignmentId, checkId, passed: true, evidence: 'npm test passed' } as Command, host, worker)
+ await env.run(tab, { type: 'work.status', conversationId: group, assignmentId, status: 'review', result: 'Ready' } as Command, host, worker)
+ await env.settled()
+ // Out for review is still the Builder's task.
+ expect(env.github.revoked).toEqual([])
+ await env.run(tab, { type: 'work.status', conversationId: group, assignmentId, status: 'done', result: 'Merged' } as Command, host, worker)
+ await env.settled()
+ expect(env.github.revoked).toEqual([token])
+ expect((await ask(env, tab, worker)).json().error.code).toBe('NO_ASSIGNMENT')
+ })
+
+ it('revokes on cancel, and a reassigned task gets a new token', async () => {
+ const env = await fresh()
+ const { tab, group, worker, assignmentId, token } = await issued(env)
+ await env.run(tab, { type: 'work.cancel', conversationId: group, assignmentId, reason: 'Not needed' } as Command)
+ await env.settled()
+ expect(env.github.revoked).toEqual([token])
+ await env.run(tab, { type: 'agent.release', agentId: worker, decision: 'keep' } as Command).catch(() => undefined)
+ await env.run(tab, { type: 'work.assign', conversationId: group, agentId: worker } as Command)
+ const again = (await ask(env, tab, worker)).json().data.token
+ expect(again).not.toBe(token)
+ })
+
+ it('revokes when the host confirms the agent stopped', async () => {
+ const env = await fresh()
+ const { tab, assignmentId, token } = await issued(env)
+ await env.store.stopped(host, tab, assignmentId, 'fixture stop receipt')
+ await env.settled()
+ expect(env.github.revoked).toEqual([token])
+ })
+
+ it('revokes when the agent is removed', async () => {
+ const env = await fresh()
+ const { tab, worker, token } = await issued(env)
+ await env.run(tab, { type: 'agent.remove', agentId: worker } as Command)
+ await env.settled()
+ expect(env.github.revoked).toEqual([token])
+ })
+
+ it('a failed revoke is logged without the token and does not hold up the task', async () => {
+ const env = await fresh()
+ const { tab, group, assignmentId, token } = await issued(env)
+ env.github.control.revokeStatus = 502
+ await env.run(tab, { type: 'work.cancel', conversationId: group, assignmentId, reason: 'Not needed' } as Command)
+ await env.settled()
+ expect((await env.store.read(owner, tab)).state.conversations.find(c => c.id === group)!.assignment!.status).toBe('cancelled')
+ expect(env.github.revoked).toEqual([])
+ expect(env.log.warn).toHaveBeenCalledWith('[github] token revoke failed', expect.objectContaining({ tabId: tab, repository: 'example/app', why: 'task ended' }))
+ expect(JSON.stringify(env.log.warn.mock.calls)).not.toContain(token)
+ })
+})
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index 82ba48af4..99fcfde83 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -236,6 +236,16 @@ const envSchema = z.object({
// Where clients read the files. https:// in production (superTabs/attachments.ts refuses anything else at startup).
SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: z.string().url().default('https://cdn.harness.autonomous.ai'),
+ // The Harness GitHub App (github/app.ts, docs/swarm-github-app.md): a Swarm agent doing a task pushes and opens pull
+ // requests with a one-hour token for its project's repository alone. Both empty: off, and POST
+ // /api/super-tabs/:tabId/github-token answers GITHUB_APP_NOT_CONFIGURED. One without the other, or a key that cannot be
+ // read, stops the backend at startup with a message that never shows the key. The ID is the numeric App ID (or the
+ // Client ID); the key is the app's PEM private key as downloaded, with its line breaks as \n, or base64 of the file.
+ GITHUB_APP_ID: z.string().default(''),
+ GITHUB_APP_PRIVATE_KEY: z.string().default(''),
+ // The app's name in github.com/apps/NAME, for the install link a refusal gives. Optional.
+ GITHUB_APP_SLUG: z.string().default(''),
+
// TTL for the in-memory subdomain→machineId cache on the public app-proxy hot path
// (avoids a Mongo lookup per request). Bounds staleness after a cross-instance app teardown.
// 60 min default (mapping is stable; a same-instance delete evicts immediately).
diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.ts
new file mode 100644
index 000000000..84de96ecb
--- /dev/null
+++ b/backend/src/github/app.test.ts
@@ -0,0 +1,202 @@
+import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'
+import { describe, expect, it } from 'vitest'
+import { cacheSecret, githubAppConfig, GitHubAppError, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'
+import { FAKE_API, fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'
+import { githubRepository } from './repository.js'
+
+const key = throwawayKey()
+const repo = githubRepository('https://github.com/acme/app')!
+const clock = () => { let t = Date.parse('2026-10-24T12:00:00Z'); return { now: () => t, advance: (ms: number) => { t += ms } } }
+const setup = (options: { slug?: string | null } = {}) => {
+ const time = clock()
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242', now: time.now })
+ return { time, github, app: fakeApp(key.privateKey, github, { now: time.now, ...options }) }
+}
+const env = (id: string, privateKey: string, slug = '') => ({ GITHUB_APP_ID: id, GITHUB_APP_PRIVATE_KEY: privateKey, GITHUB_APP_SLUG: slug })
+
+describe('GitHub App configuration', () => {
+ it('is off with nothing set and refuses half a configuration', () => {
+ expect(githubAppConfig(env('', ''))).toBeNull()
+ expect(githubAppConfig(env(' ', '\n'))).toBeNull()
+ expect(() => githubAppConfig(env('424242', ''))).toThrow('Set both GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY')
+ expect(() => githubAppConfig(env('', key.pem))).toThrow('Set both GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY')
+ expect(() => githubAppConfig(env('my app', key.pem))).toThrow('numeric App ID or its Client ID')
+ expect(() => githubAppConfig(env('424242', key.pem, 'Not A Slug'))).toThrow('github.com/apps/NAME')
+ })
+
+ it('reads the key as a PEM file, with escaped line breaks, or as base64, and takes a Client ID', () => {
+ const escaped = key.pem.trim().replace(/\n/g, '\\n')
+ for (const value of [key.pem, escaped, Buffer.from(key.pem).toString('base64')]) {
+ const config = githubAppConfig(env('424242', value, 'harness-fixture'))!
+ expect(config.privateKey.asymmetricKeyType).toBe('rsa')
+ expect(config.slug).toBe('harness-fixture')
+ }
+ expect(githubAppConfig(env('Iv23liFixture0001', key.pem))!.appId).toBe('Iv23liFixture0001')
+ })
+
+ it('refuses a key it cannot use without repeating the value', () => {
+ const secret = 'not-a-key-secret-material'
+ const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()
+ const broken = key.pem.replace(/[A-Za-z]{20}/, 'secretsecretsecretse')
+ for (const [value, message] of [[secret, /not a PEM private key/], [ec, /RSA key/], [broken, /could not be read/],
+ [Buffer.from(secret).toString('base64'), /not a PEM private key/]] as const) {
+ let error: unknown
+ try { readPrivateKey(value) } catch (thrown) { error = thrown }
+ expect((error as Error).message).toMatch(message)
+ expect((error as Error).message).not.toContain('secret')
+ }
+ })
+
+ it('derives a 32-byte cache key from the private key and app id', () => {
+ const config = githubAppConfig(env('424242', key.pem))!
+ expect(cacheSecret(config)).toHaveLength(32)
+ expect(cacheSecret(config).equals(cacheSecret({ ...config, appId: '1' }))).toBe(false)
+ })
+})
+
+describe('the app JWT', () => {
+ it('is RS256, issued by the app a minute back, valid at most ten minutes, and reused until a minute before it ends', () => {
+ const { app, time } = setup()
+ const jwt = app.jwt()
+ const [header, payload, signature] = jwt.split('.') as [string, string, string]
+ expect(JSON.parse(Buffer.from(header, 'base64url').toString())).toEqual({ alg: 'RS256', typ: 'JWT' })
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString())
+ const seconds = Math.floor(time.now() / 1000)
+ expect(claims).toEqual({ iat: seconds - 60, exp: seconds + 540, iss: '424242' })
+ expect(verify('sha256', Buffer.from(`${header}.${payload}`), createPublicKey(key.privateKey), Buffer.from(signature, 'base64url'))).toBe(true)
+ time.advance(7 * 60_000)
+ expect(app.jwt()).toBe(jwt)
+ time.advance(60_000)
+ expect(app.jwt()).not.toBe(jwt)
+ })
+})
+
+describe('installation lookup', () => {
+ it('finds the installation with the app JWT and remembers it for ten minutes', async () => {
+ const { app, github, time } = setup()
+ github.installed.set('acme/app', 77)
+ expect(await app.installation(repo)).toBe(77)
+ expect(github.calls[0]).toMatchObject({ method: 'GET', path: '/repos/acme/app/installation' })
+ expect(github.calls[0]!.auth).toMatch(/^Bearer [\w-]+\.[\w-]+\.[\w-]+$/)
+ expect(await app.installation(repo)).toBe(77)
+ expect(github.calls).toHaveLength(1)
+ time.advance(10 * 60_000 + 1)
+ expect(await app.installation(repo)).toBe(77)
+ expect(github.calls).toHaveLength(2)
+ })
+
+ it('remembers a missing installation for one minute only', async () => {
+ const { app, github, time } = setup()
+ expect(await app.installation(repo)).toBeNull()
+ github.installed.set('acme/app', 78)
+ expect(await app.installation(repo)).toBeNull()
+ time.advance(60_001)
+ expect(await app.installation(repo)).toBe(78)
+ })
+
+ it('says the credentials are wrong when GitHub refuses the JWT, and that GitHub is away when it does not answer', async () => {
+ const time = clock()
+ const other = throwawayKey()
+ const github = fakeGitHub({ publicKey: other.publicKey, appId: '424242', now: time.now })
+ const app = fakeApp(key.privateKey, github, { now: time.now })
+ await expect(app.installation(repo)).rejects.toMatchObject({ code: 'GITHUB_APP_MISCONFIGURED', status: 503 })
+ github.control.down = true
+ await expect(app.installation(repo)).rejects.toMatchObject({ code: 'GITHUB_UNAVAILABLE', status: 503 })
+ })
+
+ it('treats an answer without an id as GitHub being unavailable', async () => {
+ const app = fakeApp(key.privateKey, { fetch: (async () => new Response('{}', { status: 200 })) as typeof fetch } as never)
+ await expect(app.installation(repo)).rejects.toMatchObject({ code: 'GITHUB_UNAVAILABLE', status: 502 })
+ })
+})
+
+describe('installation tokens', () => {
+ it('asks for exactly the one repository and the minimum permissions', async () => {
+ const { app, github } = setup()
+ const minted = await app.createToken(77, repo)
+ expect(minted.token).toBe('ghs_fixture_1')
+ expect(Date.parse(minted.expiresAt)).toBeGreaterThan(Date.parse('2026-10-24T12:59:00Z'))
+ const call = github.calls.at(-1)!
+ expect(call).toMatchObject({ method: 'POST', path: '/app/installations/77/access_tokens' })
+ expect(call.body).toEqual({ repositories: ['app'],
+ permissions: { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read' } })
+ expect(TOKEN_PERMISSIONS).toEqual((call.body as { permissions: unknown }).permissions)
+ })
+
+ it('names a repository the installation does not cover as not installed, with the install link, and a missing permission apart', async () => {
+ const { app, github } = setup()
+ github.installed.set('acme/app', 77)
+ await app.installation(repo)
+ github.control.tokenStatus = 422
+ github.control.tokenMessage = 'There is at least one repository that does not exist or is not accessible to the parent installation.'
+ const refusal = await app.createToken(77, repo).then(() => { throw new Error('expected a refusal') }, (error: unknown) => error as GitHubAppError)
+ expect(refusal).toMatchObject({ code: 'GITHUB_APP_NOT_INSTALLED', status: 409,
+ details: { installUrl: 'https://github.com/apps/harness-fixture/installations/new' } })
+ expect(refusal.message).toContain('acme/app')
+ // The installation is looked up again next time.
+ const calls = github.calls.length
+ await app.installation(repo)
+ expect(github.calls.length).toBe(calls + 1)
+ github.control.tokenMessage = 'The permissions requested are not granted to this installation.'
+ await expect(app.createToken(77, repo)).rejects.toMatchObject({ code: 'GITHUB_APP_PERMISSIONS', status: 409 })
+ github.control.tokenStatus = 500
+ await expect(app.createToken(77, repo)).rejects.toMatchObject({ code: 'GITHUB_UNAVAILABLE', status: 502 })
+ })
+
+ it('leaves the install link out when no app name is configured', async () => {
+ const { app } = setup({ slug: null })
+ expect(app.installUrl()).toBeNull()
+ expect(app.notInstalled(repo).details).toBeUndefined()
+ expect(app.notInstalled(repo).message).toBe('The Harness GitHub App is not installed on acme/app. Ask an owner of acme to install it.')
+ })
+
+ 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)
+ await app.revoke(token)
+ expect(github.calls.at(-1)).toMatchObject({ method: 'DELETE', path: '/installation/token', auth: `Bearer ${token}` })
+ expect(github.revoked).toEqual([token])
+ await app.revoke(token)
+ const second = await app.createToken(77, repo)
+ github.control.revokeStatus = 500
+ await expect(app.revoke(second.token)).rejects.toMatchObject({ code: 'GITHUB_UNAVAILABLE' })
+ })
+})
+
+describe('default branch protection', () => {
+ it('reads a ruleset that requires a pull request with the agent token', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo)
+ github.protection.set('acme/app', { rules: [{ type: 'deletion' }, { type: 'pull_request', parameters: {} }] })
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: 'main', protection: 'pull_request' })
+ expect(github.calls.slice(-2).map(c => c.path)).toEqual(['/repos/acme/app', '/repos/acme/app/rules/branches/main'])
+ expect(github.calls.slice(-2).every(c => c.auth === `Bearer ${token}`)).toBe(true)
+ })
+
+ it('falls back to classic protection, which it cannot read further, or none, and remembers the answer ten minutes', async () => {
+ const { app, github, time } = setup()
+ const { token } = await app.createToken(77, repo)
+ github.protection.set('acme/app', { branch: 'trunk', protected: true })
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: 'trunk', protection: 'classic' })
+ github.protection.set('acme/app', { branch: 'trunk', protected: false })
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: 'trunk', protection: 'classic' })
+ time.advance(10 * 60_000 + 1)
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: 'trunk', protection: 'none' })
+ })
+
+ it('answers unknown, and asks again next time, when GitHub cannot say', async () => {
+ const { app, github } = setup()
+ const { token } = await app.createToken(77, repo)
+ github.protection.set('acme/app', { fail: true })
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: null, protection: 'unknown' })
+ github.control.down = true
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: null, protection: 'unknown' })
+ github.control.down = false
+ github.protection.set('acme/app', {})
+ expect(await app.defaultBranch(repo, token)).toEqual({ branch: 'main', protection: 'none' })
+ })
+
+ it('never talks to the real GitHub in these tests', () => {
+ expect(FAKE_API).not.toContain('api.github.com')
+ })
+})
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
new file mode 100644
index 000000000..5bc5e43af
--- /dev/null
+++ b/backend/src/github/app.ts
@@ -0,0 +1,215 @@
+/**
+ * The Harness GitHub App (docs/swarm-github-app.md): how the backend proves it is the app, finds the app's installation
+ * on a repository and creates installation access tokens for that one repository.
+ *
+ * A token comes from an installation, never from a person: GitHub user tokens cannot be narrowed to one repository, an
+ * installation token can, and it lasts an hour (docs/plans/2026-10-24-swarm-team-account.md, Findings). Only node's
+ * crypto signs the app's JWT. Nothing here logs a token or the private key.
+ */
+import { createPrivateKey, hkdfSync, sign, type KeyObject } from 'node:crypto'
+import type { GitHubRepository } from './repository.js'
+
+/** What a Swarm agent's token may do, and nothing more: push to and read the repository, open and update pull requests,
+ * and read checks and workflow runs to see whether its pull request passes. */
+export const TOKEN_PERMISSIONS = { contents: 'write', pull_requests: 'write', checks: 'read', actions: 'read', metadata: 'read' } as const
+
+/** A refusal with the code clients act on; `details` adds fields beside it, such as the install link. */
+export class GitHubAppError extends Error {
+ constructor(readonly code: string, message: string, readonly status: number, readonly details?: Record<string, unknown>) {
+ super(message)
+ this.name = 'GitHubAppError'
+ }
+}
+
+export interface GitHubAppConfig { appId: string; privateKey: KeyObject; slug: string | null }
+
+/** The app's private key as GitHub hands it out (a PEM file), with its line breaks written as `\n`, or base64 of it. The
+ * error never repeats the value. */
+export function readPrivateKey(value: string): KeyObject {
+ let pem = value.trim().replace(/\\n/g, '\n')
+ if (!pem.includes('-----BEGIN')) {
+ const decoded = /^[A-Za-z0-9+/=\s]+$/.test(pem) ? Buffer.from(pem, 'base64').toString('utf8') : ''
+ if (!decoded.includes('-----BEGIN')) throw new Error('GITHUB_APP_PRIVATE_KEY is not a PEM private key or base64 of one.')
+ pem = decoded.trim()
+ }
+ let key: KeyObject
+ try { key = createPrivateKey(pem) } catch { throw new Error('GITHUB_APP_PRIVATE_KEY could not be read as a private key.') }
+ if (key.asymmetricKeyType !== 'rsa') throw new Error('GITHUB_APP_PRIVATE_KEY must be the RSA key GitHub generated for the app.')
+ return key
+}
+
+/** Both empty: the feature is off. One without the other, or a value that cannot be right, stops the backend at startup
+ * rather than failing the first agent that asks. */
+export function githubAppConfig(env: { GITHUB_APP_ID: string; GITHUB_APP_PRIVATE_KEY: string; GITHUB_APP_SLUG: string }): GitHubAppConfig | null {
+ const appId = env.GITHUB_APP_ID.trim(), key = env.GITHUB_APP_PRIVATE_KEY.trim(), slug = env.GITHUB_APP_SLUG.trim()
+ if (!appId && !key) return null
+ if (!appId || !key) throw new Error('Set both GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY for the Harness GitHub App, or neither.')
+ // The numeric App ID, or the app's Client ID, which GitHub also takes as the JWT issuer.
+ if (!/^(?:[0-9]{1,12}|Iv[0-9A-Za-z.]{4,40})$/.test(appId)) throw new Error('GITHUB_APP_ID must be the app\'s numeric App ID or its Client ID.')
+ if (slug && !/^[a-z0-9](?:[a-z0-9-]{0,98}[a-z0-9])?$/.test(slug)) throw new Error('GITHUB_APP_SLUG must be the app\'s name as in github.com/apps/NAME.')
+ return { appId, privateKey: readPrivateKey(key), slug: slug || null }
+}
+
+/** The key that seals cached tokens (github/tokens.ts), derived from the app's own private key: whoever can read the cache
+ * without it learns nothing, and no further secret has to be configured. */
+export function cacheSecret(config: GitHubAppConfig): Buffer {
+ const der = config.privateKey.export({ type: 'pkcs8', format: 'der' })
+ return Buffer.from(hkdfSync('sha256', der, 'harness-github-token-cache', config.appId, 32))
+}
+
+/** Where the default branch stands: a ruleset requires a pull request; classic branch protection is on, which an app
+ * without administration access cannot read further; nothing protects it; or it could not be read. */
+export type BranchProtection = 'pull_request' | 'classic' | 'none' | 'unknown'
+export interface DefaultBranch { branch: string | null; protection: BranchProtection }
+
+const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')
+const INSTALLATION_TTL_MS = 10 * 60_000
+const NOT_INSTALLED_TTL_MS = 60_000
+const BRANCH_TTL_MS = 10 * 60_000
+const REQUEST_TIMEOUT_MS = 10_000
+
+export interface GitHubAppOptions {
+ fetch?: typeof fetch
+ now?: () => number
+ /** api.github.com unless a test serves a fake. */
+ apiUrl?: string
+}
+
+export class GitHubApp {
+ private readonly fetch: typeof fetch
+ private readonly now: () => number
+ private readonly apiUrl: string
+ private signed: { jwt: string; until: number } | null = null
+ private readonly installations = new Map<string, { id: number | null; until: number }>()
+ private readonly branches = new Map<string, { value: DefaultBranch; until: number }>()
+
+ constructor(readonly config: GitHubAppConfig, options: GitHubAppOptions = {}) {
+ this.fetch = options.fetch ?? fetch
+ this.now = options.now ?? Date.now
+ this.apiUrl = (options.apiUrl ?? 'https://api.github.com').replace(/\/$/, '')
+ }
+
+ /** Where an owner installs the app, when its URL name is configured. */
+ installUrl(): string | null {
+ return this.config.slug ? `https://github.com/apps/${this.config.slug}/installations/new` : null
+ }
+
+ /** 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 {
+ const now = this.now()
+ if (this.signed && this.signed.until > now) return this.signed.jwt
+ const iat = Math.floor(now / 1000) - 60
+ const exp = iat + 60 + 9 * 60
+ const input = `${base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))}.${base64url(JSON.stringify({ iat, exp, iss: this.config.appId }))}`
+ const jwt = `${input}.${base64url(sign('sha256', Buffer.from(input), this.config.privateKey))}`
+ this.signed = { jwt, until: (exp - 60) * 1000 }
+ return jwt
+ }
+
+ private async call(method: string, path: string, auth: string, body?: unknown): Promise<{ status: number; body: Record<string, unknown> | unknown[] }> {
+ let response: Response
+ try {
+ 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' } : {}) },
+ ...(body ? { body: JSON.stringify(body) } : {}),
+ })
+ } catch {
+ throw new GitHubAppError('GITHUB_UNAVAILABLE', 'GitHub did not answer. Try again in a minute.', 503)
+ }
+ const text = await response.text().catch(() => '')
+ let parsed: unknown = {}
+ try { parsed = text ? JSON.parse(text) : {} } catch { parsed = {} }
+ return { status: response.status, body: parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : {} }
+ }
+
+ private misconfigured(): GitHubAppError {
+ return new GitHubAppError('GITHUB_APP_MISCONFIGURED', 'GitHub refused the Harness GitHub App\'s credentials. Check GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY on the server.', 503)
+ }
+
+ notInstalled(repository: GitHubRepository): GitHubAppError {
+ const installUrl = this.installUrl()
+ return new GitHubAppError('GITHUB_APP_NOT_INSTALLED',
+ `The Harness GitHub App is not installed on ${repository.fullName}. Ask an owner of ${repository.owner} to install it${installUrl ? `: ${installUrl}` : ''}.`,
+ 409, installUrl ? { installUrl } : undefined)
+ }
+
+ /** The installation that covers [repository], or null when the app is not installed there. Remembered ten minutes,
+ * and a missing installation one minute, so a busy Swarm does not ask GitHub for every token. */
+ async installation(repository: GitHubRepository): Promise<number | null> {
+ const key = repository.fullName.toLowerCase()
+ const known = this.installations.get(key)
+ if (known && known.until > this.now()) return known.id
+ const answer = await this.call('GET', `/repos/${repository.owner}/${repository.name}/installation`, `Bearer ${this.jwt()}`)
+ if (answer.status === 401) throw this.misconfigured()
+ if (answer.status === 404) {
+ this.installations.set(key, { id: null, until: this.now() + NOT_INSTALLED_TTL_MS })
+ return null
+ }
+ const id = (answer.body as Record<string, unknown>).id
+ if (answer.status !== 200 || typeof id !== 'number') throw new GitHubAppError('GITHUB_UNAVAILABLE', `GitHub could not look up the app on ${repository.fullName}.`, 502)
+ this.installations.set(key, { id, until: this.now() + INSTALLATION_TTL_MS })
+ return id
+ }
+
+ /** A token for [repository] alone, with TOKEN_PERMISSIONS alone. */
+ async createToken(installationId: number, repository: GitHubRepository): Promise<{ token: string; expiresAt: string }> {
+ const answer = await this.call('POST', `/app/installations/${installationId}/access_tokens`, `Bearer ${this.jwt()}`,
+ { repositories: [repository.name], permissions: TOKEN_PERMISSIONS })
+ const body = answer.body as Record<string, unknown>
+ if (answer.status === 201 && typeof body.token === 'string' && typeof body.expires_at === 'string' && Number.isFinite(Date.parse(body.expires_at))) {
+ return { token: body.token, expiresAt: body.expires_at }
+ }
+ if (answer.status === 401) throw this.misconfigured()
+ if (answer.status === 404 || answer.status === 422 || answer.status === 403) {
+ this.installations.delete(repository.fullName.toLowerCase())
+ // GitHub says which: the installation lacks the repository, or has not accepted a permission asked for.
+ if (/permission/i.test(String(body.message ?? ''))) {
+ throw new GitHubAppError('GITHUB_APP_PERMISSIONS',
+ `The Harness GitHub App on ${repository.owner} has not been granted all the permissions it needs. An owner of ${repository.owner} should accept its requested permissions in the app's installation settings.`, 409)
+ }
+ throw this.notInstalled(repository)
+ }
+ throw new GitHubAppError('GITHUB_UNAVAILABLE', `GitHub could not create a token for ${repository.fullName}.`, 502)
+ }
+
+ /** Ends [token] at once (DELETE /installation/token, authorised by the token itself). One GitHub already ended reads as
+ * done. */
+ async revoke(token: string): Promise<void> {
+ const answer = await this.call('DELETE', '/installation/token', `Bearer ${token}`)
+ if (answer.status === 204 || answer.status === 401) return
+ throw new GitHubAppError('GITHUB_UNAVAILABLE', `GitHub did not revoke the token (HTTP ${answer.status}).`, 502)
+ }
+
+ /** The default branch and whether pushing to it straight needs a pull request, read with the agent's own token
+ * (metadata and contents read): rulesets first (GET /repos/{owner}/{repo}/rules/branches/{branch}), then classic
+ * protection's flag on the branch. Remembered ten minutes; a failed read is `unknown`, never a refusal. */
+ async defaultBranch(repository: GitHubRepository, token: string): Promise<DefaultBranch> {
+ const key = repository.fullName.toLowerCase()
+ const known = this.branches.get(key)
+ if (known && known.until > this.now()) return known.value
+ const auth = `Bearer ${token}`, path = `/repos/${repository.owner}/${repository.name}`
+ let value: DefaultBranch = { branch: null, protection: 'unknown' }
+ try {
+ const repo = await this.call('GET', path, auth)
+ const branch = (repo.body as Record<string, unknown>).default_branch
+ if (repo.status === 200 && typeof branch === 'string' && branch) {
+ value = { branch, protection: 'unknown' }
+ const rules = await this.call('GET', `${path}/rules/branches/${encodeURIComponent(branch)}`, auth)
+ if (rules.status === 200 && Array.isArray(rules.body) && rules.body.some(rule => (rule as Record<string, unknown>)?.type === 'pull_request')) {
+ value = { branch, protection: 'pull_request' }
+ } else {
+ const classic = await this.call('GET', `${path}/branches/${encodeURIComponent(branch)}`, auth)
+ const flag = (classic.body as Record<string, unknown>).protected
+ if (classic.status === 200 && typeof flag === 'boolean') value = { branch, protection: flag ? 'classic' : 'none' }
+ }
+ }
+ } catch (error) {
+ if (!(error instanceof GitHubAppError)) throw error
+ }
+ if (value.protection !== 'unknown') this.branches.set(key, { value, until: this.now() + BRANCH_TTL_MS })
+ return value
+ }
+}
diff --git a/backend/src/github/attribution.ts b/backend/src/github/attribution.ts
new file mode 100644
index 000000000..c996a29e9
--- /dev/null
+++ b/backend/src/github/attribution.ts
@@ -0,0 +1,24 @@
+/** Who a Swarm agent's commits and pull requests say the work is for, and which agent and machine did it. The machine
+ * writes the trailers into each commit message (cli/src/superTabs/githubTools.ts); the line opens the pull request body. */
+export interface Attribution {
+ requestedBy: { name: string; email: string }
+ agent: string
+ machine: string | null
+ trailers: string[]
+ pullRequestLine: string
+}
+
+/** One line of plain text: no control characters, and no angle brackets, which would end an address in a trailer. */
+const plain = (text: string, max = 100) => text.replace(/[\x00-\x1f\x7f<>]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max).trim()
+
+export function attribution(input: { requester: { name: string | null; email: string }; agentName: string; machineName: string | null }): Attribution {
+ const email = plain(input.requester.email, 254).replace(/\s/g, '')
+ const name = plain(input.requester.name ?? '') || plain(email.split('@')[0] ?? '') || email
+ const agent = plain(input.agentName) || 'Agent'
+ const machine = input.machineName ? plain(input.machineName) || null : null
+ return {
+ requestedBy: { name, email }, agent, machine,
+ trailers: [`Co-authored-by: ${name} <${email}>`, `Harness-Agent: ${agent}`, ...(machine ? [`Harness-Machine: ${machine}`] : [])],
+ pullRequestLine: `Requested by ${name} (${email}) through Harness.`,
+ }
+}
diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.ts
new file mode 100644
index 000000000..5a0e1aa00
--- /dev/null
+++ b/backend/src/github/fakeGitHub.ts
@@ -0,0 +1,84 @@
+/**
+ * Tests only: a fake GitHub REST API for the Harness GitHub App, and a throwaway RSA key. Nothing here reaches github.com.
+ */
+import { createPublicKey, generateKeyPairSync, verify, type KeyObject } from 'node:crypto'
+import { GitHubApp, type GitHubAppConfig } from './app.js'
+
+export const FAKE_API = 'https://github.fake.test'
+
+export function throwawayKey(): { privateKey: KeyObject; pem: string; publicKey: KeyObject } {
+ const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })
+ return { privateKey, pem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), publicKey: createPublicKey(privateKey) }
+}
+
+export interface FakeCall { method: string; path: string; auth: string; body: unknown }
+
+/** One fake GitHub: which repositories have the app (`installed`, by `owner/name`, lower case), what each default branch's
+ * protection is, and every request it was sent. A request whose JWT is not signed by [publicKey] is answered 401. */
+export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?: () => number }) {
+ const now = options.now ?? Date.now
+ const installed = new Map<string, number>()
+ const protection = new Map<string, { rules?: unknown[]; protected?: boolean; branch?: string; fail?: boolean }>()
+ const calls: FakeCall[] = []
+ const issued = new Set<string>()
+ const revoked: string[] = []
+ let minted = 0
+ const control = { revokeStatus: 204, tokenStatus: 201 as number, tokenMessage: '', down: false }
+ const json = (status: number, body?: unknown) => new Response(body === undefined ? null : JSON.stringify(body), { status })
+ const jwtValid = (auth: string) => {
+ const jwt = auth.replace(/^Bearer /, '')
+ const [header, payload, signature] = jwt.split('.')
+ if (!header || !payload || !signature) return false
+ if (!verify('sha256', Buffer.from(`${header}.${payload}`), options.publicKey, Buffer.from(signature, 'base64url'))) return false
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString()) as { iat: number; exp: number; iss: string }
+ const seconds = Math.floor(now() / 1000)
+ return claims.iss === options.appId && claims.iat <= seconds && claims.exp > seconds && claims.exp - claims.iat <= 600
+ }
+ const fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input))
+ const method = init?.method ?? 'GET'
+ const auth = String((init?.headers as Record<string, string> | undefined)?.Authorization ?? '')
+ const body = init?.body ? JSON.parse(String(init.body)) : undefined
+ calls.push({ method, path: url.pathname, auth, body })
+ if (control.down) throw new TypeError('fetch failed')
+ let match: RegExpExecArray | null
+ if (method === 'GET' && (match = /^\/repos\/([^/]+)\/([^/]+)\/installation$/.exec(url.pathname))) {
+ if (!jwtValid(auth)) return json(401, { message: 'Bad credentials' })
+ const id = installed.get(`${match[1]}/${match[2]}`.toLowerCase())
+ return id === undefined ? json(404, { message: 'Not Found' }) : json(200, { id, account: { login: match[1] } })
+ }
+ 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 })
+ const token = `ghs_fixture_${++minted}`
+ issued.add(token)
+ return json(201, { token, expires_at: new Date(now() + 3600_000).toISOString(), permissions: (body as { permissions: unknown }).permissions })
+ }
+ if (method === 'DELETE' && url.pathname === '/installation/token') {
+ const token = auth.replace(/^Bearer /, '')
+ if (!issued.has(token)) return json(401, { message: 'Bad credentials' })
+ if (control.revokeStatus !== 204) return json(control.revokeStatus, { message: 'Server Error' })
+ issued.delete(token)
+ revoked.push(token)
+ return json(204)
+ }
+ const repoPath = /^\/repos\/([^/]+)\/([^/]+)(\/.*)?$/.exec(url.pathname)
+ if (method === 'GET' && repoPath) {
+ if (!issued.has(auth.replace(/^Bearer /, ''))) return json(401, { message: 'Bad credentials' })
+ const known = protection.get(`${repoPath[1]}/${repoPath[2]}`.toLowerCase()) ?? {}
+ if (known.fail) return json(500, { message: 'Server Error' })
+ const branch = known.branch ?? 'main'
+ if (!repoPath[3]) return json(200, { full_name: `${repoPath[1]}/${repoPath[2]}`, default_branch: branch })
+ if (repoPath[3] === `/rules/branches/${encodeURIComponent(branch)}`) return json(200, known.rules ?? [])
+ if (repoPath[3] === `/branches/${encodeURIComponent(branch)}`) return json(200, { name: branch, protected: known.protected ?? false })
+ }
+ return json(404, { message: 'Not Found' })
+ }) as typeof globalThis.fetch
+ return { fetch, calls, installed, protection, revoked, issued, control }
+}
+
+/** A configured app talking to [github]. */
+export function fakeApp(key: KeyObject, github: ReturnType<typeof fakeGitHub>, options: { appId?: string; slug?: string | null; now?: () => number } = {}) {
+ const config: GitHubAppConfig = { appId: options.appId ?? '424242', privateKey: key, slug: options.slug === undefined ? 'harness-fixture' : options.slug }
+ return new GitHubApp(config, { fetch: github.fetch, apiUrl: FAKE_API, now: options.now })
+}
diff --git a/backend/src/github/holds.ts b/backend/src/github/holds.ts
new file mode 100644
index 000000000..e9452cf4d
--- /dev/null
+++ b/backend/src/github/holds.ts
@@ -0,0 +1,23 @@
+import type { SuperTabState, WorkStatus } from '../superTabs/model.js'
+
+/** An agent's task in progress, which a GitHub token may serve. */
+export interface WorkHold { agentId: string; assignmentId: string }
+
+/** The statuses of a task still in the agent's hands: working, waiting on a person, stuck, or out for review (a Builder
+ * fixes what its Reviewer finds). Done, stopped, cancelled and reconciling (its agent removed) are not. */
+export const HOLDING: ReadonlySet<WorkStatus> = new Set<WorkStatus>(['working', 'needs_human', 'blocked', 'review'])
+
+/** Every task in progress in [state], held by an agent still in it. */
+export function workHolds(state: Pick<SuperTabState, 'agents' | 'conversations'>): WorkHold[] {
+ return state.conversations.flatMap(group => {
+ const work = group.assignment
+ return work && HOLDING.has(work.status) && state.agents.some(a => a.id === work.agentId)
+ ? [{ agentId: work.agentId, assignmentId: work.id }] : []
+ })
+}
+
+/** The holds in [before] that [after] no longer has: the task ended, went to another agent or attempt, or its agent left. */
+export function endedHolds(before: Pick<SuperTabState, 'agents' | 'conversations'>, after: Pick<SuperTabState, 'agents' | 'conversations'>): WorkHold[] {
+ const still = new Set(workHolds(after).map(hold => `${hold.agentId}:${hold.assignmentId}`))
+ return workHolds(before).filter(hold => !still.has(`${hold.agentId}:${hold.assignmentId}`))
+}
diff --git a/backend/src/github/repository.test.ts b/backend/src/github/repository.test.ts
new file mode 100644
index 000000000..ac39c7339
--- /dev/null
+++ b/backend/src/github/repository.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest'
+import { attribution } from './attribution.js'
+import { endedHolds, workHolds } from './holds.js'
+import { githubRepository } from './repository.js'
+import type { Conversation, SuperTabState, WorkStatus } from '../superTabs/model.js'
+
+describe('github repository addresses', () => {
+ it('reads https, ssh and scp-like github.com addresses', () => {
+ for (const url of ['https://github.com/acme/app', 'https://github.com/acme/app.git', 'https://github.com/acme/app/', 'http://github.com/acme/app',
+ 'https://GitHub.com/acme/app', 'ssh://[email protected]/acme/app.git', '[email protected]:acme/app.git', '[email protected]:acme/app']) {
+ expect(githubRepository(url), url).toEqual({ owner: 'acme', name: 'app', fullName: 'acme/app' })
+ }
+ expect(githubRepository('https://github.com/a-b/my.repo_1')).toEqual({ owner: 'a-b', name: 'my.repo_1', fullName: 'a-b/my.repo_1' })
+ })
+
+ it('refuses other hosts, credentials, extra path parts and impossible names', () => {
+ for (const url of [null, undefined, '', 'not a url', 'https://gitlab.com/acme/app', 'https://github.com.evil.test/acme/app',
+ 'https://[email protected]/acme/app', 'https://github.com:8443/acme/app', 'ssh://[email protected]/acme/app', 'git://github.com/acme/app',
+ 'https://github.com/acme', 'https://github.com/acme/app/tree/main', 'https://github.com/acme/app?x=1', 'https://github.com/-acme/app',
+ 'https://github.com/ac--me/app', 'https://github.com/acme/..', 'https://github.com/acme/a%20b', '[email protected]:acme/app.git']) {
+ expect(githubRepository(url), String(url)).toBeNull()
+ }
+ })
+})
+
+const group = (id: string, agentId: string, status: WorkStatus, assignmentId = `${id}-attempt`): Conversation => ({
+ id, title: id, leadId: null, agentIds: [agentId], archived: false, brief: '', checks: [], lastMessageSequence: 0,
+ assignment: { id: assignmentId, agentId, status, result: null, configuration: { engine: 'codex', model: null, effort: null, contextWindow: null, engineVersion: null },
+ execution: { machineId: 'm', harnessId: 'h', machineOwnerId: 'u' } },
+})
+const state = (conversations: Conversation[], agents = ['a1', 'a2', 'a3']) =>
+ ({ agents: agents.map(id => ({ id })), conversations } as unknown as Pick<SuperTabState, 'agents' | 'conversations'>)
+
+describe('tasks in an agent\'s hands', () => {
+ it('counts working, waiting, stuck and in-review tasks of agents still present', () => {
+ const before = state([group('g1', 'a1', 'working'), group('g2', 'a2', 'review'), group('g3', 'a3', 'needs_human'), group('g4', 'a1', 'blocked'),
+ group('g5', 'a2', 'done'), group('g6', 'a3', 'reconciling'), group('g7', 'gone', 'working'), { ...group('g8', 'a1', 'working'), assignment: null }])
+ expect(workHolds(before).map(h => h.assignmentId)).toEqual(['g1-attempt', 'g2-attempt', 'g3-attempt', 'g4-attempt'])
+ })
+
+ it('ends a hold when the task is done, cancelled, stopped, reconciling, reassigned or its agent leaves', () => {
+ const before = state([group('g1', 'a1', 'working'), group('g2', 'a2', 'working'), group('g3', 'a3', 'review'), group('g4', 'a1', 'blocked')])
+ const after = state([group('g1', 'a1', 'done'), group('g2', 'a2', 'working', 'new-attempt'), group('g3', 'a3', 'working'), group('g4', 'a1', 'cancelled')], ['a1', 'a2'])
+ expect(endedHolds(before, after)).toEqual([{ agentId: 'a1', assignmentId: 'g1-attempt' }, { agentId: 'a2', assignmentId: 'g2-attempt' },
+ { agentId: 'a3', assignmentId: 'g3-attempt' }, { agentId: 'a1', assignmentId: 'g4-attempt' }])
+ expect(endedHolds(before, before)).toEqual([])
+ expect(endedHolds(state([group('g1', 'a1', 'working')]), state([group('g1', 'a1', 'review')]))).toEqual([])
+ expect(endedHolds(state([group('g1', 'a1', 'working')]), state([group('g1', 'a1', 'stopped')]))).toHaveLength(1)
+ })
+})
+
+describe('attribution', () => {
+ it('names the requester, the agent and the machine in trailers and the pull request line', () => {
+ expect(attribution({ requester: { name: 'Ada Lovelace', email: '[email protected]' }, agentName: 'Atlas', machineName: 'Studio Mac' })).toEqual({
+ requestedBy: { name: 'Ada Lovelace', email: '[email protected]' }, agent: 'Atlas', machine: 'Studio Mac',
+ trailers: ['Co-authored-by: Ada Lovelace <[email protected]>', 'Harness-Agent: Atlas', 'Harness-Machine: Studio Mac'],
+ pullRequestLine: 'Requested by Ada Lovelace ([email protected]) through Harness.',
+ })
+ })
+
+ it('falls back to the address for a missing name and keeps every value on one line', () => {
+ const made = attribution({ requester: { name: ' ', email: '[email protected]' }, agentName: 'Builder\nHarness-Agent: forged', machineName: null })
+ expect(made.trailers).toEqual(['Co-authored-by: grace <[email protected]>', 'Harness-Agent: Builder Harness-Agent: forged'])
+ expect(attribution({ requester: { name: 'Eve <[email protected]>', email: '[email protected]' }, agentName: '', machineName: '\n' }).trailers)
+ .toEqual(['Co-authored-by: Eve [email protected] <[email protected]>', 'Harness-Agent: Agent'])
+ })
+})
diff --git a/backend/src/github/repository.ts b/backend/src/github/repository.ts
new file mode 100644
index 000000000..f638b8aee
--- /dev/null
+++ b/backend/src/github/repository.ts
@@ -0,0 +1,27 @@
+/** A repository on github.com, as a Swarm project records it (superTabs/commands.ts `repositoryUrl`). */
+export interface GitHubRepository { owner: string; name: string; fullName: string }
+
+// GitHub's own limits: an owner is 1–39 letters, digits and single dashes; a repository name is letters, digits, `.`, `_`
+// and `-`, never `.` or `..` alone.
+const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}$/
+const NAME = /^[A-Za-z0-9._-]{1,100}$/
+
+/** `owner/name` of a github.com repository address (https, ssh or scp-like), or null for any other host or shape. */
+export function githubRepository(url: string | null | undefined): GitHubRepository | null {
+ if (!url) return null
+ let path: string
+ const scp = /^git@github\.com:(.+)$/i.exec(url)
+ if (scp) path = scp[1]!
+ else {
+ let parsed: URL
+ try { parsed = new URL(url) } catch { return null }
+ if (parsed.hostname.toLowerCase() !== 'github.com' || parsed.port || parsed.search || parsed.hash) return null
+ if (parsed.protocol === 'ssh:' ? parsed.username !== 'git' : !['https:', 'http:'].includes(parsed.protocol) || parsed.username) return null
+ path = parsed.pathname.replace(/^\//, '')
+ }
+ const parts = path.replace(/\/$/, '').replace(/\.git$/i, '').split('/')
+ if (parts.length !== 2) return null
+ const [owner, name] = parts as [string, string]
+ if (!OWNER.test(owner) || !NAME.test(name) || name === '.' || name === '..') return null
+ return { owner, name, fullName: `${owner}/${name}` }
+}
diff --git a/backend/src/github/tokens.test.ts b/backend/src/github/tokens.test.ts
new file mode 100644
index 000000000..2349147e3
--- /dev/null
+++ b/backend/src/github/tokens.test.ts
@@ -0,0 +1,152 @@
+import { randomBytes } from 'node:crypto'
+import { describe, expect, it, vi } from 'vitest'
+import { fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'
+import { githubRepository } from './repository.js'
+import { GitHubTokens, MemoryTokenCache, RedisTokenCache, REUSE_MARGIN_MS, type TokenCache } from './tokens.js'
+
+const key = throwawayKey()
+const repository = githubRepository('[email protected]:acme/app.git')!
+const setup = (cacheOverride?: TokenCache) => {
+ let t = Date.parse('2026-10-24T12:00:00Z')
+ const now = () => t
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242', now })
+ github.installed.set('acme/app', 77)
+ const cache = new MemoryTokenCache(now)
+ const log = { warn: vi.fn() }
+ const tokens = new GitHubTokens(fakeApp(key.privateKey, github, { now }), cacheOverride ?? cache, { now, log, secret: randomBytes(32) })
+ return { github, cache, log, tokens, advance: (ms: number) => { t += ms } }
+}
+const request = (assignmentId = 'attempt-1', agentId = 'agent-1') => ({ tabId: 'tab-1', agentId, assignmentId, repository })
+
+describe('agent tokens', () => {
+ it('mints one for the task and gives the same token again until ten minutes before it expires', async () => {
+ const { tokens, github, advance } = setup()
+ const first = await tokens.issue(request())
+ expect(first).toMatchObject({ token: 'ghs_fixture_1', repository: 'acme/app', defaultBranch: 'main', defaultBranchProtected: false,
+ defaultBranchProtection: 'none' })
+ advance(60 * 60_000 - REUSE_MARGIN_MS - 1000)
+ expect((await tokens.issue(request())).token).toBe('ghs_fixture_1')
+ advance(2000)
+ const renewed = await tokens.issue(request())
+ expect(renewed.token).toBe('ghs_fixture_2')
+ // The old one is close to its end and may still be in use: it is left to expire, not revoked.
+ expect(github.revoked).toEqual([])
+ expect(github.calls.filter(c => c.path.endsWith('/access_tokens'))).toHaveLength(2)
+ })
+
+ it('says when the default branch requires a pull request', async () => {
+ const { tokens, github } = setup()
+ github.protection.set('acme/app', { rules: [{ type: 'pull_request' }] })
+ expect(await tokens.issue(request())).toMatchObject({ defaultBranchProtected: true, defaultBranchProtection: 'pull_request' })
+ })
+
+ it('asks GitHub once for concurrent requests from the same task', async () => {
+ const { tokens, github } = setup()
+ const [a, b] = await Promise.all([tokens.issue(request()), tokens.issue(request())])
+ expect(a.token).toBe(b.token)
+ expect(github.calls.filter(c => c.path.endsWith('/access_tokens'))).toHaveLength(1)
+ })
+
+ it('keeps tokens apart per agent and seals them in the cache', async () => {
+ const stored: string[] = []
+ const memory = new MemoryTokenCache()
+ const spy: TokenCache = { get: k => memory.get(k), delete: k => memory.delete(k),
+ set: async (k, v, ttl) => { stored.push(v); await memory.set(k, v, ttl) } }
+ const { tokens } = setup(spy)
+ const one = await tokens.issue(request('attempt-1', 'agent-1'))
+ const two = await tokens.issue(request('attempt-2', 'agent-2'))
+ expect(one.token).not.toBe(two.token)
+ expect(stored).toHaveLength(2)
+ for (const value of stored) {
+ expect(value).not.toContain('ghs_')
+ expect(value).not.toContain('attempt')
+ }
+ })
+
+ it('revokes a token cached for an earlier task before minting for the new one', async () => {
+ const { tokens, github } = setup()
+ const first = await tokens.issue(request('attempt-1'))
+ const second = await tokens.issue(request('attempt-2'))
+ expect(second.token).not.toBe(first.token)
+ expect(github.revoked).toEqual([first.token])
+ })
+
+ it('refuses a repository the app is not installed on, with the install link', async () => {
+ const { tokens, github } = setup()
+ github.installed.clear()
+ await expect(tokens.issue(request())).rejects.toMatchObject({ code: 'GITHUB_APP_NOT_INSTALLED', status: 409,
+ details: { installUrl: 'https://github.com/apps/harness-fixture/installations/new' } })
+ })
+
+ it('still answers when the cache is away, and logs that without the token', async () => {
+ const broken: TokenCache = { get: async () => { throw new Error('redis down') }, set: async () => { throw new Error('redis down') },
+ delete: async () => { throw new Error('redis down') } }
+ const { tokens, log } = setup(broken)
+ const issued = await tokens.issue(request())
+ expect(issued.token).toBe('ghs_fixture_1')
+ await tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])
+ expect(log.warn).toHaveBeenCalled()
+ expect(JSON.stringify(log.warn.mock.calls)).not.toContain('ghs_')
+ })
+
+ it('ignores a cache entry it cannot open', async () => {
+ const memory = new MemoryTokenCache()
+ const { tokens } = setup({ get: async () => 'garbage.value', set: (k, v, t) => memory.set(k, v, t), delete: k => memory.delete(k) })
+ expect((await tokens.issue(request())).token).toBe('ghs_fixture_1')
+ })
+})
+
+describe('revoking when a task ends', () => {
+ it('revokes and forgets the token of each ended task, and only that task\'s', async () => {
+ const { tokens, github } = setup()
+ const one = await tokens.issue(request('attempt-1', 'agent-1'))
+ const two = await tokens.issue(request('attempt-2', 'agent-2'))
+ await tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }, { agentId: 'agent-2', assignmentId: 'older-attempt' },
+ { agentId: 'agent-3', assignmentId: 'attempt-3' }])
+ expect(github.revoked).toEqual([one.token])
+ // Forgotten: the next request for the same task mints a fresh token, and agent-2 keeps its own.
+ expect((await tokens.issue(request('attempt-1', 'agent-1'))).token).not.toBe(one.token)
+ expect((await tokens.issue(request('attempt-2', 'agent-2'))).token).toBe(two.token)
+ })
+
+ it('logs a failed revoke without the token, drops it anyway and never throws', async () => {
+ const { tokens, github, log } = setup()
+ const issued = await tokens.issue(request())
+ github.control.revokeStatus = 500
+ await expect(tokens.release('tab-1', [{ agentId: 'agent-1', assignmentId: 'attempt-1' }])).resolves.toBeUndefined()
+ expect(log.warn).toHaveBeenCalledWith('[github] token revoke failed', { tabId: 'tab-1', agentId: 'agent-1', repository: 'acme/app',
+ why: 'task ended', code: 'GITHUB_UNAVAILABLE' })
+ expect(JSON.stringify(log.warn.mock.calls)).not.toContain(issued.token)
+ github.control.revokeStatus = 204
+ expect((await tokens.issue(request())).token).not.toBe(issued.token)
+ })
+
+ it('refuses a sealing key of the wrong size', () => {
+ const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242' })
+ expect(() => new GitHubTokens(fakeApp(key.privateKey, github), new MemoryTokenCache(), { secret: Buffer.alloc(16) })).toThrow('32-byte key')
+ })
+})
+
+describe('token caches', () => {
+ it('expires memory entries', async () => {
+ let t = 0
+ const cache = new MemoryTokenCache(() => t)
+ await cache.set('k', 'v', 1000)
+ expect(await cache.get('k')).toBe('v')
+ t = 1000
+ expect(await cache.get('k')).toBeNull()
+ await cache.set('k', 'v', 1000)
+ await cache.delete('k')
+ expect(await cache.get('k')).toBeNull()
+ })
+
+ it('stores Redis entries with a millisecond expiry', async () => {
+ const redis = { get: vi.fn(async () => 'sealed'), set: vi.fn(async () => 'OK' as const), del: vi.fn(async () => 1) }
+ const cache = new RedisTokenCache(redis as never)
+ expect(await cache.get('k')).toBe('sealed')
+ await cache.set('k', 'v', 1234.7)
+ await cache.delete('k')
+ expect(redis.set).toHaveBeenCalledWith('k', 'v', 'PX', 1234)
+ expect(redis.del).toHaveBeenCalledWith('k')
+ })
+})
diff --git a/backend/src/github/tokens.ts b/backend/src/github/tokens.ts
new file mode 100644
index 000000000..d6cc1945b
--- /dev/null
+++ b/backend/src/github/tokens.ts
@@ -0,0 +1,184 @@
+/**
+ * Installation tokens for Swarm agents (routes/superTabs.ts `github-token`): one per agent and task, kept until ten
+ * minutes before it expires, and revoked as soon as that task ends (superTabs/store.ts `workEnded`).
+ *
+ * The cache is shared by every backend process (Redis in production), so a task closed on one process revokes the token
+ * another process issued. Entries are sealed with a key derived from the app's private key (github/app.ts
+ * `cacheSecret`). Nothing here logs a token.
+ */
+import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'
+import type { Redis } from 'ioredis'
+import { logger } from '../utils/logger.js'
+import { GitHubApp, GitHubAppError, cacheSecret, githubAppConfig, type BranchProtection } from './app.js'
+import type { GitHubRepository } from './repository.js'
+import type { WorkHold } from './holds.js'
+
+export interface TokenCache {
+ get(key: string): Promise<string | null>
+ set(key: string, value: string, ttlMs: number): Promise<void>
+ delete(key: string): Promise<void>
+}
+
+/** One process's cache, for tests and a backend without Redis. */
+export class MemoryTokenCache implements TokenCache {
+ private readonly entries = new Map<string, { value: string; until: number }>()
+ constructor(private readonly now: () => number = Date.now) {}
+ async get(key: string) {
+ const entry = this.entries.get(key)
+ if (!entry || entry.until <= this.now()) { this.entries.delete(key); return null }
+ return entry.value
+ }
+ async set(key: string, value: string, ttlMs: number) { this.entries.set(key, { value, until: this.now() + ttlMs }) }
+ async delete(key: string) { this.entries.delete(key) }
+}
+
+/** The backend's shared Redis (lib/bus.ts `pub`), which fails fast rather than queueing while Redis is away. */
+export class RedisTokenCache implements TokenCache {
+ constructor(private readonly redis: Pick<Redis, 'get' | 'set' | 'del'>) {}
+ async get(key: string) { return this.redis.get(key) }
+ async set(key: string, value: string, ttlMs: number) { await this.redis.set(key, value, 'PX', Math.max(1, Math.floor(ttlMs))) }
+ async delete(key: string) { await this.redis.del(key) }
+}
+
+/** What one agent's task may use. */
+export interface TokenRequest { tabId: string; agentId: string; assignmentId: string; repository: GitHubRepository }
+export interface IssuedToken {
+ token: string
+ expiresAt: string
+ repository: string
+ defaultBranch: string | null
+ /** True only when a ruleset is known to require a pull request on the default branch. False asks the Lead to warn
+ * people that this token can push to it straight. */
+ defaultBranchProtected: boolean
+ defaultBranchProtection: BranchProtection
+}
+interface Entry { token: string; expiresAt: string; repository: string; assignmentId: string }
+
+/** A token is handed out again until this long before it expires, so whoever holds it has at least that long. */
+export const REUSE_MARGIN_MS = 10 * 60_000
+const KEY_PREFIX = 'harness:github-token:v1'
+
+export interface GitHubTokensOptions {
+ now?: () => number
+ log?: Pick<typeof logger, 'warn'>
+ /** The sealing key (github/app.ts `cacheSecret`). */
+ secret: Buffer
+}
+
+export class GitHubTokens {
+ private readonly now: () => number
+ private readonly log: Pick<typeof logger, 'warn'>
+ private readonly secret: Buffer
+ private readonly flights = new Map<string, Promise<IssuedToken>>()
+
+ constructor(readonly app: GitHubApp, private readonly cache: TokenCache, options: GitHubTokensOptions) {
+ this.now = options.now ?? Date.now
+ this.log = options.log ?? logger
+ if (options.secret.length !== 32) throw new Error('The GitHub token cache needs a 32-byte key.')
+ this.secret = options.secret
+ }
+
+ private key(tabId: string, agentId: string) { return `${KEY_PREFIX}:${tabId}:${agentId}` }
+
+ private seal(entry: Entry): string {
+ const iv = randomBytes(12)
+ const cipher = createCipheriv('aes-256-gcm', this.secret, iv)
+ const body = Buffer.concat([cipher.update(JSON.stringify(entry), 'utf8'), cipher.final()])
+ return [iv, cipher.getAuthTag(), body].map(part => part.toString('base64url')).join('.')
+ }
+
+ private open(value: string | null): Entry | null {
+ if (!value) return null
+ try {
+ const [iv, tag, body] = value.split('.').map(part => Buffer.from(part, 'base64url'))
+ const decipher = createDecipheriv('aes-256-gcm', this.secret, iv!)
+ decipher.setAuthTag(tag!)
+ const entry = JSON.parse(Buffer.concat([decipher.update(body!), decipher.final()]).toString('utf8')) as Entry
+ return typeof entry.token === 'string' && typeof entry.expiresAt === 'string' && typeof entry.assignmentId === 'string'
+ && typeof entry.repository === 'string' ? entry : null
+ } catch { return null }
+ }
+
+ private async read(key: string): Promise<Entry | null> {
+ try { return this.open(await this.cache.get(key)) } catch (error) {
+ this.log.warn('[github] token cache unreadable', { error: error instanceof Error ? error.message : String(error) })
+ return null
+ }
+ }
+
+ /** The agent's token for its task: the cached one while it has more than REUSE_MARGIN_MS left, else a new one. A token
+ * cached for an earlier task or another repository is revoked first. */
+ async issue(request: TokenRequest): Promise<IssuedToken> {
+ const key = this.key(request.tabId, request.agentId)
+ const flight = `${key}:${request.assignmentId}:${request.repository.fullName}`
+ const running = this.flights.get(flight)
+ if (running) return running
+ const work = this.mint(key, request).finally(() => this.flights.delete(flight))
+ this.flights.set(flight, work)
+ return work
+ }
+
+ private async mint(key: string, request: TokenRequest): Promise<IssuedToken> {
+ const repository = request.repository.fullName
+ const cached = await this.read(key)
+ let entry: Entry | null = null
+ if (cached && cached.assignmentId === request.assignmentId && cached.repository === repository) {
+ if (Date.parse(cached.expiresAt) - this.now() > REUSE_MARGIN_MS) entry = cached
+ // Close to its end, it is left to expire: the agent may still be using it.
+ } else if (cached) {
+ await this.revoke(request.tabId, request.agentId, cached, 'replaced')
+ await this.forget(key)
+ }
+ if (!entry) {
+ const installation = await this.app.installation(request.repository)
+ if (installation === null) throw this.app.notInstalled(request.repository)
+ const minted = await this.app.createToken(installation, request.repository)
+ entry = { ...minted, repository, assignmentId: request.assignmentId }
+ const ttl = Date.parse(minted.expiresAt) - this.now()
+ if (ttl > 0) {
+ try { await this.cache.set(key, this.seal(entry), ttl) } catch (error) {
+ // Not cached, it cannot be revoked when the task ends; it still expires within the hour.
+ this.log.warn('[github] token not cached', { tabId: request.tabId, agentId: request.agentId, repository,
+ error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+ }
+ const branch = await this.app.defaultBranch(request.repository, entry.token)
+ return { token: entry.token, expiresAt: entry.expiresAt, repository, defaultBranch: branch.branch,
+ defaultBranchProtected: branch.protection === 'pull_request', defaultBranchProtection: branch.protection }
+ }
+
+ private async revoke(tabId: string, agentId: string, entry: Entry, why: string): Promise<void> {
+ try { await this.app.revoke(entry.token) } catch (error) {
+ this.log.warn('[github] token revoke failed', { tabId, agentId, repository: entry.repository, why,
+ code: error instanceof GitHubAppError ? error.code : 'ERROR' })
+ }
+ }
+
+ private async forget(key: string): Promise<void> {
+ try { await this.cache.delete(key) } catch (error) {
+ this.log.warn('[github] token cache entry not removed', { error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+
+ /** The tasks that ended in [tabId] (done, cancelled, stopped, reassigned, or the agent removed): each one's cached token is
+ * revoked and forgotten. Never throws; a failed revoke is logged without the token and leaves the token to expire. */
+ async release(tabId: string, ended: readonly WorkHold[]): Promise<void> {
+ for (const hold of ended) {
+ const key = this.key(tabId, hold.agentId)
+ const entry = await this.read(key)
+ if (!entry || entry.assignmentId !== hold.assignmentId) continue
+ await this.revoke(tabId, hold.agentId, entry, 'task ended')
+ await this.forget(key)
+ }
+ }
+}
+
+/** The app from the server's environment, sharing tokens through Redis; null when it is not configured. */
+export async function githubTokensFromEnv(env: { GITHUB_APP_ID: string; GITHUB_APP_PRIVATE_KEY: string; GITHUB_APP_SLUG: string }): Promise<GitHubTokens | null> {
+ const config = githubAppConfig(env)
+ if (!config) return null
+ // Loaded only when configured: importing the bus opens its Redis connections.
+ const { pub } = await import('../lib/bus.js')
+ return new GitHubTokens(new GitHubApp(config), new RedisTokenCache(pub), { secret: cacheSecret(config) })
+}
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index fb137535b..9067b3a59 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -14,6 +14,11 @@ import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'
import { machineObservationSchema } from '../superTabs/machines.js'
import { joinSwarmSchema, previewJoinSchema, saveSharingSchema } from '../superTabs/sharing.js'
import { holdReason } from '../superTabs/holdNotice.js'
+import { GitHubAppError } from '../github/app.js'
+import { githubRepository } from '../github/repository.js'
+import { attribution } from '../github/attribution.js'
+import { githubTokensFromEnv, type GitHubTokens } from '../github/tokens.js'
+import { logger } from '../utils/logger.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const tabParams = z.object({ tabId: id })
@@ -43,18 +48,24 @@ const deliveryAction = z.discriminatedUnion('type', [
const mentionQuery = z.object({ state: z.enum(['waiting', 'earlier']) }).strict()
const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()
const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()
+const githubToken = z.object({ machineId: id }).strict()
async function respond(reply: FastifyReply, action: () => Promise<unknown>) {
try { sendSuccess(reply, await action()) } catch (error) {
+ if (error instanceof GitHubAppError) return sendError(reply, error.message, error.code, error.status, error.details)
if (!(error instanceof SuperTabError)) throw error
sendError(reply, error.message, error.code, error.status)
}
}
-/** Uses the normal authenticated control API. It never accepts caller-provided host/contributor identities. */
-export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore } = {}) {
- const store = options.store ?? new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env))
+/** Uses the normal authenticated control API. It never accepts caller-provided host/contributor identities.
+ * `github` is the Harness GitHub App (github/tokens.ts): read from the environment unless given, null when off. */
+export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore; github?: GitHubTokens | null } = {}) {
+ const github = options.github !== undefined ? options.github : await githubTokensFromEnv(env)
+ // A task that ends revokes the token it was given; a revoke that fails is logged inside and never blocks the write.
+ const store = options.store ?? new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env),
+ { workEnded: (tabId, ended) => { void github?.release(tabId, ended).catch(error => logger.warn('[github] release failed', { tabId, error: String(error) })) } })
app.get('/api/super-tabs/grids', (req, reply) => respond(reply, () => store.hostGrids(req.user!)))
app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/pools', { preHandler: validateParams(hostParams) },
(req, reply) => respond(reply, () => store.hostPools(req.user!, req.params.machineId)))
@@ -113,9 +124,26 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
(req, reply) => respond(reply, () => store.terminalResult(req.user!, req.params.tabId, req.params.requestId, req.query.asAgentId, 20_000)))
app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/assignments', { preHandler: validateParams(hostParams) },
(req, reply) => respond(reply, () => store.hostAssignments(req.user!, req.params.machineId)))
+ // `githubApp` (only when the server has the app) lets a Lead's start wire its token into another person's work (cli/src/superTabs/start.ts).
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId',
{ preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },
- (req, reply) => respond(reply, () => store.read(req.user!, req.params.tabId, req.query.asAgentId)))
+ (req, reply) => respond(reply, async () => ({ ...await store.read(req.user!, req.params.tabId, req.query.asAgentId), ...(github ? { githubApp: true } : {}) })))
+ // A one-hour installation token for the repository of the calling agent's task, for git and gh on its machine
+ // (docs/swarm-github-app.md). Only that agent's host, on the machine running it, while the task is in its hands.
+ app.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof githubToken> }>('/api/super-tabs/:tabId/github-token',
+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery), validateBody(githubToken)] },
+ (req, reply) => respond(reply, async () => {
+ if (!github) throw new GitHubAppError('GITHUB_APP_NOT_CONFIGURED', 'This Harness server has no GitHub App configured.', 503)
+ const grant = await store.githubAssignment(req.user!, req.params.tabId, req.query.asAgentId, req.body.machineId)
+ const repository = githubRepository(grant.repositoryUrl)
+ if (!repository) {
+ throw new SuperTabError('REPOSITORY_NOT_GITHUB', grant.repositoryUrl
+ ? 'This project\'s repository is not on github.com, so the Harness GitHub App cannot give a token for it.'
+ : 'This project has no repository address yet. Its owner or Lead can share it (project.repository).', 409)
+ }
+ const issued = await github.issue({ tabId: grant.tabId, agentId: grant.agentId, assignmentId: grant.assignmentId, repository })
+ return { ...issued, ...attribution(grant) }
+ }))
app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof operation> }>('/api/super-tabs/:tabId/commands',
{ preHandler: [validateParams(tabParams), validateBody(operation, { named: true })] },
(req, reply) => respond(reply, () => store.execute(req.user!, req.params.tabId,
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index d38b25ff6..d66ae0270 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -20,6 +20,8 @@ import {
SuperTabError, isLeads, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type MessageDraft, type SuperTabState,
} from './model.js'
import { holdNoticeText, type HoldReason } from './holdNotice.js'
+import { agentDisplayName } from './agentNames.js'
+import { endedHolds, HOLDING, type WorkHold } from '../github/holds.js'
import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, type TerminalEffect } from './terminal.js'
import { closeAssignment, closeUnassignedStart, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
import { listMentions, markDone, mentionsWaiting, readMention, resolveByReply, writeMentions } from './mentions.js'
@@ -109,11 +111,17 @@ async function abandonedStarts(tx: Transaction, tabId: string, state: SuperTabSt
return candidates.filter(s => (recorded.get(stableId(tabId, s.actorKey, s.id)) ?? 0) <= now - ABANDONED_START_MS).map(s => s.id)
}
+export interface SuperTabStoreHooks {
+ /** Tasks that stopped being in an agent's hands with this write (github/holds.ts): done, cancelled, stopped, given to
+ * another attempt, or their agent removed. Called after the write commits; it must not throw. */
+ workEnded?: (tabId: string, ended: WorkHold[]) => void
+}
+
/** Persistent coordination. Host adapters own execution and must confirm their local session grants. */
export class SuperTabStore {
readonly native: SuperTabNativeStore
constructor(private readonly db: PrismaClient, private readonly now: () => number = Date.now,
- private readonly attachments: Attachments | null = null) {
+ private readonly attachments: Attachments | null = null, private readonly hooks: SuperTabStoreHooks = {}) {
this.native = new SuperTabNativeStore({
transaction: body => transaction(db, body),
row: async (tx, user, tabId) => { const row = await this.row(tx, user, tabId); return { row, state: stateOf(row) } },
@@ -363,7 +371,10 @@ export class SuperTabStore {
async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string) {
const { operationId, command } = operationSchema.parse(input)
- return transaction(this.db, async tx => {
+ let ended: WorkHold[] = []
+ const done = await transaction(this.db, async tx => {
+ // A retried attempt starts again: only the attempt that commits says which tasks ended.
+ ended = []
const row = await this.row(tx, user, tabId)
const original = stateOf(row)
// Removal retries can arrive after the actor itself left. Return only this host's exact prior receipt.
@@ -607,6 +618,7 @@ export class SuperTabStore {
await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: {
revision, state: json(effects.state), ...indexes(effects.state),
} })
+ ended = endedHolds(original, effects.state)
await writeRouteEffects(tx, tabId, effects.routeDecisions, context.now)
if (command.type === 'agent.startFailed') {
const start = original.starts?.find(s => s.id === command.startId)
@@ -677,6 +689,43 @@ export class SuperTabStore {
revision, result: json(effects.result) } })
return { revision, result: effects.result }
})
+ this.endWork(tabId, ended)
+ return done
+ }
+
+ private endWork(tabId: string, ended: WorkHold[]): void {
+ if (!ended.length || !this.hooks.workEnded) return
+ try { this.hooks.workEnded(tabId, ended) } catch (error) {
+ logger.warn('[super-tab] work-ended hook failed', { tabId, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+
+ /** What the Harness GitHub App may mint a token for (routes/superTabs.ts `github-token`): the calling host's own agent, on
+ * the machine its host names, with a task in its hands. Who the work is for, and the agent's and machine's names, go
+ * into its commits (github/attribution.ts). The caller checks that the repository is on GitHub. */
+ async githubAssignment(user: AuthUser, tabId: string, asAgentId: string | undefined, machineId: string) {
+ if (!asAgentId) fail('AGENT_REQUIRED', 'Ask for a GitHub token as the agent doing the work (asAgentId).', 400)
+ return transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ const actor = await this.actor(tx, user, state, asAgentId)
+ // A read-only contribution reads; it does not push.
+ author(state, actor, true)
+ const target = agent(state, asAgentId)
+ if (target.machineId !== machineId) fail('FORBIDDEN', 'Only the machine running this agent can ask for its GitHub token.', 403)
+ const group = state.conversations.find(c => !isLeads(c) && c.assignment?.agentId === target.id && HOLDING.has(c.assignment.status)
+ && c.assignment.execution.machineId === target.machineId && c.assignment.execution.machineOwnerId === target.machineOwnerId)
+ ?? fail('NO_ASSIGNMENT', 'This agent has no task in progress. A GitHub token is only for an agent working on a task.')
+ const project = groupProject(state, group)
+ const owner = await tx.user.findUnique({ where: { id: project.ownerId }, select: { name: true, email: true } })
+ const requester = owner ?? { name: null, email: state.people.find(p => p.id === project.ownerId)?.email ?? '' }
+ if (!requester.email) fail('NOT_FOUND', 'This project\'s owner is unavailable.', 404)
+ const contributed = state.machines?.find(m => m.machineId === target.machineId)?.name
+ const machineName = contributed ?? await tx.machine.findFirst({ where: { machineId: target.machineId, userId: target.machineOwnerId },
+ select: { name: true, hostname: true } }).then(m => m?.name ?? m?.hostname ?? null)
+ return { tabId, agentId: target.id, assignmentId: group.assignment!.id, repositoryUrl: project.repository?.repositoryUrl ?? null,
+ requester: { name: requester.name?.trim() || null, email: requester.email },
+ agentName: agentDisplayName(state.agents, target.id) ?? target.displayName ?? target.name, machineName: machineName?.trim() || null }
+ })
}
/** Streams one file into the bucket for a later `message.send` by the same actor in the same conversation. Access is
@@ -1299,9 +1348,12 @@ export class SuperTabStore {
/** Only the recorded execution host may attest that the actual session/attempt has stopped. */
async stopped(user: AuthUser, tabId: string, assignmentId: string, receipt: string) {
- return transaction(this.db, async tx => {
+ let ended: WorkHold[] = []
+ const done = await transaction(this.db, async tx => {
+ ended = []
const row = await this.row(tx, user, tabId)
const state = stateOf(row)
+ const before = { agents: state.agents, conversations: structuredClone(state.conversations) }
const group = state.conversations.find(c => c.assignment?.id === assignmentId)
const assignment = group?.assignment
if (!assignment || assignment.execution.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can confirm this stop.', 403)
@@ -1340,7 +1392,10 @@ export class SuperTabStore {
} })
await this.writeMessages(tx, tabId, state, notices, revision)
if (!prior) await tx.superTabStopReceipt.create({ data: { id, tabId, assignmentId, ...execution, receipt } })
+ ended = endedHolds(before, state)
return { confirmed: true }
})
+ this.endWork(tabId, ended)
+ return done
}
}
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 213c7d684..78701c606 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -1,4 +1,4 @@
import { defineConfig } from 'vitest/config'
-export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts'], hookTimeout: 120000, testTimeout: 30000,
+export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts'], hookTimeout: 120000, testTimeout: 30000,
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 568efaea0..145f51782 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -162,6 +162,8 @@ export class BackendSocket {
swarmRole?: import('./lib/swarmSkills.js').SwarmRole
/** The skills of the Swarm project it joins; absent from a start before modes, which launches on orchestration. */
swarmSkillMode?: import('./lib/swarmSkills.js').SwarmSkillMode
+ /** With swarmRole: git and gh use the Harness GitHub App's token for the agent's task (lib/swarmGitHub.ts). */
+ swarmGitHub?: true
/** The name the pane opens under, instead of the next `agent-N`; null to number it. */
name: string | null
/** The engine's named agent the pane opens AS (`NAMED_AGENT_ARGS` in engineLaunch.ts; opencode
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index c5499f4a8..1be9b32ef 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2648,6 +2648,7 @@ async function logsExportCommand(json: boolean): Promise<void> {
import { orchestratorCommand } from './orchestrator/command.js'
import { superTabCommand } from './superTabs/command.js'
+import { gitCredentialCommand } from './superTabs/gitCredential.js'
import { paneOwner, sendCommand } from './messages/command.js'
import { agentOrigin, closeCommand, psCommand, replyCommand, showCommand, waitCommand, whoamiCommand } from './agentClient/commands.js'
import { agentsHelp, helpFor } from './agentClient/help.js'
@@ -2731,6 +2732,10 @@ switch (cmd) {
case 'super-tab':
superTabCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
+ case 'git-credential':
+ // git's credential helper in a Swarm agent's session (docs/swarm-github-app.md); git runs it, people do not.
+ gitCredentialCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ break
case 'login':
// The result line goes out FIRST (loginCommand prints it), then the daemon is swapped onto the
// account: the desktop app reads that line and does not wait for a restart it observes anyway.
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index da60f0ada..572c24f23 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -27,6 +27,7 @@ import { projectsRoot } from '../../lib/projectFolder.js'
import { NativeFiles } from '../../engines/kit/nativeFiles.js'
import { agentLaunchArgs } from '../../lib/agentAttribution.js'
import { WindowsBatchLaunchRefused } from '../../lib/windows/launch.js'
+import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'
vi.mock('../../lib/projectFolder.js', async real => {
const actual = await real<typeof import('../../lib/projectFolder.js')>()
@@ -73,6 +74,8 @@ vi.mock('../../engines/launchPrep.js', () => ({ folderTrust: (engine: string, pr
? { trusts: (path: string) => trust.claudeTrusts(path), record: (path: string) => trust.preTrustClaudeProject(path) }
: engine === 'codex' ? { trusts: (path: string) => trust.codexTrusts(path, profile), record: (path: string) => trust.preTrustCodexProject(path, profile) } : null }))
vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
+// The Harness GitHub App's launch writes files in the daemon's folder (lib/swarmGitHub.ts): never this machine's here.
+vi.mock('../../lib/swarmGitHub.js', () => ({ swarmGitHubLaunch: vi.fn(() => null) }))
// The pull request line (lib/agentAttribution.ts) reads the person's engine settings: never this machine's here.
vi.mock('../../lib/agentAttribution.js', () => ({
agentLaunchArgs: vi.fn((_engine: string, startedBy: string | null | undefined) => startedBy === 'agent' ? ['--settings', '{"attribution":{}}'] : []),
@@ -197,6 +200,33 @@ describe('creating an agent', () => {
expect(vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1]?.extraArgs).toContain('--dsh')
})
+ it('gives a session doing another person\'s project work the GitHub App\'s git and gh, and keeps that on its skill', async () => {
+ vi.mocked(swarmGitHubLaunch).mockReturnValueOnce({ env: { GIT_CONFIG_PARAMETERS: 'fixture', GH_CONFIG_DIR: '/fixture/gh' }, clearEnv: ['GH_TOKEN'] })
+ expect(await setup().create(request({ cwd: folder(), swarmRole: 'dev', swarmGitHub: true }))).toMatchObject({ ok: true })
+ const pane = vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0]
+ expect(swarmGitHubLaunch).toHaveBeenCalledWith(pane.sessionLabel)
+ expect(pane.swarmSkill).toEqual({ role: 'dev', key: pane.sessionLabel, github: true })
+ expect(pane.env).toMatchObject({ GIT_CONFIG_PARAMETERS: 'fixture', GH_CONFIG_DIR: '/fixture/gh' })
+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls.at(-1)![1]?.clearEnv).toContain('GH_TOKEN')
+ })
+
+ it('launches as before where the GitHub App does not apply, and without a role never asks', async () => {
+ await setup().create(request({ cwd: folder(), swarmRole: 'dev', swarmGitHub: true }))
+ const pane = vi.mocked(createAndRegisterPane).mock.calls.at(-1)![0]
+ expect(pane.swarmSkill).toEqual({ role: 'dev', key: pane.sessionLabel })
+ expect(pane.env).not.toHaveProperty('GIT_CONFIG_PARAMETERS')
+ vi.mocked(swarmGitHubLaunch).mockClear()
+ await setup().create(request({ cwd: folder(), swarmGitHub: true }))
+ expect(swarmGitHubLaunch).not.toHaveBeenCalled()
+ })
+
+ it('refuses before opening a pane when the GitHub App\'s files cannot be written', async () => {
+ vi.mocked(swarmGitHubLaunch).mockImplementationOnce(() => { throw Error('fixture disk full') })
+ expect(await setup().create(request({ cwd: folder(), swarmRole: 'dev', swarmGitHub: true })))
+ .toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED', detail: 'Error: fixture disk full' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
it('refuses an unsafe Swarm runtime before opening a pane', async () => {
const cwd = folder(['.harness'])
expect(await setup().create(request({ cwd, swarmRole: 'dev' }))).toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index d749bf509..b7d4259e7 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -1,4 +1,5 @@
import { prepareSwarmSkill } from '../../lib/swarmSkills.js'
+import { swarmGitHubLaunch } from '../../lib/swarmGitHub.js'
import type { NativeLaunch, NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'
/**
* Creating an agent (`agent_create`): open a fresh pane running the chosen engine in the chosen
@@ -330,14 +331,22 @@ export function createAgentCreator({
// key wins on its own terms — OpenCode picked Anthropic over a grid it had been handed, and said
// only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login
// is supposed to use exactly these variables.
- const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv)]
+ // Another person's project work (superTabs/start.ts): git and gh use the Harness GitHub App's token for the task,
+ // never this machine owner's own GitHub login (lib/swarmGitHub.ts). Kept on the row's skill, so a relaunch keeps it.
+ let swarmGitHub: ReturnType<typeof swarmGitHubLaunch> = null
+ if (input.swarmRole && input.swarmGitHub) {
+ try { swarmGitHub = swarmGitHubLaunch(label) }
+ catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
+ }
+ const clearEnv = [...(gridLaunch ? gridConflictingEnvToClear(gridLaunch) : []), ...harnessEnvToClear(dshEnv), ...swarmGitHub?.clearEnv ?? []]
// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it
// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was
// checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.
// A harness another agent started says so in the pull requests it opens (lib/agentAttribution.ts), last, as every
// relaunch appends it (`buildLaunchOverrides`), and read from the person's settings where this launch reads them.
// What Harness tells the agent (its instructions, and the pull request line for one another agent started), last.
- const swarmSkill = input.swarmRole ? { role: input.swarmRole, key: label, ...(input.swarmSkillMode ? { mode: input.swarmSkillMode } : {}) } : undefined
+ const swarmSkill = input.swarmRole ? { role: input.swarmRole, key: label, ...(input.swarmSkillMode ? { mode: input.swarmSkillMode } : {}),
+ ...(swarmGitHub ? { github: true as const } : {}) } : undefined
let swarmInstructions: string | undefined
if (swarmSkill) {
try { swarmInstructions = prepareSwarmSkill(cwd, swarmSkill).instructions }
@@ -384,7 +393,7 @@ export function createAgentCreator({
paneLaunch: windowsPaneLaunch(engine, { ...launchOptions, held: isWindowsHeldPane(argv) }),
// Windows: the variables the argv's `/usr/bin/env` prefix carries elsewhere, last (engineLaunchEnv).
env: mergedLaunchEnv(freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? profileEnvironment(engine, codexHome) : undefined), dshEnv),
- mergedLaunchEnv(scmLaunchEnv(scmLaunchRecord), native?.environment)), !!grid,
+ mergedLaunchEnv(mergedLaunchEnv(scmLaunchEnv(scmLaunchRecord), swarmGitHub?.env), native?.environment)), !!grid,
permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')), engineLaunchEnv(engine, native)),
grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index be246a6d4..c74236fc6 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -291,6 +291,19 @@ describe('agent_create, refused before any pane exists', () => {
expect(vi.mocked(create!).mock.calls).toHaveLength(calls)
})
+ it('passes the GitHub App flag with a Swarm role only, and refuses anything else before dispatch', async () => {
+ const { ask, create } = setup()
+ await ask({ engine: 'codex', cwd: '/w', swarmRole: 'dev', swarmGitHub: true })
+ expect(vi.mocked(create!).mock.calls.at(-1)![0]).toMatchObject({ swarmRole: 'dev', swarmGitHub: true })
+ await ask({ engine: 'codex', cwd: '/w', swarmRole: 'dev' })
+ expect(vi.mocked(create!).mock.calls.at(-1)![0]).not.toHaveProperty('swarmGitHub')
+ const calls = vi.mocked(create!).mock.calls.length
+ for (const payload of [{ swarmRole: 'dev', swarmGitHub: false }, { swarmRole: 'dev', swarmGitHub: 'yes' }, { swarmGitHub: true }]) {
+ expect(await ask({ engine: 'claude', cwd: '/w', ...payload })).toMatchObject({ error: 'INVALID_SWARM_ROLE' })
+ }
+ expect(vi.mocked(create!).mock.calls).toHaveLength(calls)
+ })
+
it('a first prompt that is not text, too long, or for an engine that cannot take one', async () => {
const { ask, create } = setup()
expect(await ask({ engine: 'claude', cwd: '/w', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index f006d16f3..186b1761c 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -404,6 +404,12 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
if (swarmSkillMode !== undefined && !isSwarmSkillMode(swarmSkillMode)) {
reply({ error: 'INVALID_SWARM_ROLE', detail: 'A Swarm skill mode is default or orchestration.' }); return
}
+ // Another person's project work: git and gh use the Harness GitHub App's token for the task (lib/swarmGitHub.ts).
+ // Only `true`, and only with a role; a start from before the app sends none and launches as it did.
+ const swarmGitHub = payload.swarmGitHub
+ if (swarmGitHub !== undefined && (swarmGitHub !== true || !isSwarmRole(swarmRole))) {
+ reply({ error: 'INVALID_SWARM_ROLE', detail: 'swarmGitHub is true, with a Swarm role.' }); return
+ }
// Blank is "number it", the same as absent — a client that sends an empty field is not
// asking for an agent with no name.
const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null
@@ -472,7 +478,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
codexHome,
dsh,
prompt,
- ...(isSwarmRole(swarmRole) ? { swarmRole, ...(swarmSkillMode ? { swarmSkillMode } : {}) } : {}),
+ ...(isSwarmRole(swarmRole) ? { swarmRole, ...(swarmSkillMode ? { swarmSkillMode } : {}), ...(swarmGitHub ? { swarmGitHub } : {}) } : {}),
name,
agent,
resumeSessionId,
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 26c02040a..0ac84d62d 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -1,4 +1,6 @@
-import { rmSync } from 'node:fs'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { env } from '../config/env.js'
import { agentSettingsPath } from './agentSettings.js'
@@ -439,3 +441,37 @@ describe('buildLaunchOverrides — what the app is told about web search', () =>
expect(profile.ok && profile.overrides).not.toHaveProperty('gridLaunchRecord')
})
})
+
+describe('buildLaunchOverrides — a Swarm session on the Harness GitHub App', () => {
+ const skill = { role: 'dev' as const, key: 'harness-claude-github-fixture', github: true as const }
+ const workspace = () => mkdtempSync(join(tmpdir(), 'overrides-github-'))
+
+ it('relaunches with the app\'s git and gh, and clears inherited GitHub token variables', async () => {
+ const { d } = deps()
+ const result = await buildLaunchOverrides(d, 'claude', { cwd: workspace(), swarmSkill: skill }, 'agent-1', () => true)
+ if (!result.ok) throw new Error(result.error)
+ const session = join(env.ADAPTER_DATA_DIR, 'swarm-github', 'sessions', skill.key)
+ expect(result.overrides.env).toMatchObject({ GH_CONFIG_DIR: join(session, 'gh'), HARNESS_SWARM_GITHUB_DIR: session, GIT_TERMINAL_PROMPT: '0' })
+ expect(result.overrides.env.GIT_CONFIG_PARAMETERS).toContain(`'core.hookspath'='${join(env.ADAPTER_DATA_DIR, 'swarm-github', 'hooks')}'`)
+ expect(result.overrides.clearEnv).toEqual(expect.arrayContaining(['GH_TOKEN', 'GITHUB_TOKEN']))
+ })
+
+ it('relaunches a session without the flag exactly as before', async () => {
+ const { d } = deps()
+ const result = await buildLaunchOverrides(d, 'claude', { cwd: workspace(), swarmSkill: { role: 'dev', key: 'harness-claude-plain' } }, 'agent-1', () => true)
+ if (!result.ok) throw new Error(result.error)
+ expect(result.overrides.env).not.toHaveProperty('GIT_CONFIG_PARAMETERS')
+ expect(result.overrides.clearEnv).not.toContain('GH_TOKEN')
+ })
+
+ it('refuses the relaunch when the app\'s files cannot be written', async () => {
+ const root = join(env.ADAPTER_DATA_DIR, 'swarm-github')
+ rmSync(root, { recursive: true, force: true })
+ writeFileSync(root, 'not a folder')
+ try {
+ const { d } = deps()
+ expect(await buildLaunchOverrides(d, 'claude', { cwd: workspace(), swarmSkill: skill }, 'agent-1', () => true))
+ .toMatchObject({ ok: false, error: 'SWARM_SKILL_FAILED' })
+ } finally { rmSync(root, { force: true }) }
+ })
+})
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index b8762d82d..2d0e9f94e 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -1,4 +1,5 @@
import { prepareSwarmSkill, type SwarmSkill } from './swarmSkills.js'
+import { swarmGitHubLaunch } from './swarmGitHub.js'
/**
* What a pane has to be launched WITH, beyond the engine's own argv, for the engine to come back
* where it was: on the same grid with the same credential, or under the same Codex profile.
@@ -270,6 +271,12 @@ export async function prepareLaunchOverrides(
if (!current()) return changed
const scmEnv = scmLaunchEnv(source.scmLaunch)
if (scmEnv) overrides = { ...overrides, env: { ...overrides.env, ...scmEnv } }
+ // A session started for another person's project keeps git and gh on the Harness GitHub App (lib/swarmGitHub.ts).
+ if (source.swarmSkill?.github) {
+ let github: ReturnType<typeof swarmGitHubLaunch>
+ try { github = swarmGitHubLaunch(source.swarmSkill.key) } catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }
+ if (github) overrides = { ...overrides, env: { ...overrides.env, ...github.env }, clearEnv: [...overrides.clearEnv, ...github.clearEnv] }
+ }
// The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an
// engine with a contract could have had it recorded (create refuses the rest, AGENT_UNSUPPORTED),
// so the guard is for a row edited by hand — it relaunches as a general session rather than
diff --git a/cli/src/lib/swarmGitHub.spec.ts b/cli/src/lib/swarmGitHub.spec.ts
new file mode 100644
index 000000000..6561a6fc0
--- /dev/null
+++ b/cli/src/lib/swarmGitHub.spec.ts
@@ -0,0 +1,181 @@
+import { spawnSync } from 'node:child_process'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, describe, expect, it } from 'vitest'
+import { GIT_HOOK_NAMES, gitConfigParameters, shellWord, swarmGitHubLaunch, swarmGitHubSessionDir, writeSessionGitHub, writeSwarmGitHubTools } from './swarmGitHub.js'
+
+// Real git against folders made here, with a home of its own and no system config: never this machine's git settings,
+// and nothing reaches github.com (only `git credential fill` and `git ls-remote --get-url`, which make no connection).
+const root = mkdtempSync(join(tmpdir(), 'swarm-github-'))
+afterAll(() => rmSync(root, { recursive: true, force: true }))
+let made = 0
+const fresh = (name: string) => { const dir = join(root, `${name}-${made++}`); mkdirSync(dir, { recursive: true }); return dir }
+const home = fresh('home')
+const script = (file: string, body: string) => { writeFileSync(file, `#!/bin/sh\n${body}\n`); chmodSync(file, 0o755); return file }
+const git = (cwd: string, args: string[], env: Record<string, string> = {}, input?: string) => spawnSync('git', args, {
+ cwd, input, encoding: 'utf8', env: { PATH: process.env.PATH!, HOME: home, GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Fixture', GIT_COMMITTER_EMAIL: '[email protected]', ...env },
+})
+
+describe('git configuration for a Swarm session', () => {
+ it('quotes values for git as `git -c` does, single quotes included', () => {
+ expect(shellWord("it's")).toBe(`'it'\\''s'`)
+ const parameters = gitConfigParameters("/data/it's/git-credential", '/data/hooks')
+ expect(parameters).toContain(`'credential.https://github.com.helper'=''`)
+ expect(parameters).toContain(`'core.hookspath'='/data/hooks'`)
+ })
+
+ it('makes Harness\'s helper the only one git asks for github.com, keeps other hosts on their own, and fetches ssh over https', () => {
+ const dir = fresh('credential')
+ const ownerLog = join(dir, 'owner.log')
+ const owner = script(join(dir, 'owner-helper'), `echo "$1" >> '${ownerLog}'\n[ "$1" = get ] && printf 'username=owner\\npassword=owner-secret\\n'`)
+ writeFileSync(join(home, '.gitconfig'), `[credential]\n\thelper = ${owner}\n`)
+ const helper = script(join(dir, "Harness's helper"), `cat > '${join(dir, 'asked.txt')}'\n[ "$1" = get ] && printf 'username=x-access-token\\npassword=task-token\\n'`)
+ const env = { GIT_CONFIG_PARAMETERS: gitConfigParameters(helper, join(dir, 'hooks')) }
+ const github = git(dir, ['credential', 'fill'], env, 'url=https://github.com/acme/app.git\n\n')
+ expect(github.stdout).toContain('password=task-token')
+ // git sends the repository's path, which the helper checks.
+ expect(readFileSync(join(dir, 'asked.txt'), 'utf8')).toContain('path=acme/app.git')
+ expect(existsSync(ownerLog)).toBe(false)
+ const other = git(dir, ['credential', 'fill'], env, 'url=https://gitlab.example.com/acme/app.git\n\n')
+ expect(other.stdout).toContain('password=owner-secret')
+ expect(git(dir, ['ls-remote', '--get-url', '[email protected]:acme/app.git'], env).stdout.trim()).toBe('https://github.com/acme/app.git')
+ expect(git(dir, ['ls-remote', '--get-url', 'ssh://[email protected]/acme/app.git'], env).stdout.trim()).toBe('https://github.com/acme/app.git')
+ expect(git(dir, ['ls-remote', '--get-url', '[email protected]:acme/app.git'], env).stdout.trim()).toBe('[email protected]:acme/app.git')
+ rmSync(join(home, '.gitconfig'))
+ })
+})
+
+describe('the shared helper and hooks', () => {
+ it('writes the helper for this daemon\'s CLI and one hook for every hook git runs, private to its user, once', () => {
+ const dataDir = fresh('data')
+ const { helper, hooks } = writeSwarmGitHubTools({ dataDir, command: "'/opt/node' '/opt/harness/cli.js'", port: 18500, machineId: 'machine-1' })
+ expect(readFileSync(helper, 'utf8')).toBe('#!/bin/sh\n# Written by Harness for Swarm agents\' git (docs/swarm-github-app.md); rewritten as agents start.\n'
+ + `ADAPTER_DATA_DIR='${dataDir}' exec '/opt/node' '/opt/harness/cli.js' git-credential --port 18500 --machine 'machine-1' "$@"\n`)
+ expect(statSync(helper).mode & 0o777).toBe(0o700)
+ for (const name of GIT_HOOK_NAMES) expect(statSync(join(hooks, name)).mode & 0o777).toBe(0o700)
+ const before = statSync(join(hooks, 'pre-commit')).ino
+ writeSwarmGitHubTools({ dataDir, command: "'/opt/node' '/opt/harness/cli.js'", port: 18500, machineId: 'machine-1' })
+ expect(statSync(join(hooks, 'pre-commit')).ino).toBe(before)
+ writeSwarmGitHubTools({ dataDir, command: "'/opt/node' '/opt/harness/cli.js'", port: 18501, machineId: 'machine-1' })
+ expect(readFileSync(helper, 'utf8')).toContain('--port 18501')
+ })
+})
+
+// One daemon folder for every session below, as on a machine: macOS checks each new executable the first time it runs,
+// which takes seconds for a fresh set of hooks.
+describe('commits in a Swarm session', { timeout: 60_000 }, () => {
+ const shared = fresh('daemon')
+ const cli = script(join(shared, 'fake-cli'), `echo "$*" >> "$HARNESS_SWARM_GITHUB_DIR/cli.log"\n[ "$6" = trailers ] && printf 'Co-authored-by: Ada <[email protected]>\\nHarness-Agent: Atlas\\n' > "$HARNESS_SWARM_GITHUB_DIR/trailers"\nexit 0`)
+ /** A repository and a session whose fake CLI answers `trailers` by writing them, and logs every call. */
+ function session() {
+ const dir = fresh('commit')
+ const repo = join(dir, 'repo')
+ mkdirSync(repo)
+ const launch = swarmGitHubLaunch(`harness-claude-fixture-${made}`, { dataDir: shared, command: `/bin/sh ${shellWord(cli)}`, port: 18500, machineId: 'machine-1' }, 'darwin')!
+ expect(git(repo, ['init', '-q', '-b', 'main']).status).toBe(0)
+ const env = { GIT_CONFIG_PARAMETERS: launch.env.GIT_CONFIG_PARAMETERS!, HARNESS_SWARM_GITHUB_DIR: launch.env.HARNESS_SWARM_GITHUB_DIR! }
+ const commit = (args: string[], extra: Record<string, string> = {}) => git(repo, ['commit', '-q', '--allow-empty', ...args], { ...env, ...extra })
+ const message = () => git(repo, ['log', '-1', '--format=%B'], env).stdout
+ const own = (name: string, body: string, where = join(repo, '.git', 'hooks')) => { mkdirSync(where, { recursive: true }); script(join(where, name), body) }
+ return { dir, repo, env, commit, message, own, calls: join(launch.env.HARNESS_SWARM_GITHUB_DIR!, 'cli.log'), trailers: join(launch.env.HARNESS_SWARM_GITHUB_DIR!, 'trailers') }
+ }
+
+ it('adds the trailers after the repository\'s own hooks, once, and without them the commit asks the CLI for them', () => {
+ const s = session()
+ s.own('pre-commit', `touch '${join(s.dir, 'pre-commit-ran')}'`)
+ s.own('prepare-commit-msg', 'printf "\\nTicket: OPS-1\\n" >> "$1"')
+ expect(s.commit(['-m', 'Add search']).status).toBe(0)
+ expect(existsSync(join(s.dir, 'pre-commit-ran'))).toBe(true)
+ expect(s.message()).toBe('Add search\n\nTicket: OPS-1\nCo-authored-by: Ada <[email protected]>\nHarness-Agent: Atlas\n\n')
+ expect(readFileSync(s.calls, 'utf8')).toBe('git-credential --port 18500 --machine machine-1 trailers\n')
+ expect(s.commit(['--amend', '--no-edit']).status).toBe(0)
+ expect(s.message().match(/Harness-Agent/g)).toHaveLength(1)
+ // The file is there now: no second call.
+ expect(s.commit(['-m', 'Second']).status).toBe(0)
+ expect(readFileSync(s.calls, 'utf8').trim().split('\n')).toHaveLength(1)
+ })
+
+ it('keeps the trailers with --no-verify, a message from the editor, and a message file', () => {
+ const s = session()
+ writeFileSync(s.trailers, 'Co-authored-by: Ada <[email protected]>\n')
+ expect(s.commit(['--no-verify', '-m', 'Skip checks']).status).toBe(0)
+ expect(s.message()).toContain('Co-authored-by: Ada <[email protected]>')
+ const editor = script(join(s.dir, 'editor'), 'printf "Written in the editor\\n" > "$1"')
+ expect(s.commit([], { GIT_EDITOR: editor }).status).toBe(0)
+ expect(s.message()).toBe('Written in the editor\n\nCo-authored-by: Ada <[email protected]>\n\n')
+ writeFileSync(join(s.dir, 'msg.txt'), 'From a file\n')
+ expect(s.commit(['-F', join(s.dir, 'msg.txt')]).status).toBe(0)
+ expect(s.message()).toContain('From a file\n\nCo-authored-by: Ada <[email protected]>')
+ })
+
+ it('still aborts an empty message, and the repository\'s own failing hook still refuses the commit', () => {
+ const s = session()
+ writeFileSync(s.trailers, 'Harness-Agent: Atlas\n')
+ const empty = s.commit(['-m', ''])
+ expect(empty.status).not.toBe(0)
+ expect(empty.stderr).toContain('empty commit message')
+ s.own('commit-msg', 'echo "commit-msg says no" >&2\nexit 1')
+ const refused = s.commit(['-m', 'Bad'])
+ expect(refused.status).not.toBe(0)
+ expect(refused.stderr).toContain('commit-msg says no')
+ })
+
+ it('runs hooks from the repository\'s own hooksPath, and hands a pre-push hook its input', () => {
+ const s = session()
+ writeFileSync(s.trailers, 'Harness-Agent: Atlas\n')
+ expect(git(s.repo, ['config', 'core.hooksPath', '.husky'], s.env).status).toBe(0)
+ s.own('pre-commit', `touch '${join(s.dir, 'husky-ran')}'`, join(s.repo, '.husky'))
+ s.own('pre-push', `cat > '${join(s.dir, 'pushed.txt')}'`, join(s.repo, '.husky'))
+ expect(s.commit(['-m', 'With husky']).status).toBe(0)
+ expect(existsSync(join(s.dir, 'husky-ran'))).toBe(true)
+ const remote = join(s.dir, 'remote.git')
+ expect(git(s.dir, ['init', '-q', '--bare', remote]).status).toBe(0)
+ expect(git(s.repo, ['push', '-q', remote, 'main'], s.env).status).toBe(0)
+ expect(readFileSync(join(s.dir, 'pushed.txt'), 'utf8')).toMatch(/^refs\/heads\/main [0-9a-f]{40} refs\/heads\/main 0{40}\n$/)
+ })
+})
+
+describe('a session\'s gh login and trailers', () => {
+ it('writes gh\'s login for github.com, private to its user, and empties it on request', () => {
+ const dir = fresh('gh')
+ writeSessionGitHub(dir, 'ghs_fixtureToken0000001', ['Co-authored-by: Ada <[email protected]>', 'bad line', 'Harness-Agent: Atlas\nInjected: x'])
+ expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('github.com:\n users:\n x-access-token:\n oauth_token: ghs_fixtureToken0000001\n'
+ + ' git_protocol: https\n oauth_token: ghs_fixtureToken0000001\n user: x-access-token\n')
+ expect(readFileSync(join(dir, 'gh', 'config.yml'), 'utf8')).toBe('version: "1"\n')
+ expect(statSync(join(dir, 'gh', 'hosts.yml')).mode & 0o777).toBe(0o600)
+ expect(readFileSync(join(dir, 'trailers'), 'utf8')).toBe('Co-authored-by: Ada <[email protected]>\n')
+ writeSessionGitHub(dir, null)
+ expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')
+ // Trailers are kept: who the work is for does not change with the token.
+ expect(readFileSync(join(dir, 'trailers'), 'utf8')).toBe('Co-authored-by: Ada <[email protected]>\n')
+ writeSessionGitHub(dir, 'not a token\n oauth_token: other')
+ expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')
+ })
+})
+
+describe('a Swarm session\'s launch', () => {
+ it('names the session\'s gh folder and Harness\'s git settings, clears inherited GitHub tokens, and starts with no gh login', () => {
+ const dataDir = fresh('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_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'])
+ expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toBe('{}\n')
+ // A relaunch keeps a login the daemon has written since.
+ writeSessionGitHub(dir, 'ghs_fixtureToken0000002')
+ swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'linux')
+ expect(readFileSync(join(dir, 'gh', 'hosts.yml'), 'utf8')).toContain('ghs_fixtureToken0000002')
+ })
+
+ it('does not apply on Windows or to a key unfit for a path', () => {
+ const dataDir = fresh('none')
+ expect(swarmGitHubLaunch('harness-codex-abc', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'win32')).toBeNull()
+ expect(swarmGitHubLaunch('../escape', { dataDir, command: 'harness', port: 18473, machineId: 'm1' }, 'darwin')).toBeNull()
+ expect(existsSync(join(dataDir, 'swarm-github'))).toBe(false)
+ })
+})
diff --git a/cli/src/lib/swarmGitHub.ts b/cli/src/lib/swarmGitHub.ts
new file mode 100644
index 000000000..f6434a807
--- /dev/null
+++ b/cli/src/lib/swarmGitHub.ts
@@ -0,0 +1,165 @@
+/**
+ * git and gh for a Swarm agent doing another person's project work, through the Harness GitHub App
+ * (docs/swarm-github-app.md) instead of this machine owner's own GitHub login.
+ *
+ * Everything reaches the agent as environment variables, because those survive what its shells do: Codex runs every
+ * command in a login shell, Claude Code replays the person's startup files, and on a Mac both put Homebrew's folders
+ * back in front of PATH, so a wrapper placed first on PATH would be passed over. So:
+ *
+ * - git reads `GIT_CONFIG_PARAMETERS` (the variable `git -c` itself uses, above every config file): for github.com its
+ * credential helpers are reset to Harness's alone, which asks the daemon for the task's token
+ * (superTabs/gitCredential.ts) and answers only for the task's repository; ssh remotes of github.com are fetched and
+ * pushed over https, so no ssh key of the owner is used; and `core.hooksPath` names hooks that run the repository's
+ * own hook first, then add the attribution trailers to each commit message.
+ * - gh reads `GH_CONFIG_DIR`, a folder of this session's own whose token the daemon keeps fresh (superTabs/github.ts)
+ * and empties when the task ends. The owner's gh configuration is never read.
+ *
+ * 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 { join } from 'node:path'
+import { env } from '../config/env.js'
+import { daemonCommand } from './daemonCommand.js'
+import { readAuthSession } from './authSession.js'
+import { computerId } from './daemonState.js'
+
+/** Every hook git runs from `core.hooksPath`, so a repository's own hooks all still run. */
+export const GIT_HOOK_NAMES = ['applypatch-msg', 'pre-applypatch', 'post-applypatch', 'pre-commit', 'pre-merge-commit', 'prepare-commit-msg',
+ 'commit-msg', 'post-commit', 'pre-rebase', 'post-checkout', 'post-merge', 'pre-push', 'pre-receive', 'update', 'proc-receive',
+ 'post-receive', 'post-update', 'reference-transaction', 'push-to-checkout', 'pre-auto-gc', 'post-rewrite', 'sendemail-validate',
+ 'p4-changelist', 'p4-prepare-changelist', 'p4-post-changelist', 'p4-pre-submit', 'post-index-change'] as const
+
+/** Variables that would put another GitHub login in front of the session's own (gh reads them before its config). */
+export const SWARM_GITHUB_CLEAR_ENV = ['GH_TOKEN', 'GITHUB_TOKEN', 'GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN']
+
+/** A word for a POSIX shell. */
+export const shellWord = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`
+
+export const swarmGitHubRoot = (dataDir: string) => join(dataDir, 'swarm-github')
+const SESSION_KEY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/
+/** This session's own folder: its gh configuration and its commit trailers. Null for a key unfit for a path. */
+export function swarmGitHubSessionDir(dataDir: string, key: string): string | null {
+ return 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 {
+ 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', ''],
+ ['credential.https://github.com.helper', `!${shellWord(helper)}`],
+ // git sends the repository's path to the helper, which answers only for the task's repository.
+ ['credential.https://github.com.usehttppath', 'true'],
+ ['url.https://github.com/.insteadof', '[email protected]:'],
+ ['url.https://github.com/.insteadof', 'ssh://[email protected]/'],
+ ['core.hookspath', hooks],
+ ]
+ return entries.map(([key, value]) => `${shellWord(key)}=${shellWord(value)}`).join(' ')
+}
+
+export function credentialHelperScript(input: { command: string; port: number; machineId: string; dataDir: string }): string {
+ return '#!/bin/sh\n'
+ + '# Written by Harness for Swarm agents\' git (docs/swarm-github-app.md); rewritten as agents start.\n'
+ + `ADAPTER_DATA_DIR=${shellWord(input.dataDir)} exec ${input.command} git-credential --port ${input.port} --machine ${shellWord(input.machineId)} "$@"\n`
+}
+
+/** One script for every hook: the repository's own hook first (found with Harness's settings left out); then, for a
+ * commit message that has words in it, each trailer the message does not already have, anywhere in it (an amend keeps one
+ * of each). An empty message is left alone so that it still aborts the commit. */
+export function hookScript(input: { hooks: string; helper: string }): string {
+ return `#!/bin/sh
+# Written by Harness for Swarm agents (docs/swarm-github-app.md): runs this repository's own hook, then adds to each
+# commit message who the work is for and which agent and machine did it.
+ours=${shellWord(input.hooks)}
+name=\${0##*/}
+own=$(GIT_CONFIG_PARAMETERS= git rev-parse --git-path hooks 2>/dev/null)
+if [ -n "$own" ] && [ -x "$own/$name" ] && [ "$(cd "$own" 2>/dev/null && pwd -P)" != "$(cd "$ours" && pwd -P)" ]; then
+ case $name in
+ prepare-commit-msg|commit-msg) "$own/$name" "$@" || exit $? ;;
+ *) exec "$own/$name" "$@" ;;
+ esac
+fi
+case $name in prepare-commit-msg|commit-msg) ;; *) exit 0 ;; esac
+msg=$1
+dir=$HARNESS_SWARM_GITHUB_DIR
+[ -n "$msg" ] && [ -f "$msg" ] && [ -n "$dir" ] || exit 0
+[ -n "$(git stripspace --strip-comments < "$msg" 2>/dev/null)" ] || exit 0
+[ -s "$dir/trailers" ] || ${shellWord(input.helper)} trailers >/dev/null 2>&1
+[ -s "$dir/trailers" ] || exit 0
+set --
+while IFS= read -r line || [ -n "$line" ]; do
+ [ -n "$line" ] && ! grep -qxF -- "$line" "$msg" && set -- "$@" --trailer "$line"
+done < "$dir/trailers"
+[ $# -gt 0 ] && git interpret-trailers --in-place --if-exists addIfDifferent "$@" "$msg" 2>/dev/null
+exit 0
+`
+}
+
+/** Writes [text] to [file] unless it already says exactly that; never through a half-written file. */
+function writeIfChanged(file: string, text: string, mode: number): void {
+ try { if (readFileSync(file, 'utf8') === text) { chmodSync(file, mode); return } } catch { /* absent: written below */ }
+ const next = `${file}.${process.pid}.next`
+ writeFileSync(next, text, { mode })
+ chmodSync(next, mode)
+ renameSync(next, file)
+}
+
+export interface SwarmGitHubTools { dataDir: string; command: string; port: number; machineId: string }
+const defaultTools = (): SwarmGitHubTools => ({ dataDir: env.ADAPTER_DATA_DIR, command: daemonCommand(), port: env.PORT,
+ machineId: readAuthSession()?.machineId || computerId() })
+
+/** The helper and the hooks, shared by every session on this machine, written for this daemon's CLI. */
+export function writeSwarmGitHubTools(tools: SwarmGitHubTools): { helper: string; hooks: string } {
+ const root = swarmGitHubRoot(tools.dataDir)
+ const bin = join(root, 'bin'), hooks = join(root, 'hooks')
+ for (const dir of [root, bin, hooks]) mkdirSync(dir, { recursive: true, mode: 0o700 })
+ const helper = join(bin, 'git-credential')
+ writeIfChanged(helper, credentialHelperScript(tools), 0o700)
+ const script = hookScript({ hooks, helper })
+ for (const name of GIT_HOOK_NAMES) writeIfChanged(join(hooks, name), script, 0o700)
+ return { helper, hooks }
+}
+
+const GH_CONFIG = 'version: "1"\n'
+/** gh's own token format, and nothing that could break out of the YAML around it. */
+const TOKEN = /^[A-Za-z0-9_]{20,255}$/
+
+/** 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 {
+ 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)
+ const hosts = token && TOKEN.test(token)
+ ? `github.com:\n users:\n x-access-token:\n oauth_token: ${token}\n git_protocol: https\n oauth_token: ${token}\n user: x-access-token\n`
+ : '{}\n'
+ writeIfChanged(join(gh, 'hosts.yml'), hosts, 0o600)
+ if (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)
+ }
+}
+
+/**
+ * The launch of a Swarm session that uses the app ([key]: its session label, `SwarmSkill.key`): its environment, and the
+ * variables to clear from what it inherits. Writes the shared tools and the session's folder first. Null where it does not
+ * apply: on Windows, whose git does not run these shell scripts, or for a key unfit for a path.
+ */
+export function swarmGitHubLaunch(key: string, tools: SwarmGitHubTools = defaultTools(), platform: NodeJS.Platform = process.platform):
+ { env: Record<string, string>; clearEnv: string[] } | null {
+ const dir = swarmGitHubSessionDir(tools.dataDir, key)
+ if (platform === 'win32' || !dir) return null
+ const { helper, hooks } = writeSwarmGitHubTools(tools)
+ if (!existsSync(join(dir, 'gh', 'hosts.yml'))) writeSessionGitHub(dir, null)
+ return {
+ env: {
+ GIT_CONFIG_PARAMETERS: gitConfigParameters(helper, hooks),
+ // 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'),
+ GH_PROMPT_DISABLED: '1',
+ GH_NO_UPDATE_NOTIFIER: '1',
+ HARNESS_SWARM_GITHUB_DIR: dir,
+ },
+ clearEnv: [...SWARM_GITHUB_CLEAR_ENV],
+ }
+}
diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.ts
index 21e9e1859..6cbb55949 100644
--- a/cli/src/lib/swarmSkills.spec.ts
+++ b/cli/src/lib/swarmSkills.spec.ts
@@ -319,6 +319,9 @@ describe('built-in Swarm skills', () => {
// An unknown mode is dropped, not refused: the session keeps its role and launches as before modes.
expect(parseSwarmSkill({ role: 'dev', key: 'x', mode: 'light' })).toEqual({ role: 'dev', key: 'x' })
expect(parseSwarmSkill({ role: 'dev', key: 'x', mode: 'orchestration' })).toEqual({ role: 'dev', key: 'x', mode: 'orchestration' })
+ // The Harness GitHub App's flag is kept for relaunches, and only as true.
+ expect(parseSwarmSkill({ role: 'dev', key: 'x', github: true })).toEqual({ role: 'dev', key: 'x', github: true })
+ expect(parseSwarmSkill({ role: 'dev', key: 'x', github: 'yes' })).toEqual({ role: 'dev', key: 'x' })
expect(() => prepareSwarmSkill(fixture(), { role: 'lead', key: '' })).toThrow()
})
diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.ts
index 78c25efc6..b48651771 100644
--- a/cli/src/lib/swarmSkills.ts
+++ b/cli/src/lib/swarmSkills.ts
@@ -8,16 +8,19 @@ export type SwarmRole = 'lead' | 'dev' | 'review'
/** A Swarm project's skill set, which its owner chooses (2026-10-23): Default is the team process alone, Harness orchestration
* adds Harness practices. A session saved without one launched before modes, on the orchestration text. */
export type SwarmSkillMode = 'default' | 'orchestration'
-export interface SwarmSkill { role: SwarmRole; key: string; mode?: SwarmSkillMode }
+/** `github`: git and gh in this session use the Harness GitHub App's token for its task (lib/swarmGitHub.ts), set when a
+ * start does another person's project work (superTabs/start.ts) and kept for every relaunch. */
+export interface SwarmSkill { role: SwarmRole; key: string; mode?: SwarmSkillMode; github?: true }
/** What a session's current Swarm membership grants it, before it has a key. */
-export type SwarmSkillGrant = Omit<SwarmSkill, 'key'>
+export type SwarmSkillGrant = Omit<SwarmSkill, 'key' | 'github'>
export const isSwarmRole = (value: unknown): value is SwarmRole => value === 'lead' || value === 'dev' || value === 'review'
export const isSwarmSkillMode = (value: unknown): value is SwarmSkillMode => value === 'default' || value === 'orchestration'
export function parseSwarmSkill(value: unknown): SwarmSkill | undefined {
if (!value || typeof value !== 'object') return undefined
- const { role, key, mode } = value as Partial<SwarmSkill>
- return isSwarmRole(role) && typeof key === 'string' && key.length > 0 ? { role, key, ...(isSwarmSkillMode(mode) ? { mode } : {}) } : undefined
+ const { role, key, mode, github } = value as Partial<SwarmSkill>
+ return isSwarmRole(role) && typeof key === 'string' && key.length > 0
+ ? { role, key, ...(isSwarmSkillMode(mode) ? { mode } : {}), ...(github === true ? { github } : {}) } : undefined
}
/** The owner's texts, used verbatim. */
diff --git a/cli/src/superTabs/gitCredential.spec.ts b/cli/src/superTabs/gitCredential.spec.ts
new file mode 100644
index 000000000..03804ce86
--- /dev/null
+++ b/cli/src/superTabs/gitCredential.spec.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { Daemon, Where } from '../agentClient/daemon.js'
+import { gitCredentialCommand, parseCredentialRequest, requestedRepository } from './gitCredential.js'
+
+const where = (): Where => ({ port: 18500, dataDir: '/fixture/data', machineId: 'machine-1' })
+const frames = [{ id: 'harness-1', tmuxPane: '%7', status: 'active', engine: 'codex', name: 'Builder' }]
+const token = { token: 'ghs_fixture_token_1', expiresAt: '2026-10-24T13:00:00.000Z', repository: 'acme/app', trailers: ['Co-authored-by: Ada <[email protected]>', 'Harness-Agent: Atlas'] }
+
+/** A daemon that lists one agent in pane %7 and answers its token request with [answer]. */
+function daemon(answer: Record<string, unknown> = { ok: true, value: token }) {
+ const requests: Array<[string, Record<string, unknown> | undefined]> = []
+ const open = vi.fn(async (at: Where) => {
+ expect(at).toMatchObject({ port: 18500, machineId: 'machine-1' })
+ return { machineId: at.machineId, close: vi.fn(), request: async (type: string, payload?: Record<string, unknown>) => {
+ requests.push([type, payload])
+ return type === 'agents_list' ? { agents: frames } : answer
+ } } as Daemon
+ })
+ return { open, requests }
+}
+async function run(argv: string[], input: string, answer?: Record<string, unknown>, pane = '%7') {
+ const fake = daemon(answer)
+ const out: string[] = [], err: string[] = []
+ const code = await gitCredentialCommand(argv, { where, open: fake.open, pane, input: async () => input, print: t => out.push(t), warn: t => err.push(t) })
+ return { code, out: out.join(''), err: err.join('\n'), requests: fake.requests, open: fake.open }
+}
+const ask = (url: string) => `protocol=https\nhost=${new URL(url).host}\npath=${new URL(url).pathname.slice(1)}\n\n`
+
+describe('git\'s credential request', () => {
+ it('reads key=value lines up to the blank line, and a url', () => {
+ expect(parseCredentialRequest('protocol=https\nhost=github.com\npath=acme/app.git\n\nignored=1\n'))
+ .toEqual({ protocol: 'https', host: 'github.com', path: 'acme/app.git' })
+ expect(parseCredentialRequest('url=https://github.com/acme/app.git\r\n')).toMatchObject({ protocol: 'https', host: 'github.com', path: 'acme/app.git' })
+ expect(parseCredentialRequest('url=not a url\ncapability[]=authtype\n')).toEqual({ url: 'not a url', 'capability[]': 'authtype' })
+ })
+
+ it('names a github.com repository over https only, with its path', () => {
+ expect(requestedRepository({ protocol: 'https', host: 'GitHub.com', path: 'Acme/App.git/' })).toBe('acme/app')
+ for (const fields of <Array<Record<string, string>>>[{ protocol: 'http', host: 'github.com', path: 'acme/app' }, { protocol: 'https', host: 'gitlab.com', path: 'acme/app' },
+ { protocol: 'https', host: 'github.com:8443', path: 'acme/app' }, { protocol: 'https', host: 'github.com' },
+ { protocol: 'https', host: 'github.com', path: 'acme/app/extra' }, { protocol: 'https', host: 'github.com', path: 'acme/a b' }]) {
+ expect(requestedRepository(fields)).toBeNull()
+ }
+ })
+})
+
+describe('harness git-credential', () => {
+ it('answers get for the task\'s repository with the token, as the agent in the calling pane', async () => {
+ const result = await run(['get'], ask('https://github.com/acme/app.git'))
+ expect(result.code).toBe(0)
+ expect(result.out).toBe(`username=x-access-token\npassword=ghs_fixture_token_1\npassword_expiry_utc=${Date.parse(token.expiresAt) / 1000}\n`)
+ expect(result.requests).toEqual([['agents_list', {}], ['super_tabs', { action: 'githubToken', harnessId: 'harness-1' }]])
+ expect(result.err).toBe('')
+ })
+
+ it('warns when the default branch does not require a pull request, and still answers', async () => {
+ const result = await run(['get'], ask('https://github.com/acme/app.git'), { ok: true, value: { ...token, defaultBranch: 'main', defaultBranchProtected: false } })
+ expect(result.out).toContain('password=ghs_fixture_token_1')
+ expect(result.err).toBe('harness: main of acme/app does not require a pull request, so this token could push to it directly. Push to your own branch and open a pull request.')
+ const unnamed = await run(['get'], ask('https://github.com/acme/app.git'), { ok: true, value: { ...token, defaultBranchProtected: false } })
+ expect(unnamed.err).toContain('harness: the default branch of acme/app does not require a pull request')
+ expect((await run(['get'], ask('https://github.com/acme/app.git'), { ok: true, value: { ...token, defaultBranchProtected: true } })).err).toBe('')
+ })
+
+ it('gives another host, plain http or no path nothing, without asking the daemon', async () => {
+ for (const input of [ask('https://gitlab.example.com/acme/app.git'), 'protocol=http\nhost=github.com\npath=acme/app\n\n', 'protocol=https\nhost=github.com\n\n']) {
+ const result = await run(['get'], input)
+ expect(result).toMatchObject({ code: 0, out: '', err: '' })
+ expect(result.open).not.toHaveBeenCalled()
+ }
+ })
+
+ it('gives another repository on github.com nothing, and says why', async () => {
+ const result = await run(['get'], ask('https://github.com/acme/other.git'))
+ expect(result.out).toBe('')
+ expect(result.err).toBe('harness: this agent\'s GitHub token is for acme/app, its task\'s repository, not acme/other.')
+ })
+
+ it('passes on the server\'s refusal, outside a Swarm agent\'s pane too, and gives nothing', async () => {
+ const refused = await run(['get'], ask('https://github.com/acme/app'), { error: 'GITHUB_APP_NOT_INSTALLED',
+ detail: 'The Harness GitHub App is not installed on acme/app. Ask an owner of acme to install it: https://github.com/apps/harness/installations/new.' })
+ expect(refused.out).toBe('')
+ expect(refused.err).toContain('harness: no GitHub token for acme/app: The Harness GitHub App is not installed on acme/app.')
+ const outside = await run(['get'], ask('https://github.com/acme/app'), undefined, '%99')
+ expect(outside.out).toBe('')
+ expect(outside.err).toContain('outside a Swarm agent\'s harness')
+ expect(outside.requests).toEqual([['agents_list', {}]])
+ const fake = { open: vi.fn(async () => { throw new Error('connect ENOENT') }) }
+ const err: string[] = []
+ expect(await gitCredentialCommand(['get'], { where, open: fake.open as never, pane: '%7', input: async () => ask('https://github.com/acme/app'),
+ print: () => {}, warn: t => err.push(t) })).toBe(0)
+ expect(err.join('')).toContain('connect ENOENT')
+ })
+
+ it('reads and ignores store and erase', async () => {
+ for (const action of ['store', 'erase']) {
+ const result = await run([action], `${ask('https://github.com/acme/app')}username=x-access-token\npassword=old\n`)
+ expect(result).toMatchObject({ code: 0, out: '', err: '' })
+ expect(result.open).not.toHaveBeenCalled()
+ }
+ })
+
+ it('prints the commit trailers, or nothing when there is no token', async () => {
+ expect((await run(['trailers'], '')).out).toBe('Co-authored-by: Ada <[email protected]>\nHarness-Agent: Atlas\n')
+ expect((await run(['trailers'], '', { error: 'NO_ASSIGNMENT' }))).toMatchObject({ code: 0, out: '' })
+ })
+
+ it('takes the daemon\'s port and machine from flags, and refuses anything else', async () => {
+ const opened: Where[] = []
+ await gitCredentialCommand(['--port', '18501', '--machine', 'machine-2', 'trailers'], { where, pane: '%7', print: () => {}, warn: () => {},
+ open: (async (at: Where) => { opened.push(at); throw new Error('stop') }) as never })
+ expect(opened[0]).toMatchObject({ port: 18501, machineId: 'machine-2', dataDir: '/fixture/data' })
+ for (const argv of [[], ['fill'], ['get', 'extra'], ['--port', 'x', 'get'], ['--machine', '../m', 'get']]) {
+ const err: string[] = []
+ expect(await gitCredentialCommand(argv, { where, print: () => {}, warn: t => err.push(t) })).toBe(2)
+ expect(err[0]).toContain('harness git-credential')
+ }
+ })
+})
diff --git a/cli/src/superTabs/gitCredential.ts b/cli/src/superTabs/gitCredential.ts
new file mode 100644
index 000000000..3fe6b3c08
--- /dev/null
+++ b/cli/src/superTabs/gitCredential.ts
@@ -0,0 +1,123 @@
+/**
+ * `harness git-credential`: git's credential helper for a Swarm agent doing another person's project work
+ * (docs/swarm-github-app.md). git runs it as the helper for github.com (lib/swarmGitHub.ts):
+ *
+ * - `get` reads git's request and answers `username=x-access-token` and `password=<token>` with the Harness GitHub App
+ * token of the calling agent's task, only when the request is for https://github.com and the task's own repository.
+ * Anything else gets no answer, and git goes on without one.
+ * - `store` and `erase` are read and ignored: the token is the backend's to keep and revoke.
+ * - `trailers` prints the attribution trailers for the agent's commits, one per line (the commit hooks' fallback).
+ *
+ * The calling agent is found as `harness super-tab` finds it: its tmux pane, in the daemon's list of agents. The token is
+ * written to git alone, on stdout, and never logged.
+ */
+import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'
+import { callerOf, type Frame } from '../agentClient/model.js'
+import { identifier, object } from './wire.js'
+
+const USAGE = 'harness git-credential [--port N --machine ID] get|store|erase|trailers'
+const TIMEOUT_MS = 15_000
+
+export interface GitCredentialDeps {
+ where?: () => Where
+ open?: typeof openDaemon
+ pane?: string
+ /** All of standard input (git's request). */
+ input?: () => Promise<string>
+ print?: (text: string) => void
+ warn?: (text: string) => void
+}
+
+/** git's request: `key=value` lines up to a blank line. A `url` fills in what it names. */
+export function parseCredentialRequest(text: string): Record<string, string> {
+ const fields: Record<string, string> = {}
+ for (const line of text.split('\n')) {
+ const clean = line.replace(/\r$/, '')
+ if (!clean) break
+ const at = clean.indexOf('=')
+ if (at > 0) fields[clean.slice(0, at)] = clean.slice(at + 1)
+ }
+ if (fields.url) {
+ try {
+ const url = new URL(fields.url)
+ fields.protocol ??= url.protocol.replace(/:$/, '')
+ fields.host ??= url.host
+ if (fields.path === undefined && url.pathname.length > 1) fields.path = decodeURIComponent(url.pathname.slice(1))
+ } catch { /* not a URL: the other fields stand */ }
+ }
+ return fields
+}
+
+/** `owner/name` of the repository a github.com request names, or null for any other host or no path. */
+export function requestedRepository(fields: Record<string, string>): string | null {
+ if (fields.protocol !== 'https' || fields.host?.toLowerCase() !== 'github.com' || !fields.path) return null
+ const parts = fields.path.replace(/\/+$/, '').replace(/\.git$/i, '').split('/')
+ return parts.length === 2 && parts.every(part => /^[A-Za-z0-9._-]+$/.test(part)) ? parts.join('/').toLowerCase() : null
+}
+
+async function readAll(): Promise<string> {
+ const chunks: Buffer[] = []
+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer)
+ return Buffer.concat(chunks).toString('utf8')
+}
+
+/** The calling agent's token answer from its daemon: `{ ok, value }`, or `{ error, detail }`. */
+async function askToken(where: Where, deps: GitCredentialDeps): Promise<Record<string, unknown>> {
+ let daemon: Daemon | null = null
+ try {
+ daemon = await (deps.open ?? openDaemon)(where)
+ const listed = await daemon.request('agents_list', {}, TIMEOUT_MS)
+ const caller = callerOf(Array.isArray(listed.agents) ? listed.agents as Frame[] : [], deps.pane ?? process.env.TMUX_PANE, where.machineId)
+ if (!caller) return { error: 'NOT_A_SWARM_AGENT', detail: 'git asked for a GitHub token outside a Swarm agent\'s harness.' }
+ return await daemon.request('super_tabs', { action: 'githubToken', harnessId: caller.agentId }, TIMEOUT_MS)
+ } catch (error) {
+ return { error: 'DAEMON_UNREACHABLE', detail: error instanceof Error ? error.message : String(error) }
+ } finally { daemon?.close() }
+}
+
+export async function gitCredentialCommand(argv: readonly string[], deps: GitCredentialDeps = {}): Promise<number> {
+ const print = deps.print ?? (text => process.stdout.write(text))
+ const warn = deps.warn ?? (text => process.stderr.write(`${text}\n`))
+ const where = { ...(deps.where ?? (() => whereFor(process.env.TMUX_PANE)))() }
+ const positional: string[] = []
+ for (let i = 0; i < argv.length; i++) {
+ if (argv[i] === '--port') where.port = Number(argv[++i])
+ else if (argv[i] === '--machine') where.machineId = argv[++i] ?? ''
+ else positional.push(argv[i]!)
+ }
+ const [action] = positional
+ if (positional.length !== 1 || !['get', 'store', 'erase', 'trailers'].includes(action!) || !Number.isInteger(where.port)
+ || where.port < 1 || where.port > 65535 || !identifier(where.machineId)) {
+ warn(USAGE)
+ return 2
+ }
+ if (action === 'trailers') {
+ const answer = await askToken(where, deps)
+ const trailers = object(answer.value).trailers
+ if (answer.ok === true && Array.isArray(trailers)) print(trailers.filter(t => typeof t === 'string').map(t => `${t}\n`).join(''))
+ return 0
+ }
+ const request = parseCredentialRequest(await (deps.input ?? readAll)())
+ if (action !== 'get') return 0
+ const wanted = requestedRepository(request)
+ // Another host, plain http, or no path to check the repository against: not this helper's to answer.
+ if (!wanted) return 0
+ const answer = await askToken(where, deps)
+ const value = object(answer.value)
+ if (answer.ok !== true || typeof value.token !== 'string' || typeof value.repository !== 'string') {
+ warn(`harness: no GitHub token for ${wanted}: ${String(answer.detail ?? answer.error ?? 'the Harness server did not answer')}`)
+ return 0
+ }
+ if (value.repository.toLowerCase() !== wanted) {
+ warn(`harness: this agent's GitHub token is for ${value.repository}, its task's repository, not ${wanted}.`)
+ return 0
+ }
+ // The token can push to any branch nothing protects: said on every use, so the agent tells its Lead, who tells the people.
+ if (value.defaultBranchProtected === false) {
+ const branch = typeof value.defaultBranch === 'string' ? value.defaultBranch : 'the default branch'
+ warn(`harness: ${branch} of ${value.repository} does not require a pull request, so this token could push to it directly. Push to your own branch and open a pull request.`)
+ }
+ const expiry = Date.parse(String(value.expiresAt))
+ print(`username=x-access-token\npassword=${value.token}\n${Number.isFinite(expiry) ? `password_expiry_utc=${Math.floor(expiry / 1000)}\n` : ''}`)
+ return 0
+}
diff --git a/cli/src/superTabs/github.spec.ts b/cli/src/superTabs/github.spec.ts
new file mode 100644
index 000000000..31d51e574
--- /dev/null
+++ b/cli/src/superTabs/github.spec.ts
@@ -0,0 +1,161 @@
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterAll, describe, expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { swarmGitHubSessionDir } from '../lib/swarmGitHub.js'
+import { GitHubTokenRefresher, githubToken, RENEW_BELOW_MS } from './github.js'
+
+const root = mkdtempSync(join(tmpdir(), 'super-tab-github-'))
+afterAll(() => rmSync(root, { recursive: true, force: true }))
+let made = 0
+
+type Reply = { status: number; body: Record<string, unknown> }
+const ok = (data: unknown): Reply => ({ status: 200, body: { success: true, data } })
+const refuse = (status: number, code: string, message = code): Reply => ({ status, body: { success: false, error: { code, message } } })
+const issued = (token: string, expiresAt = '2026-10-24T13:00:00.000Z') => ok({ token, expiresAt, repository: 'acme/app',
+ trailers: ['Co-authored-by: Ada <[email protected]>', 'Harness-Agent: Atlas'] })
+const row = (tabId: string, agentId: string, harnessId = 'harness-1', extra: Record<string, unknown> = {}) =>
+ ({ tabId, agent: { id: agentId, harnessId, machineId: 'machine-1' }, ...extra })
+
+/** A core whose backend answers by path; one session per harness id, started to use the app unless `plain`. */
+function setup(routes: (method: string, path: string, body: unknown) => Reply, sessions: Array<{ id: string; plain?: boolean }> = [{ id: 'harness-1' }]) {
+ const dataDir = join(root, `data-${made++}`)
+ const live = sessions.map(s => ({ agentId: s.id, swarmSkill: { role: 'dev', key: `harness-codex-${s.id}`, ...(s.plain ? {} : { github: true }) } }) as unknown as RegisteredSession)
+ const backend = vi.fn(async (method: string, path: string, body?: unknown) => routes(method, path, body))
+ const core = fakeCore({ dataDir, account: { backend }, agents: { live: vi.fn(() => live), byAgent: vi.fn((id: string) => live.find(s => s.agentId === id)) } })
+ const hosts = (id = 'harness-1') => readFileSync(join(swarmGitHubSessionDir(dataDir, `harness-codex-${id}`)!, 'gh', 'hosts.yml'), 'utf8')
+ const trailers = (id = 'harness-1') => readFileSync(join(swarmGitHubSessionDir(dataDir, `harness-codex-${id}`)!, 'trailers'), 'utf8')
+ return { core, backend, hosts, trailers }
+}
+
+describe('a local agent\'s GitHub token', () => {
+ it('is asked for as the agent the roster lists for that harness on this machine, and written into its gh login', async () => {
+ const { core, backend, hosts, trailers } = setup((method, path) => method === 'GET' ? ok([row('tab-1', 'agent-1')])
+ : path === '/api/super-tabs/tab-1/github-token?asAgentId=agent-1' ? issued('ghs_fixtureToken0000001') : refuse(404, 'NOT_FOUND'))
+ const answer = await githubToken(core, 'harness-1')
+ expect(answer).toMatchObject({ ok: true, value: { token: 'ghs_fixtureToken0000001', repository: 'acme/app', tabId: 'tab-1', agentId: 'agent-1' } })
+ expect(backend).toHaveBeenCalledWith('GET', '/api/super-tabs/hosts/machine-1', undefined)
+ expect(backend).toHaveBeenCalledWith('POST', '/api/super-tabs/tab-1/github-token?asAgentId=agent-1', { machineId: 'machine-1' })
+ expect(hosts()).toContain('oauth_token: ghs_fixtureToken0000001')
+ expect(trailers()).toBe('Co-authored-by: Ada <[email protected]>\nHarness-Agent: Atlas\n')
+ })
+
+ it('tries the harness\'s next Swarm when one has no task for it, and skips stopping and closing rows and other harnesses', async () => {
+ const { core, backend } = setup((method, path) => method === 'GET'
+ ? ok([row('tab-0', 'agent-0', 'harness-2'), row('tab-x', 'agent-x', 'harness-1', { stopRequested: true }), row('tab-y', 'agent-y', 'harness-1', { closeSession: true }),
+ row('tab-1', 'agent-1'), row('tab-2', 'agent-2')])
+ : path.startsWith('/api/super-tabs/tab-1/') ? refuse(409, 'NO_ASSIGNMENT') : issued('ghs_fixtureToken0000002'))
+ expect(await githubToken(core, 'harness-1')).toMatchObject({ ok: true, value: { tabId: 'tab-2' } })
+ expect(backend.mock.calls.filter(c => c[0] === 'POST').map(c => c[1])).toEqual([
+ '/api/super-tabs/tab-1/github-token?asAgentId=agent-1', '/api/super-tabs/tab-2/github-token?asAgentId=agent-2'])
+ })
+
+ it('passes on the most telling refusal and empties the gh login when the server decided', async () => {
+ const answers: Record<string, Reply> = { 'tab-1': refuse(409, 'NO_ASSIGNMENT'), 'tab-2': refuse(409, 'GITHUB_APP_NOT_INSTALLED', 'Install it: https://github.com/apps/x/installations/new') }
+ const { core, hosts } = setup((method, path) => method === 'GET' ? ok([row('tab-1', 'agent-1'), row('tab-2', 'agent-2')])
+ : path.includes('tab-0') ? issued('x') : answers[path.split('/')[3]!]!)
+ expect(await githubToken(core, 'harness-1')).toEqual({ error: 'GITHUB_APP_NOT_INSTALLED', detail: 'Install it: https://github.com/apps/x/installations/new', status: 409 })
+ expect(hosts()).toBe('{}\n')
+ })
+
+ it('keeps an unexpired token when the server cannot be reached, and empties it when the app is not configured', async () => {
+ let reply = issued('ghs_fixtureToken0000003')
+ const { core, hosts } = setup((method) => method === 'GET' ? ok([row('tab-1', 'agent-1')]) : reply)
+ await githubToken(core, 'harness-1')
+ reply = refuse(503, 'BACKEND_UNAVAILABLE')
+ expect(await githubToken(core, 'harness-1')).toMatchObject({ error: 'BACKEND_UNAVAILABLE' })
+ expect(hosts()).toContain('ghs_fixtureToken0000003')
+ reply = refuse(503, 'GITHUB_APP_NOT_CONFIGURED')
+ await githubToken(core, 'harness-1')
+ expect(hosts()).toBe('{}\n')
+ })
+
+ it('refuses a harness that is not running here, one in no Swarm, and a reply without a token', async () => {
+ const { core } = setup(method => method === 'GET' ? ok([]) : ok({}))
+ expect(await githubToken(core, 'harness-9')).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
+ expect(await githubToken(core, '../x')).toEqual({ error: 'INVALID_REQUEST' })
+ expect(await githubToken(core, 'harness-1')).toMatchObject({ error: 'NOT_A_SWARM_AGENT' })
+ const broken = setup(method => method === 'GET' ? ok([row('tab-1', 'agent-1')]) : ok({ token: 7 }))
+ expect(await githubToken(broken.core, 'harness-1')).toMatchObject({ error: 'GITHUB_UNAVAILABLE' })
+ const offline = setup(() => refuse(502, 'BACKEND_UNAVAILABLE'))
+ expect(await githubToken(offline.core, 'harness-1')).toMatchObject({ error: 'BACKEND_UNAVAILABLE' })
+ })
+
+ it('writes nothing for a person\'s own agent, which keeps its own GitHub login', async () => {
+ const { core } = setup(method => method === 'GET' ? ok([row('tab-1', 'agent-1')]) : issued('ghs_fixtureToken0000004'), [{ id: 'harness-1', plain: true }])
+ expect(await githubToken(core, 'harness-1')).toMatchObject({ ok: true })
+ expect(() => readFileSync(join(core.dataDir, 'swarm-github'))).toThrow()
+ })
+})
+
+describe('keeping gh\'s token fresh', () => {
+ const clock = () => { let t = Date.parse('2026-10-24T12:00:00.000Z'); return { now: () => t, advance: (ms: number) => { t += ms } } }
+
+ it('gives a session with a task a token, renews it ten minutes before it expires, and takes it away when the task ends', async () => {
+ const time = clock()
+ let work = [{ tabId: 'tab-1', assignmentId: 'attempt-1', harnessId: 'harness-1' }]
+ let next = 1
+ const { core, backend, hosts } = setup((method, path) => path.endsWith('/assignments') ? ok(work)
+ : method === 'GET' ? ok([row('tab-1', 'agent-1')])
+ : issued(`ghs_fixtureToken000000${next++}`, new Date(time.now() + 3600_000).toISOString()))
+ const refresher = new GitHubTokenRefresher(core, { now: time.now })
+ await refresher.tick()
+ expect(hosts()).toContain('ghs_fixtureToken0000001')
+ const asked = () => backend.mock.calls.filter(c => c[0] === 'POST').length
+ time.advance(60_000)
+ await refresher.tick()
+ expect(asked()).toBe(1)
+ time.advance(3600_000 - 60_000 - RENEW_BELOW_MS)
+ await refresher.tick()
+ expect(asked()).toBe(2)
+ expect(hosts()).toContain('ghs_fixtureToken0000002')
+ // A new task asks again at once.
+ work = [{ tabId: 'tab-1', assignmentId: 'attempt-2', harnessId: 'harness-1' }]
+ await refresher.tick()
+ expect(asked()).toBe(3)
+ work = []
+ await refresher.tick()
+ expect(hosts()).toBe('{}\n')
+ expect(asked()).toBe(3)
+ })
+
+ it('reads nothing from the backend while no session uses the app, and leaves tokens be while it is away', async () => {
+ const quiet = setup(() => ok([]), [{ id: 'harness-1', plain: true }])
+ await new GitHubTokenRefresher(quiet.core).tick()
+ expect(quiet.backend).not.toHaveBeenCalled()
+ let away = false
+ const { core, hosts } = setup((method, path) => away ? refuse(502, 'BACKEND_UNAVAILABLE')
+ : path.endsWith('/assignments') ? ok([{ tabId: 'tab-1', assignmentId: 'attempt-1', harnessId: 'harness-1' }])
+ : method === 'GET' ? ok([row('tab-1', 'agent-1')]) : issued('ghs_fixtureToken0000009'))
+ const refresher = new GitHubTokenRefresher(core)
+ await refresher.tick()
+ away = true
+ await refresher.tick()
+ expect(hosts()).toContain('ghs_fixtureToken0000009')
+ })
+
+ it('starts once, looks again on its interval, and stops', async () => {
+ vi.useFakeTimers()
+ try {
+ const { core, backend } = setup(path => path === 'GET' ? ok([]) : ok([]))
+ const refresher = new GitHubTokenRefresher(core, { intervalMs: 1000 })
+ refresher.start()
+ refresher.start()
+ await vi.advanceTimersByTimeAsync(2500)
+ expect(backend.mock.calls.filter(c => String(c[1]).endsWith('/assignments')).length).toBe(3)
+ refresher.stop()
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(backend.mock.calls.filter(c => String(c[1]).endsWith('/assignments')).length).toBe(3)
+ } finally { vi.useRealTimers() }
+ })
+
+ it('logs a look that fails and goes on', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const core = fakeCore({ agents: { live: vi.fn(() => { throw new Error('registry gone') }) } })
+ await new GitHubTokenRefresher(core).tick()
+ expect(warn).toHaveBeenCalledWith('[super-tab] GitHub tokens not refreshed · registry gone')
+ warn.mockRestore()
+ })
+})
diff --git a/cli/src/superTabs/github.ts b/cli/src/superTabs/github.ts
new file mode 100644
index 000000000..ce37a3f61
--- /dev/null
+++ b/cli/src/superTabs/github.ts
@@ -0,0 +1,144 @@
+/**
+ * The daemon's half of the Harness GitHub App (docs/swarm-github-app.md): it asks the backend for the token of a local
+ * Swarm agent's task, as that agent, and keeps the agent's gh login (lib/swarmGitHub.ts) holding a live token while the
+ * task lasts and none after it.
+ *
+ * The token goes to git through `harness git-credential` (superTabs/gitCredential.ts), which asks here over the local
+ * socket, and to gh through the session's own `hosts.yml`. Nothing here logs a token.
+ */
+import type { CoreApi } from '../core/api.js'
+import { swarmGitHubSessionDir, writeSessionGitHub } from '../lib/swarmGitHub.js'
+import { backend, identifier, object, SuperTabHostError } from './host.js'
+
+type Json = Record<string, unknown>
+type Session = NonNullable<ReturnType<CoreApi['agents']['byAgent']>>
+const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
+
+/** The session's own folder when it was started to use the app, else null. */
+function githubDir(core: CoreApi, session: Session | undefined): string | null {
+ const skill = session?.swarmSkill
+ return skill?.github ? swarmGitHubSessionDir(core.dataDir, skill.key) : null
+}
+
+/** Refusals that mean the session must not keep a token: anything the backend decided, and no app on the server. A
+ * backend that could not be reached decides nothing, and an unexpired token stays. */
+const decided = (error: SuperTabHostError) => (error.status >= 400 && error.status < 500) || error.code === 'GITHUB_APP_NOT_CONFIGURED'
+
+/**
+ * The token of [harnessId]'s task: asked as each Swarm membership this machine's roster lists for that harness (one,
+ * nearly always), the first that has a task answering. For a session started to use the app, its gh login and commit
+ * trailers are written from the answer, and its login emptied on a refusal.
+ */
+export async function githubToken(core: CoreApi, harnessId: string): Promise<Json> {
+ const machineId = core.daemon.machineId()
+ if (!identifier(machineId) || !identifier(harnessId)) return { error: 'INVALID_REQUEST' }
+ const session = core.agents.byAgent(harnessId)
+ if (!session) return { error: 'AGENT_UNAVAILABLE', detail: 'This harness is not running on this machine.' }
+ const dir = githubDir(core, session)
+ let refusal: Json | null = null
+ try {
+ const rows = list(await backend(core, 'GET', `/api/super-tabs/hosts/${machineId}`)).filter(row => {
+ const agent = object(row.agent)
+ return identifier(row.tabId) && identifier(agent.id) && agent.machineId === machineId && agent.harnessId === harnessId
+ && row.closeSession !== true && row.stopRequested !== true
+ })
+ for (const row of rows) {
+ const tabId = String(row.tabId), agentId = String(object(row.agent).id)
+ try {
+ const value = object(await backend(core, 'POST', `/api/super-tabs/${tabId}/github-token?asAgentId=${agentId}`, { machineId }))
+ if (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') : [])
+ return { ok: true, value: { ...value, tabId, agentId } }
+ } catch (error) {
+ if (!(error instanceof SuperTabHostError)) throw error
+ // A task in another Swarm this harness also belongs to is still worth asking for; any other refusal says more.
+ if (!refusal || refusal.error === 'NO_ASSIGNMENT') refusal = { error: error.code, detail: error.message, status: error.status, decided: decided(error) }
+ }
+ }
+ } catch (error) {
+ if (!(error instanceof SuperTabHostError)) throw error
+ refusal = { error: error.code, detail: error.message, status: error.status, decided: decided(error) }
+ }
+ refusal ??= { error: 'NOT_A_SWARM_AGENT', detail: 'This harness is not an agent in a Swarm on this machine.', decided: true }
+ const { decided: final, ...answer } = refusal
+ if (dir && final) writeSessionGitHub(dir, null)
+ return answer
+}
+
+/** How often the daemon looks at its sessions' tasks. A token is renewed once it has this much left or less. */
+export const REFRESH_INTERVAL_MS = 60_000
+export const RENEW_BELOW_MS = 10 * 60_000
+
+/**
+ * Keeps each local session started to use the app holding a token for its task while the task lasts: renewed before it
+ * runs out (the backend hands out a new one ten minutes before expiry), and taken away when the task ends, so gh, which
+ * reads its login each time it runs, never holds a stale or finished task's token for long. One backend read a minute,
+ * and only while such a session is running.
+ */
+export class GitHubTokenRefresher {
+ private timer: NodeJS.Timeout | null = null
+ private running: Promise<void> | null = null
+ private readonly primed = new Map<string, { assignmentId: string; expiresAt: number }>()
+ private readonly now: () => number
+ private readonly intervalMs: number
+
+ constructor(private readonly core: CoreApi, options: { now?: () => number; intervalMs?: number } = {}) {
+ this.now = options.now ?? Date.now
+ this.intervalMs = options.intervalMs ?? REFRESH_INTERVAL_MS
+ }
+
+ start(): void {
+ if (this.timer) return
+ this.timer = setInterval(() => { void this.tick() }, this.intervalMs)
+ this.timer.unref?.()
+ void this.tick()
+ }
+
+ stop(): void {
+ if (this.timer) clearInterval(this.timer)
+ this.timer = null
+ this.primed.clear()
+ }
+
+ /** One look; a look still running is not started twice. */
+ tick(): Promise<void> {
+ this.running ??= this.look().catch(error => {
+ console.warn(`[super-tab] GitHub tokens not refreshed · ${error instanceof Error ? error.message : String(error)}`)
+ }).finally(() => { this.running = null })
+ return this.running
+ }
+
+ private async look(): Promise<void> {
+ const sessions = this.core.agents.live().flatMap(session => {
+ const dir = githubDir(this.core, session)
+ return dir ? [{ session, dir }] : []
+ })
+ for (const id of this.primed.keys()) if (!sessions.some(s => s.session.agentId === id)) this.primed.delete(id)
+ if (!sessions.length) return
+ const machineId = this.core.daemon.machineId()
+ if (!identifier(machineId)) return
+ let work: Json[]
+ try { work = list(await backend(this.core, 'GET', `/api/super-tabs/hosts/${machineId}/assignments`)) } catch (error) {
+ if (error instanceof SuperTabHostError) return
+ throw error
+ }
+ for (const { session, dir } of sessions) {
+ const id = session.agentId
+ const task = work.find(row => row.harnessId === id && identifier(row.assignmentId))
+ if (!task) {
+ // No task in its hands: no token in its gh login.
+ writeSessionGitHub(dir, null)
+ this.primed.delete(id)
+ continue
+ }
+ const known = this.primed.get(id)
+ if (known && known.assignmentId === task.assignmentId && known.expiresAt - this.now() > RENEW_BELOW_MS) continue
+ const answer = await githubToken(this.core, id)
+ const expiresAt = Date.parse(String(object(answer.value).expiresAt))
+ if (answer.ok === true && Number.isFinite(expiresAt)) this.primed.set(id, { assignmentId: String(task.assignmentId), expiresAt })
+ else this.primed.delete(id)
+ }
+ }
+}
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index edf86afb2..a07e49833 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -661,6 +661,34 @@ describe('a Lead\'s terminal result', () => {
})
})
+describe('GitHub App tokens through the service', () => {
+ it('gives a local agent its task\'s token, never one asked for through the relay', async () => {
+ const call = vi.fn<CoreApi['account']['backend']>(async (method, path) => ({ status: 200, body: { success: true, data: method === 'GET' && path.endsWith('/machine-1')
+ ? [{ tabId: 'tab-1', agent: { id: 'agent-1', machineId: 'machine-1', harnessId: 'native' } }]
+ : { token: 'ghs_fixtureToken0000001', expiresAt: '2026-10-24T13:00:00.000Z', repository: 'acme/app', trailers: [] } } }))
+ const service = superTabService(fakeCore({ account: { backend: call }, agents: { byAgent: vi.fn(() => ({ agentId: 'native' }) as never) } }),
+ { githubTokens: () => ({ start: vi.fn(), stop: vi.fn() }) })
+ expect(await service.requests.super_tabs({ action: 'githubToken', harnessId: 'native' }, owner))
+ .toMatchObject({ ok: true, value: { token: 'ghs_fixtureToken0000001', tabId: 'tab-1', agentId: 'agent-1' } })
+ expect(call).toHaveBeenCalledWith('POST', '/api/super-tabs/tab-1/github-token?asAgentId=agent-1', { machineId: 'machine-1' })
+ const calls = call.mock.calls.length
+ expect(await service.requests.super_tabs({ action: 'githubToken', harnessId: 'native' }, { local: false, owner: true, accountOwner: true } as never))
+ .toEqual({ error: 'OWNER_REQUIRED' })
+ expect(await service.requests.super_tabs({ action: 'githubToken', harnessId: 'native' }, visitor)).toEqual({ error: 'OWNER_REQUIRED' })
+ expect(call.mock.calls.length).toBe(calls)
+ })
+
+ it('keeps the tokens fresh while connected, and stops with the service', () => {
+ const tokens = { start: vi.fn(), stop: vi.fn() }
+ const service = superTabService(fakeCore(), { githubTokens: () => tokens })
+ service.port.connected()
+ expect(tokens.start).toHaveBeenCalledTimes(1)
+ service.port.disconnected()
+ service.port.stop()
+ expect(tokens.stop).toHaveBeenCalledTimes(2)
+ })
+})
+
// Lead mentions (spec 2026-10-24-lead-mentions): a post names people by id or email; the backend gets their person ids,
// and only a Lead's help offers it.
describe('mentions on a post', () => {
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 25cd04e11..662307bf2 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -10,6 +10,7 @@ import { CapacityReservations, type ReservationBook } from './reservations.js'
import { ContributionPreparations, prepareContribution } from './contribution.js'
import { messageIdOf } from './attach.js'
import { cardId, SwarmCards } from './cards.js'
+import { GitHubTokenRefresher, githubToken } from './github.js'
const POST_HELP = 'reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.'
const HELP = {
@@ -132,6 +133,8 @@ export interface SuperTabServiceOptions {
reservations?: (core: CoreApi, machineId: string) => ReservationBook
/** The Swarm cards' reader (superTabs/cards.ts), for a spec. */
cards?: (core: CoreApi, machineId: string) => SwarmCards
+ /** What keeps Swarm sessions' GitHub tokens fresh (superTabs/github.ts), for a spec. */
+ githubTokens?: (core: CoreApi) => Pick<GitHubTokenRefresher, 'start' | 'stop'>
}
export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {
const preparations = new ContributionPreparations(input => (options.prepareContribution ?? prepareContribution)(core, input))
@@ -163,9 +166,12 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
}
return swarmCards
}
- const disconnect = () => { preparations.clear(); host?.stop(); host = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null }
+ // Sessions doing another person's project work keep a live GitHub App token while their task lasts, and none after.
+ const tokens = (options.githubTokens ?? (api => new GitHubTokenRefresher(api)))(core)
+ const disconnect = () => { preparations.clear(); host?.stop(); host = null; book?.stop(); book = null; bookMachine = null; swarmCards?.want(false); swarmCards = null; cardsMachine = null; tokens.stop() }
const port = {
connected: () => {
+ tokens.start()
if (identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))) wake()
},
disconnected: disconnect,
@@ -189,6 +195,12 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
return await wake().prepareNative(payload.tabId, payload.contextId, payload.action === 'renewNative', closed)
}
if (!asker.owner || (!asker.local && asker.accountOwner !== true)) return { error: 'OWNER_REQUIRED' }
+ // `harness git-credential` in a local agent's shell (superTabs/gitCredential.ts): the token of that agent's task,
+ // which goes to this computer's own processes alone, never to another machine through the relay.
+ if (payload.action === 'githubToken') {
+ if (!asker.local) return { error: 'OWNER_REQUIRED' }
+ return await githubToken(core, String(payload.harnessId ?? ''))
+ }
if (payload.action === 'swarmRole') {
const grant = await port.swarmRole(String(payload.harnessId ?? ''))
return { ok: true, role: grant ? grant.role : grant, ...(grant ? { mode: grant.mode } : {}) }
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index 119d64b9f..51db09f22 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import { inspectCapacity, startAgent } from './start.js'
import { buildEngineCommandArgv } from '../lib/engineLaunch.js'
const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }
-function fixture(options: { state?: Record<string, unknown> | Error; refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; acceptedLaunchModel?: { model: string | null; effort: string | null }; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
+function fixture(options: { state?: Record<string, unknown> | Error; githubApp?: boolean; refuse?: string; loseCancel?: boolean; loseFailure?: boolean; launchModel?: string[]; acceptedLaunchModel?: { model: string | null; effort: string | null }; refuseModel?: string; frame?: string; guest?: boolean; identity?: { sessionId: string; createdAt: string } } = {}) {
const start = { creationId: 'super-native-receipt', error: null as string | null, request: { machineId: 'target', conversationId: 'group', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }, dispatched: false }
let nativeState = 'missing', lostJoin = false
@@ -10,7 +10,7 @@ function fixture(options: { state?: Record<string, unknown> | Error; refuse?: st
if (payload.action === 'startStatus') return { ok: true, value: structuredClone(start) }
if (payload.action === 'status') {
if (options.state instanceof Error) throw options.state
- return { ok: true, value: { revision: 1, state: options.state ?? { conversations: [{ id: 'group' }] } } }
+ return { ok: true, value: { revision: 1, state: options.state ?? { conversations: [{ id: 'group' }] }, ...(options.githubApp ? { githubApp: true } : {}) } }
}
const cmd = payload.command as Record<string, unknown>
if (cmd.type === 'agent.startDispatch') start.dispatched = true
@@ -809,3 +809,34 @@ it('waits for the initial engine binding before recording a timed launch identit
expect(await startAgent({ action: 'start', tabId: 'tab', operationId: 'binding-start', request: f.start.request }, f.scoped, where, f.open)).toMatchObject({ error: 'START_PENDING' })
expect(f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).some(c => c?.type === 'agent.started')).toBe(false)
})
+
+describe('Swarm starts for another person\'s project', () => {
+ const state = { ownerId: 'owner-1', people: [{ id: 'owner-1', email: '[email protected]' }, { id: 'host-1', email: '[email protected]' }],
+ projects: [{ id: 'lead', ownerId: 'host-1' }, { id: 'p1', ownerId: 'owner-1', skillMode: 'default' }], conversations: [{ id: 'group', projectId: 'p1' }] }
+ const started = async (options: Parameters<typeof fixture>[0], machineOwnerId = 'host-1') => {
+ const f = fixture(options)
+ Object.assign(f.start, { machineOwnerId })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ ok: true })
+ return f.request.mock.calls.find(c => c[0] === 'agent_create')![1]!
+ }
+
+ it('wires the Harness GitHub App and says whom the work is for when the project\'s owner is not the machine\'s', async () => {
+ const payload = await started({ state, githubApp: true })
+ expect(payload).toMatchObject({ swarmRole: 'dev', swarmSkillMode: 'default', swarmGitHub: true })
+ expect(String(payload.prompt)).toMatch(/not this computer's own GitHub login\. Start each pull request body with: Requested by owner@example\.com through Harness\.$/)
+ })
+
+ it('reads a Swarm from before projects as its owner\'s', async () => {
+ const legacy = { ownerId: 'owner-1', people: state.people, conversations: [{ id: 'group' }] }
+ expect(await started({ state: legacy, githubApp: true })).toMatchObject({ swarmGitHub: true })
+ })
+
+ it('launches as before for the machine owner\'s own project, on a server without the app, or when the Swarm cannot be read', async () => {
+ for (const [options, owner] of [[{ state, githubApp: true }, 'owner-1'], [{ state }, 'host-1'], [{ state: new Error('offline'), githubApp: true }, 'host-1'],
+ [{ state: { ...state, conversations: [{ id: 'other' }] }, githubApp: true }, 'host-1'], [{ state: { ...state, people: [] }, githubApp: true }, 'host-1']] as const) {
+ const payload = await started(options, owner)
+ expect(payload).not.toHaveProperty('swarmGitHub')
+ expect(String(payload.prompt)).not.toContain('GitHub App')
+ }
+ })
+})
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index e6d97e311..58a6c3b03 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -51,14 +51,35 @@ export async function inspectCapacity(target: Daemon, request: Json) {
return { capacity, engine, quota, ...admission(capacity, engine, quota, requirements, !!request.codexHome || !!request.gridModel) }
}
-/** The skills of the project whose group the agent joins, so it starts on that text and is never moved to it at once. A
- * project from before modes, or a state this start cannot read, is orchestration; the host moves a running agent to its
- * project's mode (superTabs/host.ts) if that guess is wrong. */
-async function projectSkillMode(scoped: ScopedRequest, conversationId: unknown): Promise<SwarmSkillMode> {
- const state = object(object(object(await scoped({ action: 'status' }).catch(() => ({}))).value).state)
- return groupSkillMode(state, (Array.isArray(state.conversations) ? state.conversations.map(object) : []).find(group => group.id === conversationId))
+/** What the start reads from the Swarm about the project whose group the agent joins:
+ *
+ * - its skills, so the agent starts on that text and is never moved to it at once. A project from before modes, or a
+ * state this start cannot read, is orchestration; the host moves a running agent to its project's mode
+ * (superTabs/host.ts) if that guess is wrong.
+ * - whether the agent does another person's project work (the project's owner is not the machine's owner) on a server
+ * with the Harness GitHub App, and whom that work is for. Then git and gh in the session use the app's token for its
+ * task instead of the machine owner's GitHub login (lib/swarmGitHub.ts, docs/swarm-github-app.md). A person's own
+ * agents, a server without the app, and a state this start cannot read launch as before.
+ */
+export async function projectFacts(scoped: ScopedRequest, conversationId: unknown, machineOwnerId: unknown):
+ Promise<{ mode: SwarmSkillMode; github: { requester: string } | null }> {
+ const answer = object(object(await scoped({ action: 'status' }).catch(() => ({}))).value)
+ const state = object(answer.state)
+ const group = (Array.isArray(state.conversations) ? state.conversations.map(object) : []).find(group => group.id === conversationId)
+ const mode = groupSkillMode(state, group)
+ // A Swarm from before projects is one project, its owner's.
+ const project = Array.isArray(state.projects) ? state.projects.map(object).find(p => p.id === (group?.projectId ?? 'lead')) : { ownerId: state.ownerId }
+ const ownerId = project?.ownerId
+ const requester = (Array.isArray(state.people) ? state.people.map(object) : []).find(p => p.id === ownerId)?.email
+ const github = answer.githubApp === true && group && identifier(ownerId) && identifier(machineOwnerId) && ownerId !== machineOwnerId
+ && typeof requester === 'string' && requester ? { requester } : null
+ return { mode, github }
}
+/** What an agent doing another person's project work is told about git, gh and its pull requests. */
+export const githubPromptLine = (requester: string) => `git and gh here use a Harness GitHub App token for this project's repository while you `
+ + `have a task, not this computer's own GitHub login. Start each pull request body with: Requested by ${requester} through Harness.`
+
/** Whether the machine launches `engine` with a model of its own for that session (lib/launchModel.ts). A daemon from
* before the flags does not name the field, and agent_create would silently drop a model it does not know. */
const launchesWithModel = (capacity: Json, engine: unknown) => Array.isArray(capacity.launchModel) && capacity.launchModel.includes(engine)
@@ -158,13 +179,15 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher
// Engines without a full mode retain their existing approving launch flags.
// The backend starts a Reviewer only on Claude Code or Codex, the engines with built-in Swarm skills.
const skilled = ['claude', 'codex'].includes(String(request.engine)), reviewer = request.role === 'reviewer'
- const role = reviewer ? 'review' : 'dev', mode = skilled ? await projectSkillMode(scoped, request.conversationId) : null
+ const role = reviewer ? 'review' : 'dev', facts = skilled ? await projectFacts(scoped, request.conversationId, start.machineOwnerId) : null
+ const mode = facts?.mode ?? null, github = facts?.github ?? null
const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent', bypassPermission: true,
...(permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),
...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),
+ ...(github ? { swarmGitHub: true } : {}),
prompt: `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer
? `Do not review yet. You review work in conversation ${request.conversationId} when it is ready for review.`
- : `Do not begin project work yet. Your lead will assign work in conversation ${request.conversationId}.`} Reply in that conversation using harness super-tab --tab ${input.tabId} post ${request.conversationId} 'your message' UNIQUE_OPERATION_ID. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`,
+ : `Do not begin project work yet. Your lead will assign work in conversation ${request.conversationId}.`} Reply in that conversation using harness super-tab --tab ${input.tabId} post ${request.conversationId} 'your message' UNIQUE_OPERATION_ID. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.${github ? ` ${githubPromptLine(github.requester)}` : ''}`,
...(request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`,
// No branch named: the repository's default branch, fetched, not the host checkout's old HEAD.
...(request.branchRef ? { branchRef: request.branchRef } : { branchBase: 'default' }) } : { cwd: request.cwd }),
diff --git a/docs/swarm-github-app.md b/docs/swarm-github-app.md
new file mode 100644
index 000000000..42849482f
--- /dev/null
+++ b/docs/swarm-github-app.md
@@ -0,0 +1,244 @@
+# Swarm GitHub App
+
+When a Swarm agent works on another person's project, it pushes commits and opens
+pull requests with the **Harness GitHub App**, not the GitHub login of the computer
+it runs on. Each token is for the project's one repository and lasts at most an hour.
+Harness revokes it as soon as the agent's task ends.
+
+The agent's commits name the person whose project it is as co-author, along with the
+agent and the computer. This is step 4 of the
+[Swarm team account plan](plans/2026-10-24-swarm-team-account.md).
+
+## Set it up
+
+An owner of the GitHub organization does this once. A Harness server administrator
+then adds three settings.
+
+### 1. Create the app
+
+On GitHub, open the organization, then **Settings → Developer settings → GitHub Apps
+→ New GitHub App**, and fill in:
+
+| Field | Value |
+| --- | --- |
+| GitHub App name | A name of your choice, for example `Harness for Acme`. GitHub needs it to be unique. |
+| Homepage URL | `https://harness.autonomous.ai` |
+| Callback URL, Setup URL | Leave empty. |
+| Webhook → Active | Clear it. Harness subscribes to no events. |
+| Repository permissions | **Contents:** Read and write. **Pull requests:** Read and write. **Checks:** Read-only. **Actions:** Read-only. **Metadata:** Read-only (GitHub sets this one). Leave every other permission at *No access*. |
+| Organization and account permissions | No access. |
+| Where can this GitHub App be installed? | **Only on this account** |
+
+Click **Create GitHub App**. These settings match this manifest, if you prefer to
+register with [GitHub's manifest flow](https://docs.github.com/apps/sharing-github-apps/registering-a-github-app-from-a-manifest):
+
+```json
+{
+ "name": "Harness for Acme",
+ "url": "https://harness.autonomous.ai",
+ "public": false,
+ "hook_attributes": { "active": false },
+ "default_permissions": {
+ "contents": "write",
+ "pull_requests": "write",
+ "checks": "read",
+ "actions": "read",
+ "metadata": "read"
+ },
+ "default_events": []
+}
+```
+
+On the app's page:
+
+1. Note the **App ID** near the top.
+2. Under **Private keys**, click **Generate a private key**. GitHub downloads a
+ `.pem` file. It is the app's only credential: keep it in your secret store.
+3. Note the app's name in its public address, `https://github.com/apps/NAME`.
+ This is the slug.
+
+### 2. Install it
+
+On the app's page, click **Install App** and choose the organization. Select **Only
+select repositories** and pick the repositories your Swarm projects use, or choose
+**All repositories**. Click **Install**. You can add repositories later from the
+organization's **Settings → GitHub Apps → Configure**.
+
+If a project uses a repository the app is not installed on, its agents cannot push.
+They receive the install link to pass on to an organization owner.
+
+### 3. Require pull requests on the default branch
+
+A token that can write contents can push straight to any branch that nothing
+protects. On each repository, or once for the organization, open **Settings → Rules →
+Rulesets → New branch ruleset**. Target the default branch, turn on **Require a pull
+request before merging**, set **Enforcement status** to *Active* and save. Leave the
+app off the bypass list.
+
+Harness checks this when it hands out a token. It still gives the token when the
+default branch is unprotected, but it reports `defaultBranchProtected: false`. Each
+time git uses that token, `harness git-credential` warns the agent, so the agent can
+tell its Lead and the Lead can warn people. Harness reads rulesets with the app's metadata
+permission. It cannot read classic branch protection rules without administration
+access, which it does not request. A branch protected only by a classic rule
+therefore reports `defaultBranchProtection: "classic"` and
+`defaultBranchProtected: false`. A ruleset removes that false warning.
+
+### 4. Configure the Harness server
+
+Set these on the backend and deploy it:
+
+| Variable | Value |
+| --- | --- |
+| `GITHUB_APP_ID` | The App ID (the app's Client ID also works). |
+| `GITHUB_APP_PRIVATE_KEY` | The `.pem` file's contents. You can paste them as they are, with line breaks written as `\n`, or as base64: `base64 < key.pem \| tr -d '\n'`. |
+| `GITHUB_APP_SLUG` | The app's name from `https://github.com/apps/NAME`. Optional; it adds the install link to refusals. |
+
+If both of the first two are empty, the feature is off and nothing changes. If only
+one of them is set, or the key cannot be read, the backend stops at startup with a
+message that never shows the key. Once the key is configured, delete the downloaded
+copy.
+
+To try it, start an agent from a Lead on someone else's computer, for a project
+whose repository has the app installed. When it has a task, `git push` and
+`gh pr create` work in its terminal. `git log -1` shows the trailers, and on GitHub
+the push and pull request appear as the app.
+
+## Which agents use it
+
+Harness wires the app into an agent when the start meets all of these conditions:
+
+- The agent is a Claude Code or Codex agent started by a Swarm Lead.
+- The project's owner is not the owner of the computer the agent runs on.
+- The server has the app configured.
+
+A person's own agents, starts on a server without the app, and computers whose Harness
+is too old to understand the request keep using the computer's own git and gh
+configuration. The decision is recorded with the session, so a relaunch keeps it.
+In the planned team account, every Swarm agent qualifies, because the owner's login
+is not there. Windows is not wired yet.
+
+## How git and gh get the token
+
+Everything reaches the agent through environment variables, because those survive
+what its shells do. Codex runs every command in a login shell, and Claude Code
+replays the person's startup files. On a Mac, both put Homebrew's folders back at
+the front of `PATH`. A `gh` wrapper placed first on `PATH` would be skipped, so
+Harness does not use one.
+
+- **git** reads `GIT_CONFIG_PARAMETERS`, the variable `git -c` uses, which overrides
+ every config file:
+ - For `https://github.com`, it clears the credential helpers git has read so far
+ and sets `harness git-credential` as the only one. It also sets `useHttpPath`, so
+ the helper sees which repository git wants.
+ - `[email protected]:` and `ssh://[email protected]/` remotes are fetched and pushed over
+ HTTPS, so no SSH key of the owner is used.
+ - `core.hooksPath` points to Harness's hooks. Each one runs the repository's own
+ hook first, from the repository's own `core.hooksPath` or `.git/hooks`.
+ - `GIT_TERMINAL_PROMPT=0` makes a missing credential fail at once instead of
+ waiting for input that never comes.
+- **`harness git-credential get`** finds the calling agent from its tmux pane, the way
+ `harness super-tab` does. It asks the local daemon for the token of that agent's
+ task and answers `username=x-access-token` and `password=<token>`, but only for
+ `https://github.com` and only for the task's repository. A request for another
+ host or another repository gets no answer. It ignores `store` and `erase`.
+- **gh** reads `GH_CONFIG_DIR`, a folder belonging to the session. The daemon writes
+ the token into that folder's `hosts.yml`: when the task starts, again before the
+ token expires, and every time git asks for it. When the task ends, the daemon
+ empties the file. gh reads the file each time it runs, so it never holds a stale
+ token. `GH_TOKEN` and `GITHUB_TOKEN` are cleared from what the agent inherits.
+ gh never reads the owner's configuration.
+
+The daemon checks its sessions' tasks once a minute, and only while such a session
+is running. The backend returns the same token until ten minutes before it expires.
+
+## Attribution
+
+Each commit message gets these trailers, added by the `prepare-commit-msg` hook after
+the repository's own hook has run:
+
+```text
+Co-authored-by: Ada Lovelace <[email protected]>
+Harness-Agent: Atlas
+Harness-Machine: Studio Mac
+```
+
+The co-author is the project's owner, under their Harness account name and email
+address. The `commit-msg` hook adds any missing trailers to a message written in an
+editor. Trailers already in the message are not added again, so an amend keeps one
+of each. An empty message still aborts the commit.
+
+The `prepare-commit-msg` hook runs even with `--no-verify`. Two things leave a commit
+without trailers: plumbing such as `git commit-tree`, and a command that sets its own
+`-c core.hooksPath`.
+
+The agent is told to start each pull request body with `Requested by <owner's email>
+through Harness.` The token response also carries `pullRequestLine` with the owner's
+name. This line depends on the agent following its instructions. Harness does not
+assign the pull request, because it does not know the person's GitHub login.
+
+## The token endpoint
+
+`POST /api/super-tabs/:tabId/github-token?asAgentId=AGENT` with body
+`{ "machineId": "MACHINE" }`.
+
+The caller must be the account that hosts the agent, sending from the computer that
+runs it. The agent must have a task in progress: working, waiting on a person, stuck,
+or out for review. The response is:
+
+```json
+{
+ "token": "ghs_…",
+ "expiresAt": "2026-10-24T13:00:00Z",
+ "repository": "acme/app",
+ "defaultBranch": "main",
+ "defaultBranchProtected": true,
+ "defaultBranchProtection": "pull_request",
+ "requestedBy": { "name": "Ada Lovelace", "email": "[email protected]" },
+ "agent": "Atlas",
+ "machine": "Studio Mac",
+ "trailers": ["Co-authored-by: Ada Lovelace <[email protected]>", "Harness-Agent: Atlas", "Harness-Machine: Studio Mac"],
+ "pullRequestLine": "Requested by Ada Lovelace ([email protected]) through Harness."
+}
+```
+
+`defaultBranchProtection` takes one of these values:
+
+- `pull_request`: a ruleset requires a pull request.
+- `classic`: classic protection is on, but its settings cannot be read.
+- `none`: nothing protects the branch.
+- `unknown`: GitHub could not say.
+
+The endpoint refuses with these codes:
+
+| Code | Status | When |
+| --- | --- | --- |
+| `GITHUB_APP_NOT_CONFIGURED` | 503 | The server has no app. |
+| `AGENT_REQUIRED` | 400 | No `asAgentId`. |
+| `FORBIDDEN` | 403 | Another account's agent, or the agent runs on another computer. |
+| `NO_ASSIGNMENT` | 409 | The agent has no task in progress. |
+| `REPOSITORY_NOT_GITHUB` | 409 | The project has no repository address, or one outside github.com. |
+| `GITHUB_APP_NOT_INSTALLED` | 409 | The app does not cover the repository. When the slug is set, the response includes `installUrl`. |
+| `GITHUB_APP_PERMISSIONS` | 409 | The installation has not accepted the permissions above. |
+| `GITHUB_APP_MISCONFIGURED`, `GITHUB_UNAVAILABLE` | 503/502 | GitHub refused the app's credentials, or did not answer. |
+
+Each token is cached per agent and task, sealed with a key derived from the app's
+private key, in the backend's shared Redis. The backend serves the cached token until
+ten minutes before it expires. The token is revoked (`DELETE /installation/token`)
+and dropped when the task is done, cancelled or stopped, when the agent is removed,
+or when the agent starts a new task. If a revocation fails, Harness logs it without
+the token and the task's change goes ahead. The token then expires within the hour.
+The server never logs a token.
+
+## Known limits
+
+- Preparing a Swarm worktree still fetches with the computer's own git setup, in
+ the daemon, before the agent starts. A team account has no such login, so its first
+ fetch of a private repository is a follow-up.
+- On a personal computer, startup files that export `GITHUB_TOKEN` reach Claude
+ Code's and Codex's commands again. gh then uses that token. The team account has
+ no such files.
+- If Redis is unavailable, Harness still issues tokens but cannot revoke them when
+ the 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
+ check or the agent's first git command that needs credentials.
diff --git a/docs/swarms.md b/docs/swarms.md
index cfe7cda5f..714711934 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -196,3 +196,8 @@ Use the matching backend, CLI and Desktop versions together for this feature:
A signed internal Desktop artifact alone does not update the backend or host
CLI. Validate the coordinated versions in an internal environment before a
public Desktop release.
+
+When the server has the Harness GitHub App, an agent working on another person's
+project pushes and opens pull requests with a one-hour token for that project's
+repository, instead of its computer's own GitHub login. See
+[Swarm GitHub App](swarm-github-app.md) for setup.