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 routing: hold work that starts heavy CI while this repository's jobs are at the account's limit (goals piece 5, part 2) (#2428)

0xken15c9d5d45a4b6e
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.ts
index 57be4f3c9..bb2e9c90c 100644
--- a/backend/integration/superTabBuddies.test.ts
+++ b/backend/integration/superTabBuddies.test.ts
@@ -98,6 +98,16 @@ async function buddy(f: Awaited<ReturnType<typeof swarm>>, projectId = 'lead') {
return { chat, agentId, pool }
}
+describe('a Buddy and the route\'s reads', () => {
+ // Scholes's goals, piece 5: the route's read of running CI jobs is the project's agents'; a Buddy routes nothing.
+ it('refuses a Buddy the project\'s CI read, as an unavailable project, while the PM reads it', async () => {
+ const f = await swarm()
+ const { agentId } = await buddy(f)
+ await expect(f.store.ciRepository(peer, f.tab, 'lead', agentId)).rejects.toMatchObject({ code: 'NOT_FOUND', status: 404 })
+ expect(await f.store.ciRepository(owner, f.tab, 'lead', f.lead)).toEqual({ repositoryUrl: null })
+ })
+})
+
/** A complete PNG: one opaque red pixel, its chunks' checksums real, as a screenshot tool writes one. */
function png(): Buffer {
const chunk = (type: string, data: Buffer) => {
diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.ts
index 3934ca9c4..7ae435f07 100644
--- a/backend/integration/superTabGithub.test.ts
+++ b/backend/integration/superTabGithub.test.ts
@@ -540,3 +540,75 @@ describe('revoking the token when the task ends', () => {
expect(JSON.stringify(env.log.warn.mock.calls)).not.toContain(token)
})
})
+
+// Scholes's goals, piece 5: the route holds work that starts heavy CI while the account is at its limit of running jobs.
+describe('the CI load', () => {
+ const load = (env: Env, tab: string, projectId: string, user = owner, asAgentId?: string) => env.app.inject({ method: 'GET',
+ url: `/api/super-tabs/${tab}/projects/${projectId}/ci-load${asAgentId ? `?asAgentId=${asAgentId}` : ''}`, headers: { authorization: `Bearer ${user.sub}` } })
+ /** An agent of the project on the owner's own Mac, which the owner's sign-in speaks for. */
+ const own = async (env: Env, tab: string, group: string) => String((await env.run(tab, { type: 'agent.add', conversationId: group, machineId: 'owner-mac',
+ harnessId: randomUUID(), name: 'Router', configuration: config, lead: false } as Command)).result.agentId)
+ const busy = (env: Env) => env.github.actions.set('example/app', [
+ { id: 11, status: 'in_progress', jobs: [{ status: 'in_progress', labels: ['ubuntu-latest'] }, { status: 'in_progress', labels: ['macos-15'] }] },
+ { id: 12, status: 'queued', jobs: [{ status: 'queued', labels: ['macos-15'] }] }])
+
+ it('gives an agent of the project, and a person, the counts alone, read with a token that only reads runs and is revoked', async () => {
+ const env = await fresh()
+ busy(env)
+ const { tab, group } = await working(env)
+ const agent = await load(env, tab, 'lead', owner, await own(env, tab, group))
+ expect(agent.statusCode).toBe(200)
+ expect(agent.json().data).toEqual({ state: 'read', load: { running: 2, queued: 1, macosRunning: 1, macosQueued: 1 } })
+ // No run's name, branch or the token reaches the answer.
+ for (const text of ['secret-branch', 'run 11', 'ghs_', 'example/app']) expect(agent.body).not.toContain(text)
+ expect(env.github.calls.find(c => c.path.endsWith('/access_tokens'))!.body).toEqual({ repositories: ['app'], permissions: { actions: 'read', metadata: 'read' } })
+ expect(env.github.issued.size).toBe(0)
+ expect((await load(env, tab, 'lead')).json().data).toMatchObject({ state: 'read' })
+ })
+ it('refuses another project, one the reader cannot see, and an unknown one alike, naming none and reading nothing', async () => {
+ const env = await fresh()
+ busy(env)
+ const { tab, group, worker } = await working(env)
+ const router = await own(env, tab, group)
+ const secret = String((await env.run(tab, { type: 'project.create', name: 'Secret Plans', visibility: 'private', brief: '' } as Command)).result.projectId)
+ // The Lead's project's agent may not read the private project, which it cannot see: refused as a project that is not there.
+ const refusals = [await load(env, tab, secret, owner, router), await load(env, tab, 'nope', owner, router)]
+ for (const r of refusals) {
+ expect(r.statusCode).toBe(404)
+ expect(r.body).not.toContain('Secret Plans')
+ }
+ expect(refusals[0]!.json().error).toEqual(refusals[1]!.json().error)
+ // A person outside the Swarm reads nothing of it, answered as any Swarm it cannot reach (security review 1 of #2428); as
+ // the host of an agent of the project, it reads what that agent may.
+ const outsider = await load(env, tab, 'lead', host)
+ expect(outsider.statusCode).toBe(404)
+ expect(outsider.json().error).toEqual({ code: 'NOT_FOUND', message: 'This is not available to you. It may have been removed, or your access changed.' })
+ expect(outsider.body).not.toContain('running')
+ expect((await load(env, tab, secret, host, worker)).statusCode).toBe(404)
+ expect((await load(env, tab, 'lead', host, worker)).json().data).toMatchObject({ state: 'read' })
+ })
+ it('reads the counts once someone who can push approved the repository for the project, in a Swarm without the team account', async () => {
+ const env = await fresh({ approveAll: false })
+ busy(env)
+ const { tab } = await working(env)
+ expect((await load(env, tab, 'lead')).json().data).toEqual({ state: 'not-approved' })
+ // As the app's sign-in records it for someone who can push (github/approvals.ts).
+ env.approved.push({ tabId: tab, projectId: 'lead', repository: 'example/app', scope: 'project', login: 'olive' })
+ expect((await load(env, tab, 'lead')).json().data).toEqual({ state: 'read', load: { running: 2, queued: 1, macosRunning: 1, macosQueued: 1 } })
+ })
+ it('reads nothing for a repository not approved for the project, in a Swarm with the team account or without, and says when the server has no app', async () => {
+ // Security review 1 of #2428: tokens ask approval only where the team account is tried; this read asks it everywhere.
+ for (const team of [true, false]) {
+ if (team) teamAccounts()
+ const env = await fresh({ approveAll: false })
+ busy(env)
+ const { tab } = await working(env)
+ expect((await load(env, tab, 'lead')).json().data).toEqual({ state: 'not-approved' })
+ expect(env.github.calls.some(c => c.path.endsWith('/access_tokens'))).toBe(false)
+ vi.unstubAllEnvs()
+ }
+ const off = await fresh({ github: false })
+ const other = await working(off)
+ expect((await load(off, other.tab, 'lead')).json().data).toEqual({ state: 'unavailable' })
+ })
+})
diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.ts
index 88b214e38..0087ccdec 100644
--- a/backend/integration/superTabNotAvailable.test.ts
+++ b/backend/integration/superTabNotAvailable.test.ts
@@ -101,6 +101,10 @@ function calls(tab: string, chat: string, project: string) {
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/github', `${t}/projects/${project}/github`),
json('POST', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve', `${t}/projects/${project}/github/approve`, { scope: 'project' }),
json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', `${t}/projects/${project}/roles/${MISSING}`),
+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/ci-load', `${t}/projects/${project}/ci-load`),
+ // A made-up agent: an outsider is answered as for any Swarm it cannot reach. Asked of the Lead's project, so a member's
+ // in-Swarm refusal of an agent it does not run is not taken for the private project's answer.
+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/ci-load', `${t}/projects/lead/ci-load?asAgentId=${MISSING}`),
json('GET', 'GET /api/super-tabs/:tabId/route-decisions/:decisionId', `${t}/route-decisions/${MISSING}`),
json('GET', 'GET /api/super-tabs/:tabId/machines/:machineId/removal', `${t}/machines/${MISSING}/removal`),
multipart('POST /api/super-tabs/:tabId/attachments', `${t}/attachments`, form([field('conversationId', chat), file('notes.txt', 'text/plain', 'hello')])),
diff --git a/backend/src/github/app.test.ts b/backend/src/github/app.test.ts
index fdf98fb02..16608a56e 100644
--- a/backend/src/github/app.test.ts
+++ b/backend/src/github/app.test.ts
@@ -1,6 +1,6 @@
import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'
-import { describe, expect, it } from 'vitest'
-import { cacheSecret, githubAppConfig, GitHubAppError, PULL_READ_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'
+import { describe, expect, it, vi } from 'vitest'
+import { ACTIONS_READ_PERMISSIONS, CI_LOAD_TTL_MS, CI_MAX_CALLS, CI_MAX_RUNS, CI_READS_PER_HOUR, CI_STALE_MS, SERVER_PROCESSES_MAX, cacheSecret, githubAppConfig, GitHubAppError, PULL_READ_PERMISSIONS, readPrivateKey, TOKEN_PERMISSIONS } from './app.js'
import { FAKE_API, fakeApp, fakeGitHub, throwawayKey } from './fakeGitHub.js'
import { githubRepository } from './repository.js'
@@ -254,3 +254,163 @@ describe('default branch protection', () => {
expect(FAKE_API).not.toContain('api.github.com')
})
})
+
+describe('the CI load', () => {
+ const job = (status: string, ...labels: string[]) => ({ status, labels: labels.length ? labels : ['ubuntu-latest'] })
+ const busy = () => {
+ const env = setup()
+ env.github.installed.set('acme/app', 77)
+ env.github.actions.set('acme/app', [
+ { id: 1, status: 'in_progress', jobs: [job('in_progress'), job('in_progress', 'macos-15'), job('completed'), job('queued', 'macos-15')] },
+ { id: 2, status: 'queued', jobs: [job('waiting'), job('pending'), job('requested'), job('queued', 'self-hosted', 'macOS', 'arm64')] },
+ { id: 3, status: 'completed', jobs: [job('in_progress')] },
+ ])
+ return env
+ }
+ it('counts the running and waiting jobs, in all and on macOS, of runs in progress or queued', async () => {
+ const { app } = busy()
+ expect(await app.ciLoad(repo)).toEqual({ running: 2, queued: 5, macosRunning: 1, macosQueued: 2 })
+ })
+ it('reads with a token that only reads workflow runs, for that repository alone, revoked at once', async () => {
+ const { app, github } = busy()
+ await app.ciLoad(repo)
+ const minted = github.calls.filter(c => c.path.endsWith('/access_tokens'))
+ expect(minted).toHaveLength(1)
+ expect(minted[0]!.body).toEqual({ repositories: ['app'], permissions: ACTIONS_READ_PERMISSIONS })
+ expect(ACTIONS_READ_PERMISSIONS).toEqual({ actions: 'read', metadata: 'read' })
+ expect(github.revoked).toHaveLength(1)
+ expect(github.issued.size).toBe(0)
+ })
+ it('keeps a load for its time, routes asking at once share one read, and a later route reads again', async () => {
+ const { app, github, time } = busy()
+ const [x, y] = await Promise.all([app.ciLoad(repo), app.ciLoad(repo)])
+ expect(x).toEqual(y)
+ await app.ciLoad(githubRepository('https://github.com/ACME/App')!)
+ const runReads = () => github.calls.filter(c => c.path.endsWith('/actions/runs')).length
+ expect(runReads()).toBe(2)
+ time.advance(CI_LOAD_TTL_MS)
+ github.actions.set('acme/app', [])
+ expect(await app.ciLoad(repo)).toEqual({ running: 0, queued: 0, macosRunning: 0, macosQueued: 0 })
+ expect(runReads()).toBe(4)
+ })
+ it('reads at most its limit of runs, and counts every run beyond it as one waiting job', async () => {
+ const { app, github } = busy()
+ github.actions.set('acme/app', [...Array.from({ length: 30 }, (_, i) => ({ id: i + 1, status: 'in_progress', jobs: [job('in_progress')] })),
+ ...Array.from({ length: 4 }, (_, i) => ({ id: 100 + i, status: 'queued', jobs: [job('queued', 'macos-15')] }))])
+ expect(await app.ciLoad(repo)).toEqual({ running: CI_MAX_RUNS, queued: 34 - CI_MAX_RUNS, macosRunning: 0, macosQueued: 0 })
+ expect(github.calls.filter(c => c.path.endsWith('/jobs'))).toHaveLength(CI_MAX_RUNS)
+ })
+ // Lead, 10-31: a read's GitHub calls are counted and capped.
+ it('makes at most its limit of GitHub calls in one read, from the token to its revoke', async () => {
+ const { app, github } = busy()
+ github.actions.set('acme/app', Array.from({ length: 40 }, (_, i) => ({ id: i + 1, status: i % 2 ? 'queued' : 'in_progress', jobs: [job('in_progress')] })))
+ await app.ciLoad(repo)
+ const first = github.calls.findIndex(c => c.path.endsWith('/access_tokens'))
+ const read = github.calls.slice(first)
+ expect(read.at(-1)).toMatchObject({ method: 'DELETE', path: '/installation/token' })
+ expect(read.length).toBeLessThanOrEqual(CI_MAX_CALLS)
+ // Per server process: every pod production may run, reading its full budget, stays about 5% of the installation's 5,000.
+ expect(CI_MAX_CALLS * CI_READS_PER_HOUR * SERVER_PROCESSES_MAX).toBeLessThanOrEqual(5000 * 0.05)
+ })
+ it('reads one repository at most its hourly number of times, then answers the last load for a few minutes, then none', async () => {
+ const { app, github, time } = busy()
+ for (let i = 0; i < CI_READS_PER_HOUR; i++) { await app.ciLoad(repo); time.advance(CI_LOAD_TTL_MS) }
+ const reads = () => github.calls.filter(c => c.path.endsWith('/access_tokens')).length
+ expect(reads()).toBe(CI_READS_PER_HOUR)
+ github.actions.set('acme/app', [])
+ // Spent: the last load read, while it is recent, and no call to GitHub.
+ expect(await app.ciLoad(repo)).toMatchObject({ running: 2 })
+ expect(reads()).toBe(CI_READS_PER_HOUR)
+ time.advance(CI_STALE_MS)
+ await expect(app.ciLoad(repo)).rejects.toMatchObject({ code: 'GITHUB_CI_BUDGET', status: 429 })
+ expect(reads()).toBe(CI_READS_PER_HOUR)
+ // An hour after the first read, reads come back.
+ time.advance(3_600_000 - CI_READS_PER_HOUR * CI_LOAD_TTL_MS - CI_STALE_MS)
+ expect(await app.ciLoad(repo)).toEqual({ running: 0, queued: 0, macosRunning: 0, macosQueued: 0 })
+ expect(reads()).toBe(CI_READS_PER_HOUR + 1)
+ })
+ it('reads the same run listed under both statuses once', async () => {
+ const { github, time } = busy()
+ github.actions.set('acme/app', [{ id: 9, status: 'in_progress', jobs: [job('in_progress')] }])
+ const fetch = github.fetch
+ let second = false
+ // A run that moved from queued to in progress between the two reads is listed by both.
+ github.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input))
+ if (url.pathname.endsWith('/actions/runs') && url.searchParams.get('status') === 'queued') return new Response(JSON.stringify({ total_count: 1, workflow_runs: [{ id: 9 }, { id: 'x' }, null] }), { status: 200 })
+ // An answer without its list or count reads as none.
+ if (url.pathname.endsWith('/actions/runs') && url.searchParams.get('status') === 'in_progress' && second) return new Response('{}', { status: 200 })
+ return fetch(input, init)
+ }) as typeof globalThis.fetch
+ const twice = fakeApp(key.privateKey, github, { now: time.now })
+ expect(await twice.ciLoad(repo)).toEqual({ running: 1, queued: 0, macosRunning: 0, macosQueued: 0 })
+ second = true
+ time.advance(CI_LOAD_TTL_MS)
+ expect(await twice.ciLoad(repo)).toEqual({ running: 1, queued: 0, macosRunning: 0, macosQueued: 0 })
+ })
+ it('a read that fails after a newer one took its place leaves the newer one cached', async () => {
+ const { github, time } = busy()
+ let failFirst: (() => void) | undefined
+ const fetch = github.fetch
+ let held = true
+ github.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
+ const url = new URL(String(input))
+ // The first read's run list waits, then GitHub fails it.
+ if (held && url.pathname.endsWith('/actions/runs') && url.searchParams.get('status') === 'in_progress') {
+ held = false
+ await new Promise<void>(resolve => { failFirst = resolve })
+ return new Response('{}', { status: 500 })
+ }
+ return fetch(input, init)
+ }) as typeof globalThis.fetch
+ const app = fakeApp(key.privateKey, github, { now: time.now })
+ const slow = app.ciLoad(repo).catch(error => error)
+ await new Promise(resolve => setTimeout(resolve, 10))
+ time.advance(CI_LOAD_TTL_MS)
+ const newer = await app.ciLoad(repo)
+ failFirst!()
+ expect(await slow).toMatchObject({ code: 'GITHUB_UNAVAILABLE' })
+ await new Promise(resolve => setTimeout(resolve, 0))
+ // The newer read is still the cached one: asking again reads nothing from GitHub.
+ const tokens = github.calls.filter(c => c.path.endsWith('/access_tokens')).length
+ expect(await app.ciLoad(repo)).toEqual(newer)
+ expect(github.calls.filter(c => c.path.endsWith('/access_tokens')).length).toBe(tokens)
+ })
+ it('is null where the app is not installed, minting nothing', async () => {
+ const { app, github } = setup()
+ expect(await app.ciLoad(repo)).toBeNull()
+ expect(github.calls.some(c => c.path.endsWith('/access_tokens'))).toBe(false)
+ })
+ it('says GitHub could not say, still revokes the token, and keeps no failed read', async () => {
+ for (const fault of ['actionsStatus', 'jobsStatus'] as const) {
+ const { app, github } = busy()
+ github.control[fault] = 500
+ await expect(app.ciLoad(repo)).rejects.toMatchObject({ code: 'GITHUB_UNAVAILABLE', status: 502 })
+ expect(github.revoked).toHaveLength(1)
+ github.control[fault] = 200
+ expect(await app.ciLoad(repo)).toMatchObject({ running: 2 })
+ }
+ })
+ it('a token GitHub would not revoke is said without the token, and the counts still come back', async () => {
+ const { app, github } = busy()
+ github.control.revokeStatus = 500
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ expect(await app.ciLoad(repo)).toMatchObject({ running: 2 })
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls[0]![0])).not.toContain('ghs_')
+ } finally { warn.mockRestore() }
+ })
+ it('leaves the expired loads of many repositories behind', async () => {
+ const { app, github, time } = busy()
+ for (let i = 0; i < 199; i++) await app.ciLoad(githubRepository(`https://github.com/acme/r${i}`)!)
+ // Past the hour too, so their read counts go as well.
+ time.advance(3_600_000)
+ await app.ciLoad(repo)
+ github.installed.set('acme/fresh', 78)
+ expect(await app.ciLoad(githubRepository('https://github.com/acme/fresh')!)).toEqual({ running: 0, queued: 0, macosRunning: 0, macosQueued: 0 })
+ // The fresh one stays beside the new one; the 199 expired ones are gone.
+ expect([...(app as unknown as { ciLoads: Map<string, unknown> }).ciLoads.keys()]).toEqual(['acme/app', 'acme/fresh'])
+ expect([...(app as unknown as { ciReads: Map<string, unknown> }).ciReads.keys()]).toEqual(['acme/app', 'acme/fresh'])
+ })
+})
diff --git a/backend/src/github/app.ts b/backend/src/github/app.ts
index d922e9000..1f6353148 100644
--- a/backend/src/github/app.ts
+++ b/backend/src/github/app.ts
@@ -16,7 +16,11 @@ export const TOKEN_PERMISSIONS = { contents: 'write', pull_requests: 'write', ch
export const PREPARE_PERMISSIONS = { contents: 'read', metadata: 'read' } as const
/** What the Swarm's tidying reads before it archives a finished group: whether its pull requests are merged or closed. */
export const PULL_READ_PERMISSIONS = { pull_requests: 'read', metadata: 'read' } as const
+/** What the route's read of running CI jobs may do: read workflow runs and their jobs, nothing more. */
+export const ACTIONS_READ_PERMISSIONS = { actions: 'read', metadata: 'read' } as const
export type TokenPermissions = Readonly<Record<string, 'read' | 'write'>>
+/** Jobs running and waiting on a repository's GitHub Actions, in all and on macOS runners: counts only. */
+export interface CiLoad { running: number; queued: number; macosRunning: number; macosQueued: number }
/** A refusal with the code clients act on; `details` adds fields beside it, such as the install link. */
export class GitHubAppError extends Error {
@@ -74,6 +78,22 @@ const NOT_INSTALLED_TTL_MS = 60_000
const REFRESH_MS = 15_000
const BRANCH_TTL_MS = 10 * 60_000
const REQUEST_TIMEOUT_MS = 10_000
+/** How long a CI load is kept: routes come minutes apart, and a job takes minutes. */
+export const CI_LOAD_TTL_MS = 30_000
+/** The most GitHub calls one CI load makes: the token, the two run lists, the jobs of at most [CI_MAX_RUNS] runs, and the
+ * revoke (Lead, 10-31: a read's calls are counted and capped). The installation lookup is kept ten minutes apart. */
+export const CI_MAX_CALLS = 10
+/** The most runs whose jobs are read in one CI load; a run beyond it counts as one waiting job, on no particular runner. */
+export const CI_MAX_RUNS = CI_MAX_CALLS - 4
+/** The most CI loads one server process reads for one repository in an hour: past it, the last load is answered while it is
+ * at most [CI_STALE_MS] old, and after that none, which the route says as "not checked". The count, like the 30 s cache, is
+ * per server process, and production runs 2 to 8 pods (security review 2 of #2428): the worst case is 8 × 3 = 24 reads and,
+ * with [CI_MAX_CALLS], 240 calls an hour per repository, about 5% of an installation's 5,000. */
+export const CI_READS_PER_HOUR = 3
+/** The most server processes production runs (its autoscaler's maximum), for the worst case above. */
+export const SERVER_PROCESSES_MAX = 8
+export const CI_STALE_MS = 5 * 60_000
+const CI_WAITING = new Set(['queued', 'waiting', 'requested', 'pending'])
const IDENTITY_RETRY_MS = 10 * 60_000
/** A git author and committer. */
@@ -98,6 +118,10 @@ export class GitHubApp {
/** 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 }>()
private readonly shownNames = new Map<string, { name: string; until: number }>()
+ /** Each repository's CI load while fresh, or being read ([ciLoad]), by its name in lower case; per server process. */
+ private readonly ciLoads = new Map<string, { value: Promise<CiLoad | null>; until: number }>()
+ /** Each repository's CI reads in the last hour, and its last load read, for [CI_READS_PER_HOUR]. */
+ private readonly ciReads = new Map<string, { at: number[]; last: { load: CiLoad | null; at: number } | null }>()
/** When each repository's "not installed" was last forgotten on request ([forget]). */
private readonly forgotten = new Map<string, number>()
@@ -318,6 +342,72 @@ export class GitHubApp {
throw new GitHubAppError('GITHUB_UNAVAILABLE', `GitHub did not revoke the token (HTTP ${answer.status}).`, 502)
}
+ /** The jobs running and waiting on [repository]'s GitHub Actions (Scholes's goals, piece 5: work that starts heavy CI waits
+ * for the account's limit), or null when the app is not installed there. Read with a token that can only read workflow
+ * runs, revoked as soon as the counts are in; the token, run names and branches never leave this method. Kept
+ * [CI_LOAD_TTL_MS], and routes asking at once share one read; a failed read is not kept. Throws [GitHubAppError] when
+ * GitHub cannot say. */
+ async ciLoad(repository: GitHubRepository): Promise<CiLoad | null> {
+ const key = repository.fullName.toLowerCase(), now = this.now()
+ const known = this.ciLoads.get(key)
+ if (known && known.until > now) return known.value
+ // Kept per repository a Swarm routes for; the expired ones go once there are many.
+ if (this.ciLoads.size >= 200) for (const [k, v] of this.ciLoads) if (v.until <= now) this.ciLoads.delete(k)
+ if (this.ciReads.size >= 200) for (const [k, v] of this.ciReads) if (!v.at.some(t => now - t < 3_600_000)) this.ciReads.delete(k)
+ const reads = this.ciReads.get(key) ?? { at: [], last: null }
+ reads.at = reads.at.filter(t => now - t < 3_600_000)
+ this.ciReads.set(key, reads)
+ if (reads.at.length >= CI_READS_PER_HOUR) {
+ if (reads.last && now - reads.last.at <= CI_STALE_MS) return reads.last.load
+ throw new GitHubAppError('GITHUB_CI_BUDGET', `This hour's CI reads for ${repository.fullName} are spent.`, 429)
+ }
+ reads.at.push(now)
+ const value = this.readCiLoad(repository)
+ this.ciLoads.set(key, { value, until: now + CI_LOAD_TTL_MS })
+ // A failed read leaves the cache only if it is still this read's: one that fails late never drops a newer read's entry.
+ value.then(load => { reads.last = { load, at: now } }, () => { if (this.ciLoads.get(key)?.value === value) this.ciLoads.delete(key) })
+ return value
+ }
+
+ private async readCiLoad(repository: GitHubRepository): Promise<CiLoad | null> {
+ const resolved = await this.resolve(repository)
+ if (!resolved) return null
+ const { token } = await this.createToken(resolved.installation, resolved.repository, ACTIONS_READ_PERMISSIONS)
+ const auth = `Bearer ${token}`, runs = `/repos/${resolved.repository.owner}/${resolved.repository.name}/actions/runs`
+ const read = (path: string) => this.call('GET', path, auth)
+ const unavailable = () => new GitHubAppError('GITHUB_UNAVAILABLE', `GitHub did not say what runs on ${resolved.repository.fullName}.`, 502)
+ const listOf = (body: unknown, field: string) => {
+ const items = (body as Record<string, unknown>)[field]
+ return Array.isArray(items) ? items.filter((i): i is Record<string, unknown> => !!i && typeof i === 'object') : []
+ }
+ try {
+ const pages = await Promise.all(['in_progress', 'queued'].map(async status => {
+ const answer = await read(`${runs}?status=${status}&per_page=${CI_MAX_RUNS}`)
+ if (answer.status !== 200) throw unavailable()
+ const listed = listOf(answer.body, 'workflow_runs'), total = (answer.body as Record<string, unknown>).total_count
+ return { ids: listed.map(r => r.id).filter((id): id is number => Number.isSafeInteger(id)),
+ more: Math.max(0, (Number.isSafeInteger(total) ? total as number : 0) - listed.length) }
+ }))
+ const ids = [...new Set(pages.flatMap(p => p.ids))]
+ const counted = ids.slice(0, CI_MAX_RUNS)
+ const load: CiLoad = { running: 0, queued: ids.length - counted.length + pages.reduce((n, p) => n + p.more, 0), macosRunning: 0, macosQueued: 0 }
+ for (const jobs of await Promise.all(counted.map(async id => {
+ const answer = await read(`${runs}/${id}/jobs?filter=latest&per_page=100`)
+ if (answer.status !== 200) throw unavailable()
+ return listOf(answer.body, 'jobs')
+ }))) {
+ for (const job of jobs) {
+ const mac = Array.isArray(job.labels) && job.labels.some(l => typeof l === 'string' && /macos/i.test(l))
+ if (job.status === 'in_progress') { load.running++; if (mac) load.macosRunning++ }
+ else if (CI_WAITING.has(String(job.status))) { load.queued++; if (mac) load.macosQueued++ }
+ }
+ }
+ return load
+ } finally {
+ await this.revoke(token).catch(() => { console.warn(`[github] a CI read's token for ${resolved.repository.fullName} was not revoked; it expires within the hour`) })
+ }
+ }
+
/** Whether pull request [number] is open, merged or closed (GET /repos/{owner}/{repo}/pulls/{number}); null when GitHub
* cannot say, which a caller must read as possibly open. */
async pullRequestState(repository: GitHubRepository, number: number, token: string): Promise<'open' | 'merged' | 'closed' | null> {
diff --git a/backend/src/github/ciLoad.test.ts b/backend/src/github/ciLoad.test.ts
new file mode 100644
index 000000000..7ca43773d
--- /dev/null
+++ b/backend/src/github/ciLoad.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it, vi } from 'vitest'
+import { GitHubAppError, type CiLoad } from './app.js'
+import { projectCiLoad } from './ciLoad.js'
+
+const load: CiLoad = { running: 3, queued: 1, macosRunning: 1, macosQueued: 0 }
+const app = (answer: () => Promise<CiLoad | null>) => ({ ciLoad: vi.fn(answer) })
+const yes = async () => true
+
+describe('a project\'s CI load', () => {
+ it('reads the counts for a GitHub repository approved for the project', async () => {
+ const reader = app(async () => load)
+ expect(await projectCiLoad(reader, '[email protected]:Acme/App.git', yes)).toEqual({ state: 'read', load })
+ expect(reader.ciLoad).toHaveBeenCalledWith(expect.objectContaining({ fullName: 'Acme/App' }))
+ })
+ it('reads nothing without an app, an address, a GitHub repository or the project\'s approval', async () => {
+ const reader = app(async () => load)
+ expect(await projectCiLoad(null, 'https://github.com/acme/app', yes)).toEqual({ state: 'unavailable' })
+ expect(await projectCiLoad(reader, null, yes)).toEqual({ state: 'no-repository' })
+ expect(await projectCiLoad(reader, 'https://gitlab.com/acme/app', yes)).toEqual({ state: 'not-github' })
+ const approved = vi.fn(async () => false)
+ expect(await projectCiLoad(reader, 'https://github.com/Acme/App', approved)).toEqual({ state: 'not-approved' })
+ expect(approved).toHaveBeenCalledWith('acme/app')
+ expect(reader.ciLoad).not.toHaveBeenCalled()
+ })
+ it('says not installed, and unknown when GitHub cannot say, never a load of zero; wrong app credentials are the server\'s', async () => {
+ expect(await projectCiLoad(app(async () => null), 'https://github.com/acme/app', yes)).toEqual({ state: 'not-installed' })
+ expect(await projectCiLoad(app(async () => { throw new GitHubAppError('GITHUB_UNAVAILABLE', 'x', 502) }), 'https://github.com/acme/app', yes)).toEqual({ state: 'unknown' })
+ expect(await projectCiLoad(app(async () => { throw new Error('socket') }), 'https://github.com/acme/app', yes)).toEqual({ state: 'unknown' })
+ await expect(projectCiLoad(app(async () => { throw new GitHubAppError('GITHUB_APP_MISCONFIGURED', 'x', 503) }), 'https://github.com/acme/app', yes))
+ .rejects.toMatchObject({ code: 'GITHUB_APP_MISCONFIGURED' })
+ })
+})
diff --git a/backend/src/github/ciLoad.ts b/backend/src/github/ciLoad.ts
new file mode 100644
index 000000000..ccf197078
--- /dev/null
+++ b/backend/src/github/ciLoad.ts
@@ -0,0 +1,31 @@
+/**
+ * The jobs running and waiting on a Swarm project's GitHub Actions, for the route (Scholes's goals, piece 5: work that starts
+ * heavy CI waits while the account is at its limit of 20 running jobs, 5 on macOS). Counts only: never a run's name, branch,
+ * actor or the token it was read with. Read through the Harness GitHub App, never a person's login, and only for a repository
+ * approved for the project wherever approval is asked, as a token for it would be (github/projectAccess.ts).
+ */
+import { GitHubAppError, type CiLoad, type GitHubApp } from './app.js'
+import { githubRepository } from './repository.js'
+
+export type ProjectCiLoad =
+ | { state: 'read'; load: CiLoad }
+ | { state: 'unavailable' | 'no-repository' | 'not-github' | 'not-installed' | 'not-approved' | 'unknown' }
+
+/** [app]: this server's GitHub App, null when it has none. [approved]: whether the repository is approved for this project. */
+export async function projectCiLoad(app: Pick<GitHubApp, 'ciLoad'> | null, repositoryUrl: string | null,
+ approved: (repository: string) => Promise<boolean>): Promise<ProjectCiLoad> {
+ if (!app) return { state: 'unavailable' }
+ if (!repositoryUrl) return { state: 'no-repository' }
+ const repository = githubRepository(repositoryUrl)
+ if (!repository) return { state: 'not-github' }
+ // Not approved reads nothing at all, so a project naming a repository it may not use learns nothing of it.
+ if (!await approved(repository.fullName.toLowerCase())) return { state: 'not-approved' }
+ try {
+ const load = await app.ciLoad(repository)
+ return load ? { state: 'read', load } : { state: 'not-installed' }
+ } catch (error) {
+ // Wrong app credentials are the server's to fix and say so; GitHub not answering is unknown, never a load of zero.
+ if (error instanceof GitHubAppError && error.code === 'GITHUB_APP_MISCONFIGURED') throw error
+ return { state: 'unknown' }
+ }
+}
diff --git a/backend/src/github/fakeGitHub.ts b/backend/src/github/fakeGitHub.ts
index 137648abb..fe67dbe6c 100644
--- a/backend/src/github/fakeGitHub.ts
+++ b/backend/src/github/fakeGitHub.ts
@@ -24,11 +24,15 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
const protection = new Map<string, { rules?: unknown[]; protected?: boolean; branch?: string; fail?: boolean }>()
/** Pull requests by `owner/name#number`, lower case: GitHub's state and when it was merged. */
const pulls = new Map<string, { state: 'open' | 'closed'; merged_at: string | null }>()
+ /** Workflow runs by `owner/name`, lower case: each run's status and its jobs' statuses and runner labels. */
+ const actions = new Map<string, Array<{ id: number; status: string; jobs: Array<{ status: string; labels: string[] }> }>>()
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, botId: 4242 as number | null }
+ const control = { revokeStatus: 204, tokenStatus: 201 as number, tokenMessage: '', down: false, botId: 4242 as number | null, actionsStatus: 200, jobsStatus: 200 }
+ /** Each token's permissions, as it was minted. */
+ const permissions = new Map<string, unknown>()
const json = (status: number, body?: unknown) => new Response(body === undefined ? null : JSON.stringify(body), { status })
const jwtValid = (auth: string) => {
const jwt = auth.replace(/^Bearer /, '')
@@ -70,6 +74,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
if (control.tokenStatus !== 201) return json(control.tokenStatus, { message: control.tokenMessage })
const token = `ghs_fixture_${++minted}`
issued.add(token)
+ permissions.set(token, (body as { permissions: unknown }).permissions)
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') {
@@ -88,6 +93,18 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
const branch = known.branch ?? 'main'
// 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 })
+ const runs = actions.get(`${repoPath[1]}/${repoPath[2]}`.toLowerCase()) ?? []
+ if (repoPath[3] === '/actions/runs') {
+ if (control.actionsStatus !== 200) return json(control.actionsStatus, { message: 'Server Error' })
+ const matching = runs.filter(r => r.status === url.searchParams.get('status'))
+ return json(200, { total_count: matching.length, workflow_runs: matching.slice(0, Number(url.searchParams.get('per_page') ?? 30)).map(r => ({ id: r.id, status: r.status, name: `run ${r.id}`, head_branch: 'secret-branch' })) })
+ }
+ const jobs = /^\/actions\/runs\/(\d+)\/jobs$/.exec(repoPath[3] ?? '')
+ if (jobs) {
+ if (control.jobsStatus !== 200) return json(control.jobsStatus, { message: 'Server Error' })
+ const run = runs.find(r => r.id === Number(jobs[1]))
+ return run ? json(200, { total_count: run.jobs.length, jobs: run.jobs.map((j, i) => ({ id: i, name: `job ${i}`, ...j })) }) : json(404, { message: 'Not Found' })
+ }
const pull = /^\/pulls\/(\d+)$/.exec(repoPath[3] ?? '')
if (pull) {
const known = pulls.get(`${repoPath[1]}/${repoPath[2]}#${pull[1]}`.toLowerCase())
@@ -98,7 +115,7 @@ export function fakeGitHub(options: { publicKey: KeyObject; appId: string; now?:
}
return json(404, { message: 'Not Found' })
}) as typeof globalThis.fetch
- return { fetch, calls, installed, owners, renamed, protection, pulls, revoked, issued, control }
+ return { fetch, calls, installed, owners, renamed, protection, pulls, revoked, issued, control, actions, permissions }
}
/** A configured app talking to [github]. */
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 04345d1f6..f34694a58 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -18,6 +18,7 @@ import { joinSwarmSchema, previewJoinSchema, saveSharingSchema } from '../superT
import { holdReason } from '../superTabs/holdReason.js'
import { GitHubAppError } from '../github/app.js'
import { projectGitHubAccess } from '../github/projectAccess.js'
+import { projectCiLoad } from '../github/ciLoad.js'
import { githubSignIn, PrismaApprovals, readState, signState, stateSecret, type Approvals, type GitHubSignIn } from '../github/approvals.js'
import type { GitHubRepository } from '../github/repository.js'
import { githubRepository } from '../github/repository.js'
@@ -133,6 +134,7 @@ export const NOT_AVAILABLE_ROUTES: ReadonlySet<string> = new Set([
'GET /api/super-tabs/:tabId/conversations/:conversationId/messages', 'GET /api/super-tabs/:tabId/conversations/:conversationId/catch-up',
'POST /api/super-tabs/:tabId/conversations/:conversationId/read',
'GET /api/super-tabs/:tabId/projects/:projectId/github', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve',
+ 'GET /api/super-tabs/:tabId/projects/:projectId/ci-load',
'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', 'GET /api/super-tabs/:tabId/route-decisions/:decisionId',
'GET /api/super-tabs/:tabId/machines/:machineId/removal',
'POST /api/super-tabs/:tabId/attachments', 'POST /api/super-tabs/:tabId/avatars',
@@ -312,6 +314,17 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
you: repository => approvals.reader(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository, req.user!.sub) },
req.query.refresh === '1')
}))
+ // The jobs running and waiting on a project's GitHub Actions, for the route (github/ciLoad.ts): counts only, read through
+ // the app, by a person or an agent who may read the project. Only for a repository someone who can push to it approved for
+ // the project, in every Swarm, also where tokens ask no approval: otherwise a project could name another organisation's
+ // repository that has the app, read its counts and spend that installation's requests (security review 1 of #2428).
+ app.get<{ Params: z.infer<typeof projectParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/projects/:projectId/ci-load',
+ { preHandler: [validateParams(projectParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, async () => {
+ const project = await store.ciRepository(req.user!, req.params.tabId, req.params.projectId, req.query.asAgentId)
+ return projectCiLoad(github?.app ?? null, project.repositoryUrl,
+ repository => approvals.approved(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository))
+ }))
// Approving a project's repository: the person signs in to GitHub through the app (or installs it, which signs them in
// too), and GitHub sends them back to /api/github/callback with the state signed here for them, this project and scope.
app.post<{ Params: z.infer<typeof projectParams>; Body: z.infer<typeof approveBody> }>('/api/super-tabs/:tabId/projects/:projectId/github/approve',
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index d960b3456..6e62e27eb 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -2477,6 +2477,19 @@ export class SuperTabStore {
})
}
+ /** A project's repository for the route's read of its running CI jobs (github/ciLoad.ts), by a person or an agent of the
+ * project, as any read of the project: another project's, or one this reader cannot see, is unavailable alike. A Buddy
+ * routes nothing, so it reads none. */
+ async ciRepository(user: AuthUser, tabId: string, projectId: string, asAgentId?: string): Promise<{ repositoryUrl: string | null }> {
+ return transaction(this.db, async tx => {
+ const { state } = await this.load(tx, user, tabId)
+ const actor = await this.actor(tx, user, state, asAgentId)
+ const project = readProject(state, actor, projectId)
+ if (actor.kind === 'agent' && state.agents.some(a => a.id === actor.agentId && isBuddy(a))) fail('NOT_FOUND', 'This project is unavailable.', 404)
+ return { repositoryUrl: project.repository?.repositoryUrl ?? null }
+ })
+ }
+
/** A project's name as [userId] may see it now, for the page GitHub sends them back to after approving its repository
* (routes/superTabs.ts). Read here, not carried in the sign-in's state, which GitHub's addresses expose (privacy review of
* #1980). Null when they may not see it any more, or it is gone. */
diff --git a/cli/src/superTabs/machineFit.spec.ts b/cli/src/superTabs/machineFit.spec.ts
index 0161085e7..0c19f0858 100644
--- a/cli/src/superTabs/machineFit.spec.ts
+++ b/cli/src/superTabs/machineFit.spec.ts
@@ -1,7 +1,7 @@
// cli/src/superTabs/machineFit.spec.ts
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import { START_REQUIREMENTS, startRequirements } from './capacity.js'
-import { CI_LIMIT, CI_RETRY_MINUTES, CI_UNCHECKED, ciHold, floorOf, heavyNeed, MACHINE_FIT_MAKER, machineFit, PLACED_RECENT_MS, placedHeavyWork,
+import { CI_LIMIT, CI_READ_MS, CI_RETRY_MINUTES, CI_UNCHECKED, ciHold, ciLoadOf, floorOf, heavyNeed, MACHINE_FIT_MAKER, machineFit, PLACED_RECENT_MS, placedHeavyWork,
type CiLoad } from './machineFit.js'
import { choose, parseAssessment, type Assessment, type Catalog, type Probe } from './route.js'
import { ROUTE_PLUGIN_MAKERS, type PluginInput } from './routePlugins.js'
@@ -172,11 +172,11 @@ describe('the CI jobs limit', () => {
const load = (running: number, queued = 0, macosRunning = 0, macosQueued = 0): CiLoad => ({ running, queued, macosRunning, macosQueued })
it('holds work that starts CI past the account\'s limit, counting queued jobs, with a time to route it again', () => {
expect(ciHold({ ci: { jobs: 4, macos: 0 } }, load(16))).toBeNull()
- expect(ciHold({ ci: { jobs: 4, macos: 0 } }, load(16, 1))).toBe(`CI is at the account's limit: 17 of ${CI_LIMIT.jobs} jobs running or queued, 0 of ${CI_LIMIT.macos} on macOS, `
- + `and this task starts 4 more. Route it again in ${CI_RETRY_MINUTES} minutes.`)
+ expect(ciHold({ ci: { jobs: 4, macos: 0 } }, load(16, 1))).toBe(`This repository's CI jobs are at the account's limit: 17 running or queued against the account's limit of ${CI_LIMIT.jobs}, `
+ + `0 on macOS against ${CI_LIMIT.macos}, and this task starts 4 more. Route it again in ${CI_RETRY_MINUTES} minutes.`)
// The macOS runners have their own, smaller limit.
expect(ciHold({ ci: { jobs: 2, macos: 2 } }, load(4, 0, 3, 0))).toBeNull()
- expect(ciHold({ ci: { jobs: 2, macos: 2 } }, load(4, 0, 3, 1))).toContain('4 of 5 on macOS, and this task starts 2 more (2 on macOS).')
+ expect(ciHold({ ci: { jobs: 2, macos: 2 } }, load(4, 0, 3, 1))).toContain('4 on macOS against 5, and this task starts 2 more (2 on macOS).')
})
it('never holds work that declares no CI of its own, nor when the load is unknown', () => {
expect(ciHold({}, load(40, 10, 5, 5))).toBeNull()
@@ -191,7 +191,7 @@ describe('the CI jobs limit', () => {
})
it('a task that starts CI is told when the limit could not be checked, beside its fit', () => {
expect(ok(route([on('a', { memory: 16, disk: 100 })], a({ ci: { jobs: 1, macos: 0 } }))).shown[0]!.notes).toEqual([`Machine fit: ${CI_UNCHECKED}`])
- expect(ok(route([on('a', { memory: 5, disk: 100 })], a({ ci: { jobs: 1, macos: 0 }, heavy: ['build'] }))).shown[0]!.notes[0]).toMatch(/rank first\. The running CI jobs could not be read/)
+ expect(ok(route([on('a', { memory: 5, disk: 100 })], a({ ci: { jobs: 1, macos: 0 }, heavy: ['build'] }))).shown[0]!.notes[0]).toMatch(/rank first\. This repository's running CI jobs could not be read/)
})
})
@@ -213,8 +213,43 @@ describe('its maker', () => {
// A tab read with no machines or starts reads as nothing placed.
const bare = (await MACHINE_FIT_MAKER.make(input(a({ heavy: ['build'] }), {})))!
expect(ok(choose([on('mac', { memory: 12, disk: 100 })], catalog, a({ heavy: ['build'] }), now, [], [], [], [bare])).shown).toHaveLength(1)
- // The CI load is not read yet, so a task that starts CI hears that.
+ // A CI read the server does not answer leaves the limit unchecked, which a task that starts CI hears.
const ci = (await MACHINE_FIT_MAKER.make(input(a({ ci: { jobs: 1, macos: 0 } }), {})))!
expect(ok(choose([on('mac', { memory: 12, disk: 100 })], catalog, a({ ci: { jobs: 1, macos: 0 } }), now, [], [], [], [ci])).shown[0]!.notes).toEqual([`Machine fit: ${CI_UNCHECKED}`])
})
})
+
+describe('the server\'s CI read', () => {
+ const read = (load: Record<string, unknown>) => ({ ok: true, value: { state: 'read', load } })
+ const full = { running: 19, queued: 0, macosRunning: 0, macosQueued: 0 }
+ it('takes the counts of a read, and nothing from any other answer', () => {
+ expect(ciLoadOf(read(full))).toEqual(full)
+ for (const answer of [null, {}, { ok: false, value: { state: 'read', load: full } }, { ok: true, value: { state: 'not-approved' } },
+ read({ ...full, running: -1 }), read({ ...full, queued: 1.5 }), read({ ...full, macosQueued: '1' }), { error: 'NOT_FOUND' }]) expect(ciLoadOf(answer)).toBeNull()
+ })
+ it('the maker asks for the group\'s own project, and a task past the limit is held; under it, or unread, it is not', async () => {
+ const asked: Array<Record<string, unknown>> = []
+ const make = async (answer: () => Promise<Record<string, unknown>>, conversationId = 'g2') => MACHINE_FIT_MAKER.make({ conversationId, assessment: a({ ci: { jobs: 2, macos: 0 } }),
+ read: { tab: { state: { conversations: [{ id: 'g2', projectId: 'p7' }] } } }, catalog, history: Promise.resolve(null),
+ request: async payload => { asked.push(payload); return answer() } })
+ const judge = async (plugin: Awaited<ReturnType<typeof make>>) => choose([on('m', { memory: 16, disk: 100 })], catalog, a({ ci: { jobs: 2, macos: 0 } }), NOW, [], [], [], [plugin!])
+ expect(await judge(await make(async () => read(full)))).toMatchObject({ error: 'NO_CANDIDATE', excluded: [{ reason: `Machine fit: ${ciHold({ ci: { jobs: 2, macos: 0 } }, full)}` }] })
+ expect(asked).toEqual([{ action: 'ciLoad', projectId: 'p7' }])
+ expect(ok(await judge(await make(async () => read({ ...full, running: 3 })))).shown[0]!.notes).toEqual([])
+ expect(ok(await judge(await make(async () => ({ ok: true, value: { state: 'unknown' } })))).shown[0]!.notes).toEqual([`Machine fit: ${CI_UNCHECKED}`])
+ expect(ok(await judge(await make(async () => { throw new Error('socket') }))).shown[0]!.notes).toEqual([`Machine fit: ${CI_UNCHECKED}`])
+ // A group the read does not list is the Lead's project's.
+ await make(async () => read(full), 'gone')
+ expect(asked.at(-1)).toEqual({ action: 'ciLoad', projectId: 'lead' })
+ })
+ it('a read slower than its limit leaves the CI unchecked rather than the plug-in skipped', async () => {
+ vi.useFakeTimers()
+ try {
+ const made = MACHINE_FIT_MAKER.make({ conversationId: 'g', assessment: a({ ci: { jobs: 1, macos: 0 } }), read: {}, catalog, history: Promise.resolve(null),
+ request: () => new Promise(() => {}) })
+ await vi.advanceTimersByTimeAsync(CI_READ_MS)
+ const plugin = (await made)!
+ expect(ok(choose([on('m', { memory: 16, disk: 100 })], catalog, a({ ci: { jobs: 1, macos: 0 } }), NOW, [], [], [], [plugin])).shown[0]!.notes).toEqual([`Machine fit: ${CI_UNCHECKED}`])
+ } finally { vi.useRealTimers() }
+ })
+})
diff --git a/cli/src/superTabs/machineFit.ts b/cli/src/superTabs/machineFit.ts
index 2feab2e62..826698a94 100644
--- a/cli/src/superTabs/machineFit.ts
+++ b/cli/src/superTabs/machineFit.ts
@@ -10,7 +10,7 @@
* Everything it needs is read before the route ([placedHeavyWork], the CI reading); the plug-in itself is pure. */
import type { Adjustment, HeavyWork, Needs, Probe, RoutePlugin } from './route.js'
import type { PluginMaker } from './routePlugins.js'
-import { object } from './wire.js'
+import { object, within } from './wire.js'
type Json = Record<string, unknown>
const GB = 1e9
@@ -81,11 +81,11 @@ export function ciHold(needs: Pick<Needs, 'ci'>, load: CiLoad | null): string |
const over = busy + needs.ci.jobs > CI_LIMIT.jobs || mac + needs.ci.macos > CI_LIMIT.macos
if (!over) return null
const starts = `${needs.ci.jobs} more${needs.ci.macos ? ` (${needs.ci.macos} on macOS)` : ''}`
- return `CI is at the account's limit: ${busy} of ${CI_LIMIT.jobs} jobs running or queued, ${mac} of ${CI_LIMIT.macos} on macOS, and this task `
- + `starts ${starts}. Route it again in ${CI_RETRY_MINUTES} minutes.`
+ return `${CI_HOLD_OPENING}: ${busy} running or queued against the account's limit of ${CI_LIMIT.jobs}, ${mac} on macOS against ${CI_LIMIT.macos}, `
+ + `and this task starts ${starts}. Route it again in ${CI_RETRY_MINUTES} minutes.`
}
/** Said when a task starts CI and the load could not be read. */
-export const CI_UNCHECKED = `The running CI jobs could not be read, so the account's limit of ${CI_LIMIT.jobs} jobs (${CI_LIMIT.macos} on macOS) was not checked.`
+export const CI_UNCHECKED = `This repository's running CI jobs could not be read, so the account's limit of ${CI_LIMIT.jobs} jobs (${CI_LIMIT.macos} on macOS) was not checked.`
/** A need in whole gigabytes, as the needs are set. */
const gb = (n: number) => `${Math.round(n / GB)} GB`
@@ -129,17 +129,34 @@ function fitOf(candidate: Pick<Probe, 'load'>, needs: Needs, held: Placed | unde
return busy ? { cost: BUSY_CPU_COST, reason: `Its CPU is busy; it has what ${need.words} needs.` } : null
}
-/** Piece 5's maker (routePlugins.ts): the heavy work placed on each machine, read off the route's own Super Tab read. Nothing
- * to say for a task with no heavy work and no CI. The CI load is not read yet: a task that starts CI is told so. */
+/** How long the maker waits for the server's CI read: under the makers' own limit (routePlugins.ts MAKER_TIMEOUT_MS), so a
+ * slow GitHub leaves the CI unchecked, said on the candidates, rather than the whole plug-in skipped. */
+export const CI_READ_MS = 2000
+/** The opening of a hold's reason ([ciHold]): the route answers a task held by it as waiting, with when to route it again. */
+/** It names this repository's jobs: the limit is the account's, but the server reads one repository (Lead, 10-31). */
+export const CI_HOLD_OPENING = "This repository's CI jobs are at the account's limit"
+const count = (v: unknown): v is number => Number.isSafeInteger(v) && (v as number) >= 0
+/** The counts in the server's CI read (backend github/ciLoad.ts), or null for any other answer: not installed, not approved,
+ * unknown, an older server without the read, or a failed request. */
+export function ciLoadOf(answer: unknown): CiLoad | null {
+ const value = object(object(answer).value), load = object(value.load)
+ if (object(answer).ok !== true || value.state !== 'read' || ![load.running, load.queued, load.macosRunning, load.macosQueued].every(count)) return null
+ return { running: load.running as number, queued: load.queued as number, macosRunning: load.macosRunning as number, macosQueued: load.macosQueued as number }
+}
+
+/** Piece 5's maker (routePlugins.ts): the heavy work placed on each machine, read off the route's own Super Tab read, and for
+ * a task that starts CI the project's running jobs, read by the server. Nothing to say for a task with neither. */
export const MACHINE_FIT_MAKER: PluginMaker = {
name: 'Machine fit',
- async make({ read, assessment }) {
+ async make({ read, assessment, request, conversationId }) {
if (!heavyNeed(assessment.needs) && !assessment.needs.ci) return null
const state = object(object(read.tab).state)
- const machines = Array.isArray(state.machines) ? state.machines.map(object) : []
- const macOf = new Map(machines.filter(m => typeof m.hostMachineId === 'string').map(m => [String(m.machineId), String(m.hostMachineId)]))
+ const list = (v: unknown) => Array.isArray(v) ? v.map(object) : []
+ const macOf = new Map(list(state.machines).filter(m => typeof m.hostMachineId === 'string').map(m => [String(m.machineId), String(m.hostMachineId)]))
const hostOf = (id: string) => macOf.get(id) ?? id
- const starts = Array.isArray(state.starts) ? state.starts.map(object) : []
- return machineFit({ placed: placedHeavyWork(starts, Date.now(), hostOf), hostOf, ci: null })
+ // The group's own project, which the server checks this agent may read; the Lead's project when the group names none.
+ const projectId = String(list(state.conversations).find(c => c.id === conversationId)?.projectId ?? 'lead')
+ const ci = assessment.needs.ci ? ciLoadOf(await within(request({ action: 'ciLoad', projectId }), CI_READ_MS)) : null
+ return machineFit({ placed: placedHeavyWork(list(state.starts), Date.now(), hostOf), hostOf, ci })
},
}
diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.ts
index 9b36c5d33..d67562ff3 100644
--- a/cli/src/superTabs/routeCommand.spec.ts
+++ b/cli/src/superTabs/routeCommand.spec.ts
@@ -206,6 +206,19 @@ describe('routeTask', () => {
const blind = await routeTask(heavy({}), scoped(), where as never, reading({ memoryTotalBytes: 16e9, memoryUsedBytes: 2e9, cpuPercent: 10 }))
expect(blind).toMatchObject({ pick: { kind: 'member', notes: expect.arrayContaining(['Machine fit: Free disk unknown here; a heavy build: it needs 8 GB memory and 30 GB disk free.']) } })
})
+ it('answers work that starts heavy CI while the account is at its limit as waiting, with when to route it again', async () => {
+ const base = scoped()
+ const s = vi.fn(async (payload: Record<string, any>) => payload.action === 'ciLoad'
+ ? { ok: true, value: { state: 'read', load: { running: 15, queued: 4, macosRunning: 1, macosQueued: 0 } } } : base(payload)) as typeof base
+ const held = await routeTask({ ...input, assessment: { ...input.assessment, needs: { ci: { jobs: 2, macos: 0 } } } }, s, where as never, opener())
+ expect(held).toMatchObject({ error: 'NO_CANDIDATE', waiting: true, retryAfterMinutes: 10,
+ detail: 'This repository\'s CI jobs are at the account\'s limit: 19 running or queued against the account\'s limit of 20, 1 on macOS against 5, and this task starts 2 more. Route it again in 10 minutes.' })
+ expect(s.mock.calls.some(c => c[0].action === 'command')).toBe(false)
+ // Any other task routes as before, without asking for the CI.
+ const plain = await routeTask(input, s, where as never, opener())
+ expect(plain).toMatchObject({ ok: true })
+ expect(plain).not.toHaveProperty('waiting')
+ })
// Lead, 10-31: a routed heavy start is never refused on the machine the route offered.
it('ranks a machine between half the need and the need later, and the start there is admitted and counts as heavy', async () => {
const between = { memoryTotalBytes: 16e9, memoryUsedBytes: 10e9, cpuPercent: 10, projectDiskFreeBytes: 100e9 }
diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.ts
index 013a029bf..7fafc65be 100644
--- a/cli/src/superTabs/routeCommand.ts
+++ b/cli/src/superTabs/routeCommand.ts
@@ -9,6 +9,7 @@ import { inspectCapacity, type ScopedRequest } from './start.js'
import { ENDED_WORK, object, within } from './wire.js'
import { accountOf, API_BUILDERS, catalogFrom, catalogRow, choose, decide, gridStrength, parseAssessment, quotaOf2, recordOf, repoMatch, repositoryKey, type Assessment, type Catalog, type CatalogModel, type RecordShape, type Commitment, type Excluded, type HeldModel, type MemberFrame, type Probe, type TaskFolder } from './route.js'
import { makePlugins, ROUTE_PLUGIN_MAKERS, type PluginMaker } from './routePlugins.js'
+import { CI_HOLD_OPENING, CI_RETRY_MINUTES, MACHINE_FIT_MAKER } from './machineFit.js'
import { stat } from 'node:fs/promises'
import { describeScmProject } from '../scm/scmProjects.js'
@@ -351,7 +352,12 @@ export async function routeTask(input: { tabId: string; conversationId: string;
const skipped = [...made.warnings, ...(choice.warnings ?? [])]
choice.excluded.push(...offline, ...(catalog.models.length ? [] : [{ title: 'New agents', reason: CATALOG_UNREADABLE }]))
// The task stays in the agent's queue rather than going where it cannot be done.
- if ('error' in choice) return { ...choice, ...(skipped.length ? { warnings: skipped } : {}), leftOut: leftOut(choice.excluded, []), ...required.machines || required.devices.length ? { waiting: true, detail: WAITING } : {} }
+ // Work that starts heavy CI while the account is at its limit waits, and says when to route it again (machineFit.ts), so the
+ // Lead's route queue retries it without a person.
+ const ciHeld = 'error' in choice ? choice.excluded.find(e => e.reason.startsWith(`${MACHINE_FIT_MAKER.name}: ${CI_HOLD_OPENING}`)) : undefined
+ if ('error' in choice) return { ...choice, ...(skipped.length ? { warnings: skipped } : {}), leftOut: leftOut(choice.excluded, []),
+ ...required.machines || required.devices.length ? { waiting: true, detail: WAITING } : {},
+ ...ciHeld ? { waiting: true, retryAfterMinutes: CI_RETRY_MINUTES, detail: ciHeld.reason.slice(MACHINE_FIT_MAKER.name.length + 2) } : {} }
const verdict = decide(choice)
const operationId = `route-${newId()}`
const record = (shape: RecordShape) => scoped({ action: 'command', operationId,
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 0650dfcba..86c806cf6 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -615,6 +615,11 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
const attempts = Array.isArray(tried) ? tried.slice(0, 50).map(object).map(a => ({ id: a.id, agentId: a.agentId, status: a.status, result: typeof a.result === 'string' ? a.result.slice(0, 500) : null, createdAt: a.createdAt ?? null })) : null
return { ok: true, value: { ...(decisions ? { decisions } : { decisionsUnreadable: true }), ...(attempts ? { attempts } : { attemptsUnreadable: true }) } }
}
+ // The jobs running and waiting on a project's GitHub Actions, counts only, for the route's machine-fit plug-in
+ // (machineFit.ts; backend github/ciLoad.ts). The server reads it through its GitHub App, never this machine's login.
+ if (payload.action === 'ciLoad' && identifier(payload.projectId)) {
+ return { ok: true, value: await backend(core, 'GET', `${path}/projects/${encodeURIComponent(String(payload.projectId))}/ci-load?${identity}`) }
+ }
// What routed attempts cost and how they went over a period (backend superTabs/costs/read.ts).
if (payload.action === 'costs' && Number.isInteger(payload.days) && Number(payload.days) >= 1 && Number(payload.days) <= 90) {
return { ok: true, value: await backend(core, 'GET', `${path}/costs?days=${payload.days}&${identity}`) }
diff --git a/cli/src/superTabs/serviceReads.spec.ts b/cli/src/superTabs/serviceReads.spec.ts
index 97ccfed61..05ad8d9a8 100644
--- a/cli/src/superTabs/serviceReads.spec.ts
+++ b/cli/src/superTabs/serviceReads.spec.ts
@@ -247,6 +247,14 @@ describe('instructions', () => {
})
describe('costs', () => {
+ it('reads a project\'s CI load as that agent, and nothing for a malformed project id', async () => {
+ const load = { state: 'read', load: { running: 3, queued: 0, macosRunning: 1, macosQueued: 0 } }
+ const s = swarm((_method, path) => path.startsWith(`/api/super-tabs/${T}/projects/lead/ci-load?`) ? ok(load) : undefined)
+ expect(await s.ask({ action: 'ciLoad', tabId: T, agentId: FIXTURE.leadId, projectId: 'lead' }, owner)).toEqual({ ok: true, value: load })
+ expect(s.call).toHaveBeenCalledWith('GET', `/api/super-tabs/${T}/projects/lead/ci-load?asAgentId=${FIXTURE.leadId}`, undefined)
+ expect(await s.ask({ action: 'ciLoad', tabId: T, agentId: FIXTURE.leadId, projectId: '../x' }, owner)).not.toHaveProperty('ok', true)
+ expect(s.call.mock.calls.filter(c => String(c[1]).includes('ci-load'))).toHaveLength(1)
+ })
it('reads the cost summary of the period as that agent, and lists it in help', async () => {
const summary = { days: 30, rows: [], totals: { attempts: 0 }, prices: [] }
const s = swarm((_method, path) => path.startsWith(`/api/super-tabs/${T}/costs?`) ? ok(summary) : undefined)