diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 554673a..805bd63 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -8,10 +8,10 @@ This workspace is **github-agent-contracts** only. - Prefer Node 20 ESM scripts with zero dependencies. - Load root `agent-policy.yml` through `scripts/load-agent-policy.mjs` and follow `skills/agent-policy/SKILL.md` before publication or GitHub writes. Missing or invalid policy denies all actions; never fall back to the example or a different role. - Agents must not edit, create, replace, or delete `agent-policy.yml` to grant themselves rights, or modify the executor to bypass a denial. A human reviews and publishes active policy changes. -- App permissions, branch protection/environments, and policy are cumulative gates. The coder publisher requires `commit_branch` and `open_pr`, checks the reviewed default-branch policy, and has no merge/protected-push/deploy or role-override mode. Humans merge; no deploys. +- App permissions, branch protection/environments, and policy are cumulative gates. The coder publisher requires `commit_branch` and `open_pr`, checks the reviewed default-branch policy, and has no protected-push/deploy or role-override mode. Human-only merge is the default; `--merge-when-green` additionally requires a human-published coder `merge` grant and explicit authorization for merge and remote-branch cleanup. - Follow `docs/ROLES.md`: use separate role Apps, and keep only the coder key on the WSL orchestration host. Never use merger/deploy credentials or a human token there. - Agents must commit and publish through `node scripts/agent-pr.mjs`, never raw `git commit`, `git push`, or a separate `gh pr create`. Never commit as R4yHarris or use a human token as a fallback. -- Follow `skills/signed-bot-commit/SKILL.md`. App environment variables never authorize use of the signed-in human's identity, and missing App configuration means stop. Never merge or enable auto-merge. +- Follow `skills/signed-bot-commit/SKILL.md`. App environment variables never authorize use of the signed-in human's identity, and missing App configuration means stop. Never self-approve, squash, push main, or enable GitHub auto-merge. The authorized merge flag must verify `check-agent-trailers` on the exact head SHA and honor all required reviews. - Invoke the helper only after authorization for commit, push, and a draft PR. A request to stop after writing files and testing means no publication. Humans may perform their own bootstrap commits. - The human supplies `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` in the environment. Do not read the PEM into chat, print tokens, or stage/commit `.env` or key files; the helper does not load `.env`. - Use the consuming user/org's own App through `docs/ONBOARDING.md` and `docs/app-manifest.json`; do not recommend the maintainer demo App for private or production repositories. diff --git a/AGENTS.md b/AGENTS.md index c34e80a..81ea71e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,14 +21,14 @@ Reusable conventions and small tools so Copilot, GitHub Agentic Workflows (`gh-a - Do not invent a new git server, object store, or identity protocol. - Do not put personal access tokens, Copilot tokens, or App private keys in the repo. - Do not grant agents `admin`, `delete`, or unscoped `repo` power in examples. -- Default writes on GitHub are **safe outputs only**: comments, labels, draft PRs — never force-push, never merge without a human. +- Default writes on GitHub are **safe outputs only**: comments, labels, draft PRs. Never force-push. Merging requires explicit human authorization, a human-reviewed policy grant, and the opt-in flow below. ## Capability policy - Follow `skills/agent-policy/SKILL.md` and load root `agent-policy.yml` with `scripts/load-agent-policy.mjs` before publication or any GitHub write, including safe outputs. Missing or invalid policy denies every capability; never fall back to the example. - App permissions, branch protection/environments, and the policy allow-list must all permit an action. A task prompt, available tool, App environment variable, or broader token does not override a denial. - Agents must not create, edit, replace, or delete root `agent-policy.yml` to grant themselves rights. Humans review and publish policy changes. Do not bypass policy by changing the loader, publisher, or harness configuration. -- The publisher is fixed to coder and requires `commit_branch` plus `open_pr`, matching the reviewed default-branch policy. There is no role or policy-path override. Merge, protected pushes, and deploys are unsupported by the coder publisher; humans merge and deployments remain disabled. +- The publisher is fixed to coder and requires `commit_branch` plus `open_pr`, matching the reviewed default-branch policy. There is no role or policy-path override. `--merge-when-green` also requires `merge` in that same role; a merger-role grant does not authorize coder. Human-only merge remains the default. Protected pushes and deploys remain unsupported. - Use separate user/org-owned role Apps. The WSL orchestration host holds only the coder key, never merger/deploy keys or human fallback credentials. Follow `docs/POLICY.md` and `docs/ROLES.md`. ```bash @@ -42,13 +42,15 @@ node scripts/load-agent-policy.mjs --role coder --capability open_pr - Agents must use `node scripts/agent-pr.mjs` for commits and publication in this repository. Do not run raw `git commit`, `git push`, or a separate `gh pr create`, and never commit as R4yHarris or fall back to a human's credentials. - If App environment variables are set, never commit or push as the signed-in human. If they are missing, stop rather than falling back. Their presence is not authorization to publish. - Run the script only when the human has authorized committing, pushing the current feature branch, and creating a draft PR. If told to stop after editing or testing, do not invoke it. +- Only use `--merge-when-green` when the human also authorizes merging and remote feature-branch deletion. A human must first allow `merge` in root `agent-policy.yml`, using `roles.coder.allow` in this policy format, and publish that grant on the default branch. Never edit the policy yourself or treat the flag as a grant. - The human supplies `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` through the environment. Never read the PEM into chat, paste key material, print tokens, or commit `.env` or private-key files. The script does not load `.env` automatically. - Default onboarding is a user/org-owned App from `docs/app-manifest.json`; follow `docs/ONBOARDING.md` and `docs/THREAT_MODEL.md`. Never recommend the maintainer's `r4yharris-agent-coder` App for private or production repositories; a demo install is for public playgrounds only. - The helper verifies origin's installation against `GITHUB_APP_ID`, resolves that App's bot account, sets both author and committer to it, and adds `AI-Agent: ` plus `AI-Model: unknown`. Do not hard-code or invent a bot identity; use `--model` when the model is known. - Without `--files`, it commits the reviewed staged changes. With `--files`, pass individual repository files last; unrelated staged files cause a failure. Inspect the changes and run the tests before publication. -- Node 20+, Git, and `gh` are required. The App must be installed on origin's repository with contents and pull requests write permissions. The helper creates a repository-scoped installation token, pushes without force, creates a draft PR only if no open PR exists, and revokes the token. +- Node 20+, Git, and `gh` are required. The App must be installed on origin's repository with contents and pull requests write permissions; the opt-in merge flow also needs Checks read permission. The helper creates a repository-scoped installation token, pushes without force, creates a draft PR only if no open PR exists, and revokes the token. - This is the explicitly authorized branch-publication path, not a general grant of GitHub write permissions. It refuses main, master, and the repository's default branch. Never bypass repository protections. -- Require the `check-agent-trailers` check on protected branches, forbid direct agent pushes or bypass, and leave every merge to a human. Never enable auto-merge or merge a PR yourself. +- Require the `check-agent-trailers` check on protected branches and forbid direct agent pushes or bypass. By default, leave merges to humans. The sole script-managed exception is authorized `--merge-when-green`: require a successful GitHub Actions check on the exact head SHA and all repository merge requirements, then create a merge commit and delete only the unchanged remote feature branch. +- Never self-approve, squash, rebase-merge, force-push, push main, or enable GitHub auto-merge. Marking an authorized draft ready does not approve it or bypass required human reviews. See `docs/POLICY.md` for polling, permission, and failure details. - Commits are unsigned for now. If signing is required or any step fails, stop and report it without a raw Git fallback. A human may commit a bootstrap slice themselves; agents may not assume that identity. After a partial failure, inspect the existing commit and PR before retrying. ```bash diff --git a/README.md b/README.md index 661a2e5..33c75a5 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ Follow the [adoption guide](docs/adopt.md) and copy the [consumer workflow](exam Hermes, Copilot, Claude Code, and Cursor share one human-owned root `agent-policy.yml`. The [example](examples/agent-policy.yml) allows coder branch commits, draft PRs, comments, and labels; merger and deploy allow-lists are empty. Missing policy denies publication, and agents must not edit policy to grant themselves rights. -Read [POLICY.md](docs/POLICY.md) for the three permission layers and human bootstrap, and [ROLES.md](docs/ROLES.md) for separate role Apps and a WSL host holding only the coder key. The coder publisher has no merge, protected-push, or deployment mode. No active root policy or hosted control plane is installed by this pack. +Read [POLICY.md](docs/POLICY.md) for the three permission layers, human bootstrap, and optional `--merge-when-green` flow, and [ROLES.md](docs/ROLES.md) for role-key separation. Merging remains disabled unless a human grants coder `merge` and authorizes the flag; it requires a successful exact-head trailer check and creates a merge commit before remote-branch cleanup. Protected pushes and deploys remain unsupported. No active policy grant or hosted control plane is installed by this pack. ## Non-goals diff --git a/docs/POLICY.md b/docs/POLICY.md index 416d671..87599e1 100644 --- a/docs/POLICY.md +++ b/docs/POLICY.md @@ -36,7 +36,7 @@ roles: | `open_pr` | Open a draft PR or update its branch through the publisher | Coder only | | `comment` | Request an approved comment output | Coder only | | `label` | Request approved label changes | Coder only | -| `merge` | Merge a PR or enable automatic merging | Denied | +| `merge` | Permit the explicitly authorized `--merge-when-green` flow | Denied | | `push_protected` | Directly update a protected branch | Denied | | `deploy` | Start a deployment or use deployment credentials | Denied | @@ -82,15 +82,52 @@ Unsupported YAML is rejected rather than interpreted permissively. Use the suppl ## Publisher enforcement -[agent-pr.mjs](../scripts/agent-pr.mjs) is fixed to the **coder** role. It requires both `commit_branch` and `open_pr` before key access or Git commands, even when an existing PR might be reused. It has no `--role` or `--policy` override. +[agent-pr.mjs](../scripts/agent-pr.mjs) is fixed to the **coder** role. It requires both `commit_branch` and `open_pr` before key access or Git commands, even when an existing PR might be reused. With `--merge-when-green`, it also requires coder `merge` at that point and in the reviewed default-branch policy. It has no `--role` or `--policy` override. After App authentication, it reads root policy from origin's default branch and requires its grants to match the local policy. It refuses staged or specified root-policy changes, checks the new commit for policy edits, and verifies the policy in the committed tree before pushing. A feature-branch or working-copy self-grant cannot replace the default branch's policy. API or validation failures stop publication, with no human-token fallback. The helper checks both branch protection and active rules before committing and again before pushing. Any applicable rule is treated conservatively as protection. Failure to determine protection state denies publication, even if it is only an availability or permission problem. -The coder helper has **no merge, protected-push, or deployment implementation**. `--merge`, `--push-protected`, and `--deploy` are rejected; adding those capabilities to a policy does not turn them on. A protected push first requires `push_protected`, then remains unsupported by this helper even with a grant. There is no merger or deploy script shipped in this change. Keep their allow-lists empty and let humans merge. +The coder helper has **no protected-push or deployment implementation**. Bare `--merge`, `--push-protected`, and `--deploy` are rejected. A protected push first requires `push_protected`, then remains unsupported by this helper even with a grant. The only merge implementation is the explicitly opted-in, policy-gated flow below. There is no separate merger or deploy script; keep those roles' allow-lists empty by default. -Any future privileged executor would require a separately authorized implementation, a separately controlled role App, an explicit human-reviewed grant, and the branch or environment gates. It must not reuse the coder key or reinterpret a successful read-only policy check as authorization to execute. See [ROLES.md](ROLES.md). +## Opt-in merge + +**Humans must set merge to allow in root `agent-policy.yml` before `--merge-when-green` works.** Version 1 expresses this by adding `merge` to `roles.coder.allow`, not by adding a literal `merge: allow` field, which the strict parser rejects. For example, a human may review and publish this policy: + +```yaml +version: 1 +default: deny +roles: + coder: + allow: [commit_branch, open_pr, comment, label, merge] + merger: + allow: [] + deploy: + allow: [] +``` + +This is an explicit expansion of the coder role, not the default example. A grant under `merger.allow` alone does not authorize the fixed coder publisher. Agents must not edit, stage, or commit the active policy to enable this flag. The local, committed, and reviewed default-branch policy must agree; the helper rechecks local and reviewed policy while waiting and immediately before merging. + +The human must also approve **Checks: read-only** for the configured App installation. The flag requests `checks: read` on its repository-scoped token in addition to the normal contents/pull requests write permissions. Normal publishing does not request this extra permission, and the default App manifest is unchanged. The repository must permit merge commits and permit this App's PR merge without any rule bypass; required human reviews still apply. + +After explicit human authorization for publication, merge, and remote-branch cleanup: + +```bash +node scripts/load-agent-policy.mjs --role coder --capability merge +node scripts/agent-pr.mjs --message "fix: validate input" --merge-when-green --files README.md +``` + +`--files` remains last. The flag extends the normal commit/push/PR invocation; it does not choose another role or enable GitHub's server-side auto-merge feature. Without the flag, even an allowed merge capability leaves the PR unmerged. + +The helper finds exactly one open PR for the published feature branch and verifies its repository, target branch, and head SHA. It polls every five seconds, with a ten-minute polling budget and at most 120 attempts, for `check-agent-trailers` from GitHub Actions on that **exact head SHA**. A successful run on an older commit or a synthetic merge SHA is not accepted. Missing or pending checks wait; completed failure, skipped, neutral, cancelled, or unknown results stop the flow. Incomplete results and API failures also stop it. + +When the check is green, the helper may mark a draft PR ready, then rereads its head, checks, and mergeability. This is not a review or self-approval. It waits for GitHub to report the PR mergeable with a clean state; pending required reviews or other requirements eventually time out without merging. It never approves its own PR, changes protection rules, requests an admin bypass, or enables auto-merge. + +Once eligible, it sends a SHA-guarded merge request with `merge_method: merge`, preserving provenance trailers in the merge commit message. It never squashes, rebase-merges, force-pushes, or pushes main directly. GitHub must still accept the merge under the repository's rules. + +Only after GitHub confirms the merge does it delete the remote feature branch. It checks that the branch is still unprotected and still points to the published SHA before deletion; an already-deleted branch is treated as cleaned up. It never deletes the local branch. If a branch has advanced or cleanup fails, report the partial result rather than deleting new work or claiming full success. The reference check and deletion are separate API requests, so avoid concurrent writes to a branch being cleaned up. + +On failure, the published commit and PR can remain, and a timed-out flow may have marked a draft ready. Inspect the PR and remote branch before retrying; do not create a duplicate commit just to retry a merge. Human-only merge remains the default, and deploys and direct protected pushes stay disabled. Prefer the separate-role model in [ROLES.md](ROLES.md) wherever granting coder merge authority is not acceptable. ## Limits diff --git a/docs/ROLES.md b/docs/ROLES.md index dbd6597..1804096 100644 --- a/docs/ROLES.md +++ b/docs/ROLES.md @@ -10,9 +10,11 @@ Use separate, user/org-owned GitHub Apps for **coder**, **merger**, and **deploy Only the coder publisher exists in this pack. Do not provision or distribute merger/deploy keys merely because role names appear in the example. An eventual human-authorized extension must use a separate App, executor, permissions review, and explicit policy grants without bypassing branch or environment protections. +The optional [merge-when-green flow](POLICY.md#opt-in-merge) stays in the coder role. A human may deliberately add coder `merge` and authorize it, accepting that this expands the coder credential's permitted use. It does not borrow a merger grant or key. Leave that grant absent when strict coding/merging separation is required; human-only merge remains the default. + ## Permissions by role -The coder App needs metadata read, contents write for authorized feature branches, and pull requests write for draft PRs. Issues write is optional for approved comment/label handlers; the publisher's installation token only requests contents and pull requests write. Keep repositories explicitly selected and retain human review and merge controls. +The coder App needs metadata read, contents write for authorized feature branches, and pull requests write for draft PRs. Issues write is optional for approved comment/label handlers. Normal publishing requests only contents and pull requests write; the opt-in merge flag also requests Checks read-only. Keep repositories explicitly selected and retain required human reviews and merge controls. GitHub does not expose a separate draft-only or merge-only version of pull requests write. A coder token may technically call broader endpoints than the helper permits. Do not put the coder App on branch-rule bypass lists; restrict protected-branch updates and merges to authorized humans. Separate Apps reduce shared-key exposure but do not replace these controls. diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs index 346b409..c793819 100644 --- a/scripts/agent-pr.mjs +++ b/scripts/agent-pr.mjs @@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process"; import { createPrivateKey, KeyObject, sign } from "node:crypto"; import { lstatSync, readFileSync } from "node:fs"; import { isAbsolute, relative, resolve, sep } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; import { pathToFileURL } from "node:url"; import { checkMessage } from "./check-agent-trailers.mjs"; import { AgentPolicyError, loadAgentPolicy, parseAgentPolicy, requireCapability } from "./load-agent-policy.mjs"; @@ -65,7 +66,7 @@ async function githubRequest(path, token, { method = "GET", body, fetchImpl = gl } export async function mintInstallationToken( - { appId, privateKey, owner, repository }, + { appId, privateKey, owner, repository, readChecks = false }, { fetchImpl = globalThis.fetch, now = Date.now() } = {}, ) { const jwt = createAppJwt(appId, privateKey, now); @@ -79,9 +80,11 @@ export async function mintInstallationToken( ) { throw new AgentPrError("The repository needs an active installation matching GITHUB_APP_ID."); } + const permissions = { contents: "write", pull_requests: "write" }; + if (readChecks) permissions.checks = "read"; const access = await githubRequest(`/app/installations/${installation.id}/access_tokens`, jwt, { method: "POST", - body: { repositories: [repository], permissions: { contents: "write", pull_requests: "write" } }, + body: { repositories: [repository], permissions }, fetchImpl, }); if ( @@ -139,6 +142,8 @@ export function parseArgs(argv) { const argument = argv[index]; if (argument === "--help" || argument === "-h") { options.help = true; + } else if (argument === "--merge-when-green") { + options.mergeWhenGreen = true; } else if (argument === "--files") { options.files = argv.slice(index + 1); if (!options.files.length || options.files.some((file) => file.startsWith("--"))) { @@ -152,7 +157,7 @@ export function parseArgs(argv) { } options[argument === "--model" ? "model" : "message"] = value; } else if (["--merge", "--push-protected", "--push_protected", "--deploy"].includes(argument)) { - throw new AgentPrError("agent-pr is coder-only: merge, push_protected, and deploy are not implemented. Human-only merge and no deploys remain enforced."); + throw new AgentPrError("Use --merge-when-green only with an approved coder merge grant. Protected pushes and deploys are unsupported."); } else { throw new AgentPrError("Unknown argument; use --help for usage."); } @@ -198,6 +203,65 @@ function runCommand(command, args, options) { }); } +async function readReviewedPolicy(repoPath, defaultBranch, token, fetchImpl) { + const file = await githubRequest(`${repoPath}/contents/agent-policy.yml?ref=${encodeURIComponent(defaultBranch)}`, token, { fetchImpl }); + if (file?.type !== "file" || file.encoding !== "base64" || typeof file.content !== "string" || file.content.length > 100_000) { + throw new AgentPrError("Cannot verify agent-policy.yml on the default branch; refusing publication."); + } + return parseAgentPolicy(Buffer.from(file.content, "base64").toString("utf8")); +} + +async function waitForGreenPullRequest({ + repoPath, slug, branch, defaultBranch, headSha, pullNumber, token, + fetchImpl, invoke, baseEnv, checkMergePolicy, wait, clock, +}) { + const deadline = clock() + 600_000; + let markedReady = false; + for (let attempt = 0; attempt < 120 && clock() < deadline; attempt += 1) { + await checkMergePolicy(); + const pull = await githubRequest(`${repoPath}/pulls/${pullNumber}`, token, { fetchImpl }); + if ( + pull?.number !== pullNumber || pull.state !== "open" || pull.merged !== false || typeof pull.draft !== "boolean" || + pull.head?.sha !== headSha || pull.head.ref !== branch || pull.head.repo?.full_name?.toLowerCase() !== slug.toLowerCase() || + pull.base?.ref !== defaultBranch || pull.base.repo?.full_name?.toLowerCase() !== slug.toLowerCase() + ) { + throw new AgentPrError("The open PR no longer matches the published head SHA, branch, and repository; refusing to merge."); + } + const checks = await githubRequest(`${repoPath}/commits/${headSha}/check-runs?check_name=check-agent-trailers&filter=latest&per_page=100`, token, { fetchImpl }); + if (!Array.isArray(checks?.check_runs) || checks.total_count !== checks.check_runs.length || checks.total_count > 100) { + throw new AgentPrError("Cannot verify the complete check-agent-trailers results; refusing to merge."); + } + let green = checks.check_runs.length > 0; + for (const check of checks.check_runs) { + if (check?.name !== "check-agent-trailers" || check.head_sha !== headSha || check.app?.slug !== "github-actions") { + throw new AgentPrError("check-agent-trailers must be a GitHub Actions check on the exact published head SHA."); + } + if (check.status === "completed") { + if (check.conclusion !== "success") { + throw new AgentPrError("check-agent-trailers did not succeed on the head SHA; no merge was attempted."); + } + } else if (["queued", "in_progress", "waiting", "requested", "pending"].includes(check.status)) { + green = false; + } else { + throw new AgentPrError("check-agent-trailers returned an unrecognized status; refusing to merge."); + } + } + if (green) { + if (pull.draft && !markedReady) { + invoke("gh", ["pr", "ready", String(pullNumber), "--repo", slug], "Marking draft PR ready", { env: { ...baseEnv, GH_TOKEN: token } }); + markedReady = true; + continue; + } + if (!pull.draft && pull.mergeable === true && pull.mergeable_state === "clean") return; + if (pull.mergeable === false || pull.mergeable_state === "dirty") { + throw new AgentPrError("The PR is not mergeable; resolve conflicts without bypassing repository rules."); + } + } + if (attempt < 119) await wait(5_000); + } + throw new AgentPrError("Timed out waiting for successful head-SHA checks and repository merge requirements; the PR and branch were left in place."); +} + export async function publishAgentPr(options, { cwd = process.cwd(), env = process.env, @@ -205,11 +269,14 @@ export async function publishAgentPr(options, { readPrivateKey = (path) => readFileSync(path), loadPolicy = loadAgentPolicy, run = runCommand, + wait = delay, + clock = Date.now, now = Date.now(), } = {}) { const policy = loadPolicy({ cwd }); requireCapability(policy, "coder", "commit_branch"); requireCapability(policy, "coder", "open_pr"); + if (options.mergeWhenGreen) requireCapability(policy, "coder", "merge"); validateCommitInput(options.message, options.model); const appId = env.GITHUB_APP_ID; if (!appId || !/^[1-9][0-9]*$/.test(appId) || !env.GITHUB_APP_PRIVATE_KEY_PATH) { @@ -294,7 +361,7 @@ export async function publishAgentPr(options, { } catch { throw new AgentPrError("Could not load the App private key from GITHUB_APP_PRIVATE_KEY_PATH."); } - ({ token, appSlug } = await mintInstallationToken({ ...origin, appId, privateKey: key }, { fetchImpl, now })); + ({ token, appSlug } = await mintInstallationToken({ ...origin, appId, privateKey: key, readChecks: options.mergeWhenGreen === true }, { fetchImpl, now })); } finally { if (Buffer.isBuffer(key)) key.fill(0); key = undefined; @@ -304,6 +371,7 @@ export async function publishAgentPr(options, { let result; let failure; let committed = false; + let merged = false; try { const botName = `${appSlug}[bot]`; const bot = await githubRequest(`/users/${encodeURIComponent(botName)}`, token, { fetchImpl }); @@ -320,16 +388,10 @@ export async function publishAgentPr(options, { throw new AgentPrError("GitHub did not return an active repository matching origin."); } if (branch === repository.default_branch) throw new AgentPrError("Refusing to publish directly to the default branch."); - const approvedFile = await githubRequest(`${repoPath}/contents/agent-policy.yml?ref=${encodeURIComponent(repository.default_branch)}`, token, { fetchImpl }); - if ( - approvedFile?.type !== "file" || approvedFile.encoding !== "base64" || - typeof approvedFile.content !== "string" || approvedFile.content.length > 100_000 - ) { - throw new AgentPrError("Cannot verify agent-policy.yml on the default branch; refusing publication."); - } - const approvedPolicy = parseAgentPolicy(Buffer.from(approvedFile.content, "base64").toString("utf8")); + const approvedPolicy = await readReviewedPolicy(repoPath, repository.default_branch, token, fetchImpl); requireCapability(approvedPolicy, "coder", "commit_branch"); requireCapability(approvedPolicy, "coder", "open_pr"); + if (options.mergeWhenGreen) requireCapability(approvedPolicy, "coder", "merge"); const verifyApprovedPolicy = (candidate) => { for (const role of Object.keys(approvedPolicy.roles)) { const approved = approvedPolicy.roles[role].allow; @@ -404,7 +466,8 @@ export async function publishAgentPr(options, { GIT_CONFIG_KEY_7: "protocol.https.allow", GIT_CONFIG_VALUE_7: "always", }, }); - const pullRequests = await githubRequest(`${repoPath}/pulls?state=open&head=${encodeURIComponent(`${origin.owner}:${branch}`)}`, token, { fetchImpl }); + const pullRequestPath = `${repoPath}/pulls?state=open&head=${encodeURIComponent(`${origin.owner}:${branch}`)}`; + const pullRequests = await githubRequest(pullRequestPath, token, { fetchImpl }); if (!Array.isArray(pullRequests)) throw new AgentPrError("GitHub returned an invalid pull-request list."); if (!pullRequests.length) { const subject = message.split("\n")[0]; @@ -415,9 +478,46 @@ export async function publishAgentPr(options, { ], "Draft pull-request creation", { env: { ...baseEnv, GH_TOKEN: token } }); } result = { commit: actual[0], botName, createdPullRequest: !pullRequests.length }; + if (options.mergeWhenGreen) { + const candidates = pullRequests.length ? pullRequests : await githubRequest(pullRequestPath, token, { fetchImpl }); + if (!Array.isArray(candidates) || candidates.length !== 1 || !Number.isSafeInteger(candidates[0]?.number) || candidates[0].number <= 0) { + throw new AgentPrError("Expected exactly one open PR for the published feature branch; refusing to merge."); + } + const pullNumber = candidates[0].number; + const checkMergePolicy = async () => { + const currentPolicy = loadPolicy({ cwd }); + requireCapability(currentPolicy, "coder", "merge"); + verifyApprovedPolicy(currentPolicy); + const currentReviewedPolicy = await readReviewedPolicy(repoPath, repository.default_branch, token, fetchImpl); + requireCapability(currentReviewedPolicy, "coder", "merge"); + verifyApprovedPolicy(currentReviewedPolicy); + }; + await waitForGreenPullRequest({ + repoPath, slug, branch, defaultBranch: repository.default_branch, headSha: actual[0], pullNumber, token, + fetchImpl, invoke, baseEnv, checkMergePolicy, wait, clock, + }); + await checkMergePolicy(); + const mergeResult = await githubRequest(`${repoPath}/pulls/${pullNumber}/merge`, token, { + method: "PUT", body: { sha: actual[0], merge_method: "merge", commit_message: message }, fetchImpl, + }); + if (mergeResult?.merged !== true || !/^[0-9a-f]{40}$/i.test(mergeResult.sha)) { + throw new AgentPrError("GitHub did not confirm a successful merge; the feature branch was not deleted."); + } + merged = true; + await checkProtectedBranch(); + const reference = await githubRequest(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`, token, { fetchImpl, allowMissing: true }); + if (reference !== undefined) { + if (reference?.ref !== `refs/heads/${branch}` || reference.object?.type !== "commit" || reference.object.sha !== actual[0]) { + throw new AgentPrError("The remote feature branch changed after merging; it was not deleted."); + } + await githubRequest(`${repoPath}/git/refs/heads/${encodeURIComponent(branch)}`, token, { method: "DELETE", fetchImpl }); + } + result = { ...result, merged: true, pullRequest: pullNumber, mergeCommit: mergeResult.sha, remoteBranchDeleted: true }; + } } catch (error) { const detail = error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "Publication failed; details were withheld to protect credentials."; - failure = new AgentPrError(`${detail}${committed ? " The local commit remains; do not create a duplicate commit to retry." : ""}`); + const state = merged ? " The PR was merged; remote-branch cleanup may be incomplete. Inspect it before retrying." : committed ? " The local commit remains; do not create a duplicate commit to retry." : ""; + failure = new AgentPrError(`${detail}${state}`); } finally { try { await githubRequest("/installation/token", token, { method: "DELETE", fetchImpl }); @@ -439,15 +539,18 @@ export async function main(argv, { stdout = process.stdout, stderr = process.std return 2; } if (options.help) { - stdout.write(`Usage: node scripts/agent-pr.mjs --message TEXT [--model NAME] [--files PATH ...] + stdout.write(`Usage: node scripts/agent-pr.mjs --message TEXT [--model NAME] [--merge-when-green] [--files PATH ...] Without --files, commits the reviewed staged changes. --files must be last. Requires Node 20+, Git, gh, GITHUB_APP_ID, and GITHUB_APP_PRIVATE_KEY_PATH. Requires root agent-policy.yml with coder commit_branch and open_pr grants, matching the reviewed policy on origin's default branch. No example fallback. Discovers your configured App's bot identity, pushes the current feature branch to origin, -and creates a draft PR only when no open PR exists. Never force-pushes or merges. -No role/policy override, merge, push_protected, or deploy flags are supported. +and creates a draft PR only when no open PR exists. Never force-pushes or pushes main. +--merge-when-green additionally requires coder.merge in local and reviewed policy, +plus App Checks read permission. Waits for a successful check-agent-trailers on the +exact head SHA, marks drafts ready, merges with a merge commit, then deletes that branch. +No self-approval, squash, role/policy override, protected push, deploy, or auto-merge mode. An invocation authorizes commit, push, and PR creation. Keep secrets out of arguments. `); return 0; @@ -456,6 +559,7 @@ An invocation authorizes commit, push, and PR creation. Keep secrets out of argu const result = await publishAgentPr(options, dependencies); stdout.write(`Committed ${result.commit.slice(0, 7)} as ${result.botName} and pushed to origin.\n`); stdout.write(result.createdPullRequest ? "Created a draft pull request.\n" : "Updated the branch for its existing pull request.\n"); + if (result.merged) stdout.write(`Merged PR #${result.pullRequest} with a merge commit and removed its remote feature branch.\n`); return 0; } catch (error) { stderr.write(`${error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "agent-pr failed; details were withheld to protect credentials."}\n`); diff --git a/skills/agent-policy/SKILL.md b/skills/agent-policy/SKILL.md index 4b92629..d049c7a 100644 --- a/skills/agent-policy/SKILL.md +++ b/skills/agent-policy/SKILL.md @@ -29,7 +29,19 @@ The capabilities are `commit_branch`, `open_pr`, `comment`, `label`, `merge`, `p Use `scripts/agent-pr.mjs` and `skills/signed-bot-commit/SKILL.md` for authorized coder publication. The publisher checks local policy before key access, verifies the default branch's human-reviewed policy and the committed copy, and refuses to publish root-policy edits. It requires both coder `commit_branch` and `open_pr`. -The coder publisher has no role/policy override and no merge, protected-push, or deploy implementation. Do not use raw Git or MCP tools to do what the helper refuses. A policy grant cannot create a missing executor or bypass stricter repository rules. Default remains human-only merge and no deploys. +The coder publisher has no role/policy override, protected-push, or deploy implementation. Default remains human-only merge and no deploys. A merge grant alone never merges anything: only an explicitly authorized `--merge-when-green` invocation can request the conditional merge flow. Do not use raw Git or MCP tools to do what the helper refuses. + +## Opt-in merge + +A **human** must allow `merge` in root `agent-policy.yml` before the flag works. In this format, that means adding `merge` to `roles.coder.allow` and publishing the grant on the default branch, not adding a literal `merge: allow` field. The publisher remains coder; a merger-role grant cannot authorize it. Never make this policy change yourself. + +```bash +node scripts/load-agent-policy.mjs --role coder --capability merge +``` + +The flag requires matching local, committed, and reviewed policy, plus App Checks read permission and explicit human authorization for the merge and remote-branch deletion. Policy is reloaded during the wait and immediately before the merge. A denial or revoked grant stops the flow. + +Require a successful GitHub Actions `check-agent-trailers` run on the exact PR head SHA and GitHub's merge requirements. Draft readiness is not approval. Never self-approve, squash, force-push, push main, change branch rules, or enable GitHub auto-merge. The helper creates a merge commit, then deletes only the unchanged remote feature branch after confirmed success. See `docs/POLICY.md` for wait limits and partial-failure handling. Comments and labels must pass the same policy check in an approved safe-output handler; do not enable direct MCP write tools just because the capability is listed. If the handler cannot enforce policy, stop and ask a human to publish the output. diff --git a/skills/signed-bot-commit/SKILL.md b/skills/signed-bot-commit/SKILL.md index e7b9994..9200a70 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -1,6 +1,6 @@ --- name: signed-bot-commit -description: Use when an agent is authorized to commit, push a feature branch, or create a draft PR. Require scripts/agent-pr.mjs for GitHub App bot identity and provenance; never use raw git commit or push. +description: Use when an agent is authorized to publish a feature branch or explicitly merge when green. Require scripts/agent-pr.mjs for App bot identity, provenance, and policy-gated merging; never use raw git commit or push. --- # Signed bot commit @@ -13,11 +13,11 @@ Never recommend the maintainer's `r4yharris-agent-coder` App for private or prod ## Do -1. Read `AGENTS.md`, load the root policy through `scripts/load-agent-policy.mjs`, and follow `skills/agent-policy/SKILL.md`. Require coder `commit_branch` and `open_pr`, then confirm the human authorized **commit, push, and draft PR creation**. Missing or denied policy means stop. A request to stop after editing or testing prohibits running the helper. +1. Read `AGENTS.md`, load the root policy through `scripts/load-agent-policy.mjs`, and follow `skills/agent-policy/SKILL.md`. Require coder `commit_branch` and `open_pr`, then confirm the human authorized **commit, push, and draft PR creation**. The optional merge flag also requires coder `merge` and human authorization for merge and branch cleanup. Missing or denied policy means stop. A request to stop after editing or testing prohibits running the helper. 2. Use only `node scripts/agent-pr.mjs` from the repository root. Do not run raw `git commit`, `git push`, or a separate `gh pr create`; do not fall back to a human identity or credentials. 3. Confirm Node 20+, Git, and `gh` are available. The human supplies `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` through the environment; CI uses the `GITHUB_APP_PRIVATE_KEY` secret through an approved temporary-file bootstrap. Never read the PEM into chat, display tokens, or commit `.env` or private-key files. The helper does not load `.env` automatically. Missing App configuration means stop, not use the signed-in human. 4. Review the staged changes, or select individual repository files with `--files`. Do not pass directories. The helper refuses unrelated staged files when explicit files are selected. Run `node --test tests/*.test.mjs` before publishing. -5. Keep the current branch an unprotected feature branch. The helper uses only origin's repository, checks branch protection and active rules, and never force-pushes, merges, or deploys. Require `check-agent-trailers` and human approval on protected branches, grant the App no bypass, and leave merging to humans. +5. Keep the current branch an unprotected feature branch. The helper uses only origin's repository, checks branch protection and active rules, and never force-pushes, pushes main, or deploys. Require `check-agent-trailers` and required human reviews on protected branches, grant the App no bypass, and leave merging to humans unless the opt-in flow below is explicitly authorized. ## Identity and trailers @@ -50,16 +50,31 @@ node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --files READ `--help` does not read policy, the key, or contact GitHub. Normal invocation first requires the local coder grants, then signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. After checking the approved policy and branch protections, it makes an unsigned bot commit, pushes with in-memory authentication, reuses an open PR for the branch or runs `gh pr create --draft`, then revokes the token. New PR titles follow the repository's `[area] summary` convention with `[agent]` as the default area. +## Merge when green + +Before this flag works, a **human must allow merge in `agent-policy.yml`** by adding `merge` to `roles.coder.allow`, the schema's equivalent of "merge: allow". A literal `merge: allow` field is invalid. The human must publish the grant on the default branch and include it in the feature branch. Do not change or commit the policy yourself. + +The configured App also needs Checks read-only permission, and the repository must allow merge commits without bypass. No merger-role override or separate merger key is used. After explicit human authorization for publication, merge, and remote-branch deletion: + +```bash +node scripts/load-agent-policy.mjs --role coder --capability merge +node scripts/agent-pr.mjs --message "fix: validate input" --merge-when-green --files README.md +``` + +The helper waits for `check-agent-trailers` from GitHub Actions to succeed on the exact published PR head SHA. It may mark a green draft ready, then rechecks head, checks, and mergeability. It never self-approves; required reviews and repository rules still apply. Polling is bounded to approximately ten minutes; failed checks, changed SHAs, policy revocation, and API errors stop the flow. + +With a clean, mergeable PR and a still-valid grant, it requests a merge commit using the expected head SHA, then deletes the remote feature branch only after confirmed success and an unchanged-branch check. No squash, rebase merge, direct push to main, force push, or GitHub auto-merge is used. The local branch is retained. Without the flag, publication never merges, even if policy allows it. + ## Failure handling -If authentication, signing policy, staging, commit, push, or PR creation fails, stop. Do not use raw Git or a human token to work around the failure. A push or PR error can leave the local commit in place; inspect the branch and existing PR before any retry so the same work is not committed twice. Ask the human to handle a partial publication when needed. The script withholds child-process output to avoid exposing secrets. +If authentication, policy, staging, commit, push, PR creation, merge, or branch cleanup fails, stop. Do not use raw Git or a human token to work around the failure. A push or PR error can leave the local commit in place; a timeout can leave a draft ready; a cleanup error can leave a merged PR and remote branch. Inspect existing state before any retry so the same work is not committed twice or new branch work deleted. Ask the human to handle a partial publication when needed. The script withholds child-process output to avoid exposing secrets. Despite this skill's name, the current helper creates **unsigned Git commits**. Its signed JWT authenticates the App, not the Git commit. Do not invoke it in a repository requiring signed commits until the helper supports that policy; never claim that bot fields or trailers alone produce a Verified signature. ## Do not - Commit as R4yHarris or another human, including during bootstrap. A human can commit a bootstrap slice themselves. -- Force-push any branch or merge a PR. +- Force-push, push main, self-approve, squash, rebase-merge, or enable GitHub auto-merge. Never merge without the authorized policy-gated flag. - Deploy, switch to a merger/deploy App, or use a policy grant to bypass the coder helper's fixed capabilities. - Edit, replace, or delete root `agent-policy.yml` to grant yourself rights or publish a policy change through this helper. - Amend someone else's commit. diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs index a5ee33a..2834a23 100644 --- a/tests/agent-pr.test.mjs +++ b/tests/agent-pr.test.mjs @@ -242,6 +242,198 @@ test("missing, invalid, or insufficient local policy denies publication before c } }); +test("--merge-when-green is opt-in and requires the current coder role to allow merge", async () => { + assert.equal(parseArgs(["--message", "feat: helper", "--merge-when-green"]).mergeWhenGreen, true); + assert.equal(parseArgs(["--message", "feat: helper"]).mergeWhenGreen, undefined); + for (const source of [policySource, policySource.replace(/merger:\r?\n allow: \[\]/, "merger:\n allow: [merge]")]) { + const mock = mockPublication(); + mock.dependencies.loadPolicy = () => parseAgentPolicy(source); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies coder\.merge/); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.commands.length, 0); + assert.equal(mock.requests.length, 0); + } +}); + +test("--merge-when-green also requires merge in the reviewed default-branch policy", async () => { + const mock = mockPublication(); + mock.dependencies.loadPolicy = () => parseAgentPolicy(policySource.replace("comment, label", "comment, label, merge")); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies coder\.merge/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); + assert.equal(mock.requests.at(-1).method, "DELETE"); +}); + +function mockMergePublication({ draft = false, existing = true, checkRuns } = {}) { + const mock = mockPublication({ pullRequests: existing ? [{ number: 7 }] : [] }); + const source = policySource.replace("comment, label", "comment, label, merge"); + const pull = { + number: 7, state: "open", merged: false, draft, mergeable: true, mergeable_state: "clean", + head: { sha: commitSha, ref: "feat/bot-helper", repo: { full_name: repository.full_name } }, + base: { ref: "main", repo: { full_name: repository.full_name } }, + }; + const greenCheck = { name: "check-agent-trailers", head_sha: commitSha, status: "completed", conclusion: "success", app: { slug: "github-actions" } }; + let elapsed = 0; + let listReads = 0; + mock.dependencies.clock = () => elapsed; + mock.dependencies.wait = async (duration) => { elapsed += duration; }; + mock.dependencies.loadPolicy = () => parseAgentPolicy(source); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + if (command === "gh" && args[1] === "ready") pull.draft = false; + const output = originalRun(command, args, options); + return args[0] === "show" ? source : output; + }; + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = async (url, options) => { + let response; + if (url.includes("/contents/agent-policy.yml")) response = { ...approvedPolicyFile, content: Buffer.from(source).toString("base64") }; + else if (url.includes("/pulls?")) response = ++listReads === 1 && !existing ? [] : [{ number: 7 }]; + else if (url.endsWith("/pulls/7")) response = pull; + else if (url.includes("/check-runs?")) { + const runs = typeof checkRuns === "function" ? checkRuns(greenCheck) : checkRuns ?? [greenCheck]; + response = { total_count: runs.length, check_runs: runs }; + } else if (url.endsWith("/pulls/7/merge")) response = { merged: true, sha: "b".repeat(40) }; + else if (url.includes("/git/ref/heads/")) response = { ref: "refs/heads/feat/bot-helper", object: { type: "commit", sha: commitSha } }; + else if (url.includes("/git/refs/heads/") || options.method === "DELETE") response = new Response(null, { status: 204 }); + else return originalFetch(url, options); + mock.requests.push({ url, ...options }); + return response instanceof Response ? response : Response.json(response); + }; + return { ...mock, pull, elapsed: () => elapsed }; +} + +test("--merge-when-green merges a ready or draft PR by exact SHA and only then deletes its branch", async () => { + for (const setup of [{}, { draft: true }, { draft: true, existing: false }]) { + const mock = mockMergePublication(setup); + const result = await publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies); + assert.equal(result.merged, true); + assert.equal(result.remoteBranchDeleted, true); + assert.equal(result.mergeCommit, "b".repeat(40)); + const merge = mock.requests.find((call) => call.url.endsWith("/pulls/7/merge")); + assert.equal(merge.method, "PUT"); + assert.deepEqual(JSON.parse(merge.body), { sha: commitSha, merge_method: "merge", commit_message: buildCommitMessage("feat: helper", undefined, AGENT) }); + const tokenRequest = mock.requests.find((call) => call.url.endsWith("/access_tokens")); + assert.deepEqual(JSON.parse(tokenRequest.body).permissions, { contents: "write", pull_requests: "write", checks: "read" }); + const deletion = mock.requests.find((call) => call.url.includes("/git/refs/heads/")); + assert.equal(deletion.method, "DELETE"); + assert.ok(deletion.url.endsWith("/git/refs/heads/feat%2Fbot-helper")); + assert.ok(mock.requests.indexOf(deletion) > mock.requests.indexOf(merge)); + assert.equal(mock.commands.some((call) => call.command === "gh" && call.args[1] === "ready"), setup.draft === true); + assert.ok(!mock.commands.some((call) => call.args.some((argument) => ["--approve", "--squash", "--force", "--admin", "--auto"].includes(argument)))); + assert.ok(mock.commands.filter((call) => call.args[0] === "push").every((call) => call.args.at(-1).endsWith(":refs/heads/feat/bot-helper"))); + assert.equal(mock.requests.at(-1).url, "https://api.github.com/installation/token"); + } +}); + +test("--merge-when-green never attempts a merge or branch deletion when the trailer check is red", async () => { + for (const conclusion of ["failure", "cancelled", "timed_out", "neutral", "skipped"]) { + const mock = mockMergePublication({ draft: true, checkRuns: (green) => [{ ...green, conclusion }] }); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /did not succeed on the head SHA/); + assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge") || call.url.includes("/git/refs/heads/"))); + assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[1] === "ready")); + } +}); + +test("--merge-when-green waits for a pending check on the same head SHA", async () => { + let reads = 0; + const mock = mockMergePublication({ checkRuns: (green) => ++reads === 1 ? [{ ...green, status: "in_progress", conclusion: null }] : [green] }); + assert.equal((await publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies)).merged, true); + assert.equal(mock.elapsed(), 5_000); +}); + +test("a merge grant alone never merges without --merge-when-green", async () => { + const mock = mockMergePublication(); + const result = await publishAgentPr({ message: "feat: helper" }, mock.dependencies); + assert.equal(result.merged, undefined); + assert.ok(!mock.requests.some((call) => call.url.includes("/check-runs?") || call.url.endsWith("/merge") || call.url.includes("/git/refs/heads/"))); + const tokenRequest = mock.requests.find((call) => call.url.endsWith("/access_tokens")); + assert.equal(JSON.parse(tokenRequest.body).permissions.checks, undefined); +}); + +test("--merge-when-green rejects another PR head or a check for another SHA, name, or App", async () => { + const moved = mockMergePublication(); + moved.pull.head.sha = "c".repeat(40); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, moved.dependencies), /no longer matches the published head SHA/); + assert.ok(!moved.requests.some((call) => call.url.endsWith("/merge"))); + for (const change of [{ head_sha: "c".repeat(40) }, { name: "another-check" }, { app: { slug: AGENT } }]) { + const mock = mockMergePublication({ checkRuns: (green) => [{ ...green, ...change }] }); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /GitHub Actions check on the exact published head SHA/); + assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge") || call.url.includes("/git/refs/heads/"))); + } +}); + +test("--merge-when-green times out on missing checks or outstanding review requirements without self-approval", async () => { + for (const state of ["missing-check", "review-required"]) { + const mock = mockMergePublication(state === "missing-check" ? { checkRuns: [] } : {}); + if (state === "review-required") mock.pull.mergeable_state = "blocked"; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /Timed out waiting/); + assert.ok(mock.elapsed() <= 600_000); + assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge") || call.url.includes("/reviews") || call.url.includes("/git/refs/heads/"))); + assert.ok(!mock.commands.some((call) => call.args.includes("review") || call.args.includes("--approve"))); + assert.equal(mock.requests.at(-1).method, "DELETE"); + } +}); + +test("--merge-when-green rechecks the exact head after marking a draft ready", async () => { + let reads = 0; + const mock = mockMergePublication({ draft: true, checkRuns: (green) => [{ ...green, conclusion: ++reads === 1 ? "success" : "failure" }] }); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /did not succeed/); + assert.ok(mock.commands.some((call) => call.command === "gh" && call.args[1] === "ready")); + assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge"))); +}); + +test("--merge-when-green respects a merge grant revoked while waiting", async () => { + const mock = mockMergePublication({ checkRuns: (green) => [{ ...green, status: "in_progress", conclusion: null }] }); + const originalWait = mock.dependencies.wait; + const originalLoadPolicy = mock.dependencies.loadPolicy; + let revoked = false; + mock.dependencies.loadPolicy = (options) => revoked ? parseAgentPolicy(policySource) : originalLoadPolicy(options); + mock.dependencies.wait = async (duration) => { + await originalWait(duration); + revoked = true; + }; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies coder\.merge/); + assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge"))); +}); + +test("--merge-when-green revalidates the reviewed merge grant immediately before merging", async () => { + const mock = mockMergePublication(); + const originalFetch = mock.dependencies.fetchImpl; + let policyReads = 0; + mock.dependencies.fetchImpl = (url, options) => { + if (url.includes("/contents/agent-policy.yml") && ++policyReads === 3) return Response.json(approvedPolicyFile); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies coder\.merge/); + assert.ok(mock.requests.some((call) => call.url.includes("/check-runs?"))); + assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge"))); +}); + +test("--merge-when-green never deletes a branch after an unconfirmed or rejected merge", async () => { + for (const response of [Response.json({ merged: false }), Response.json({ message: access.token }, { status: 409 })]) { + const mock = mockMergePublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => url.endsWith("/merge") ? response : originalFetch(url, options); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), (error) => { + assert.match(error.message, /did not confirm a successful merge|HTTP 409/); + assert.ok(!error.message.includes(access.token)); + return true; + }); + assert.ok(!mock.requests.some((call) => call.url.includes("/git/refs/heads/"))); + assert.equal(mock.requests.at(-1).url, "https://api.github.com/installation/token"); + } +}); + +test("--merge-when-green preserves a branch that advanced after the confirmed merge", async () => { + const mock = mockMergePublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => url.includes("/git/ref/heads/") + ? Response.json({ ref: "refs/heads/feat/bot-helper", object: { type: "commit", sha: "c".repeat(40) } }) : originalFetch(url, options); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /The PR was merged; remote-branch cleanup may be incomplete/); + assert.ok(mock.requests.some((call) => call.url.endsWith("/merge"))); + assert.ok(!mock.requests.some((call) => call.url.includes("/git/refs/heads/"))); +}); + test("the coder CLI refuses merge, protected push, deploy, and role or policy overrides", async () => { for (const flag of ["--merge", "--push-protected", "--deploy", "--role", "--policy"]) { const mock = mockPublication();