From 9ff783b0ffacf1ce6e7346b634825a701965c838 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:23:31 +0000 Subject: [PATCH] feat(pr-assistant): block merge when the repo has no AGENTS.md Owner rule: AGENTS.md is mandatory in every repo. Applies to all merge paths (dependabot, waived, owner /merge); API errors fail closed. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn6JQKCBc5BkLb7fbceRnN --- AGENTS.md | 2 ++ ts/src/agents/pr_assistant/agents-md-gate.ts | 15 +++++++++++++++ ts/src/agents/pr_assistant/merge-flow.ts | 7 +++++++ ts/tests/pr-assistant.test.ts | 2 +- ts/tests/pr-flow-hardening.test.ts | 15 ++++++++++++++- 5 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 ts/src/agents/pr_assistant/agents-md-gate.ts diff --git a/AGENTS.md b/AGENTS.md index 8a14cb59..ced84a50 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,6 +135,8 @@ GitHub API 5.000 req/h (monitorado pelo `BaseAgent`); burst opcional de tarefas ## 🧾 Merge Gate e falhas de billing do CI +**AGENTS.md obrigatório:** repositório sem `AGENTS.md` na raiz nunca tem PR mesclado pelo bot (`agents_md_missing`; erro de API = `agents_md_check_failed`, falha fechada), mesmo sem código relacionado, dependabot ou `/merge` do owner. Implementado em `pr_assistant/agents-md-gate.ts`; o `intelligence-standardizer` abre o PR que cria o arquivo. + Quando o GitHub Actions se recusa a iniciar um job por billing ("recent account payments have failed", "spending limit needs to be increased"), o job **nunca rodou** — é problema de conta, não de código. Por decisão do owner, isso **não diff --git a/ts/src/agents/pr_assistant/agents-md-gate.ts b/ts/src/agents/pr_assistant/agents-md-gate.ts new file mode 100644 index 00000000..0a1178cc --- /dev/null +++ b/ts/src/agents/pr_assistant/agents-md-gate.ts @@ -0,0 +1,15 @@ +/** Owner rule: AGENTS.md is mandatory in every repository, so a PR on a repo without it is never merged by the bot. */ +import type { GithubClient, PR } from "../../github/client.ts"; + +export const AGENTS_MD_MARKER = ""; +const BODY = `${AGENTS_MD_MARKER}\n## 🚫 AGENTS.md ausente\n\nEste repositório não tem \`AGENTS.md\` na raiz, que é obrigatório. O bot **não aprova nem mescla** este PR até o arquivo existir (o agente \`intelligence-standardizer\` abre um PR para criá-lo).`; + +/** Checks the default branch. missing = definitely absent; unknown = API error (fail closed, retried next round). */ +export async function agentsMdState(gh: Pick, repo: string): Promise<"present" | "missing" | "unknown"> { + try { return (await gh.pathExists(repo, "AGENTS.md")) ? "present" : "missing"; } + catch { return "unknown"; } +} +export async function noteAgentsMdMissing(gh: Pick, pr: PR, comments: any[]): Promise { + if (comments.some((c) => (c.body ?? "").includes(AGENTS_MD_MARKER))) return; + try { await gh.commentOnPr(pr, BODY); } catch { /* the block itself is already recorded */ } +} diff --git a/ts/src/agents/pr_assistant/merge-flow.ts b/ts/src/agents/pr_assistant/merge-flow.ts index 0d34940a..a0ba5222 100644 --- a/ts/src/agents/pr_assistant/merge-flow.ts +++ b/ts/src/agents/pr_assistant/merge-flow.ts @@ -4,6 +4,7 @@ import type { PRAssistantAgent, Results } from "./agent.ts"; import * as billing from "./billing-gate.ts"; import * as notify from "./notifications.ts"; import { checkPipelineStatus } from "./pipeline.ts"; +import { agentsMdState, noteAgentsMdMissing } from "./agents-md-gate.ts"; import { approvalFor } from "./review-approval.ts"; export async function tryMerge(a: PRAssistantAgent, pr: PR, results: Results, comments: any[], reviewExempt = false): Promise { @@ -16,6 +17,12 @@ export async function tryMerge(a: PRAssistantAgent, pr: PR, results: Results, co // Last line of defence: whatever path got here, merge only on an explicit APPROVE pinned to this exact head SHA. const approvedSha = pr.head.sha; if (a.requireReview && !reviewExempt && !(await reviewApproved(a, pr))) { a.recordBlocked(results, pr, repo, "review_not_approved", approvedSha); return; } + // Owner rule, applies to every PR (even unrelated code, dependabot, owner /merge): no AGENTS.md in the repo, no merge. + const agentsMd = await agentsMdState(gh, repo); + if (agentsMd !== "present") { + if (agentsMd === "missing" && !a.simulationMode) await noteAgentsMdMissing(gh, pr, comments); + a.recordBlocked(results, pr, repo, agentsMd === "missing" ? "agents_md_missing" : "agents_md_check_failed", approvedSha); return; + } if (a.simulationMode) { a.log(`[SIMULATION] would merge PR #${pr.number} in ${repo}`); results.skipped.push({ pr: pr.number, title: pr.title, reason: "simulation", repository: repo }); return; } const ms = pr.mergeable_state; if (ms === null || ms === undefined || ms === "unknown") { a.recordBlocked(results, pr, repo, "mergeable_state_unknown"); return; } diff --git a/ts/tests/pr-assistant.test.ts b/ts/tests/pr-assistant.test.ts index a3b06249..7eb30655 100644 --- a/ts/tests/pr-assistant.test.ts +++ b/ts/tests/pr-assistant.test.ts @@ -18,7 +18,7 @@ const pr = (o: any = {}) => ({ number: 7, title: "t", html_url: "u", mergeable: function fakeGh(p: any, over: any = {}) { const calls: any[] = []; const gh: any = { - calls, getIssueComments: async () => [], getCombinedStatus: async () => ({ statuses: [] }), getCheckRuns: async () => [{ name: "ci", status: "completed", conclusion: "success" }], + calls, pathExists: async () => true, getIssueComments: async () => [], getCombinedStatus: async () => ({ statuses: [] }), getCheckRuns: async () => [{ name: "ci", status: "completed", conclusion: "success" }], getPull: async () => p, commentOnPr: async (_p: any, b: string) => { calls.push(["comment", b]); }, addLabelToPr: async () => {}, getLabels: async () => [], createLabel: async () => {}, updatePrBranch: async () => [true, "", "abc"], mergePr: async (_p: any, m: string, sha: string) => { calls.push(["merge", m, sha]); return [true, "ok"]; }, acceptReviewSuggestions: async () => [true, "", 0], addAssigneeToPr: async () => [true, "ok"], requestReviewerOnPr: async () => [true, "ok"], getFiles: async () => [], diff --git a/ts/tests/pr-flow-hardening.test.ts b/ts/tests/pr-flow-hardening.test.ts index 98ce1cd7..170ec1a6 100644 --- a/ts/tests/pr-flow-hardening.test.ts +++ b/ts/tests/pr-flow-hardening.test.ts @@ -34,7 +34,7 @@ function fakeGh(p: any, over: any = {}) { getLabels: async () => [], createLabel: async () => {}, updatePrBranch: async () => [true, "", SHA], getFiles: async () => files, getCommits: async () => [{ sha: SHA, commit: { committer: { date: iso(T0) } } }], mergePr: async (_p: any, m: string, sha: string) => { calls.push(["merge", m, sha]); return [true, "ok"]; }, acceptReviewSuggestions: async () => [true, "", 0], addAssigneeToPr: async () => [true, "ok"], requestReviewerOnPr: async () => [true, "ok"], createStatus: async () => {}, setDraft: async () => {}, - removeLabel: async (_p: any, l: string) => { calls.push(["unlabel", l]); }, getContents: async () => null, ...over, + removeLabel: async (_p: any, l: string) => { calls.push(["unlabel", l]); }, getContents: async () => null, pathExists: async () => true, ...over, }; return gh; } @@ -184,3 +184,16 @@ test("review fixes: a waived PR is still scanned for credentials before merging" await a.processPr(p, r); expect(merged(gh)).toBe(false); expect(r.blocked[0].reason).toStartWith("waived_credential_found"); }); +test("AGENTS.md is mandatory: missing blocks even an owner-approved PR, warns once, and an API error fails closed", async () => { + const approved = [{ user: { login: "juninmd" }, body: `\n**Veredito:** \`APPROVE\`\nSHA \`${SHA.slice(0, 8)}\`` }]; + const p = pr(), gh = fakeGh(p, { pathExists: async () => false, getIssueComments: async () => approved }), r = results(); + await agent(gh).tryMerge(p, r, []); + expect(merged(gh)).toBe(false); expect(r.blocked[0].reason).toBe("agents_md_missing"); + expect(gh.calls.filter((c: any) => c[0] === "comment")).toHaveLength(1); + const g2 = fakeGh(p, { pathExists: async () => false, getIssueComments: async () => approved }), r2 = results(); + await agent(g2).tryMerge(p, r2, [{ body: "" }]); + expect(g2.calls.some((c: any) => c[0] === "comment")).toBe(false); + const g3 = fakeGh(p, { pathExists: async () => { throw new Error("500"); }, getIssueComments: async () => approved }), r3 = results(); + await agent(g3).tryMerge(p, r3, []); + expect(merged(g3)).toBe(false); expect(r3.blocked[0].reason).toBe("agents_md_check_failed"); +});