feat(ops): promote último commit ci-stage green sem exigir head verde
agent:promote passa a escolher o SHA mais novo à frente de main com ci-stage success e usa promote/last-green quando o head de stage está vermelho, destravando o bootstrap manual para main.
This commit is contained in:
parent
e2bc366c10
commit
b533139eb2
4 changed files with 168 additions and 27 deletions
|
|
@ -27,7 +27,7 @@ stage → CI stage green → auto-promote (workflow promote-stage-to-main.yml)
|
|||
|
||||
**Done = PR mergeado em `stage` com CI verde.** Falha de CI no teu PR — infra do workflow, teste pré-existente ou regressão da feature — é tua até o merge. "Fora do escopo da feature" não é motivo para parar: corrige na mesma branch. Triagem das três classes: (a) **infra do workflow** (job mal configurado, step faltando) → fix no workflow no mesmo PR; (b) **teste pré-existente quebrado ou frágil** → repair no mesmo PR, no padrão dos specs irmãos; (c) **regressão da feature** → fix normal. Exceção de blast radius: se o fix exigir migration, access control ou Consent, para e escala com Opções — esses nunca se corrigem "de passagem". Flaky não se resolve com retry: repair, ou quarentena justificada no PR + débito registrado (`capture-review-debts`).
|
||||
|
||||
- **Só humano:** `pnpm db:refresh:stage` (refresh semanal do snapshot), editar envs Vercel/Neon, rodar `pnpm build` contra qualquer banco remoto. `pnpm agent:promote --i-am-human` permanece como override manual de emergência (mesmas verificações, sem esperar o workflow).
|
||||
- **Só humano:** `pnpm db:refresh:stage` (refresh semanal do snapshot), editar envs Vercel/Neon, rodar `pnpm build` contra qualquer banco remoto. `pnpm agent:promote --i-am-human` permanece como override manual (promove o último commit ci-stage green em `stage`, mesmo com head vermelho).
|
||||
- **Auto-promote:** `promote-stage-to-main.yml` dispara quando `ci-stage.yml` termina com sucesso. Só promove se o `headSha` do run ainda for o head de `stage` (commit mais novo ganha quando o CI enfileira). Recusa se `main` divergiu de `stage` (hotfix: merge `main` em `stage` + CI stage green de novo).
|
||||
- **Merge em stage sem estar na head:** branch protection de `stage` com `strict=false` — PR pode auto-merger com CI green mesmo que outro PR tenha entrado antes; conflito de merge continua bloqueando (rebase obrigatório). Aplicar/reparar: `pnpm configure:branch-protection`.
|
||||
- **Secret opcional:** `PROMOTE_GITHUB_TOKEN` (PAT admin do repo) se `GITHUB_TOKEN` não conseguir `gh pr merge --admin` na proteção de `main`. Settings → Actions → "Allow GitHub Actions to create and approve pull requests" também ajuda.
|
||||
|
|
@ -43,7 +43,7 @@ stage → CI stage green → auto-promote (workflow promote-stage-to-main.yml)
|
|||
| `pnpm agent:prioritize -- <issue> <P0..P3>` | Troca a label `prio:*` |
|
||||
| `pnpm agent:file-miss -- --title ...` | Issue `kind:agent-miss` → harvest em guardrail (`docs/GUARDRAILS.md`) |
|
||||
| `pnpm agent:pool -- status\|tick --dry-run\|doctor` | Inspeção local do pool de workers Cloud; start/stop/pause **remotos** via `gh workflow run agent-pool.yml -f action=…` (ver "Agent pool" abaixo) |
|
||||
| `pnpm agent:promote -- --i-am-human` | **Override manual:** PR `stage→main` + merge se CI stage green (auto-promote faz isso sozinho) |
|
||||
| `pnpm agent:promote -- --i-am-human` | **Override manual:** PR `main` ← último commit em `stage` com ci-stage green (não exige head verde; auto-promote só no head) |
|
||||
| `pnpm push [-- -u origin HEAD …]` | **Canônico:** `ensure-repo-deps` + `gate:push` + `git push --no-verify` (gate no script — não depende do Husky) |
|
||||
| `pnpm configure:branch-protection [-- --dry-run]` | Ajusta proteção de `stage` (`strict=false`) e `main` (0 reviews — auto-promote substitui o humano) |
|
||||
| `pnpm db:seed:minimal` | DB mínimo sintético (contrato: [`scripts/lib/seed-minimal-manifest.mjs`](../scripts/lib/seed-minimal-manifest.mjs), pin `tests/unit/seedMinimalManifest.unit.spec.ts`) |
|
||||
|
|
|
|||
|
|
@ -1,20 +1,28 @@
|
|||
/**
|
||||
* `pnpm agent:promote -- --i-am-human` — manual override: promote `stage` → `main`.
|
||||
*
|
||||
* Normal path: `promote-stage-to-main.yml` auto-merges when ci-stage is green.
|
||||
* Use this only when the workflow failed or you need to promote out of band.
|
||||
* Normal path: `promote-stage-to-main.yml` auto-merges when ci-stage is green on
|
||||
* the current stage head. Use this when the workflow failed or you need to promote
|
||||
* out of band — including when stage head is red but an older commit on stage
|
||||
* already passed ci-stage.
|
||||
*
|
||||
* Checks (in order):
|
||||
* 1. `main` has not diverged from `stage` (hotfix direto em main exige antes
|
||||
* merge/rebase de main em stage + CI stage green de novo).
|
||||
* 2. Latest ci-stage run on `stage` is green.
|
||||
* 3. Creates the PR stage→main if none is open, then merges (ci-stage is the
|
||||
* pre-promote gate; ci.yml on main is the post-merge safety net).
|
||||
* 1. `main` has not diverged from `stage` (hotfix direto em main exige merge
|
||||
* de main em stage antes).
|
||||
* 2. Newest commit on `origin/main..origin/stage` with a successful ci-stage run.
|
||||
* 3. PR into `main` from `stage` (head green) or `promote/last-green` (older green).
|
||||
* 4. Merge (ci-stage on the promoted SHA is the pre-promote gate; ci.yml on main
|
||||
* is the post-merge safety net).
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
|
||||
import { dieAgent, gh, ghJson, parseArgs } from './lib/agent-github.mjs'
|
||||
import {
|
||||
findLastGreenPromoteSha,
|
||||
greenCiStageHeadShas,
|
||||
PROMOTE_GREEN_BRANCH,
|
||||
} from './lib/agent-promote-target.mjs'
|
||||
|
||||
const die = dieAgent('promote')
|
||||
const { flags } = parseArgs(process.argv.slice(2), new Set())
|
||||
|
|
@ -23,7 +31,7 @@ if (flags['i-am-human'] !== true) {
|
|||
die(
|
||||
'Refused: promote override is human-only. Re-run as a human with:\n' +
|
||||
' pnpm agent:promote -- --i-am-human\n' +
|
||||
'Auto-promote runs via promote-stage-to-main.yml when ci-stage is green.',
|
||||
'Auto-promote runs via promote-stage-to-main.yml when ci-stage is green on stage head.',
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -41,8 +49,17 @@ try {
|
|||
)
|
||||
}
|
||||
|
||||
// 2. CI stage green on the stage head.
|
||||
const stageSha = git(['rev-parse', 'origin/stage'])
|
||||
const mainSha = git(['rev-parse', 'origin/main'])
|
||||
|
||||
if (stageSha === mainSha) {
|
||||
die(`main já está no head de stage (${stageSha.slice(0, 8)}) — nada a promover.`)
|
||||
}
|
||||
|
||||
const commitsAhead = git(['log', `origin/main..origin/stage`, '--format=%H'])
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
|
||||
const stageRuns = ghJson([
|
||||
'run',
|
||||
'list',
|
||||
|
|
@ -51,24 +68,49 @@ const stageRuns = ghJson([
|
|||
'--workflow',
|
||||
'ci-stage.yml',
|
||||
'--limit',
|
||||
'5',
|
||||
'100',
|
||||
'--json',
|
||||
'headSha,status,conclusion,url',
|
||||
])
|
||||
const latestStageRun = stageRuns.find((run) => run.headSha === stageSha)
|
||||
if (
|
||||
!latestStageRun ||
|
||||
latestStageRun.status !== 'completed' ||
|
||||
latestStageRun.conclusion !== 'success'
|
||||
) {
|
||||
|
||||
const promoteSha = findLastGreenPromoteSha(commitsAhead, greenCiStageHeadShas(stageRuns))
|
||||
|
||||
if (!promoteSha) {
|
||||
die(
|
||||
`CI stage não está verde no head de stage (${stageSha.slice(0, 8)}). ` +
|
||||
`Último run: ${latestStageRun ? `${latestStageRun.status}/${latestStageRun.conclusion} — ${latestStageRun.url}` : 'nenhum'}`,
|
||||
`Nenhum commit em stage à frente de main tem ci-stage verde (stage head ${stageSha.slice(0, 8)}). ` +
|
||||
'Corrija stage ou espere um run verde antes do promote.',
|
||||
)
|
||||
}
|
||||
console.log('[agent:promote] CI stage green ✓')
|
||||
|
||||
// 3. PR stage → main (create if needed).
|
||||
const promoteRun = stageRuns.find(
|
||||
(run) => run.headSha === promoteSha && run.status === 'completed' && run.conclusion === 'success',
|
||||
)
|
||||
|
||||
if (promoteSha === stageSha) {
|
||||
console.log(`[agent:promote] CI stage green no head de stage (${stageSha.slice(0, 8)}) ✓`)
|
||||
} else {
|
||||
console.log(
|
||||
`[agent:promote] stage head ${stageSha.slice(0, 8)} não está verde; ` +
|
||||
`promovendo último commit ci-stage green ${promoteSha.slice(0, 8)} ✓`,
|
||||
)
|
||||
if (promoteRun?.url) {
|
||||
console.log(`[agent:promote] run: ${promoteRun.url}`)
|
||||
}
|
||||
}
|
||||
|
||||
const prHead = promoteSha === stageSha ? 'stage' : PROMOTE_GREEN_BRANCH
|
||||
|
||||
if (prHead !== 'stage') {
|
||||
execFileSync(
|
||||
'git',
|
||||
['push', 'origin', `${promoteSha}:refs/heads/${PROMOTE_GREEN_BRANCH}`, '--force'],
|
||||
{
|
||||
stdio: 'inherit',
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// 3. PR → main (create if needed).
|
||||
let pr = ghJson([
|
||||
'pr',
|
||||
'list',
|
||||
|
|
@ -77,22 +119,48 @@ let pr = ghJson([
|
|||
'--base',
|
||||
'main',
|
||||
'--head',
|
||||
'stage',
|
||||
prHead,
|
||||
'--json',
|
||||
'number,url',
|
||||
])[0]
|
||||
|
||||
if (!pr && prHead !== 'stage') {
|
||||
const staleStagePr = ghJson([
|
||||
'pr',
|
||||
'list',
|
||||
'--state',
|
||||
'open',
|
||||
'--base',
|
||||
'main',
|
||||
'--head',
|
||||
'stage',
|
||||
'--json',
|
||||
'number,url',
|
||||
])[0]
|
||||
if (staleStagePr) {
|
||||
console.log(
|
||||
`[agent:promote] fechando PR #${staleStagePr.number} stage→main (head vermelho; promote em ${promoteSha.slice(0, 8)})`,
|
||||
)
|
||||
gh(['pr', 'close', String(staleStagePr.number)])
|
||||
}
|
||||
}
|
||||
|
||||
if (!pr) {
|
||||
const body =
|
||||
promoteSha === stageSha
|
||||
? 'Override manual via `pnpm agent:promote --i-am-human`. CI stage green no head de stage.'
|
||||
: `Override manual via \`pnpm agent:promote --i-am-human\`. Promove ci-stage green \`${promoteSha.slice(0, 8)}\` (stage head \`${stageSha.slice(0, 8)}\` não está verde).`
|
||||
const url = gh([
|
||||
'pr',
|
||||
'create',
|
||||
'--base',
|
||||
'main',
|
||||
'--head',
|
||||
'stage',
|
||||
prHead,
|
||||
'--title',
|
||||
`Promote stage → main (${new Date().toISOString().slice(0, 10)})`,
|
||||
'--body',
|
||||
'Override manual via `pnpm agent:promote --i-am-human`. CI stage green verificado antes do merge.',
|
||||
body,
|
||||
])
|
||||
pr = { number: url.split('/').pop(), url }
|
||||
console.log(`[agent:promote] created PR ${pr.url}`)
|
||||
|
|
@ -100,6 +168,8 @@ if (!pr) {
|
|||
console.log(`[agent:promote] reusing open PR ${pr.url}`)
|
||||
}
|
||||
|
||||
// 4. Merge (ci-stage was the pre-promote gate; ci.yml on main is the post-merge safety net).
|
||||
// 4. Merge (ci-stage on promoteSha was the pre-promote gate; ci.yml on main is the safety net).
|
||||
gh(['pr', 'merge', String(pr.number), '--admin', '--merge'])
|
||||
console.log(`[agent:promote] merged stage → main via PR #${pr.number}. Deploy Vercel a caminho.`)
|
||||
console.log(
|
||||
`[agent:promote] merged ${prHead} (${promoteSha.slice(0, 8)}) → main via PR #${pr.number}. Deploy Vercel a caminho.`,
|
||||
)
|
||||
|
|
|
|||
33
scripts/lib/agent-promote-target.mjs
Normal file
33
scripts/lib/agent-promote-target.mjs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
* Pure helpers for `agent-promote`: pick the newest commit on stage (ahead of main)
|
||||
* that has a successful ci-stage run — not necessarily the current stage head.
|
||||
*/
|
||||
|
||||
/** Branch used when promoting a green commit behind a red stage head. */
|
||||
export const PROMOTE_GREEN_BRANCH = 'promote/last-green'
|
||||
|
||||
/**
|
||||
* @param {string[]} commitsAhead newest-first SHAs on origin/main..origin/stage
|
||||
* @param {ReadonlySet<string>} greenShas head SHAs with ci-stage success
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function findLastGreenPromoteSha(commitsAhead, greenShas) {
|
||||
for (const sha of commitsAhead) {
|
||||
if (greenShas.has(sha)) return sha
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array<{ headSha: string; status: string; conclusion: string | null }>} stageRuns
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
export function greenCiStageHeadShas(stageRuns) {
|
||||
const green = new Set()
|
||||
for (const run of stageRuns) {
|
||||
if (run.status === 'completed' && run.conclusion === 'success') {
|
||||
green.add(run.headSha)
|
||||
}
|
||||
}
|
||||
return green
|
||||
}
|
||||
38
tests/unit/agentPromoteTarget.unit.spec.ts
Normal file
38
tests/unit/agentPromoteTarget.unit.spec.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
findLastGreenPromoteSha,
|
||||
greenCiStageHeadShas,
|
||||
} from '../../scripts/lib/agent-promote-target.mjs'
|
||||
|
||||
describe('greenCiStageHeadShas', () => {
|
||||
it('collects only completed successes', () => {
|
||||
const green = greenCiStageHeadShas([
|
||||
{ headSha: 'aaa', status: 'completed', conclusion: 'success' },
|
||||
{ headSha: 'bbb', status: 'completed', conclusion: 'failure' },
|
||||
{ headSha: 'ccc', status: 'in_progress', conclusion: null },
|
||||
])
|
||||
expect([...green]).toEqual(['aaa'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('findLastGreenPromoteSha', () => {
|
||||
it('returns the newest green commit ahead of main', () => {
|
||||
const green = new Set(['bbb', 'ddd'])
|
||||
expect(findLastGreenPromoteSha(['ccc', 'bbb', 'aaa'], green)).toBe('bbb')
|
||||
})
|
||||
|
||||
it('returns stage head when it is green', () => {
|
||||
const green = new Set(['ccc'])
|
||||
expect(findLastGreenPromoteSha(['ccc', 'bbb'], green)).toBe('ccc')
|
||||
})
|
||||
|
||||
it('returns null when nothing ahead is green', () => {
|
||||
const green = new Set(['zzz'])
|
||||
expect(findLastGreenPromoteSha(['ccc', 'bbb'], green)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when there is nothing ahead of main', () => {
|
||||
expect(findLastGreenPromoteSha([], new Set(['aaa']))).toBeNull()
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue