The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
GitHub App tokens for a repository renamed on GitHub
bitcoinbuilder3f29ebdbf7d0
diff --git a/backend/src/github/app.ts b/backend/src/github/app.tsindex 4406f718b..4a7ba02ed 100644--- a/backend/src/github/app.ts+++ b/backend/src/github/app.ts@@ -7,7 +7,7 @@* 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'+import { githubRepository, 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. */@@ -85,6 +85,8 @@ export class GitHubApp {private signed: { jwt: string; until: number } | null = nullprivate readonly installations = new Map<string, { id: number | null; until: number }>()private readonly branches = new Map<string, { value: DefaultBranch; until: number }>()+ /** A repository's name now, by the name asked for (lower case): null when it was not renamed. */+ private readonly renames = new Map<string, { repository: GitHubRepository | null; until: number }>()constructor(readonly config: GitHubAppConfig, options: GitHubAppOptions = {}) {this.fetch = options.fetch ?? fetch@@ -157,6 +159,63 @@ export class GitHubApp {return id}+ /**+ * The installation that covers [repository], with the repository under the name GitHub knows it by now; null when the+ * app is not installed there. A repository renamed on GitHub still answers to its old name for git, but not for the+ * app's installation lookup, and a Swarm project's repository address is set once: a project made from a checkout+ * whose remote still had the old name could never get a token (2026-10-27, autonomous-harness renamed openharness).+ */+ async resolve(repository: GitHubRepository): Promise<{ installation: number; repository: GitHubRepository } | null> {+ const direct = await this.installation(repository)+ if (direct !== null) return { installation: direct, repository }+ const current = await this.currentName(repository)+ if (!current) return null+ const renamed = await this.installation(current)+ return renamed === null ? null : { installation: renamed, repository: current }+ }++ /** [repository]'s name now when it was renamed, else null: read with a read-only token of its owner's installation of+ * the app, which GitHub answers by the repository's id once it moved. The token is revoked at once. */+ private async currentName(repository: GitHubRepository): Promise<GitHubRepository | null> {+ const key = repository.fullName.toLowerCase()+ const known = this.renames.get(key)+ if (known && known.until > this.now()) return known.repository+ let current: GitHubRepository | null = null+ try {+ const owner = await this.ownerInstallation(repository.owner)+ if (owner !== null) {+ const minted = await this.call('POST', `/app/installations/${owner}/access_tokens`, `Bearer ${this.jwt()}`, { permissions: { metadata: 'read' } })+ const token = (minted.body as Record<string, unknown>).token+ if (minted.status === 201 && typeof token === 'string') {+ try {+ const read = await this.call('GET', `/repos/${repository.owner}/${repository.name}`, `Bearer ${token}`)+ const fullName = (read.body as Record<string, unknown>).full_name+ const found = read.status === 200 && typeof fullName === 'string' ? githubRepository(`https://github.com/${fullName}`) : null+ if (found && found.fullName.toLowerCase() !== key) current = found+ } finally {+ await this.revoke(token).catch(() => {})+ }+ }+ }+ } catch (error) {+ if (error instanceof GitHubAppError && error.code === 'GITHUB_APP_MISCONFIGURED') throw error+ // GitHub did not say: the repository reads as not installed, as it did before.+ }+ this.renames.set(key, { repository: current, until: this.now() + (current ? INSTALLATION_TTL_MS : NOT_INSTALLED_TTL_MS) })+ return current+ }++ /** The app's installation on [owner], an organization or a user, or null. */+ private async ownerInstallation(owner: string): Promise<number | null> {+ for (const path of [`/orgs/${owner}/installation`, `/users/${owner}/installation`]) {+ const answer = await this.call('GET', path, `Bearer ${this.jwt()}`)+ if (answer.status === 401) throw this.misconfigured()+ const id = (answer.body as Record<string, unknown>).id+ if (answer.status === 200 && typeof id === 'number') return id+ }+ return null+ }+/** A token for [repository] alone, with TOKEN_PERMISSIONS alone. */async createToken(installationId: number, repository: GitHubRepository, permissions: TokenPermissions = TOKEN_PERMISSIONS): Promise<{ token: string; expiresAt: string }> {const answer = await this.call('POST', `/app/installations/${installationId}/access_tokens`, `Bearer ${this.jwt()}`,diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.tsindex 5a0e1aa00..186a592ee 100644--- a/backend/src/github/fakeGitHub.ts+++ b/backend/src/github/fakeGitHub.ts@@ -18,6 +18,9 @@ export interface FakeCall { method: string; path: string; auth: string; body: unexport function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?: () => number }) {const now = options.now ?? Date.nowconst installed = new Map<string, number>()+ /** The app's installation on an owner (`owner`, lower case), and repositories renamed (old `owner/name` → new), lower case. */+ const owners = new Map<string, number>()+ const renamed = new Map<string, string>()const protection = new Map<string, { rules?: unknown[]; protected?: boolean; branch?: string; fail?: boolean }>()const calls: FakeCall[] = []const issued = new Set<string>()@@ -47,6 +50,11 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?: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 === 'GET' && (match = /^\/(?:orgs|users)\/([^/]+)\/installation$/.exec(url.pathname))) {+ if (!jwtValid(auth)) return json(401, { message: 'Bad credentials' })+ const id = owners.get(match[1]!.toLowerCase())+ return id === undefined ? json(404, { message: 'Not Found' }) : json(200, { id })+ }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 })@@ -68,13 +76,14 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?: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 })+ // A renamed repository: GitHub redirects its old name to its id, and fetch follows, so the body names it as it is now.+ if (!repoPath[3]) return json(200, { full_name: renamed.get(`${repoPath[1]}/${repoPath[2]}`.toLowerCase()) ?? `${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 }+ return { fetch, calls, installed, owners, renamed, protection, revoked, issued, control }}/** A configured app talking to [github]. */diff --git a/backend/src/github/tokens.test.ts b/backend/src/github/tokens.test.tsindex b723245d6..d43f5ddc6 100644--- a/backend/src/github/tokens.test.ts+++ b/backend/src/github/tokens.test.ts@@ -34,6 +34,50 @@ describe('preparation tokens', () => {})})+// A repository renamed on GitHub (2026-10-27: autonomous-harness → openharness): the project keeps the old name, which+// GitHub still answers for git, and the app is installed on the repository under its new one.+describe('a repository renamed on GitHub', () => {+ const renamedSetup = () => {+ const f = setup()+ f.github.installed.clear()+ f.github.installed.set('acme/app-next', 77)+ f.github.owners.set('acme', 77)+ f.github.renamed.set('acme/app', 'acme/app-next')+ return f+ }++ it('gets its tokens under its name now, and the read-only token used to find that name is revoked at once', async () => {+ const { tokens, github } = renamedSetup()+ expect(await tokens.prepare(repository)).toMatchObject({ repository: 'acme/app' })+ const minted = github.calls.filter(c => c.path.endsWith('/access_tokens')).map(c => c.body)+ expect(minted).toEqual([{ permissions: { metadata: 'read' } }, { repositories: ['app-next'], permissions: { contents: 'read', metadata: 'read' } }])+ expect(github.revoked).toEqual(['ghs_fixture_1'])+ expect((await tokens.issue(request())).repository).toBe('acme/app')+ expect(github.calls.filter(c => c.path.endsWith('/access_tokens')).at(-1)!.body).toMatchObject({ repositories: ['app-next'] })+ // Its name now is remembered: GitHub is not asked again for it.+ expect(github.calls.filter(c => c.path === '/orgs/acme/installation')).toHaveLength(1)+ })++ it('is not installed when its owner has no installation, or the repository was never renamed', async () => {+ const none = renamedSetup()+ none.github.owners.clear()+ await expect(none.tokens.prepare(repository)).rejects.toMatchObject({ code: 'GITHUB_APP_NOT_INSTALLED' })+ expect(none.github.calls.map(c => c.path)).toContain('/users/acme/installation')+ const same = renamedSetup()+ same.github.renamed.clear()+ await expect(same.tokens.prepare(repository)).rejects.toMatchObject({ code: 'GITHUB_APP_NOT_INSTALLED' })+ expect(same.github.revoked).toEqual(['ghs_fixture_1'])+ })++ it('reads as not installed when GitHub cannot say, and wrong credentials still say so', async () => {+ const down = renamedSetup()+ down.github.control.tokenStatus = 500+ await expect(down.tokens.prepare(repository)).rejects.toMatchObject({ code: 'GITHUB_APP_NOT_INSTALLED' })+ const app = fakeApp(throwawayKey().privateKey, down.github, { now: () => Date.parse('2026-10-24T12:00:00Z') })+ await expect(app.resolve(repository)).rejects.toMatchObject({ code: 'GITHUB_APP_MISCONFIGURED' })+ })+})+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()diff --git a/backend/src/github/tokens.ts b/backend/src/github/tokens.tsindex b088cc65d..2c28f8e89 100644--- a/backend/src/github/tokens.ts+++ b/backend/src/github/tokens.ts@@ -120,6 +120,7 @@ export class GitHubTokens {private async mint(key: string, request: TokenRequest): Promise<IssuedToken> {const repository = request.repository.fullName+ let actual = request.repositoryconst cached = await this.read(key)let entry: Entry | null = nullif (cached && cached.assignmentId === request.assignmentId && cached.repository === repository) {@@ -130,9 +131,12 @@ export class GitHubTokens {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)+ // Under the name GitHub knows it by now (app.ts `resolve`); the agent's checkout keeps the name it was given, which+ // GitHub still answers for git.+ const resolved = await this.app.resolve(request.repository)+ if (resolved === null) throw this.app.notInstalled(request.repository)+ actual = resolved.repository+ const minted = await this.app.createToken(resolved.installation, actual)entry = { ...minted, repository, assignmentId: request.assignmentId }const ttl = Date.parse(minted.expiresAt) - this.now()if (ttl > 0) {@@ -143,7 +147,7 @@ export class GitHubTokens {}}}- const branch = await this.app.defaultBranch(request.repository, entry.token)+ const branch = await this.app.defaultBranch(actual, entry.token)return { token: entry.token, expiresAt: entry.expiresAt, repository, defaultBranch: branch.branch,defaultBranchProtected: branch.protection === 'pull_request', defaultBranchProtection: branch.protection }}@@ -154,9 +158,9 @@ export class GitHubTokens {* login is never used for another person's project. Never cached: one start asks once, and it lasts at most an hour.*/async prepare(repository: GitHubRepository): Promise<{ token: string; expiresAt: string; repository: string }> {- const installation = await this.app.installation(repository)- if (installation === null) throw this.app.notInstalled(repository)- const minted = await this.app.createToken(installation, repository, PREPARE_PERMISSIONS)+ const resolved = await this.app.resolve(repository)+ if (resolved === null) throw this.app.notInstalled(repository)+ const minted = await this.app.createToken(resolved.installation, resolved.repository, PREPARE_PERMISSIONS)return { ...minted, repository: repository.fullName }}