teqo/scripts/lib/agent-pool-eligibility.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

80 lines
3.2 KiB
JavaScript

/**
* Autonomous-claim eligibility for the agent pool
* (docs/plans/agent-pool-orchestrator.md §3). Pure — no IO.
*
* The pool consumes the SAME queue as `agent:claim` (buildClaimQueue) and then
* applies stricter, fail-closed predicates: anything that needs a human
* (`requirements-changed`, `needs:consent`, `blocked`) is out, migration-touching
* issues yield to the migration-lock while a schema PR is open, and an issue
* the pool already failed twice stays out (circuit breaker — enforced per
* candidate at claim time, where the comments are already being read).
*/
import { labelNames } from './agent-github.mjs'
export const POOL_CIRCUIT_BREAKER_FAILURES = 2
const EXCLUDED_STATE_LABELS = ['in-progress', 'blocked', 'done', 'in-prod']
const HUMAN_GATE_LABELS = ['requirements-changed', 'needs:consent']
/**
* @param {ReturnType<import('./agent-github.mjs').buildClaimQueue>[number]} entry queue entry from buildClaimQueue
* @param {Object} [options]
* @param {boolean} [options.migrationBusy]
* @param {number} [options.poolFailureCount]
* @returns {{ ok: true } | { ok: false, reason: string }}
*/
export const isAutonomousClaimable = (
entry,
{ migrationBusy = false, poolFailureCount = 0 } = {},
) => {
const labels = labelNames(entry.issue)
if (entry.issue.state !== 'OPEN') return { ok: false, reason: 'not-open' }
if (!labels.includes('ready')) return { ok: false, reason: 'not-ready' }
if (EXCLUDED_STATE_LABELS.some((label) => labels.includes(label))) {
return { ok: false, reason: 'state-label' }
}
if (HUMAN_GATE_LABELS.some((label) => labels.includes(label))) {
return { ok: false, reason: 'needs-human' }
}
if ((entry.blockedBy ?? []).length > 0) return { ok: false, reason: 'blocked-by-deps' }
if (poolFailureCount >= POOL_CIRCUIT_BREAKER_FAILURES) {
return { ok: false, reason: 'circuit-breaker' }
}
const serializes = Array.isArray(entry.meta?.serializes) ? entry.meta.serializes : []
const touchesSchema = labels.includes('needs:migration') || serializes.includes('migrations')
if (touchesSchema && migrationBusy) return { ok: false, reason: 'migration-busy' }
return { ok: true }
}
/** Plan link is a preference, never a blocker (v1) — status surfaces it as a warn. */
export const issueHasPlanLink = (issue) => /docs\/plans\//.test(issue?.body ?? '')
/**
* Splits the claim queue into pool-eligible entries (order preserved — the
* claim order IS the spawn order) and exclusions with their reason.
*
* @param {ReturnType<import('./agent-github.mjs').buildClaimQueue>} claimQueue
* @param {Object} [options]
* @param {boolean} [options.migrationBusy]
* @param {Map<number, number>} [options.failureCountsByIssue]
*/
export const buildPoolQueue = (
claimQueue,
{ migrationBusy = false, failureCountsByIssue = new Map() } = {},
) => {
const eligible = []
const excluded = []
for (const entry of claimQueue) {
const verdict = isAutonomousClaimable(entry, {
migrationBusy,
poolFailureCount: failureCountsByIssue.get(entry.issue.number) ?? 0,
})
if (verdict.ok) {
eligible.push({ entry, hasPlan: issueHasPlanLink(entry.issue) })
} else {
excluded.push({ entry, reason: verdict.reason })
}
}
return { eligible, excluded }
}