teqo/scripts/lib/agent-pool-github.mjs
Francisco Solla 680ff56754 feat(agent-pool): orquestrador de pool de workers Cursor Cloud (fases A–D) (#65)
* feat(agent-pool): fundacao read-only do orquestrador (fase A)

- docs/plans/agent-pool-orchestrator.md: plano completo (14 secoes)
- buildClaimQueue extraido de agent-claim para agent-github (comportamento identico, pinado)
- agent-pool-eligibility: isAutonomousClaimable puro e fail-closed + buildPoolQueue
- agent-pool-state: parsePoolConfig, marcadores pool-worker, classifyPoolClaim, spawn plan, auto-stop
- agent-pool-github: leitura de repo variables (degrada nao-estrito), claims/PRs/migration-lock
- pnpm agent:pool -- status|tick --dry-run (inspecao local; live chega na fase B)
- 34 specs unit novos (992/992 verde); lint/tsc/knip/cycles/format verdes

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>

* feat(agent-pool): spawn remoto de workers via Cursor API (fase B)

- agent-pool-cursor: client fino da Cloud Agents API v1 (fetch injetavel; CursorApiError com status/body)
- agent-pool-models: resolvePoolModel contra /v1/models (id/alias, sufixo -fast -> param, fallback composer-2.5 com warn)
- agent-pool-prompt: contrato do worker (claim pre-feito, pula passo 1; PR base stage + Closes #N; promote proibido)
- claim coordenado no tick: lock otimista + flip + marcador; agentId idempotente bc-<uuid>; 409 recupera; rollback em falha de spawn
- agent:pool workflow --action start|stop|pause|resume|tick|status (variables POOL_*); doctor; wrappers gh workflow run
- .github/workflows/agent-pool.yml (dispatch-only; schedule/triggers na fase C)
- 19 specs novos (1011/1011); lint/tsc/knip/cycles/format verdes

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>

* feat(agent-pool): ciclo de vida do supervisor (fase C)

- derivePoolClaims com status real dos runs (getCursorRun), heal de spawn via agentId deterministico, cancel de duplicatas
- reconcilePoolClaims: falha terminal -> comentario + blocked + archive; merge concluido -> slot livre + archive
- auto-stop real: fila drenada + zero ativos -> POOL_ENABLED=false (exclusoes migration-busy nao desligam)
- job summary markdown (GITHUB_STEP_SUMMARY) — superficie remota de status
- workflow: schedule */10min + pull_request closed em stage (ativam na default branch apos promote)
- 2 specs novos (1013/1013); lint/tsc/knip/cycles/format verdes

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>

* docs(agent-pool): runbook operacional e adendo do spike (fase D)

- skill agent-pool: runbook humano (pre-requisitos, start/stop/pause remoto, ciclo de vida, triage, smoke de aceite)
- AGENT-OPS: linha na tabela de comandos + secao Agent pool (canal, secrets, ativacao pos-promote)
- CHANGELOG-AGENTS: entrada curta da entrega
- engineering-audit: pause/resume do pool no protocolo do modo solitario
- plano secao 14.1: evidencias do spike 2026-07-30 (environment repo-file confirmado, id bc-<uuid>, degradacao 403, pendencias do primeiro run com CURSOR_API_KEY)

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>

* fix(test): teardown flake no homeSearchUi.unit.spec (dono do CI)

O scheduler do react (prefetch do next/link) podia disparar apos o teardown
do jsdom e derrubar o job unit com 'window is not defined' (run 30587862940).
afterEach(cleanup) — padrao dos 14 specs irmaos.

Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Francisco Solla <fsolla@users.noreply.github.com>
2026-07-30 20:08:34 -03:00

150 lines
5.1 KiB
JavaScript

/**
* gh-CLI IO wrappers for the agent pool supervisor. Pure logic lives in
* agent-pool-state.mjs / agent-pool-eligibility.mjs; the Cursor REST client in
* agent-pool-cursor.mjs. Everything here shells the authenticated `gh` — no
* GitHub token of its own, same contract as agent-github.mjs.
*/
import { randomUUID } from 'node:crypto'
import { gh, ghJson, labelNames, setLabels } from './agent-github.mjs'
import { formatPoolEvent } from './agent-pool-state.mjs'
/**
* Repo variables (Settings → Variables) as a plain map. One `gh api` call;
* pool values are scalars, so the `name=value` encoding splits on the first
* `=` only. Requires `actions: read` (read) / `actions: write` (write).
*
* Non-strict mode degrades to `{}` + a warn: inspection commands (status,
* dry-run tick) still work for a token without Actions permissions, and the
* resulting config is the disabled default — the fail-closed direction. The
* live tick stays strict: if the supervisor cannot read its own config it
* must stop loudly, never guess.
*/
export const readPoolVariables = ({ strict = true } = {}) => {
let out
try {
out = gh([
'api',
'repos/{owner}/{repo}/actions/variables',
'--paginate',
'--jq',
'.variables[] | .name + "=" + .value',
])
} catch (error) {
if (strict) throw error
console.error(
'[agent:pool] aviso: repo variables ilegíveis (token sem actions:read?) — usando defaults (pool desligado).',
)
return {}
}
const vars = {}
for (const line of out.split('\n')) {
if (!line) continue
const eq = line.indexOf('=')
vars[line.slice(0, eq)] = line.slice(eq + 1)
}
return vars
}
export const listInProgressIssues = () =>
ghJson([
'issue',
'list',
'--state',
'open',
'--label',
'in-progress',
'--limit',
'200',
'--json',
'number,title,body,state,labels,createdAt',
])
export const listIssueComments = (number) =>
ghJson(['issue', 'view', String(number), '--json', 'comments']).comments ?? []
export const listOpenPrs = () =>
ghJson(['pr', 'list', '--state', 'open', '--limit', '100', '--json', 'number,body,url'])
/** The open PR whose body closes this issue (`Closes #N` / `Fixes #N`), if any. */
export const prClosingIssue = (prs, issueNumber) =>
prs.find((pr) => new RegExp(`(?:closes|fixes) #${issueNumber}\\b`, 'i').test(pr.body ?? '')) ??
null
// Same path predicate as the ci-pr.yml migration-lock job (single source of
// truth for "schema-touching PR").
const SCHEMA_PR_PATH = /^(src\/migrations\/|src\/payload-types\.ts$|payload-types\.ts$)/
export const countOpenSchemaPrs = () =>
ghJson(['pr', 'list', '--state', 'open', '--limit', '100', '--json', 'number,files']).filter(
(pr) => (pr.files ?? []).some((file) => SCHEMA_PR_PATH.test(file.path)),
).length
/** Create or update one repo variable (POST first time, PATCH after). */
export const writePoolVariable = (name, value) => {
const existing = readPoolVariables()
if (Object.hasOwn(existing, name)) {
gh([
'api',
'-X',
'PATCH',
`repos/{owner}/{repo}/actions/variables/${name}`,
'-f',
`value=${value}`,
])
} else {
gh([
'api',
'-X',
'POST',
'repos/{owner}/{repo}/actions/variables',
'-f',
`name=${name}`,
'-f',
`value=${value}`,
])
}
}
/** Comment on an issue with human text plus the machine-readable pool marker. */
export const commentPoolEvent = (number, event, text) => {
gh(['issue', 'comment', String(number), '--body', `${text} ${formatPoolEvent(event)}`])
}
/**
* Coordinated claim (plan §4): the supervisor is the single allocator. Re-read
* the issue (same optimistic lock as agent:claim), flip ready→in-progress and
* leave the claim marker with the worker UUID the spawn will reuse as the
* idempotent `agentId`. Returns `{ ok, workerUuid }` or `{ ok: false }` when
* the race was lost — the tick just moves to the next queue entry.
*/
export const claimIssueForPool = (number, { tickIso }) => {
const fresh = ghJson(['issue', 'view', String(number), '--json', 'number,state,labels'])
const labels = labelNames(fresh)
if (fresh.state !== 'OPEN' || !labels.includes('ready') || labels.includes('in-progress')) {
return { ok: false, reason: 'lost-race' }
}
setLabels(number, { add: ['in-progress'], remove: ['ready'] })
const workerUuid = randomUUID()
commentPoolEvent(
number,
{ event: 'claim', tick: tickIso, worker: workerUuid },
`Claimed pelo pool-supervisor (tick ${tickIso}) — worker em spawn.`,
)
return { ok: true, workerUuid }
}
/** Undo the claim when the spawn itself failed — the issue goes back to ready. */
export const rollbackPoolClaim = (number, note) => {
setLabels(number, { add: ['ready'], remove: ['in-progress'] })
gh(['issue', 'comment', String(number), '--body', `Pool-supervisor: claim revertido — ${note}`])
}
/**
* Failure path: a terminally failed worker's issue leaves the claim queue for
* human triage. The pool only ever blocks issues IT claimed (claim marker).
*/
export const blockIssueFromPool = (number) => {
setLabels(number, { add: ['blocked'], remove: ['in-progress'] })
}