diff --git a/.github/workflows/agent-pr-ready-automerge.yml b/.github/workflows/agent-pr-ready-automerge.yml index 5a4ad1a..94199d0 100644 --- a/.github/workflows/agent-pr-ready-automerge.yml +++ b/.github/workflows/agent-pr-ready-automerge.yml @@ -11,8 +11,9 @@ # mergeia quando todo required check (o check-run `checks` do ci.yml) está # verde e o PR é mergeável. Nada a pollar, nada a confiar localmente. # -# Permissions: contents + pull-requests write — o suficiente para a mutation -# GraphQL com o GITHUB_TOKEN built-in. +# Permissions mínimas: a mutation de auto-merge exige só `pull-requests: +# write` — `contents: read` (default) basta para o checkout; nada de token de +# push para o código do branch de uma PR (mesmo em repo com colaboradores). name: PR Ready + auto-merge @@ -22,7 +23,7 @@ on: branches: [main] permissions: - contents: write + contents: read pull-requests: write jobs: diff --git a/docs/ops/deploy-github-runbook.md b/docs/ops/deploy-github-runbook.md index 726047c..45c23f9 100644 --- a/docs/ops/deploy-github-runbook.md +++ b/docs/ops/deploy-github-runbook.md @@ -47,6 +47,10 @@ workstation não roda mais a suíte de CI. + `bun run build` lá — precisa existir no PATH do runner; `BUN` env sobrepõe o default). - Instalar o `actions-runner` com labels `self-hosted, homeserver`. + - **Não ligar** "Send workflows to a self-hosted runner" para fork PRs + (default OFF no GitHub): o repo é público e o `deploy` executa código na + máquina de produção — se esse setting ligar algum dia, um fork PR pode + virar RCE no homeserver. - Não bloqueia PRs: o deploy é manual e só existe depois do runner. 6. **(f) Push → PR → CI → merge → flips.** O PR do próprio OPS1 valida o fluxo diff --git a/scripts/configure-branch-protection.mjs b/scripts/configure-branch-protection.mjs index dbd94c6..96dcece 100644 --- a/scripts/configure-branch-protection.mjs +++ b/scripts/configure-branch-protection.mjs @@ -13,7 +13,11 @@ */ import { createApi } from './lib/github-api.mjs' -import { DESIRED_RULE, planBranchProtectionRule } from './lib/github-branch-protection.mjs' +import { + DESIRED_RULE, + planBranchProtectionRule, + ruleMatches, +} from './lib/github-branch-protection.mjs' import { loadProjectEnv } from './lib/load-project-env.mjs' loadProjectEnv() @@ -37,7 +41,7 @@ const dryRun = flags.dryRun === true const branch = 'main' const api = createApi({}) -const repo = process.env.GITHUB_REPOSITORY ?? 'fsolla/iara-pwa' +const repo = process.env.GITHUB_REPOSITORY const existing = await api.getBranchProtection(branch) const { action } = planBranchProtectionRule(existing) @@ -66,12 +70,12 @@ if (dryRun) { await api.updateBranchProtection(DESIRED_RULE, branch) const after = await api.getBranchProtection(branch) -if (!after) { +if (!after || !ruleMatches(after)) { console.error( - `[configure:branch-protection] FALHOU: PUT respondeu mas a regra "${branch}" não aparece no servidor.`, + `[configure:branch-protection] FALHOU: PUT respondeu mas a regra "${branch}" no servidor não bate com a desejada — ${JSON.stringify(after)}`, ) process.exit(1) } console.log( `[configure:branch-protection] done — regra verificada no servidor: ${JSON.stringify(after)}`, -) \ No newline at end of file +) diff --git a/scripts/deploy-iara.sh b/scripts/deploy-iara.sh index 332d3f6..45b2eb1 100644 --- a/scripts/deploy-iara.sh +++ b/scripts/deploy-iara.sh @@ -32,11 +32,14 @@ BUN_BIN="${BUN:-$(command -v bun || echo "$HOME/.bun/bin/bun")}" say() { printf '[deploy] %s\n' "$*"; } fatal() { - trap - ERR say "FAILED: $*" >&2 exit 1 } +# --- bun no homeserver (passo manual do cutover) ------------------------- + +[ -x "$BUN_BIN" ] || fatal "bun não encontrado em $BUN_BIN — instale no homeserver (ou defina BUN)" + # --- guards ------------------------------------------------------------ main_head="$(git ls-remote "$IARA_REPO_URL" refs/heads/main | awk '{print $1}')" @@ -46,7 +49,9 @@ if [ "$main_head" != "$SHA" ]; then fi exec 9>"$DEPLOY_LOCK" -flock -w 3600 9 || fatal "another deploy holds $DEPLOY_LOCK" +# ~20min de espera pelo lock: o job tem timeout de 30min — esperar mais que +# isso seria descartado pelo GitHub de qualquer forma. +flock -w 1200 9 || fatal "another deploy holds $DEPLOY_LOCK" main_head="$(git ls-remote "$IARA_REPO_URL" refs/heads/main | awk '{print $1}')" if [ "$main_head" != "$SHA" ]; then @@ -80,6 +85,10 @@ else git -C "$WORKSPACE_DIR" fetch -q origin fi +# Workspace limpo e no SHA exato: um deploy anterior falhado (ou residuo de +# build) não contamina o build — `bun install` recria o que precisar. +git -C "$WORKSPACE_DIR" reset -q --hard "$SHA" +git -C "$WORKSPACE_DIR" clean -q -fdx git -C "$WORKSPACE_DIR" checkout -q --detach "$SHA" say "workspace at $SHA" @@ -94,4 +103,4 @@ mkdir -p "$SERVE_DIR" rsync -a --delete "$WORKSPACE_DIR/dist/" "$SERVE_DIR/" printf '%s\n' "$SHA" > "$MARKER_FILE" -say "deploy concluido em $(date -u +%H:%M:%SZ) — $SERVE_DIR runs $SHA" \ No newline at end of file +say "deploy concluido em $(date -u +%H:%M:%SZ) — $SERVE_DIR runs $SHA" diff --git a/scripts/github-pr-automerge.mjs b/scripts/github-pr-automerge.mjs index 7bf14d1..1f1324b 100644 --- a/scripts/github-pr-automerge.mjs +++ b/scripts/github-pr-automerge.mjs @@ -60,4 +60,4 @@ try { } catch (error) { console.error(`[github-pr-automerge] falhou: ${error instanceof Error ? error.message : error}`) process.exit(1) -} \ No newline at end of file +} diff --git a/scripts/lib/github-api.mjs b/scripts/lib/github-api.mjs index 5f5e754..60711e3 100644 --- a/scripts/lib/github-api.mjs +++ b/scripts/lib/github-api.mjs @@ -8,11 +8,11 @@ * Repository: `GITHUB_REPOSITORY` (set by `loadProjectEnv` from * `.forgejo/worktree.env` locally; by the runner in Actions), else the default. * - * Retry (same policy as forgejo-api): transient failures retry with - * exponential backoff — a fetch that rejects (network-level, DNS/TCP/reset) - * retries on ANY method; a 5xx retries on GET only, so read polls survive - * while write endpoints keep failing closed instead of risking duplicated - * side effects. 4xx never retries. Defaults: 3 retries, base 300 ms ×2, + * Retry (exponential backoff): um fetch que REJEITA a nível de rede + * (DNS/TCP/reset — provavelmente nunca chegou ao servidor) retrya em + * QUALQUER método; um 5xx retrya só em GET — resposta 5xx significa que o + * servidor respondeu, então escritas falham fechado ali (sem duplicar efeito + * colateral). 4xx nunca retrya. Defaults: 3 retries, base 300 ms ×2, * ±20% jitter. * * Shapes are normalized to the contract the CLI scripts use: `pr.state` ∈ @@ -81,7 +81,7 @@ export const createApi = ({ `[github-api] ${method} ${path} falhou (tentativa ${attempt}/${attemptCount}): ${reason} — retry em ${delay}ms`, ) - const headers = (withJson = true) => { + const headers = () => { const authToken = token ?? process.env.GITHUB_TOKEN if (!authToken) { throw new Error('Sem token para a API do GitHub — defina GITHUB_TOKEN.') @@ -89,7 +89,7 @@ export const createApi = ({ return { Authorization: `Bearer ${authToken}`, 'User-Agent': USER_AGENT, - ...(withJson ? { 'Content-Type': 'application/json' } : {}), + 'Content-Type': 'application/json', } } @@ -232,10 +232,15 @@ export const createApi = ({ /** * GET /repos/{owner}/{repo}/branches/{branch}/protection — normalized for * drift comparison; `null` when the branch has no protection rule (404). + * Cobre todos os campos do DESIRED_RULE (ruleMatches os compara), então o + * drift repair é completo: reviews/restrictions sem exigência viram + * `null` (o GitHub pode ecoar um objeto com count 0), booleanos são + * desembrulhados de `{ enabled }`. */ getBranchProtection: async (branch = 'main') => { const rule = await request(`/repos/${owner}/${name}/branches/${branch}/protection`) if (!rule) return null + const reviews = rule.required_pull_request_reviews return { required_status_checks: rule.required_status_checks ? { @@ -244,7 +249,13 @@ export const createApi = ({ } : null, enforce_admins: Boolean(rule.enforce_admins?.enabled ?? rule.enforce_admins), - required_pull_request_reviews: rule.required_pull_request_reviews ?? null, + required_pull_request_reviews: + !reviews || (reviews.required_approving_review_count ?? 0) === 0 ? null : reviews, + restrictions: rule.restrictions ?? null, + required_linear_history: Boolean(rule.required_linear_history), + allow_force_pushes: Boolean(rule.allow_force_pushes?.enabled ?? rule.allow_force_pushes), + allow_deletions: Boolean(rule.allow_deletions?.enabled ?? rule.allow_deletions), + block_creations: Boolean(rule.block_creations), } }, @@ -257,11 +268,7 @@ export const createApi = ({ method: 'PUT', body: payload, }), - - /** PATCH /repos/{owner}/{repo} — repo settings (e.g. allow_auto_merge). */ - updateRepository: (payload) => - request(`/repos/${owner}/${name}`, { method: 'PATCH', body: payload }), } return api -} \ No newline at end of file +} diff --git a/scripts/lib/github-branch-protection.mjs b/scripts/lib/github-branch-protection.mjs index b3cfc74..bb913ef 100644 --- a/scripts/lib/github-branch-protection.mjs +++ b/scripts/lib/github-branch-protection.mjs @@ -44,14 +44,22 @@ const sameStrings = (have, want) => /** * True when the existing rule (from `getBranchProtection`, already - * normalized) matches the desired rule on every compared field — array - * fields as sets. + * normalized) matches the desired rule on EVERY field of DESIRED_RULE — + * array fields as sets. Cobre o contrato inteiro: reviews/restrictions sem + * exigência e os booleanos (linear history, force pushes, deletions, + * creations) — drift em qualquer um deles é reparado. */ export const ruleMatches = (existing) => { if (!existing) return false const wantStatus = DESIRED_RULE.required_status_checks if (existing.enforce_admins !== DESIRED_RULE.enforce_admins) return false - if (existing.required_pull_request_reviews !== null) return false + if (existing.required_pull_request_reviews !== DESIRED_RULE.required_pull_request_reviews) + return false + if (existing.restrictions !== DESIRED_RULE.restrictions) return false + if (existing.required_linear_history !== DESIRED_RULE.required_linear_history) return false + if (existing.allow_force_pushes !== DESIRED_RULE.allow_force_pushes) return false + if (existing.allow_deletions !== DESIRED_RULE.allow_deletions) return false + if (existing.block_creations !== DESIRED_RULE.block_creations) return false const haveStatus = existing.required_status_checks if (!haveStatus) return false if (haveStatus.strict !== wantStatus.strict) return false @@ -71,4 +79,4 @@ export const ruleMatches = (existing) => { export const planBranchProtectionRule = (existing) => { if (ruleMatches(existing)) return { action: 'noop' } return { action: existing ? 'update' : 'create' } -} \ No newline at end of file +} diff --git a/scripts/lib/github-pr-flow.mjs b/scripts/lib/github-pr-flow.mjs index 951a38a..ffaf509 100644 --- a/scripts/lib/github-pr-flow.mjs +++ b/scripts/lib/github-pr-flow.mjs @@ -25,4 +25,4 @@ export const decideAutomergeAction = (pr) => { if (pr.base?.ref !== 'main') return { action: 'skip', reason: 'base-nao-main' } if (pr.draft) return { action: 'skip', reason: 'draft-veto' } return { action: 'enable-auto-merge', reason: 'ready' } -} \ No newline at end of file +} diff --git a/scripts/pr.mjs b/scripts/pr.mjs index 61cb346..bcb75ec 100644 --- a/scripts/pr.mjs +++ b/scripts/pr.mjs @@ -65,9 +65,14 @@ const pr = await api.createPullRequest({ head, base: 'main', title, body }) console.log(`[pr] PR #${pr.number} criado (Ready): ${pr.htmlUrl}`) if (flags.automerge) { - console.log(`[pr] armando auto-merge do PR #${pr.number} (rebase)…`) - await api.enableAutoMerge(pr.nodeId) - console.log( - `[pr] auto-merge armado — o GitHub mergea quando o required check "checks" ficar verde`, - ) -} \ No newline at end of file + try { + console.log(`[pr] armando auto-merge do PR #${pr.number} (rebase)…`) + await api.enableAutoMerge(pr.nodeId) + console.log( + `[pr] auto-merge armado — o GitHub mergea quando o required check "checks" ficar verde`, + ) + } catch (error) { + console.error(`[pr] falhou ao armar auto-merge: ${error instanceof Error ? error.message : error}`) + process.exit(1) + } +} diff --git a/tests/unit/github-api.test.ts b/tests/unit/github-api.test.ts index 5c7077d..5602631 100644 --- a/tests/unit/github-api.test.ts +++ b/tests/unit/github-api.test.ts @@ -52,6 +52,27 @@ describe("github-api", () => { }); }); + test("getPullRequest: estado fechado (caixa baixa, como o GitHub envia) e merged_at", async () => { + const api = apiWith(() => + ok({ + number: 8, + title: "t", + body: "", + state: "closed", + draft: false, + merged_at: "2026-08-20T00:00:00Z", + node_id: "PR_2", + head: { ref: "b", sha: "s" }, + base: { ref: "main" }, + }), + ); + + const pr = await api.getPullRequest(8); + + expect(pr?.state).toBe("CLOSED"); + expect(pr?.merged).toBe(true); + }); + test("getPullRequest 404 → null", async () => { const api = apiWith(() => ok({ message: "Not Found" }, 404)); expect(await api.getPullRequest(999)).toBeNull(); @@ -71,14 +92,23 @@ describe("github-api", () => { expect(pr).toEqual({ number: 7, title: "t", htmlUrl: "https://github.com/x/7", nodeId: "PR_1" }); }); - test("getBranchProtection normaliza para drift; 404 → null", async () => { + test("getBranchProtection normaliza para drift completo (reviews count 0 → null, booleanos)", async () => { let seen = ""; const api = apiWith((url) => { seen = url; return ok({ required_status_checks: { strict: false, checks: [{ context: "checks" }] }, enforce_admins: { enabled: true }, - required_pull_request_reviews: null, + required_pull_request_reviews: { + required_approving_review_count: 0, + dismiss_stale_reviews: false, + require_code_owner_reviews: false, + }, + restrictions: null, + required_linear_history: false, + allow_force_pushes: { enabled: false }, + allow_deletions: { enabled: true }, + block_creations: false, }); }); @@ -89,6 +119,11 @@ describe("github-api", () => { required_status_checks: { strict: false, contexts: ["checks"] }, enforce_admins: true, required_pull_request_reviews: null, + restrictions: null, + required_linear_history: false, + allow_force_pushes: false, + allow_deletions: true, + block_creations: false, }); const api404 = apiWith(() => ok({}, 404)); @@ -114,3 +149,63 @@ describe("github-api", () => { await expect(api.enableAutoMerge("PR_1")).rejects.toThrow("auto-merge disabled"); }); }); + +describe("github-api retry", () => { + const retryApi = (handler: (url: string, init?: Record) => Response | never) => + createApi({ + token: "t", + repository: "fsolla/iara-pwa", + retries: 2, + backoffMs: 0, + jitter: false, + sleepImpl: async () => {}, + fetchImpl: async (url: string | URL, init?: Record) => + handler(String(url), init), + }); + + test("GET 5xx (503) retrya até sucesso", async () => { + let calls = 0; + const api = retryApi(() => { + calls += 1; + if (calls === 1) return ok({ message: "Service Unavailable" }, 503); + return ok({ + number: 7, + title: "t", + body: "", + state: "open", + draft: false, + merged_at: null, + node_id: "PR_1", + head: { ref: "b", sha: "s" }, + base: { ref: "main" }, + }); + }); + + const pr = await api.getPullRequest(7); + + expect(calls).toBe(2); + expect(pr?.number).toBe(7); + }); + + test("escrita com 5xx não retrya (fail-closed — servidor respondeu)", async () => { + let calls = 0; + const api = retryApi(() => { + calls += 1; + return ok({ message: "boom" }, 503); + }); + + await expect(api.createPullRequest({ head: "x", title: "t", body: "b" })).rejects.toThrow(); + expect(calls).toBe(1); + }); + + test("rejeição de rede retrya em qualquer método (não chegou ao servidor)", async () => { + let calls = 0; + const api = retryApi(() => { + calls += 1; + throw new Error("ECONNRESET"); + }); + + await expect(api.getPullRequest(1)).rejects.toThrow("ECONNRESET"); + expect(calls).toBe(3); + }); +}); diff --git a/tests/unit/github-branch-protection.test.ts b/tests/unit/github-branch-protection.test.ts index a6f0763..bf5760c 100644 --- a/tests/unit/github-branch-protection.test.ts +++ b/tests/unit/github-branch-protection.test.ts @@ -10,6 +10,11 @@ const compliant = () => ({ required_status_checks: { strict: false, contexts: [REQUIRED_CHECK_CONTEXT] }, enforce_admins: true, required_pull_request_reviews: null, + restrictions: null, + required_linear_history: false, + allow_force_pushes: false, + allow_deletions: false, + block_creations: false, }); describe("github-branch-protection", () => { @@ -47,12 +52,22 @@ describe("github-branch-protection", () => { ).toBe(false); }); + test("ruleMatches: drift em allow_deletions / restrictions é detectado", () => { + expect(ruleMatches({ ...compliant(), allow_deletions: true })).toBe(false); + expect( + ruleMatches({ ...compliant(), restrictions: { users: [], teams: [], apps: [] } }), + ).toBe(false); + }); + test("plan: sem regra → create; conforme → noop; drift → update", () => { expect(planBranchProtectionRule(null)).toEqual({ action: "create" }); expect(planBranchProtectionRule(compliant())).toEqual({ action: "noop" }); expect( planBranchProtectionRule({ ...compliant(), required_status_checks: { strict: false, contexts: [] } }), ).toEqual({ action: "update" }); + expect(planBranchProtectionRule({ ...compliant(), allow_force_pushes: true })).toEqual({ + action: "update", + }); }); test("DESIRED_RULE usa apenas `checks` moderno (sem `contexts` legacy)", () => {