From 3a591b1d90d6634d51b11539320bb9832c095b8d Mon Sep 17 00:00:00 2001 From: r4yharris Date: Sun, 27 Sep 2026 21:50:42 -0400 Subject: [PATCH] fix: set trailer job display name for required check --- .github/copilot-instructions.md | 6 +- .github/workflows/check-agent-trailers.yml | 3 +- AGENTS.md | 12 +- CLAUDE.md | 2 +- README.md | 6 +- docs/HARNESSES.md | 6 +- docs/ONBOARDING.md | 10 +- docs/ORCHESTRATION-MACHINE.md | 30 +++++ docs/POLICY.md | 22 ++-- docs/ROLES.md | 12 +- docs/app-manifest.json | 1 + docs/github-app-agent-identity.md | 8 +- scripts/agent-pr.mjs | 82 +++++++++----- skills/agent-policy/SKILL.md | 8 +- skills/signed-bot-commit/SKILL.md | 18 +-- tests/agent-pr.test.mjs | 121 +++++++++++++++++++-- 16 files changed, 253 insertions(+), 94 deletions(-) create mode 100644 docs/ORCHESTRATION-MACHINE.md diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 805bd63..0b23598 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -8,11 +8,11 @@ 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 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. +- App permissions, branch protection/environments, and policy are cumulative gates. The publisher requires coder `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 `merger.merge` grant in local and reviewed policy and explicit authorization for merge and branch cleanup. Coder `merge` alone is insufficient; policy role does not switch App keys. - 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. +- Agents must commit and publish through `node scripts/agent-pr.mjs`, never raw `git commit`, `git push`, a separate `gh pr create`, or `gh pr merge` as the signed-in human. Never commit as R4yHarris or use a human token as a fallback. Staged or selected `.github/workflows/**` changes are refused before token minting; a human must publish those paths. - 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. +- After reviewing/staging files, passing tests and policy gates, invoke the helper as the final step only after authorization for commit, push, and a draft PR. A request to stop after writing files and testing means no publication. Missing App configuration means leave changes uncommitted after tests. 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. - The helper discovers the configured App's verified bot identity for author and committer and uses its slug in `AI-Agent`. `--model` defaults to `unknown`; `--files` must be last. Without it, only reviewed staged changes are committed. diff --git a/.github/workflows/check-agent-trailers.yml b/.github/workflows/check-agent-trailers.yml index 14d11f0..f38208b 100644 --- a/.github/workflows/check-agent-trailers.yml +++ b/.github/workflows/check-agent-trailers.yml @@ -7,7 +7,8 @@ permissions: contents: read jobs: - check-agent-trailers: + trailers: + name: check-agent-trailers runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 diff --git a/AGENTS.md b/AGENTS.md index 81ea71e..4f8da05 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ Reusable conventions and small tools so Copilot, GitHub Agentic Workflows (`gh-a - 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-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. +- The publisher requires coder `commit_branch` plus `open_pr`, matching the reviewed default-branch policy. There is no role or policy-path override. `--merge-when-green` additionally requires `merger.merge` in both local and reviewed default-branch policy; coder `merge` alone is insufficient. Human-only merge remains the default. A policy role is not proof of which App key is loaded: the helper uses the two supplied App environment variables and does not switch keys. 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 @@ -40,16 +40,16 @@ node scripts/load-agent-policy.mjs --role coder --capability open_pr - Follow `skills/signed-bot-commit/SKILL.md` for all publishing. The security control is the required PR check plus protected branch, bot author, and trailers; an App installation supplies authentication, not a merge exemption. - 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. +- If App environment variables are set, never commit or push as the signed-in human. If they are missing, finish after tests and leave changes uncommitted; never fall back to a human token. Their presence is not authorization to publish. +- After reviewing the files, staging or selecting only intended files, passing tests and policy gates, run the script as the final step 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 add `merge` to `roles.merger.allow` in root `agent-policy.yml` and publish that grant on the default branch. Never edit the policy yourself or treat the flag as a grant. Keep the flag disabled on coder-only WSL; a trusted launcher/operator must use a separately approved merger App/context for merging. - 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. +- Without `--files`, it commits the reviewed staged changes. With `--files`, pass individual repository files last; unrelated staged files cause a failure. Staged or selected `.github/workflows/**` paths are refused before token minting; a human must publish workflow changes. 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 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 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. +- 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. After confirmed merge, fetch origin with App auth, check out and fast-forward the default branch, and delete the local feature ref only if the worktree is clean and that ref still points to the published head included in the merge. Dirty or moved state aborts local cleanup without discarding work; report partial cleanup. - 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. diff --git a/CLAUDE.md b/CLAUDE.md index f7aef7f..1f0ecee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,3 +1,3 @@ # Repository instructions -Follow [AGENTS.md](AGENTS.md) for all repository rules and required skills. \ No newline at end of file +Follow [AGENTS.md](AGENTS.md) for all repository rules and required skills. After tests, policy gates, and reviewed staging, use `node scripts/agent-pr.mjs --message "..."` as the final step only for explicitly authorized publication with App configuration present. Otherwise leave changes uncommitted; never use human credentials or edit the active policy. Merge requires separate authorization and `merger.merge`, not merely a coder key. \ No newline at end of file diff --git a/README.md b/README.md index 33c75a5..113e746 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ This is community OSS for GitHub, not a GitHub replacement. 1. **[Register App from manifest](docs/app-manifest.json).** Create an App owned by you or your organization, keep it private to that account, and choose **Only select repositories** during installation. 2. **Configure and copy.** Supply `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` outside git, then copy AGENTS.md, the policy and commit skills, publisher/loader, and check Action/workflow as listed in [ONBOARDING.md](docs/ONBOARDING.md). A human installs the root capability policy. CI stores the key in the `GITHUB_APP_PRIVATE_KEY` secret. -3. **Protect and publish.** Require `check-agent-trailers`, disallow direct pushes to `main` and agent bypass, and reserve merges for humans. Tell the agent: "Use signed-bot-commit / scripts/agent-pr.mjs for all publish." +3. **Protect and publish.** Require `check-agent-trailers`, disallow direct pushes to `main` and agent bypass, and leave merging to humans by default. After tests, policy gates, and reviewed staging, authorized agent publication ends with `node scripts/agent-pr.mjs --message "..."`; without App configuration, stop with uncommitted changes, never a human-token fallback. The manifest is a static template, not a hosted registration button. An owner-controlled manifest callback is a follow-on; placeholder URLs must be replaced before completing GitHub's flow. The [onboarding guide](docs/ONBOARDING.md) describes that boundary and the manual registration fallback. ### Create your own App (recommended) -Your account or organization owns the App and controls its private key. No project-maintainer installation is needed. Use the [manifest](docs/app-manifest.json), [harness guide](docs/HARNESSES.md), and [threat model](docs/THREAT_MODEL.md). The App key holder can mint tokens for **every installation of that App**, so installation scope and key custody matter. +Your account or organization owns the App and controls its private key. No project-maintainer installation is needed. Use the [manifest](docs/app-manifest.json), [harness guide](docs/HARNESSES.md), [dedicated machine guide](docs/ORCHESTRATION-MACHINE.md), and [threat model](docs/THREAT_MODEL.md). The App key holder can mint tokens for **every installation of that App**, so installation scope and key custody matter. The manifest includes Checks read-only; humans must accept this permission on existing installations for opt-in merge. ### Demo App @@ -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, 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. +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 publishes `roles.merger.allow: [merge]` and explicitly authorizes the flag; coder `merge` alone is insufficient. The flag requires a successful exact-head trailer check and all GitHub reviews, creates a merge commit, and cleans up only unchanged remote and local feature refs after confirmation. Policy does not select the App key; a coder-only WSL host must disable merge and a trusted launcher/operator must use a separately approved merger App/context. 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/HARNESSES.md b/docs/HARNESSES.md index fca5c2b..e13b0ca 100644 --- a/docs/HARNESSES.md +++ b/docs/HARNESSES.md @@ -2,7 +2,7 @@ The common contract is [AGENTS.md](../AGENTS.md), which requires [agent-policy](../skills/agent-policy/SKILL.md) first, then [signed-bot-commit](../skills/signed-bot-commit/SKILL.md) and [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) for authorized publication. Use the consuming user's or organization's App from [ONBOARDING.md](ONBOARDING.md), never a shared maintainer App for private repositories. -Harness setup does not replace the required `check-agent-trailers` check, branch protection, bot authorship, or trailers. No harness may publish as the signed-in human, print credentials, or merge an agent PR. App environment variables do not themselves authorize publication. +Harness setup does not replace the required `check-agent-trailers` check, branch protection, bot authorship, or trailers. No harness may publish as the signed-in human or print credentials. Human-only merge is the default; opt-in merge needs explicit authorization, `merger.merge` in local and reviewed policy, and a separately approved merger App/context. App environment variables do not themselves authorize publication. Every harness reads the same human-owned root `agent-policy.yml` through [the loader](../scripts/load-agent-policy.mjs), not a harness-specific allow-list or cached fallback. Missing policy denies writes. No harness may edit policy to grant itself rights, change its assigned role, or deploy by default. [POLICY.md](POLICY.md) defines the shared capabilities; [ROLES.md](ROLES.md) defines operator-controlled role and key boundaries. @@ -20,7 +20,7 @@ Keep [CLAUDE.md](../CLAUDE.md) as a short pointer to AGENTS.md. Claude Code read Load AGENTS.md as repository instructions, the agent-policy skill before writes, and [skills/signed-bot-commit/SKILL.md](../skills/signed-bot-commit/SKILL.md) for publication using the installed runtime's supported mechanism. For GitHub issue, PR, or code reads, also follow the [GitHub MCP allowlist skill](../skills/github-mcp-allowlist/SKILL.md). Safe-output handlers must enforce the shared policy in addition to their tool allowlists. -Use repository-scoped installation tokens supplied by a trusted launcher; never store tokens in repository MCP configuration. Keep default agent tools read-only and write-capable credentials in the approved publication context. No Hermes runtime changes are needed. +Use repository-scoped installation tokens supplied by a trusted launcher; never store tokens in repository MCP configuration. Keep default agent tools read-only and write-capable credentials in the approved publication context. For a dedicated WSL/Hermes machine, follow [ORCHESTRATION-MACHINE.md](ORCHESTRATION-MACHINE.md): no human `gh` sign-in or forwarded SSH credentials, only the coder key, and no merge flag there. No Hermes runtime changes are needed. ## Cursor @@ -32,4 +32,4 @@ Keep root policy changes human-owned. No Cursor-specific credential, role overri If you honor **AGENTS.md**, you honor **agent-policy** and **signed-bot-commit**. Read the referenced skills and invoke the same helper after policy checks and explicit authorization, regardless of whether your runtime has a native skill loader. -When the necessary instructions, App environment, or publishing tools are unavailable, stop and report the missing prerequisite. Do not fall back to raw Git, human credentials, or automatic merging. Humans review and merge. \ No newline at end of file +After tests, policy checks, and reviewed staging, run `node scripts/agent-pr.mjs --message "docs: clarify agent contracts"` as the final step only when publication is authorized. When the necessary instructions, App environment, or publishing tools are unavailable, stop with uncommitted changes and report the missing prerequisite. Do not fall back to raw Git, human credentials, or automatic merging. Humans review and merge by default; [POLICY.md](POLICY.md) describes the separate opt-in. \ No newline at end of file diff --git a/docs/ONBOARDING.md b/docs/ONBOARDING.md index 28caafe..36062da 100644 --- a/docs/ONBOARDING.md +++ b/docs/ONBOARDING.md @@ -8,7 +8,7 @@ Browser entry point: **[Register App from manifest](app-manifest.json)**. Use a This link is a **static template, not a working registration service**. Replace its placeholder callback with an operator-controlled receiver before submitting it through [GitHub's manifest flow](https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest). Callback hosting is a follow-on, not part of this change. Until your receiver exists, use GitHub's manual App registration form with the same settings; do not submit secrets or a conversion code to this project's maintainer. -The manifest sets `public: false`, disables webhooks and user OAuth, and requests only metadata read plus contents, issues, and pull requests write. Omit issues write if you do not need comment or label outputs. It requests no administration, secrets, workflows, or organization-member permissions. GitHub has **no manifest field to default repository selection**; selecting repositories during installation is a required human step, not something the JSON enforces. +The manifest sets `public: false`, disables webhooks and user OAuth, and requests repository permissions **Metadata: read**, **Checks: read-only**, and **Contents, Issues, Pull requests: read-write**. Omit Issues write if you do not need comment or label outputs. It requests no Administration, Secrets, Workflows, Actions, or Deployments permissions. GitHub has **no manifest field to default repository selection**; selecting repositories during installation is a required human step, not something the JSON enforces. Existing App installations must have the Checks permission change accepted by a human before opt-in merge can use it. Do not install `r4yharris-agent-coder` on private or production repositories. A maintainer demo App is optional for public playgrounds only; see [the threat model](THREAT_MODEL.md). @@ -44,7 +44,7 @@ Use Node 20+, Git, and `gh` for publication. Adapt the workspace name and test c A human must review [the policy example](../examples/agent-policy.yml), install it as root `agent-policy.yml`, and publish it on the default branch through the existing human review process. Include that reviewed version in the feature branch too. Keep merger and deploy allow-lists empty. The publisher requires coder `commit_branch` and `open_pr`, checks the default-branch policy, and refuses root-policy edits; there is no example fallback. See [POLICY.md](POLICY.md) and [ROLES.md](ROLES.md). Copy their guidance with the skills when adopting the pack. -For the local Action, land the Action and both checker scripts on the target branch before enabling the workflow, because it executes the base revision's trusted checker. A human bootstraps workflow changes: the App intentionally has no workflows-write permission. Keep human review on changes to the workflow, instructions, and publisher. +For the local Action, land the Action and both checker scripts on the target branch before enabling the workflow, because it executes the base revision's trusted checker. A human bootstraps and publishes `.github/workflows/**` changes: the helper refuses staged or selected workflow paths before token minting, and the coder App intentionally has no Workflows permission. Keep human review on changes to the workflow, instructions, and publisher. ## 3. Protect the branch and publish @@ -52,13 +52,13 @@ After a successful trial PR run, configure branch protection or a ruleset for `m - Require a PR, human approval, and the **`check-agent-trailers`** check from GitHub Actions. Both supplied workflows give the job this exact name. Update existing required-check rules if adopting from an older job name. - Disallow direct pushes, force pushes, and branch deletion. Do not give the App a bypass. Limit protected-branch updates and merges to authorized humans, using the restrictions available for your account and plan. -- Never permit agent merge or auto-merge tooling. Pull requests write permission is not inherently draft-only or merge-proof; branch rules and the human merge gate are required. +- Leave agent merging disabled by default. Pull requests write permission is not inherently draft-only or merge-proof; branch rules and the human merge gate are required even for an explicitly authorized opt-in merge. Tell the agent: -> Load agent-policy first, then use signed-bot-commit / scripts/agent-pr.mjs for all publish. Never grant yourself policy rights, publish as the signed-in human, print tokens, merge, or deploy. Stop if policy or App authentication is unavailable. +> Load agent-policy first, then use signed-bot-commit / scripts/agent-pr.mjs for authorized publication after tests and reviewed staging. Never grant yourself policy rights, publish as the signed-in human, or print tokens. Do not merge without separate authorization and a human-published merger.merge grant. Stop after tests with uncommitted changes if policy or App configuration is unavailable. -Authorize a specific feature-branch publication, then let the agent use the helper. Check the bot author/committer and trailers on the resulting commits. The helper creates a draft PR or reuses an existing open PR. **Humans review and merge.** Local commits do not independently authorize a push. +Authorize a specific feature-branch publication, then let the agent use the helper as its final implementation step after tests, policy checks, and reviewed staging. Check the bot author/committer and trailers on the resulting commits. The helper creates a draft PR or reuses an existing open PR. **Humans review and merge by default**; opt-in merge requires separate authorization, reviewed `roles.merger.allow: [merge]`, an approved merger App/context, and all GitHub checks and reviews. A coder-only WSL launcher must keep the merge flag disabled. Local commits do not independently authorize a push. See [POLICY.md](POLICY.md) and [ORCHESTRATION-MACHINE.md](ORCHESTRATION-MACHINE.md). The current helper makes unsigned Git commits; its JWT signature authenticates the App, not the commit. See [THREAT_MODEL.md](THREAT_MODEL.md) for checker limits and repositories that require signed commits. diff --git a/docs/ORCHESTRATION-MACHINE.md b/docs/ORCHESTRATION-MACHINE.md new file mode 100644 index 0000000..d06a676 --- /dev/null +++ b/docs/ORCHESTRATION-MACHINE.md @@ -0,0 +1,30 @@ +# Dedicated orchestration machine + +A dedicated WSL/Hermes (or similar) environment runs agent work without a signed-in human GitHub identity. Keep the Windows host's human identities on Windows; these instructions do not log out or reconfigure Windows. + +## Credential boundary + +- Give the WSL publisher only `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` for the user/org-owned **coder** App. Keep the coder key outside the checkout and expose it only to an approved publication context. Do not put key contents or tokens in scripts, files tracked by git, chat, or logs. +- Do not mount or forward human SSH agents/keys, human GitHub tokens, Windows `gh` authentication, or merger/deploy keys into WSL. Do not use human-token environment fallbacks or a human Git credential helper there. +- Keep `--merge-when-green` disabled on the coder-only machine. A human-published `merger.merge` grant is a policy gate, not proof of which App key the helper uses. A trusted launcher/operator must arrange a separately approved merger App/context for any authorized merge; the helper does not switch keys or accept a role override. +- Missing App configuration, denied policy, or an instruction to stop after testing means leave changes uncommitted. No human identity is a fallback. + +## Remove WSL human sign-in + +In the **WSL Linux shell only**, an operator can inspect `gh auth status`, then log out any human account previously signed in there: + +```bash +gh auth logout --hostname github.com --user HUMAN_LOGIN +``` + +Replace `HUMAN_LOGIN` with the human account shown in WSL. The operator runs this command, not the agent. Remove other human SSH forwarding and token injection from the WSL launch configuration as well. Do not run a global logout on Windows; the Windows host retains the operator's identities. + +## Publication boundary + +After reviewing and staging intended files, passing tests and policy checks, and receiving explicit authorization for commit, push, and a draft PR, publication is the final implementation step: + +```bash +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" +``` + +The helper uses the configured App, not the signed-in human. It refuses staged or selected `.github/workflows/**` paths before token minting; a human publishes workflow changes. See [ONBOARDING.md](ONBOARDING.md), [POLICY.md](POLICY.md), and [ROLES.md](ROLES.md) for installation scope, grants, and required GitHub protections. No machine configuration is performed by this document. \ No newline at end of file diff --git a/docs/POLICY.md b/docs/POLICY.md index 87599e1..a9be7f4 100644 --- a/docs/POLICY.md +++ b/docs/POLICY.md @@ -82,38 +82,38 @@ 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. 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. +[agent-pr.mjs](../scripts/agent-pr.mjs) requires coder `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 `merger.merge` in the local and reviewed default-branch policy; coder `merge` alone is insufficient. It has no `--role` or `--policy` override. The role check does not identify or switch the App credential: the helper still uses the supplied `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH`. -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. +Before token minting, it refuses staged or specified root-policy changes and staged or selected `.github/workflows/**` paths; workflow changes require human publication and the coder App needs no Workflows permission. After App authentication, it reads root policy from origin's default branch and requires its grants to match the local policy. It 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 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. +The 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. ## 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: +**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.merger.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] + allow: [commit_branch, open_pr, comment, label] merger: - allow: [] + allow: [merge] 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. +This is a human-reviewed opt-in, not the default example. Coder `merge` alone does not authorize the flag. Agents must not edit, stage, or commit the active policy to enable it. The local, committed, and reviewed default-branch policy must agree; the helper rechecks local and reviewed policy while waiting and immediately before merging. A policy role is not an App identity check. The trusted launcher/operator must keep `--merge-when-green` disabled on coder-only WSL and use a separately approved merger App/context; the helper does not provision or switch keys. -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. +The human must also accept **Checks: read-only** on the configured App installation. The manifest includes it, but normal publishing requests only contents/pull requests write on its repository-scoped token; the flag additionally requests `checks: read`. The repository must permit merge commits and permit the configured 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/load-agent-policy.mjs --role merger --capability merge node scripts/agent-pr.mjs --message "fix: validate input" --merge-when-green --files README.md ``` @@ -125,9 +125,9 @@ When the check is green, the helper may mark a draft PR ready, then rereads its 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. +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. After confirmed merge it fetches origin with App auth, checks out the default branch, fast-forwards it, and deletes the local feature ref only if the worktree is clean and the ref still points to the published head included in the merge, not the generated merge commit. Dirty state, missing or conflicting work, or branch movement aborts local cleanup without discarding work. Never reset, clean, force-delete, or delete unrelated branches. Report a partial result rather than claiming full success. The remote 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. +On failure, the published commit and PR can remain, and a timed-out flow may have marked a draft ready. Inspect the PR and both remote and local branches 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. See [ROLES.md](ROLES.md) for credential separation. ## Limits diff --git a/docs/ROLES.md b/docs/ROLES.md index 1804096..a0ad9c8 100644 --- a/docs/ROLES.md +++ b/docs/ROLES.md @@ -5,16 +5,16 @@ Use separate, user/org-owned GitHub Apps for **coder**, **merger**, and **deploy | Role | Intended authority | Default state | | --- | --- | --- | | Coder | Commit unprotected feature branches, open draft PRs, request comments and labels | Only the four explicit grants in the example policy | -| Merger | A possible future, separately reviewed merge executor | Empty allow-list; humans merge | +| Merger | Policy gate for an explicitly authorized merge; separate App/context required by the operator | Empty allow-list; humans merge by default | | Deploy | A possible future executor behind approved environment gates | Empty allow-list; no deployments | -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. +Only one publication helper exists in this pack. Do not provision or distribute merger/deploy keys merely because role names appear in the example. Any opt-in merge needs a separately approved merger App/context and human authorization without bypassing branch or environment protections; deploy execution remains outside this pack. -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. +The optional [merge-when-green flow](POLICY.md#opt-in-merge) requires coder `commit_branch` and `open_pr` for publication and `merger.merge` in local and reviewed default-branch policy for merge. A grant only under `coder.merge` is insufficient. This is a policy gate, not proof of key custody: the helper still uses the supplied `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH`; it neither provisions nor switches to a merger key. The trusted launcher/operator must disable `--merge-when-green` on coder-only WSL and use a separately approved merger App/context for merging. 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. 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. +The manifest specifies Metadata read, Checks read-only, and Contents, Issues, Pull requests read-write. 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. A human must accept the permission change on existing installations. Keep repositories explicitly selected and retain required human reviews and merge controls. Staged or selected `.github/workflows/**` paths are refused before token minting and published by humans; the coder App needs no Workflows permission. 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. @@ -22,11 +22,11 @@ Merger and deploy Apps, if ever approved, must have only the permissions their i ## WSL orchestration host -The WSL orchestration box holds **only the coder App key**, stored outside the checkout and supplied to an approved publishing process. It must not hold a merger key, deploy key, production cloud credential, or a human token used as a fallback. Do not mount or forward those credentials into WSL from another host, a secret store, or an agent's environment. +The WSL orchestration box holds **only the coder App key**, stored outside the checkout and supplied to an approved publishing process. It must not hold a merger key, deploy key, production cloud credential, or a human token used as a fallback. Do not mount or forward those credentials into WSL from another host, a secret store, or an agent's environment. See [ORCHESTRATION-MACHINE.md](ORCHESTRATION-MACHINE.md) for the machine boundary. The trusted launcher fixes the publisher to the coder App and coder role. Do not let an agent change the key path or select a more privileged App. Prefer separate execution identities and an isolated publication context over giving every harness process the key. A process that can read a key can mint tokens within that App's installations; a role label cannot prevent that. -Future merger/deploy execution belongs in separately controlled environments, with separate credentials released only after the applicable human and GitHub gates. No WSL orchestration service or hosted control plane is added here. +Merger/deploy execution belongs in separately controlled environments, with separate credentials released only after the applicable human and GitHub gates. No WSL orchestration service or hosted control plane is added here. ## Human-owned policy diff --git a/docs/app-manifest.json b/docs/app-manifest.json index 320f193..0554c23 100644 --- a/docs/app-manifest.json +++ b/docs/app-manifest.json @@ -11,6 +11,7 @@ "request_oauth_on_install": false, "default_permissions": { "metadata": "read", + "checks": "read", "contents": "write", "issues": "write", "pull_requests": "write" diff --git a/docs/github-app-agent-identity.md b/docs/github-app-agent-identity.md index e4f3a8e..24aa047 100644 --- a/docs/github-app-agent-identity.md +++ b/docs/github-app-agent-identity.md @@ -10,7 +10,7 @@ Git author/committer fields that copy a human hide provenance. GitHub Apps creat Start with [ONBOARDING.md](ONBOARDING.md) and [app-manifest.json](app-manifest.json), using a unique account-specific name ending in `-agent-coder`. Register under the user or organization that owns the repositories. The template is private (`public: false`, Only on this account), with webhooks inactive, no events, and no user OAuth. -The manifest requests metadata read and contents, issues, and pull requests write for feature-branch publication and approved outputs. Omit issues write when unused. It grants no administration, secrets, workflows, or organization-member permissions. Keep read-only agent/MCP tokens separate from publication credentials. +The manifest requests repository permissions Metadata read, Checks read-only, and Contents, Issues, and Pull requests read-write for feature-branch publication, optional merge checks, and approved outputs. Omit Issues write when unused. It grants no Administration, Secrets, Workflows, Actions, or Deployments permissions. A human must accept the Checks permission change for an existing installation before using opt-in merge. Keep read-only agent/MCP tokens separate from publication credentials. Choose **Only select repositories** at installation. GitHub does not support a manifest field for that selection. Start with one repository and separate unrelated trust boundaries. @@ -62,11 +62,11 @@ The publication helper currently makes explicitly unsigned Git commits. Its sign ## Publication -Creating a local commit does not authorize a push. Default GitHub writes are approved safe outputs: comments, labels, and draft PRs. Any separately authorized branch publication must use a repository-scoped installation token, must not force-push, and must leave merging to a human. +Creating a local commit does not authorize a push. Default GitHub writes are approved safe outputs: comments, labels, and draft PRs. Any separately authorized branch publication must use a repository-scoped installation token and must not force-push. Human-only merge is the default; the explicitly authorized, policy-gated `--merge-when-green` flow is the exception. -For authorized publication, use [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) as described in the [commit skill](../skills/signed-bot-commit/SKILL.md). It loads `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` from the environment, verifies origin's installation, derives that App's bot identity, and mints a token with contents and pull requests write for that repository only. It adds `AI-Agent: ` and `AI-Model: unknown` unless `--model` is supplied. No `.env` loading, token display, global Git identity changes, or human-token fallback is provided. +For authorized publication, use [scripts/agent-pr.mjs](../scripts/agent-pr.mjs) as described in the [commit skill](../skills/signed-bot-commit/SKILL.md). It loads `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` from the environment, verifies origin's installation, derives that App's bot identity, and mints a token with contents and pull requests write for that repository only; the merge flag additionally requests Checks read. It adds `AI-Agent: ` and `AI-Model: unknown` unless `--model` is supplied. No `.env` loading, token display, global Git identity changes, or human-token fallback is provided. Staged or selected `.github/workflows/**` paths are refused before token minting; humans publish workflow changes. -Require the `check-agent-trailers` PR check and protected-branch rules with no direct agent pushes or bypass. Pull requests write is not a draft-only permission; humans must retain merge authority. A passing trailer check is not authentication of the Git author or a substitute for those rules. +Require the `check-agent-trailers` PR check and protected-branch rules with no direct agent pushes or bypass. Pull requests write is not a draft-only permission; keep human review and branch rules even for opt-in merge. A passing trailer check is not authentication of the Git author or a substitute for those rules. The policy's `merger.merge` gate does not select an App credential; a trusted launcher/operator must disable merge on coder-only WSL and use a separately approved merger App/context. ## What this repo provides diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs index c793819..c5d9938 100644 --- a/scripts/agent-pr.mjs +++ b/scripts/agent-pr.mjs @@ -157,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("Use --merge-when-green only with an approved coder merge grant. Protected pushes and deploys are unsupported."); + throw new AgentPrError("Use --merge-when-green only with an approved merger merge grant. Protected pushes and deploys are unsupported."); } else { throw new AgentPrError("Unknown argument; use --help for usage."); } @@ -276,7 +276,7 @@ export async function publishAgentPr(options, { const policy = loadPolicy({ cwd }); requireCapability(policy, "coder", "commit_branch"); requireCapability(policy, "coder", "open_pr"); - if (options.mergeWhenGreen) requireCapability(policy, "coder", "merge"); + if (options.mergeWhenGreen) requireCapability(policy, "merger", "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) { @@ -321,17 +321,20 @@ export async function publishAgentPr(options, { } invoke("gh", ["--version"], "GitHub CLI availability check"); const readStaged = () => git(["diff", "--cached", "--name-only", "--no-renames", "-z"], "Staged-file lookup").split("\0").filter(Boolean); - const rejectPolicyChanges = (changes) => { + const rejectHumanOwnedChanges = (changes) => { if (changes.some((file) => file.toLowerCase() === "agent-policy.yml")) { throw new AgentPrError("Agents cannot publish changes to root agent-policy.yml; a human must review and publish policy changes."); } + if (changes.some((file) => file.replaceAll("\\", "/").toLowerCase().startsWith(".github/workflows/"))) { + throw new AgentPrError("A human must publish changes under .github/workflows/; the coder App does not request Workflows permission."); + } }; const checkIndex = () => { const indexed = git(["ls-files", "--cached", "-z"], "Index lookup").split("\0").filter(Boolean); for (const file of indexed) safeFile(file, cwd, privateKeyPath); }; const files = [...new Set((options.files ?? []).map((file) => safeFile(file, cwd, privateKeyPath)))]; - rejectPolicyChanges(files); + rejectHumanOwnedChanges(files); for (const file of files) { try { if (lstatSync(resolve(cwd, file)).isDirectory()) { @@ -344,7 +347,7 @@ export async function publishAgentPr(options, { } } const staged = readStaged(); - rejectPolicyChanges(staged); + rejectHumanOwnedChanges(staged); checkIndex(); for (const file of staged) safeFile(file, cwd, privateKeyPath); if (files.length && staged.some((file) => !files.includes(file))) { @@ -391,7 +394,7 @@ export async function publishAgentPr(options, { 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"); + if (options.mergeWhenGreen) requireCapability(approvedPolicy, "merger", "merge"); const verifyApprovedPolicy = (candidate) => { for (const role of Object.keys(approvedPolicy.roles)) { const approved = approvedPolicy.roles[role].allow; @@ -419,7 +422,7 @@ export async function publishAgentPr(options, { git(["add", "--", ...files], "Staging selected files", { env: { ...baseEnv, GIT_LITERAL_PATHSPECS: "1" } }); } const selected = readStaged(); - rejectPolicyChanges(selected); + rejectHumanOwnedChanges(selected); checkIndex(); for (const file of selected) safeFile(file, cwd, privateKeyPath); if (!selected.length || (files.length && selected.some((file) => !files.includes(file)))) { @@ -447,25 +450,24 @@ export async function publishAgentPr(options, { } const committedFiles = git(["ls-tree", "-r", "--name-only", "-z", "HEAD"], "Committed file verification").split("\0").filter(Boolean); for (const file of committedFiles) safeFile(file, cwd, privateKeyPath); - rejectPolicyChanges(git(["diff-tree", "--root", "--no-commit-id", "--no-renames", "--name-only", "-r", "-z", actual[0]], "Committed policy-change verification").split("\0").filter(Boolean)); + rejectHumanOwnedChanges(git(["diff-tree", "--root", "--no-commit-id", "--no-renames", "--name-only", "-r", "-z", actual[0]], "Committed human-owned file verification").split("\0").filter(Boolean)); verifyApprovedPolicy(parseAgentPolicy(git(["show", `${actual[0]}:agent-policy.yml`], "Committed policy verification"))); await checkProtectedBranch(); checkBranch(); const header = `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`; - git(["push", "--no-follow-tags", pushUrl, `${actual[0]}:refs/heads/${branch}`], "Branch push", { - env: { - ...baseEnv, - GIT_CONFIG_COUNT: "8", - GIT_CONFIG_KEY_0: "credential.helper", GIT_CONFIG_VALUE_0: "", - GIT_CONFIG_KEY_1: "core.askPass", GIT_CONFIG_VALUE_1: "", - GIT_CONFIG_KEY_2: "http.extraHeader", GIT_CONFIG_VALUE_2: "", - GIT_CONFIG_KEY_3: `http.${pushUrl}.extraHeader`, GIT_CONFIG_VALUE_3: "", - GIT_CONFIG_KEY_4: `http.${pushUrl}.extraHeader`, GIT_CONFIG_VALUE_4: header, - GIT_CONFIG_KEY_5: "http.followRedirects", GIT_CONFIG_VALUE_5: "false", - GIT_CONFIG_KEY_6: "protocol.allow", GIT_CONFIG_VALUE_6: "never", - GIT_CONFIG_KEY_7: "protocol.https.allow", GIT_CONFIG_VALUE_7: "always", - }, - }); + const authenticatedEnv = { + ...baseEnv, + GIT_CONFIG_COUNT: "8", + GIT_CONFIG_KEY_0: "credential.helper", GIT_CONFIG_VALUE_0: "", + GIT_CONFIG_KEY_1: "core.askPass", GIT_CONFIG_VALUE_1: "", + GIT_CONFIG_KEY_2: "http.extraHeader", GIT_CONFIG_VALUE_2: "", + GIT_CONFIG_KEY_3: `http.${pushUrl}.extraHeader`, GIT_CONFIG_VALUE_3: "", + GIT_CONFIG_KEY_4: `http.${pushUrl}.extraHeader`, GIT_CONFIG_VALUE_4: header, + GIT_CONFIG_KEY_5: "http.followRedirects", GIT_CONFIG_VALUE_5: "false", + GIT_CONFIG_KEY_6: "protocol.allow", GIT_CONFIG_VALUE_6: "never", + GIT_CONFIG_KEY_7: "protocol.https.allow", GIT_CONFIG_VALUE_7: "always", + }; + git(["push", "--no-follow-tags", pushUrl, `${actual[0]}:refs/heads/${branch}`], "Branch push", { env: authenticatedEnv }); 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."); @@ -486,10 +488,10 @@ export async function publishAgentPr(options, { const pullNumber = candidates[0].number; const checkMergePolicy = async () => { const currentPolicy = loadPolicy({ cwd }); - requireCapability(currentPolicy, "coder", "merge"); + requireCapability(currentPolicy, "merger", "merge"); verifyApprovedPolicy(currentPolicy); const currentReviewedPolicy = await readReviewedPolicy(repoPath, repository.default_branch, token, fetchImpl); - requireCapability(currentReviewedPolicy, "coder", "merge"); + requireCapability(currentReviewedPolicy, "merger", "merge"); verifyApprovedPolicy(currentReviewedPolicy); }; await waitForGreenPullRequest({ @@ -504,6 +506,7 @@ export async function publishAgentPr(options, { throw new AgentPrError("GitHub did not confirm a successful merge; the feature branch was not deleted."); } merged = true; + result = { ...result, merged: true, pullRequest: pullNumber, mergeCommit: mergeResult.sha, remoteBranchDeleted: false }; await checkProtectedBranch(); const reference = await githubRequest(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`, token, { fetchImpl, allowMissing: true }); if (reference !== undefined) { @@ -512,11 +515,32 @@ export async function publishAgentPr(options, { } await githubRequest(`${repoPath}/git/refs/heads/${encodeURIComponent(branch)}`, token, { method: "DELETE", fetchImpl }); } - result = { ...result, merged: true, pullRequest: pullNumber, mergeCommit: mergeResult.sha, remoteBranchDeleted: true }; + result = { ...result, remoteBranchDeleted: true }; + const checkLocalCleanup = (expectedBranch) => { + if (git(["symbolic-ref", "--quiet", "--short", "HEAD"], "Local branch verification").trim() !== expectedBranch || + git(["rev-parse", "--verify", `refs/heads/${branch}^{commit}`], "Feature branch verification").trim() !== actual[0]) { + throw new AgentPrError("The local branch or published feature SHA changed; local cleanup was stopped."); + } + if (git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], "Worktree cleanliness verification")) { + throw new AgentPrError("The worktree has staged, unstaged, or untracked changes; local cleanup was stopped."); + } + }; + checkLocalCleanup(branch); + git(["fetch", "--no-tags", pushUrl, `refs/heads/${repository.default_branch}:refs/remotes/origin/${repository.default_branch}`], "Default branch fetch", { env: authenticatedEnv }); + checkLocalCleanup(branch); + git(["switch", "--", repository.default_branch], "Default branch checkout"); + checkLocalCleanup(repository.default_branch); + git(["merge", "--ff-only", `refs/remotes/origin/${repository.default_branch}`], "Default branch fast-forward"); + checkLocalCleanup(repository.default_branch); + git(["merge-base", "--is-ancestor", actual[0], "HEAD"], "Merged feature ancestry verification"); + git(["update-ref", "-d", `refs/heads/${branch}`, actual[0]], "Local feature branch deletion"); + result = { ...result, localBranchDeleted: true, checkedOutBranch: repository.default_branch }; } } catch (error) { const detail = error instanceof AgentPrError || error instanceof AgentPolicyError ? error.message : "Publication failed; details were withheld to protect credentials."; - 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." : ""; + const state = merged + ? ` PR #${result.pullRequest} was merged; ${result.remoteBranchDeleted ? "the remote feature branch was removed, but local cleanup is incomplete." : "remote-branch cleanup may be incomplete."} Inspect the branch state before retrying.` + : committed ? " The local commit remains; do not create a duplicate commit to retry." : ""; failure = new AgentPrError(`${detail}${state}`); } finally { try { @@ -547,9 +571,11 @@ 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 pushes main. ---merge-when-green additionally requires coder.merge in local and reviewed policy, +--merge-when-green additionally requires merger.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. +After remote deletion it fetches origin with the App token, fast-forwards the local +default branch, and deletes the unchanged local feature branch only if clean. 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. `); @@ -559,7 +585,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`); + if (result.merged) stdout.write(`Merged PR #${result.pullRequest} with a merge commit, removed its remote and local feature branches, and checked out ${result.checkedOutBranch}.\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 d049c7a..4e6596d 100644 --- a/skills/agent-policy/SKILL.md +++ b/skills/agent-policy/SKILL.md @@ -29,19 +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, 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. +The publisher has no role/policy override, protected-push, or deploy implementation. It refuses staged or selected `.github/workflows/**` changes before token minting; a human must publish workflows. 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. +A **human** must allow `merge` in root `agent-policy.yml` before the flag works. In this format, that means adding `merge` to `roles.merger.allow` and publishing the grant on the default branch, not adding a literal `merge: allow` field. Coder `merge` alone is insufficient. Never make this policy change yourself. The policy role is not credential selection: the helper still uses the supplied App ID and key path. Keep merge disabled on coder-only WSL; a trusted launcher/operator must use a separately approved merger App/context. ```bash -node scripts/load-agent-policy.mjs --role coder --capability merge +node scripts/load-agent-policy.mjs --role merger --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. +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. After a confirmed merge the helper deletes only the unchanged remote feature branch, then fetches origin with App auth, checks out and fast-forwards the default branch, and removes the local feature ref only if still clean and at the published head. Otherwise report partial cleanup without discarding work. See `docs/POLICY.md` for wait limits and 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 9200a70..106784d 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -13,10 +13,10 @@ 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**. 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. +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 `merger.merge` in local and reviewed default-branch policy and human authorization for merge and branch cleanup; coder `merge` alone is insufficient. 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. +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 finish after tests with uncommitted changes, 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 and refuses staged or selected `.github/workflows/**` paths before token minting. A human must publish workflow changes; the coder App needs no Workflows permission. Run `node --test tests/*.test.mjs` before publishing. With authorization and all gates passed, invoke the helper as the final implementation step. 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 @@ -48,26 +48,26 @@ To stage and commit named files, put `--files` last: node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --files README.md AGENTS.md ``` -`--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. +`--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. Only the merge flag adds Checks read to the token request. 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. +Before this flag works, a **human must allow merge in `agent-policy.yml`** by adding `merge` to `roles.merger.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: +The configured App also needs Checks read-only permission, and the repository must allow merge commits without bypass. The role check does not prove which App key is loaded: the helper uses `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH`, with no role override or automatic key switch. A trusted launcher/operator must keep merge disabled on coder-only WSL and use a separately approved merger App/context. After explicit human authorization for publication, merge, and branch cleanup in that context: ```bash -node scripts/load-agent-policy.mjs --role coder --capability merge +node scripts/load-agent-policy.mjs --role merger --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. +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. After confirmed merge it fetches origin with App auth, checks out the default branch, fast-forwards it, and deletes the local feature ref only if the worktree is clean and that ref still points to the published head included in the merge (not the generated merge commit). Missing or conflicting work, a moved ref, or dirty state aborts local cleanup without reset, clean, force deletion, or unrelated branch deletion. Report partial cleanup. No squash, rebase merge, direct push to main, force push, or GitHub auto-merge is used. Without the flag, publication never merges, even if policy allows it. ## Failure handling -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. +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; cleanup can leave a merged PR with remote or local feature refs intact. 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. diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs index 2834a23..82f189e 100644 --- a/tests/agent-pr.test.mjs +++ b/tests/agent-pr.test.mjs @@ -242,13 +242,29 @@ 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 () => { +test("workflow files in the index or explicit paths require human publication before key or token access", async () => { + for (const file of [".github/workflows/check-agent-trailers.yml", ".github/workflows/nested/ci.yml"]) { + for (const options of [{}, { files: [file] }]) { + const mock = mockPublication({ staged: [file] }); + await assert.rejects(publishAgentPr({ message: "feat: helper", ...options }, mock.dependencies), /A human must publish changes under \.github\/workflows\//); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.requests.length, 0); + assert.ok(!mock.commands.some((call) => call.args[0] === "add" || call.args.includes("commit") || call.args[0] === "push")); + } + } + const explicit = mockPublication({ staged: ["README.md"] }); + await assert.rejects(publishAgentPr({ message: "feat: helper", files: [".github/workflows/new.yml"] }, explicit.dependencies), /A human must publish/); + assert.equal(explicit.keyReads(), 0); + assert.equal(explicit.requests.length, 0); +}); + +test("--merge-when-green is opt-in and requires the merger role even if coder.merge is granted", 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]")]) { + for (const source of [policySource, policySource.replace("comment, label", "comment, label, merge")]) { const mock = mockPublication(); mock.dependencies.loadPolicy = () => parseAgentPolicy(source); - await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies coder\.merge/); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies merger\.merge/); assert.equal(mock.keyReads(), 0); assert.equal(mock.commands.length, 0); assert.equal(mock.requests.length, 0); @@ -257,15 +273,15 @@ test("--merge-when-green is opt-in and requires the current coder role to allow 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/); + mock.dependencies.loadPolicy = () => parseAgentPolicy(policySource.replace(/merger:\r?\n allow: \[\]/, "merger:\n allow: [merge]")); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies merger\.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 source = policySource.replace(/merger:\r?\n allow: \[\]/, "merger:\n allow: [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 } }, @@ -280,6 +296,14 @@ function mockMergePublication({ draft = false, existing = true, checkRuns } = {} const originalRun = mock.dependencies.run; mock.dependencies.run = (command, args, options) => { if (command === "gh" && args[1] === "ready") pull.draft = false; + if (args[0] === "rev-parse" && args[1] === "--verify") return commitSha; + if (args[0] === "status") return ""; + if (["fetch", "switch", "merge", "merge-base", "update-ref"].includes(args[0])) { + mock.commands.push({ command, args, ...options }); + if (args[0] === "switch") mock.dependencies.runBranch = args.at(-1); + return ""; + } + if (args[0] === "symbolic-ref" && mock.dependencies.runBranch) return mock.dependencies.runBranch; const output = originalRun(command, args, options); return args[0] === "show" ? source : output; }; @@ -308,6 +332,8 @@ test("--merge-when-green merges a ready or draft PR by exact SHA and only then d const result = await publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies); assert.equal(result.merged, true); assert.equal(result.remoteBranchDeleted, true); + assert.equal(result.localBranchDeleted, true); + assert.equal(result.checkedOutBranch, "main"); assert.equal(result.mergeCommit, "b".repeat(40)); const merge = mock.requests.find((call) => call.url.endsWith("/pulls/7/merge")); assert.equal(merge.method, "PUT"); @@ -318,6 +344,13 @@ test("--merge-when-green merges a ready or draft PR by exact SHA and only then d 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)); + const fetch = mock.commands.find((call) => call.args[0] === "fetch"); + assert.deepEqual(fetch.args, ["fetch", "--no-tags", "https://github.com/example-owner/example-repo.git", "refs/heads/main:refs/remotes/origin/main"]); + assert.equal(fetch.env.GIT_CONFIG_VALUE_4, mock.commands.find((call) => call.args[0] === "push").env.GIT_CONFIG_VALUE_4); + assert.deepEqual(mock.commands.filter((call) => ["switch", "merge", "merge-base", "update-ref"].includes(call.args[0])).map((call) => call.args), [ + ["switch", "--", "main"], ["merge", "--ff-only", "refs/remotes/origin/main"], + ["merge-base", "--is-ancestor", commitSha, "HEAD"], ["update-ref", "-d", "refs/heads/feat/bot-helper", commitSha], + ]); 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"))); @@ -325,6 +358,73 @@ test("--merge-when-green merges a ready or draft PR by exact SHA and only then d } }); +test("local cleanup stops on staged, unstaged, or untracked worktree changes", async () => { + for (const dirt of ["M staged.txt\0", " M unstaged.txt\0", "?? untracked.txt\0"]) { + const mock = mockMergePublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => args[0] === "status" ? dirt : originalRun(command, args, options); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /PR #7 was merged; the remote feature branch was removed, but local cleanup is incomplete/); + assert.ok(!mock.commands.some((call) => ["fetch", "switch", "merge", "update-ref"].includes(call.args[0]))); + assert.equal(mock.requests.at(-1).url, "https://api.github.com/installation/token"); + } +}); + +test("local cleanup stops if the feature SHA changes after the authenticated fetch", async () => { + const mock = mockMergePublication(); + const originalRun = mock.dependencies.run; + let fetched = false; + mock.dependencies.run = (command, args, options) => { + if (args[0] === "fetch") fetched = true; + if (fetched && args[0] === "rev-parse" && args[1] === "--verify") return "c".repeat(40); + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /published feature SHA changed; local cleanup was stopped.*PR #7 was merged/); + assert.ok(mock.commands.some((call) => call.args[0] === "fetch")); + assert.ok(!mock.commands.some((call) => ["switch", "merge", "update-ref"].includes(call.args[0]))); +}); + +test("local cleanup stops if the checked-out branch changes during the fetch", async () => { + const mock = mockMergePublication(); + const originalRun = mock.dependencies.run; + let fetched = false; + mock.dependencies.run = (command, args, options) => { + if (args[0] === "fetch") fetched = true; + if (fetched && args[0] === "symbolic-ref") return "feat/another-task"; + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /local branch or published feature SHA changed; local cleanup was stopped.*PR #7 was merged/); + assert.ok(mock.commands.some((call) => call.args[0] === "fetch")); + assert.ok(!mock.commands.some((call) => ["switch", "merge", "update-ref"].includes(call.args[0]))); +}); + +test("a failed fast-forward retains the local feature branch and reports the merged PR", async () => { + const mock = mockMergePublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + if (args[0] === "merge") throw new Error(access.token); + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), (error) => { + assert.match(error.message, /Default branch fast-forward failed.*PR #7 was merged; the remote feature branch was removed, but local cleanup is incomplete/); + assert.ok(!error.message.includes(access.token)); + return true; + }); + assert.ok(mock.commands.some((call) => call.args[0] === "switch")); + assert.ok(!mock.commands.some((call) => call.args[0] === "update-ref")); +}); + +test("an advanced feature ref cannot be deleted after the final SHA check", async () => { + const mock = mockMergePublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + if (args[0] === "update-ref") throw new Error("ref changed while deleting"); + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /Local feature branch deletion failed.*PR #7 was merged; the remote feature branch was removed, but local cleanup is incomplete/); + assert.ok(mock.commands.some((call) => call.args[0] === "merge-base")); + 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 }] }); @@ -392,7 +492,7 @@ test("--merge-when-green respects a merge grant revoked while waiting", async () await originalWait(duration); revoked = true; }; - await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies coder\.merge/); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies merger\.merge/); assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge"))); }); @@ -404,7 +504,7 @@ test("--merge-when-green revalidates the reviewed merge grant immediately before 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/); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /policy denies merger\.merge/); assert.ok(mock.requests.some((call) => call.url.includes("/check-runs?"))); assert.ok(!mock.requests.some((call) => call.url.endsWith("/merge"))); }); @@ -429,7 +529,7 @@ test("--merge-when-green preserves a branch that advanced after the confirmed me 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/); + await assert.rejects(publishAgentPr({ message: "feat: helper", mergeWhenGreen: true }, mock.dependencies), /PR #7 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/"))); }); @@ -571,7 +671,7 @@ test("the onboarding manifest is owner-only with explicit minimal permissions an assert.equal(manifest.public, false); assert.equal(manifest.request_oauth_on_install, false); assert.deepEqual(manifest.default_permissions, { - metadata: "read", contents: "write", issues: "write", pull_requests: "write", + metadata: "read", contents: "write", issues: "write", pull_requests: "write", checks: "read", }); assert.deepEqual(manifest.default_events, []); assert.equal(manifest.hook_attributes.active, false); @@ -653,6 +753,7 @@ test("help needs no environment or key and does not publish", async () => { assert.equal(await main(["--help"], { env: {}, stdout: { write: (text) => output.push(text) } }), 0); assert.match(output.join(""), /GITHUB_APP_PRIVATE_KEY_PATH/); assert.match(output.join(""), /--files/); + assert.match(output.join(""), /merger\.merge/); }); test("missing environment and an empty index fail before key access or network calls", async () => {