From 863b9d8581ded4503237ffe9f0ffc2c9e2874304 Mon Sep 17 00:00:00 2001 From: "r4yharris-agent-coder[bot]" <334673250+r4yharris-agent-coder[bot]@users.noreply.github.com> Date: Sun, 27 Sep 2026 20:40:40 -0400 Subject: [PATCH] feat: agent-pr, onboarding, and harness contracts AI-Agent: r4yharris-agent-coder AI-Model: unknown --- .env.example | 7 +- .github/copilot-instructions.md | 14 +- AGENTS.md | 22 + CLAUDE.md | 3 + README.md | 29 +- docs/DAY1_SCOPE.md | 2 +- docs/HARNESSES.md | 27 + docs/ONBOARDING.md | 68 +++ docs/THREAT_MODEL.md | 47 ++ docs/adopt.md | 8 +- docs/app-manifest.json | 19 + docs/github-app-agent-identity.md | 37 +- .../workflows/check-agent-trailers.yml | 2 +- scripts/agent-pr.mjs | 414 ++++++++++++++++ skills/signed-bot-commit/SKILL.md | 58 ++- tests/agent-pr.test.mjs | 462 ++++++++++++++++++ 16 files changed, 1171 insertions(+), 48 deletions(-) create mode 100644 CLAUDE.md create mode 100644 docs/HARNESSES.md create mode 100644 docs/ONBOARDING.md create mode 100644 docs/THREAT_MODEL.md create mode 100644 docs/app-manifest.json create mode 100644 scripts/agent-pr.mjs create mode 100644 tests/agent-pr.test.mjs diff --git a/.env.example b/.env.example index a9ba5b4..46c87fc 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ -# Non-secret identifiers only. Never add tokens or private keys here. -APP_ID= -APP_INSTALLATION_ID= +# Configuration names only. Supply values through the environment, not this file. +# The publisher does not load .env automatically. Never add key contents or tokens. +GITHUB_APP_ID= +GITHUB_APP_PRIVATE_KEY_PATH= diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 22d6003..2133f52 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -6,5 +6,17 @@ This workspace is **github-agent-contracts** only. - Edit no paths outside this repository. - Do not request or embed credentials. - Prefer Node 20 ESM scripts with zero dependencies. -- Agent commits in *other* consumer repos should use trailers from `docs/commit-trailers.md`. Commits *to this repo* during bootstrap may be human-authored without trailers. +- 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. +- 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. +- 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. +- Run tests first. On a missing prerequisite or failed publication, stop rather than falling back to raw Git; a partial failure can leave a valid local commit. Commits are unsigned, so do not invoke the helper when signing is required. - Keep examples scoped: GitHub App installation tokens, MCP tool allowlists, `permissions: read-all` plus explicit safe-outputs. + +Authorized publication example: + +```bash +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown --files README.md +``` diff --git a/AGENTS.md b/AGENTS.md index 2e8b96a..81a3f06 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,6 +23,25 @@ Reusable conventions and small tools so Copilot, GitHub Agentic Workflows (`gh-a - 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. +## Agent publication + +- 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. +- 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. +- 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. +- 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 +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown --files README.md +``` + ## Day-1 build targets Implement what `docs/DAY1_SCOPE.md` lists. Prefer small, tested files. @@ -34,6 +53,9 @@ Implement what `docs/DAY1_SCOPE.md` lists. Prefer small, tested files. node scripts/check-agent-trailers.mjs --help node scripts/check-agent-trailers.mjs --message-file path/to/msg.txt +# Publication help only; this does not read a key or contact GitHub +node scripts/agent-pr.mjs --help + # Tests node --test tests/*.test.mjs ``` diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f7aef7f --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,3 @@ +# Repository instructions + +Follow [AGENTS.md](AGENTS.md) for all repository rules and required skills. \ No newline at end of file diff --git a/README.md b/README.md index 718f59e..a27101b 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,27 @@ # github-agent-contracts -GitHub-native contracts for coding agents. **GitHub stays the repository host.** This library does not replace Git, GitHub, or an orchestrator. +GitHub-native contracts for attributable agent commits and PRs, distinct from human-authored work. **GitHub stays the repository host.** The control is a required PR check, a protected branch, bot authorship, and machine-checked trailers. The App is how agents authenticate to GitHub. This is community OSS for GitHub, not a GitHub replacement. +## Enable agent identity in 3 steps + +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 signed-bot-commit skill, publisher, and check Action/workflow as listed in [ONBOARDING.md](docs/ONBOARDING.md). 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." + +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. + +### Demo App + +`r4yharris-agent-coder` is an optional maintainer demo identity for **public playground repositories only**. Do not install it on private or production repositories or grant it protected-branch bypass. A globally shared maintainer App is not this standard's production onboarding model. + +## Shared contracts + Use it so Copilot, [GitHub Agentic Workflows](https://github.com/github/gh-aw), Hermes, Codex, Cursor, and similar tools share one repo-level convention: | Contract | Where | @@ -21,13 +39,16 @@ Humans can review the same rules agents follow, while commit trailers make claim ## Consume the contracts -- **Copilot / VS Code:** keep [AGENTS.md](AGENTS.md) at the repository root and [.github/copilot-instructions.md](.github/copilot-instructions.md) in place. Copy selected `skills//` directories into `.github/skills/` in the consuming repository for skill discovery in supported versions. +- **Copilot / VS Code:** use [AGENTS.md](AGENTS.md) and [.github/copilot-instructions.md](.github/copilot-instructions.md) only as harness configuration. They reference the common commit skill and publisher; no additional agent mode or skill autodiscovery setup is required. +- **Claude Code:** use the short [CLAUDE.md](CLAUDE.md) pointer to AGENTS.md, not a duplicate policy. - **gh-aw:** include the repository rules and relevant skills in the workflow's instructions. Start with the [issue clarifier source](.github/workflows-src/issue-clarifier.md); the agent is read-only and can request only an `add-comment` safe output. - **Hermes, Codex, and other agents:** load `AGENTS.md` as repository instructions and import the selected `SKILL.md` files using that runtime's skill mechanism. Discovery paths differ by runtime; this pack does not patch those runtimes. - **GitHub MCP:** use the [allowlist skill](skills/github-mcp-allowlist/SKILL.md) with a repository-scoped GitHub App installation token. Keep the agent's tools read-only; give approved output handlers only the capabilities they need. Adapt the workspace-specific names in the instruction files when adopting the pack. Human approval, scoped permissions, and tool restrictions enforce boundaries; prompts alone do not. +See [HARNESSES.md](docs/HARNESSES.md) for the minimal integration in each runtime. Any agent that honors AGENTS.md must honor signed-bot-commit. + ## Use in another repo Follow the [adoption guide](docs/adopt.md) and copy the [consumer workflow](examples/consumer-repo/.github/workflows/check-agent-trailers.yml). Reference the pinned public Action without copying scripts, or vendor the Action and both scripts together. No package registry or GitHub App credentials are needed for the trailer check. @@ -59,7 +80,7 @@ AI-Model: unknown The default checks messages containing `AI-Agent:` and GitHub noreply bot authors. Human privacy addresses alone do not trigger a check. For local author detection, pass `--author-email`; `--require` checks every message. Exit codes are `0` (pass), `1` (missing trailers), and `2` (usage or input error). -See the [trailer spec](docs/commit-trailers.md) for parsing rules, limitations, and the Action's `require-on-all-commits: "true"` option. +See the [trailer spec](docs/commit-trailers.md) for parsing rules and the Action's `require-on-all-commits: "true"` option. The [threat model](docs/THREAT_MODEL.md) explains why trailers and bot fields do not prove authorship, and why unsigned human commits pass the default check. ## PR workflow @@ -81,6 +102,8 @@ Review the generated workflow and configure the chosen engine's authentication o From the local repository root, after creating an empty GitHub repository: +These bootstrap commands are for a **human**. Agents must use the App-authenticated publication helper and never assume the human's identity. + ```bash git init -b main git add . diff --git a/docs/DAY1_SCOPE.md b/docs/DAY1_SCOPE.md index 7d71618..accb7bb 100644 --- a/docs/DAY1_SCOPE.md +++ b/docs/DAY1_SCOPE.md @@ -15,7 +15,7 @@ Build only this. Stop when the checklist is green. - `skills/github-mcp-allowlist/SKILL.md` - `skills/pr-safe-outputs/SKILL.md` 8. One `gh-aw` **source** workflow: `.github/workflows-src/issue-clarifier.md` (read-all, `safe-outputs.add-comment` only). -9. `.env.example` listing names of env vars only (`APP_ID`, `APP_INSTALLATION_ID`, empty values). +9. `.env.example` listing names of env vars only (`GITHUB_APP_ID`, `GITHUB_APP_PRIVATE_KEY_PATH`, empty values). ## Out diff --git a/docs/HARNESSES.md b/docs/HARNESSES.md new file mode 100644 index 0000000..d652bf0 --- /dev/null +++ b/docs/HARNESSES.md @@ -0,0 +1,27 @@ +# Harnesses + +The common contract is [AGENTS.md](../AGENTS.md), which requires [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. + +## Copilot + +Use **AGENTS.md + .github/copilot-instructions.md only** as the Copilot configuration. The Copilot file points to the common repository rules, and those rules point to the commit skill and publisher. No custom agent mode, extra prompt file, or MCP server is required for publishing. + +The referenced skill file and scripts must still be present. Do not rely on harness-specific skill autodiscovery to enforce the common contract, and do not duplicate a competing publication policy in another Copilot configuration. + +## Claude Code + +Keep [CLAUDE.md](../CLAUDE.md) as a short pointer to AGENTS.md. Claude Code reads that pointer, then follows the same commit skill and publishing script. Do not copy the full policy into both files or add Claude-specific credentials. + +## Hermes + +Load AGENTS.md as repository instructions and [skills/signed-bot-commit/SKILL.md](../skills/signed-bot-commit/SKILL.md) as the publication skill 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). + +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. + +## Generic agents + +If you honor **AGENTS.md**, you honor **signed-bot-commit**. Read the referenced skill and invoke the same helper after 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 diff --git a/docs/ONBOARDING.md b/docs/ONBOARDING.md new file mode 100644 index 0000000..92e7ae2 --- /dev/null +++ b/docs/ONBOARDING.md @@ -0,0 +1,68 @@ +# Enable agent identity in 3 steps + +Use an App **you or your organization own**. The security control is a required PR check plus a protected branch, bot authorship, and provenance trailers. The App authenticates publication; installing it alone does not enforce that control. + +## 1. Register your App + +Browser entry point: **[Register App from manifest](app-manifest.json)**. Use a unique name ending in `-agent-coder`, create it under the account or organization that owns the repositories, and keep it private: **Only on this account**. On GitHub's installation screen, choose **Only select repositories**, starting with one repository. + +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. + +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). + +## 2. Configure and copy + +Provide exactly two environment variables to the approved publisher: + +| Variable | Value supplied by the operator | +| --- | --- | +| `GITHUB_APP_ID` | The App ID from your registration, not a bot user ID | +| `GITHUB_APP_PRIVATE_KEY_PATH` | An absolute path to the private key stored outside the repository | + +No installation ID or bot name is needed. The helper discovers the installation for `origin`, verifies its App ID, and resolves that App's bot account. It does not load `.env` or use the signed-in human's token as a fallback. Never paste PEM contents, installation tokens, or client secrets into chat or tracked files. + +For CI, keep the App ID in a configuration variable and the key in the **`GITHUB_APP_PRIVATE_KEY` secret**. An operator-controlled credential step must materialize it in a restricted runner-temporary file outside the checkout, set `GITHUB_APP_PRIVATE_KEY_PATH`, and remove it afterward. The helper reads the path, not the raw CI secret. Do not expose it to fork PRs or untrusted jobs. The PR trailer-check workflow needs **no App secret**. + +Copy these files into the consuming repository, preserving paths and merging existing rules rather than overwriting them: + +```text +AGENTS.md +skills/signed-bot-commit/SKILL.md +scripts/agent-pr.mjs +scripts/check-agent-trailers.mjs +scripts/check-pr-agent-trailers.mjs +.github/actions/check-agent-trailers/action.yml +.github/workflows/check-agent-trailers.yml +``` + +Use Node 20+, Git, and `gh` for publication. Adapt the workspace name and test command in the copied rules. Follow [HARNESSES.md](HARNESSES.md) for the small harness-specific pointers, and [adopt.md](adopt.md) for the pinned public-Action alternative and vendoring details. No private-package infrastructure or runtime dependency installation is needed. + +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. + +## 3. Protect the branch and publish + +After a successful trial PR run, configure branch protection or a ruleset for `main` (and any other protected integration branch): + +- 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. + +Tell the agent: + +> Use signed-bot-commit / scripts/agent-pr.mjs for all publish. Never publish as the signed-in human, print tokens, or merge. Stop if App authentication 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. + +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. + +## Manifest flow follow-on + +The future registration button needs an operator-controlled manifest receiver, not a centrally owned App: + +1. POST the JSON as the `manifest` form parameter to `https://github.com/settings/apps/new`, or `https://github.com/organizations/YOUR_ORG/settings/apps/new` for an organization. Include an unpredictable `state` bound to the initiating session. The user reviews the name and creates their own App in GitHub. +2. GitHub redirects to the operator's `redirect_url` with a short-lived code. Validate `state` and keep the code out of logs and chat. +3. Within one hour, the operator's trusted service exchanges it at `POST /app-manifests/{code}/conversions`. The response contains the App ID and sensitive material, including the PEM and client secret. Deliver needed material only to the owner's secret store; never return or log it in public pages. Client secrets are not used by this publisher. + +The `example.invalid` callback and disabled-webhook URLs are deliberately nonfunctional placeholders. This repository ships no callback handler, hosted registration endpoint, secret storage, or client-secret management. Anyone operating the callback can see generated key material, so App ownership alone is insufficient if an untrusted service handles registration. \ No newline at end of file diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md new file mode 100644 index 0000000..a25fe16 --- /dev/null +++ b/docs/THREAT_MODEL.md @@ -0,0 +1,47 @@ +# Threat model + +## Purpose and control + +This pack is a GitHub-native attribution standard for agent commits and PRs, distinct from human-authored work. Its intended control is **required PR check + protected branch + bot author + trailers**. A GitHub App authenticates API calls and pushes; it is not the security policy or a replacement for branch protection. + +The repository owner must enable the required `check-agent-trailers` check, protect integration branches against direct updates and bypass, review agent PRs, and reserve merges for humans. The owner must also trust the reviewed checker, publisher, runner, and harness. A prompt is not an enforcement boundary against a malicious agent or operator. + +## App ownership + +Default onboarding uses [the manifest](app-manifest.json) to create an App owned by the consuming user or organization. Keep it private to that account and install it on selected repositories only. Separate Apps or keys across unrelated trust boundaries. + +**The App private key holder can mint installation tokens for every installation of that App**, up to each installation's permissions and repository access. A short token lifetime or this helper's narrower token request does not limit what a stolen App key can mint independently. Giving a third-party App access to a private repository delegates access to whoever controls that App's keys. + +A single App owned by this project's maintainer is therefore **out of scope for production onboarding**, especially third-party private repositories. Do not recommend installing `r4yharris-agent-coder` there. An optional maintainer demo App is for **public playground repositories only**, with no sensitive data and with selected-repository scope. Public repositories still have write-integrity risks; the demo owner must not receive branch-protection bypass or merge authority. + +Manifest callbacks are also a trust boundary: the code-conversion response includes a private key and client secret. Use an owner-controlled registration service, not a maintainer callback that can retain another organization's credentials. No such service is implemented here. + +## What is enforced + +| Layer | Enforcement | +| --- | --- | +| PR check | Reads all commits in the PR range and fails on missing required trailers for classified agent commits, invalid ranges, or incomplete history. Classification is an `AI-Agent:` marker or a GitHub noreply bot author address; require-all mode includes human commits. | +| Publisher | Authenticates with the configured App, discovers and verifies its bot account, sets author and committer to that bot, and adds `AI-Agent: ` and `AI-Model`. It verifies the committed identity and trailers before pushing. | +| Token scope | The helper requests contents and pull requests write for origin's single repository, keeps credentials out of arguments and output, and attempts revocation when finished. Read-only agent/MCP access should use separate read-only tokens. | +| Branch rules | A required check can block merging only when the owner configures protection without agent bypass. Human-only protected-branch updates and approval prevent direct agent publication to the integration branch. | + +The check reads Git metadata; it does not contact the App or prove who signed a push. In particular, a message-marked commit with a human email can pass if its trailers are valid: **the publisher enforces bot author/committer; the trailer check alone does not**. Keep all four controls and review unexpected identities. + +Use the pinned public Action or the vendored checker's trusted-base checkout. Never run PR-supplied publisher code with the App key, and never give the trailer-check job that key. Protect workflow and contract changes with human review; a PR must not be allowed to disable its own guardrail unnoticed. + +## What is not enforced + +- **A malicious human or privileged maintainer:** Git author fields and trailers can be forged. Someone who can bypass or rewrite repository rules, approve malicious changes, or use the App key can defeat this policy. There is no cryptographic proof that an agent, human, or named model produced particular code. +- **A stolen PEM:** An attacker can act within any reachable installation's scope. Removing one installation or rotating only an installation token does not invalidate a stolen App private key. Revoke the affected App key, revoke active tokens, audit installations and changes, and rotate credentials through an authorized operator. +- **Unsigned human commits:** They pass the default check when unmarked and not bot-authored. Require-all mode requires trailers, not signatures or proof of bot identity. The helper's Git commits are unsigned too; signed JWTs do not give them a Verified badge. Repositories requiring signed commits need a supported signing implementation before using this helper. +- **Code safety or approval quality:** Passing trailers do not prove correctness, safe dependencies, absence of secrets, or a real human review. The publisher's path checks are not a general secret scanner, and publishing existing branch history still requires review. +- **A compromised runner, harness, or local configuration:** A process able to read the App key or short-lived token is inside the credential trust boundary. Environment variables and local files are not isolation from that process. Keep write-capable credentials in an approved publishing context, not an unrestricted agent sandbox. +- **Draft-only API permissions:** GitHub's contents and pull requests write permissions can authorize more than this helper does, including merges when repository rules permit them. The script's refusal to merge is not a narrower token permission. Enforce the human merge gate in repository rules as well. + +## Permissions and recovery + +The onboarding manifest requests metadata read, contents write for feature-branch pushes, pull requests write for draft PRs, and issues write for approved comment/label outputs. Remove issues write when unused. It grants no administration, secrets, workflows, or organization-member access, subscribes to no events, and leaves webhooks inactive. Repository selection is a human installation choice, not a supported manifest field. + +Never commit PEM contents, tokens, real client secrets, or populated `.env` files. An App key is long-lived; protect it outside the checkout or in approved CI secrets. Scope installations to selected repositories, grant no agent bypass, and restrict trusted publishing jobs and their logs. + +On authentication or publication failure, stop without a human-token fallback. A local commit or pushed branch may already exist: inspect it and the PR before retrying. Token revocation can fail, so rely on expiry only as a fallback, not as proof that a compromised key is contained. \ No newline at end of file diff --git a/docs/adopt.md b/docs/adopt.md index 8d4a7cb..83c5abe 100644 --- a/docs/adopt.md +++ b/docs/adopt.md @@ -2,12 +2,14 @@ Choose a pinned public Action or vendor the Action and its scripts. Both options use ordinary GitHub files and Actions: no package registry, private-package infrastructure, GitHub App credentials, or custom secrets are required for the trailer check. +For the complete bot-identity standard, start with [ONBOARDING.md](ONBOARDING.md): register your own App from the manifest, configure the publisher, and protect the branch. This page covers the check's distribution options, not registration of a shared maintainer App. + ## Reference the public Action 1. Review the [consumer workflow](../examples/consumer-repo/.github/workflows/check-agent-trailers.yml) and copy it to `.github/workflows/check-agent-trailers.yml` in the consuming repository. Merge with any existing workflow instead of overwriting it blindly. 2. Keep `actions/checkout` pointed at the **consumer repository** with `fetch-depth: 0` and `persist-credentials: false`. The Action needs its complete PR history, not a checkout of this pack. 3. Keep the pack's `uses:` reference pinned to a reviewed, full commit SHA. The example references `R4yHarris/github-agent-contracts` at a revision containing the Action and both scripts. Review changes before updating the pin; do not switch to a moving `main` reference for convenience. -4. Enable Actions in the consumer and ensure its Actions policy permits `actions/checkout` and the referenced public Action. After a successful PR run, a human can make the trailer job a required check in repository rules. +4. Enable Actions in the consumer and ensure its Actions policy permits `actions/checkout` and the referenced public Action. After a successful PR run, a human must require the `check-agent-trailers` job in protected-branch rules for the standard to be enforced. GitHub downloads the referenced pack revision separately from the consumer checkout. The composite Action finds its scripts relative to `github.action_path`, while the runner inspects Git history in the consumer's working directory. **This option does not require copying `scripts/` into the consumer.** It also does not install a local trailer-checking CLI there. @@ -74,6 +76,6 @@ Before requiring the check, verify a PR with valid trailers passes and a marked ## Adopt the other contracts - Merge the relevant rules from [AGENTS.md](../AGENTS.md) and [Copilot instructions](../.github/copilot-instructions.md) into the consumer's instructions. Replace this pack's hard-coded workspace name, bootstrap exceptions, file references, and commands with the consumer's own rules. Do not overwrite existing policies. -- Import selected [skills](../skills/) through the consuming agent's supported discovery mechanism. For supported Copilot / VS Code versions, copy skill directories into `.github/skills/`. Read-only MCP allowlists and approved safe outputs still apply; enabling the trailer check grants no GitHub write permissions. -- GitHub App identity is optional for installing this check. Follow the [identity guide](github-app-agent-identity.md) only when an operator separately provisions an App. Do not create credential files or invent credentials as part of adoption. +- Copy the [commit skill](../skills/signed-bot-commit/SKILL.md) referenced by AGENTS.md and follow [HARNESSES.md](HARNESSES.md) for the minimal harness pointers. Copilot configuration is AGENTS.md plus its Copilot instructions; no additional skill-autodiscovery configuration is required. Read-only MCP allowlists and approved safe outputs still apply. +- GitHub App identity is optional for installing the trailer check alone, but required for App-authenticated agent publication. Follow the [identity guide](github-app-agent-identity.md) and manifest-first onboarding to provision a user/org-owned App, not a maintainer App for private repositories. Do not create credential files or invent credentials as part of adopting the files. - The [issue clarifier](../.github/workflows-src/issue-clarifier.md) is optional and independent of trailer checking. Keep it as Markdown source unless `gh aw` is already available; do not handwrite compiled lockfiles or install `gh-aw` as part of this adoption procedure. \ No newline at end of file diff --git a/docs/app-manifest.json b/docs/app-manifest.json new file mode 100644 index 0000000..320f193 --- /dev/null +++ b/docs/app-manifest.json @@ -0,0 +1,19 @@ +{ + "name": "YOUR-ACCOUNT-agent-coder", + "url": "https://github.com/R4yHarris/github-agent-contracts", + "description": "User-owned GitHub App for attributable agent commits and reviewed pull requests.", + "public": false, + "hook_attributes": { + "url": "https://example.invalid/github/webhook", + "active": false + }, + "redirect_url": "https://example.invalid/app-manifest/callback", + "request_oauth_on_install": false, + "default_permissions": { + "metadata": "read", + "contents": "write", + "issues": "write", + "pull_requests": "write" + }, + "default_events": [] +} \ No newline at end of file diff --git a/docs/github-app-agent-identity.md b/docs/github-app-agent-identity.md index d9a7d54..e4f3a8e 100644 --- a/docs/github-app-agent-identity.md +++ b/docs/github-app-agent-identity.md @@ -1,27 +1,28 @@ # GitHub App agent identity -Give each agent role its own GitHub App so commits and API calls are not your human account. +Use a GitHub App owned by the consuming user or organization so agent commits and API calls are distinct from the signed-in human. The App authenticates to GitHub; the security control is the required PR check, protected branch, bot author, and trailers. ## Why Git author/committer fields that copy a human hide provenance. GitHub Apps create a `slug[bot]` identity, the same pattern Dependabot uses. -## Day-1 setup (manual, outside this repo) +## Manifest-first setup -1. Open GitHub Settings, Developer settings, GitHub Apps, then New GitHub App. -2. Name it for a **role**, not a person: `agent-coder`, `agent-reviewer`. -3. Homepage URL can be this repository. -4. Webhook: inactive for day 1. -5. Start with repository contents, pull requests, issues, and metadata **read-only**. Leave unrelated permissions disabled. -6. Install the App on **one selected repository**, not all repositories. -7. Record its App ID and installation ID as `APP_ID` and `APP_INSTALLATION_ID`. The [.env.example](../.env.example) template contains only empty, non-secret identifiers. -8. Keep the App private key in an approved secret manager outside the checkout. Do not put it in git, an agent prompt, or an MCP config. +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. -For an approved safe-output handler, grant only the needed write permission: issues for comments or labels, pull requests for draft PRs. Keep those write-capable credentials out of the read-only agent process. Contents write is unnecessary for the issue clarifier; any separate branch-publication setup needs explicit human authorization. Never grant administration or repository deletion. +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. + +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. + +The file uses placeholder callback URLs, not a live registration endpoint. [GitHub's manifest flow](https://docs.github.com/en/apps/sharing-github-apps/registering-a-github-app-from-a-manifest) requires a trusted receiver to exchange the temporary registration code for App configuration. Owner-controlled callback hosting is a follow-on. Until it exists, an owner can manually register with the template's settings. Never send conversion responses or generated secrets to a public page or chat. + +Supply only `GITHUB_APP_ID` and `GITHUB_APP_PRIVATE_KEY_PATH` to the publisher. Keep the key outside the checkout. In CI, use `GITHUB_APP_PRIVATE_KEY` as an approved secret and materialize it outside the checkout through a trusted credential step. The helper discovers the installation and bot IDs; neither is another environment input. It does not load `.env` or use client secrets. + +Do not install a project-maintainer App on third-party private repositories. The private key holder can mint tokens for all installations of that App, regardless of this helper's narrower request. `r4yharris-agent-coder` is optional only for public playground demos, never the recommended production App. See [THREAT_MODEL.md](THREAT_MODEL.md). ## Git identity for commits -Resolve the actual App slug and bot user ID (`GET /users/slug[bot]`); the bot user ID is not the App ID. Use that identity for both the author and committer of new agent commits: +The publisher resolves the actual App slug from origin's authenticated installation and the bot user ID from `GET /users/slug[bot]`. It verifies the returned login and bot type; the bot user ID is not the App ID. It uses that identity for both the author and committer: ```text user.name slug[bot] @@ -30,11 +31,11 @@ user.email ID+slug[bot]@users.noreply.github.com Use repository-local or per-command Git settings, not global changes. Do not impersonate the supervising human or fabricate a bot user ID. Add the [required provenance trailers](commit-trailers.md); `Co-authored-by` can credit a human without changing the bot identity. -This repository permits human-authored bootstrap commits under its own instructions. That exception does not authorize agents to assume a human identity in consumer repositories. +This repository permits humans to author bootstrap commits themselves. Agents must use [the publication helper](../scripts/agent-pr.mjs), never a human identity or raw Git publication commands, including during bootstrap. ## Installation tokens -An operator or trusted credential service signs a short-lived App JWT outside the agent workspace, then requests `POST /app/installations/{APP_INSTALLATION_ID}/access_tokens`. Restrict the request to the selected repository and read-only agent permissions, for example: +An approved publisher or credential service signs a short-lived App JWT, discovers the repository installation, then requests `POST /app/installations/{installation_id}/access_tokens`. Restrict each token to the selected repository and its task. Read-only agent/MCP access uses permissions such as: ```json { @@ -57,12 +58,16 @@ The caller must enforce the approved owner and repository on every tool call. An Unsigned Git commits are acceptable for day 1 unless a consumer repository requires signing. Bot author fields and trailers do not produce a GitHub **Verified** signature and are not cryptographic proof of identity. -For an explicitly unsigned commit, use `git -c commit.gpgsign=false commit` with the bot identity and a checked message. SSH signing may be used when an operator has already provisioned an approved signing key and verification policy outside this repository. Do not generate keys here, reuse an App private key for Git signing, or bypass a consumer's signing requirement. +The publication helper currently makes explicitly unsigned Git commits. Its signed App JWT authenticates API calls, not the Git commit. Do not invoke it if a consumer requires signing; an operator must first arrange supported signing without bypassing that policy. Do not generate keys here or reuse an App private key for Git signing. ## 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. +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. + +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. + ## What this repo provides -Documentation, skills, and a local Git-based trailer checker. It does not register Apps, mint tokens, manage keys, or schedule agents. +Documentation, skills, local Git-based trailer checks, and an explicitly authorized App-authenticated publication helper. It does not register Apps, provision keys, or schedule agents. diff --git a/examples/consumer-repo/.github/workflows/check-agent-trailers.yml b/examples/consumer-repo/.github/workflows/check-agent-trailers.yml index 5a1f295..711d73f 100644 --- a/examples/consumer-repo/.github/workflows/check-agent-trailers.yml +++ b/examples/consumer-repo/.github/workflows/check-agent-trailers.yml @@ -8,7 +8,7 @@ permissions: jobs: trailers: - name: Agent commit trailers + name: check-agent-trailers runs-on: ubuntu-latest steps: - name: Check out consumer history diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs new file mode 100644 index 0000000..14e1ee9 --- /dev/null +++ b/scripts/agent-pr.mjs @@ -0,0 +1,414 @@ +#!/usr/bin/env node + +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 { pathToFileURL } from "node:url"; +import { checkMessage } from "./check-agent-trailers.mjs"; + +class AgentPrError extends Error {} + +export function createAppJwt(appId, privateKey, now = Date.now()) { + if (!/^[1-9][0-9]*$/.test(String(appId))) { + throw new AgentPrError("GITHUB_APP_ID must be a numeric App ID."); + } + try { + const key = privateKey instanceof KeyObject ? privateKey : createPrivateKey(privateKey); + if (key.type !== "private" || key.asymmetricKeyType !== "rsa") { + throw new Error("RSA private key required"); + } + const seconds = Math.floor(now / 1000); + const header = Buffer.from(JSON.stringify({ alg: "RS256", typ: "JWT" })).toString("base64url"); + const payload = Buffer.from(JSON.stringify({ + iat: seconds - 60, + exp: seconds + 540, + iss: String(appId), + })).toString("base64url"); + const input = `${header}.${payload}`; + return `${input}.${sign("RSA-SHA256", Buffer.from(input), key).toString("base64url")}`; + } catch { + throw new AgentPrError("Could not sign the App JWT; check the private key outside chat."); + } +} + +async function githubRequest(path, token, { method = "GET", body, fetchImpl = globalThis.fetch } = {}) { + let response; + try { + response = await fetchImpl(`https://api.github.com${path}`, { + method, + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + "User-Agent": "github-agent-contracts", + "X-GitHub-Api-Version": "2022-11-28", + }, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: "error", + signal: AbortSignal.timeout(30_000), + }); + } catch { + throw new AgentPrError("GitHub API request failed; check connectivity and authentication."); + } + if (!response.ok) { + throw new AgentPrError(`GitHub API request failed (HTTP ${Number(response.status)}).`); + } + if (response.status === 204) return null; + try { + return await response.json(); + } catch { + throw new AgentPrError("GitHub returned an invalid JSON response."); + } +} + +export async function mintInstallationToken( + { appId, privateKey, owner, repository }, + { fetchImpl = globalThis.fetch, now = Date.now() } = {}, +) { + const jwt = createAppJwt(appId, privateKey, now); + const repoPath = `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repository)}`; + const installation = await githubRequest(`${repoPath}/installation`, jwt, { fetchImpl }); + if ( + !Number.isSafeInteger(installation?.id) || installation.id <= 0 || + String(installation.app_id) !== String(appId) || + typeof installation.app_slug !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(installation.app_slug) || + installation.suspended_at + ) { + throw new AgentPrError("The repository needs an active installation matching GITHUB_APP_ID."); + } + const access = await githubRequest(`/app/installations/${installation.id}/access_tokens`, jwt, { + method: "POST", + body: { repositories: [repository], permissions: { contents: "write", pull_requests: "write" } }, + fetchImpl, + }); + if ( + typeof access?.token !== "string" || !access.token || /\s/.test(access.token) || + !Number.isFinite(Date.parse(access.expires_at)) || Date.parse(access.expires_at) <= now + ) { + throw new AgentPrError("GitHub did not return a valid, unexpired installation token."); + } + return { token: access.token, appSlug: installation.app_slug }; +} + +export function parseOrigin(origin) { + let url; + try { + url = new URL(origin.startsWith("git@github.com:") + ? `ssh://git@github.com/${origin.slice("git@github.com:".length)}` + : origin); + } catch { + throw new AgentPrError("origin must be a GitHub HTTPS or SSH repository URL."); + } + if ( + url.hostname !== "github.com" || !["https:", "ssh:"].includes(url.protocol) || + url.password || url.port || url.search || url.hash || + (url.protocol === "https:" ? url.username : url.username !== "git") + ) { + throw new AgentPrError("origin must use github.com without embedded credentials."); + } + const match = /^\/([A-Za-z0-9-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(url.pathname); + if (!match || [".", ".."].includes(match[2])) { + throw new AgentPrError("origin must identify exactly one GitHub owner and repository."); + } + return { owner: match[1], repository: match[2] }; +} + +function validateCommitInput(message, model = "unknown") { + if (typeof message !== "string" || !message.trim() || message.includes("\0")) { + throw new AgentPrError("Provide a nonempty commit message with --message."); + } + if (typeof model !== "string" || !model.trim() || /[\r\n\0]/.test(model)) { + throw new AgentPrError("--model must be a nonempty single-line value."); + } +} + +export function buildCommitMessage(message, model = "unknown", appSlug) { + validateCommitInput(message, model); + if (typeof appSlug !== "string" || !/^[a-z0-9][a-z0-9-]*$/.test(appSlug)) { + throw new AgentPrError("A verified App slug is required for the AI-Agent trailer."); + } + return `${message.replace(/\r\n/g, "\n").trim()}\n\nAI-Agent: ${appSlug}\nAI-Model: ${model.trim()}\n`; +} + +export function parseArgs(argv) { + const options = { model: "unknown", files: [] }; + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (argument === "--help" || argument === "-h") { + options.help = true; + } else if (argument === "--files") { + options.files = argv.slice(index + 1); + if (!options.files.length || options.files.some((file) => file.startsWith("--"))) { + throw new AgentPrError("--files must be last and followed by literal file paths."); + } + break; + } else if (argument === "--message" || argument === "-m" || argument === "--model") { + const value = argv[++index]; + if (value === undefined || value.startsWith("--")) { + throw new AgentPrError("--message and --model each need a value."); + } + options[argument === "--model" ? "model" : "message"] = value; + } else { + throw new AgentPrError("Unknown argument; use --help for usage."); + } + } + if (!options.help) validateCommitInput(options.message, options.model); + return options; +} + +function safeFile(file, cwd, privateKeyPath) { + if (typeof file !== "string" || !file || file.includes("\0")) { + throw new AgentPrError("Only literal repository file paths may be committed."); + } + const absolute = resolve(cwd, file); + const local = relative(cwd, absolute).split(sep).join("/"); + const parts = local.toLowerCase().split("/"); + const name = parts.at(-1); + if (!local || isAbsolute(local) || local === ".." || local.startsWith("../") || parts.includes(".git")) { + throw new AgentPrError("Files must stay inside this repository and outside .git."); + } + if ( + (name === ".env" || (name.startsWith(".env.") && name !== ".env.example")) || + /\.(pem|key|p12|pfx)$/i.test(name) || relative(absolute, privateKeyPath) === "" + ) { + throw new AgentPrError("Refusing to commit an environment file or private-key path."); + } + return local; +} + +function commandEnvironment(env) { + const clean = Object.fromEntries(Object.entries(env).filter(([name]) => + !/^(GIT_|GH_|GITHUB_APP_)/i.test(name) && + !/^(GITHUB_TOKEN|GITHUB_ENTERPRISE_TOKEN|SSH_ASKPASS|NODE_OPTIONS)$/i.test(name) + )); + return { ...clean, GIT_TERMINAL_PROMPT: "0", GH_PROMPT_DISABLED: "1", GH_HOST: "github.com" }; +} + +function runCommand(command, args, options) { + return execFileSync(command, args, { + ...options, + encoding: "utf8", + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, + }); +} + +export async function publishAgentPr(options, { + cwd = process.cwd(), + env = process.env, + fetchImpl = globalThis.fetch, + readPrivateKey = (path) => readFileSync(path), + run = runCommand, + now = Date.now(), +} = {}) { + 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) { + throw new AgentPrError("Set GITHUB_APP_ID and GITHUB_APP_PRIVATE_KEY_PATH in the environment; never paste the key into chat."); + } + const privateKeyPath = resolve(cwd, env.GITHUB_APP_PRIVATE_KEY_PATH); + const baseEnv = commandEnvironment(env); + const invoke = (command, args, operation, extra = {}) => { + try { + return run(command, args, { cwd, env: baseEnv, ...extra }); + } catch { + throw new AgentPrError(`${operation} failed; command output was withheld to protect credentials.`); + } + }; + const git = (args, operation, extra) => invoke("git", args, operation, extra); + const root = git(["rev-parse", "--show-toplevel"], "Repository lookup").trim(); + if (relative(root, cwd) !== "") throw new AgentPrError("Run agent-pr.mjs from the repository root."); + const branch = git(["symbolic-ref", "--quiet", "--short", "HEAD"], "Current branch lookup").trim(); + if (!branch || ["main", "master"].includes(branch)) { + throw new AgentPrError("Use a feature branch, not main, master, or a detached HEAD."); + } + const checkBranch = () => { + if (git(["symbolic-ref", "--quiet", "--short", "HEAD"], "Current branch verification").trim() !== branch) { + throw new AgentPrError("The current branch changed during publication; refusing to continue."); + } + }; + const origin = parseOrigin(git(["remote", "get-url", "origin"], "origin lookup").trim()); + const pushOrigins = git(["remote", "get-url", "--push", "--all", "origin"], "origin push URL lookup").trim().split(/\r?\n/); + if (pushOrigins.length !== 1 || JSON.stringify(parseOrigin(pushOrigins[0])) !== JSON.stringify(origin)) { + throw new AgentPrError("origin must fetch from and push to the same single GitHub repository."); + } + const slug = `${origin.owner}/${origin.repository}`; + const pushUrl = `https://github.com/${slug}.git`; + const gitConfig = git(["config", "--null", "--list"], "Git transport configuration lookup"); + for (const entry of gitConfig.split("\0").filter(Boolean)) { + const separator = entry.indexOf("\n"); + const name = entry.slice(0, separator); + const value = entry.slice(separator + 1); + if (/^url\..*\.(?:insteadof|pushinsteadof)$/i.test(name) && value && pushUrl.startsWith(value)) { + throw new AgentPrError("A Git URL rewrite would change the authenticated push destination; refusing publication."); + } + } + 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 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)))]; + for (const file of files) { + try { + if (lstatSync(resolve(cwd, file)).isDirectory()) { + throw new AgentPrError("--files accepts individual files, not directories."); + } + } catch (error) { + if (error.code !== "ENOENT") { + throw new AgentPrError("--files accepts readable individual file paths, not directories."); + } + } + } + const staged = readStaged(); + checkIndex(); + for (const file of staged) safeFile(file, cwd, privateKeyPath); + if (files.length && staged.some((file) => !files.includes(file))) { + throw new AgentPrError("Unrelated files are already staged; unstage them or omit --files to use the reviewed index."); + } + if (!files.length && !staged.length) throw new AgentPrError("Stage reviewed changes or supply --files before publishing."); + + let key; + let token; + let appSlug; + try { + try { + key = readPrivateKey(privateKeyPath); + } 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 })); + } finally { + if (Buffer.isBuffer(key)) key.fill(0); + key = undefined; + } + + const repoPath = `/repos/${encodeURIComponent(origin.owner)}/${encodeURIComponent(origin.repository)}`; + let result; + let failure; + let committed = false; + try { + const botName = `${appSlug}[bot]`; + const bot = await githubRequest(`/users/${encodeURIComponent(botName)}`, token, { fetchImpl }); + if (!Number.isSafeInteger(bot?.id) || bot.id <= 0 || bot.login !== botName || bot.type !== "Bot") { + throw new AgentPrError("GitHub did not return the bot identity for the configured App; refusing to publish."); + } + const botEmail = `${bot.id}+${botName}@users.noreply.github.com`; + const message = buildCommitMessage(options.message, options.model, appSlug); + const repository = await githubRequest(repoPath, token, { fetchImpl }); + if ( + repository?.full_name?.toLowerCase() !== slug.toLowerCase() || + typeof repository.default_branch !== "string" || !repository.default_branch || repository.archived + ) { + 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."); + checkBranch(); + if (files.length) { + git(["add", "--", ...files], "Staging selected files", { env: { ...baseEnv, GIT_LITERAL_PATHSPECS: "1" } }); + } + const selected = readStaged(); + checkIndex(); + for (const file of selected) safeFile(file, cwd, privateKeyPath); + if (!selected.length || (files.length && selected.some((file) => !files.includes(file)))) { + throw new AgentPrError("The staged changes are empty or no longer match the selected files."); + } + git(["-c", `user.name=${botName}`, "-c", `user.email=${botEmail}`, "-c", "commit.gpgsign=false", "commit", "--file=-"], "Bot commit", { + input: message, + env: { + ...baseEnv, + GIT_AUTHOR_NAME: botName, + GIT_AUTHOR_EMAIL: botEmail, + GIT_COMMITTER_NAME: botName, + GIT_COMMITTER_EMAIL: botEmail, + }, + }); + committed = true; + const actual = git(["log", "-1", "--format=%H%x00%an%x00%ae%x00%cn%x00%ce%x00%B"], "Committed identity verification").split("\0"); + const checked = checkMessage(actual[5] ?? "", true); + if ( + !/^[0-9a-f]{40}$/i.test(actual[0]) || actual[1] !== botName || actual[2] !== botEmail || + actual[3] !== botName || actual[4] !== botEmail || !checked.ok || + checked.trailers["AI-Agent"] !== appSlug || checked.trailers["AI-Model"] !== (options.model ?? "unknown").trim() + ) { + throw new AgentPrError("The new commit does not have the required bot identity and trailers; refusing to push."); + } + 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); + 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 pullRequests = await githubRequest(`${repoPath}/pulls?state=open&head=${encodeURIComponent(`${origin.owner}:${branch}`)}`, 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]; + const title = /^\[[^\]]+\] /.test(subject) ? subject : `[agent] ${subject.replace(/^[a-z]+(?:\([^)]+\))?!?:\s*/i, "")}`; + invoke("gh", [ + "pr", "create", "--repo", slug, "--head", branch, "--base", repository.default_branch, + "--draft", "--title", title, "--body", message, + ], "Draft pull-request creation", { env: { ...baseEnv, GH_TOKEN: token } }); + } + result = { commit: actual[0], botName, createdPullRequest: !pullRequests.length }; + } catch (error) { + const detail = error instanceof AgentPrError ? 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." : ""}`); + } finally { + try { + await githubRequest("/installation/token", token, { method: "DELETE", fetchImpl }); + } catch { + failure = new AgentPrError(`${failure?.message ?? "Publication completed."} Token revocation failed; it will expire automatically.`); + } + token = undefined; + } + if (failure) throw failure; + return result; +} + +export async function main(argv, { stdout = process.stdout, stderr = process.stderr, ...dependencies } = {}) { + let options; + try { + options = parseArgs(argv); + } catch (error) { + stderr.write(`${error instanceof AgentPrError ? error.message : "Invalid arguments."}\n`); + return 2; + } + if (options.help) { + stdout.write(`Usage: node scripts/agent-pr.mjs --message TEXT [--model NAME] [--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. +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. +An invocation authorizes commit, push, and PR creation. Keep secrets out of arguments. +`); + return 0; + } + try { + 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"); + return 0; + } catch (error) { + stderr.write(`${error instanceof AgentPrError ? error.message : "agent-pr failed; details were withheld to protect credentials."}\n`); + return 1; + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + process.exitCode = await main(process.argv.slice(2)); +} \ No newline at end of file diff --git a/skills/signed-bot-commit/SKILL.md b/skills/signed-bot-commit/SKILL.md index df47fde..30ab1c8 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -1,45 +1,63 @@ --- name: signed-bot-commit -description: Use when committing as an agent to set GitHub App bot author and committer identity, validate provenance trailers, and apply the repository signing policy. +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. --- # Signed bot commit +## Onboarding + +Use `docs/ONBOARDING.md` and `docs/app-manifest.json` to register an App owned by the consuming user or organization. Keep it private to that account and install it on selected repositories. The static manifest is not a hosted registration service; callback hosting is a follow-on controlled by the App owner. + +Never recommend the maintainer's `r4yharris-agent-coder` App for private or production repositories. It is an optional public-playground demo only. Whoever holds an App's private key can mint tokens for all of its installations; review `docs/THREAT_MODEL.md` before enabling access. + ## Do -1. Read `AGENTS.md` and resolve the real GitHub App bot identity using `docs/github-app-agent-identity.md`. Set both author and committer for new commits using per-command or repository-local Git settings. -2. Do not copy the supervising human’s name into `user.name`. -3. Append trailers from `docs/commit-trailers.md` and validate the message with `--require` before committing. -4. Follow the repository signing policy. Day 1 permits an explicitly unsigned commit; do not claim that a bot email or trailers create a verified signature. -5. Stop after the local commit unless a human has separately authorized publication. The default MCP allowlist does not provide Git push. Any approved publication uses a scoped installation token through an approved credential helper, never a token in a remote URL or command output. +1. Read `AGENTS.md` and confirm the human authorized **commit, push, and draft PR creation**. 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 a feature branch. The helper uses only origin's repository, refuses default-branch publication, and never force-pushes or merges. Require `check-agent-trailers` and human approval on protected branches, grant the App no bypass, and leave merging to humans. -## Commit template +## Identity and trailers -``` - +The helper verifies that origin's active installation matches `GITHUB_APP_ID`, then resolves `[bot]` from GitHub and verifies its login, bot type, and numeric user ID. Both author and committer use that account and `BOT_USER_ID+[bot]@users.noreply.github.com`. The bot user ID is not the App ID. No hard-coded maintainer identity or extra identity environment variables are needed. - +Pass a commit message without inventing credentials or manually changing Git's global configuration. The helper appends: -AI-Agent: -AI-Model: +```text +AI-Agent: +AI-Model: unknown ``` -## Local commit example +Use `--model` to replace `unknown` when the actual model is known. It checks the committed author, committer, trailers, and protected file paths before pushing the verified commit. + +## Usage + +With reviewed changes already staged: -Replace `APP_SLUG` and `BOT_USER_ID` with the verified, non-secret identity. This Bash example is for repositories that permit unsigned commits: +```bash +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model unknown +``` + +To stage and commit named files, put `--files` last: ```bash -node scripts/check-agent-trailers.mjs --require --message-file path/to/message.txt && -git -c user.name="APP_SLUG[bot]" \ - -c user.email="BOT_USER_ID+APP_SLUG[bot]@users.noreply.github.com" \ - -c commit.gpgsign=false commit --file path/to/message.txt +node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --files README.md AGENTS.md ``` -Use an operator-provisioned SSH signing key only when the repository requires or permits it. This skill does not create keys or change global Git configuration. +`--help` does not read the key or contact GitHub. Normal invocation signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. 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. + +## 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. + +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. -- Amend someone else’s commit. +- Amend someone else's commit. - Write tokens, App private keys, or signing keys into the repository. - Bypass a repository's signing or human-approval requirement. diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs new file mode 100644 index 0000000..a980ec5 --- /dev/null +++ b/tests/agent-pr.test.mjs @@ -0,0 +1,462 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { generateKeyPairSync, verify } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + buildCommitMessage, createAppJwt, main, + mintInstallationToken, parseArgs, parseOrigin, publishAgentPr, +} from "../scripts/agent-pr.mjs"; + +const AGENT = "example-org-agent"; +const BOT_NAME = `${AGENT}[bot]`; +const BOT_EMAIL = `789+${BOT_NAME}@users.noreply.github.com`; +const bot = { id: 789, login: BOT_NAME, type: "Bot" }; +const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const now = Date.UTC(2026, 8, 27, 12); +const installation = { id: 456, app_id: 123, app_slug: AGENT, suspended_at: null }; +const access = { token: "test-installation-token", expires_at: new Date(now + 3_600_000).toISOString() }; +const credentials = { appId: "123", privateKey, owner: "example-owner", repository: "example-repo" }; +const cwd = fileURLToPath(new URL("../", import.meta.url)); +const commitSha = "a".repeat(40); +const repository = { full_name: "example-owner/example-repo", default_branch: "main", archived: false }; + +function mockGitHub(responses) { + const calls = []; + const fetchImpl = async (url, options) => { + calls.push({ url, ...options }); + if (url === `https://api.github.com/users/${encodeURIComponent(BOT_NAME)}`) return Response.json(bot); + assert.ok(responses.length, "Unexpected GitHub request"); + const response = responses.shift(); + return response instanceof Response ? response : Response.json(response); + }; + return { calls, fetchImpl, now }; +} + +test("App JWT uses RS256, a backdated iat, and a short expiration", () => { + const jwt = createAppJwt("123", privateKey, now); + const [header, payload, signature] = jwt.split("."); + assert.deepEqual(JSON.parse(Buffer.from(header, "base64url")), { alg: "RS256", typ: "JWT" }); + assert.deepEqual(JSON.parse(Buffer.from(payload, "base64url")), { + iat: now / 1000 - 60, + exp: now / 1000 + 540, + iss: "123", + }); + assert.ok(verify("RSA-SHA256", Buffer.from(`${header}.${payload}`), publicKey, Buffer.from(signature, "base64url"))); +}); + +test("installation token is scoped to the origin repository and required write permissions", async () => { + const github = mockGitHub([installation, access]); + assert.deepEqual(await mintInstallationToken(credentials, github), { token: access.token, appSlug: AGENT }); + assert.deepEqual(github.calls.map((call) => [call.method, call.url]), [ + ["GET", "https://api.github.com/repos/example-owner/example-repo/installation"], + ["POST", "https://api.github.com/app/installations/456/access_tokens"], + ]); + assert.deepEqual(JSON.parse(github.calls[1].body), { + repositories: ["example-repo"], + permissions: { contents: "write", pull_requests: "write" }, + }); + assert.equal(github.calls[0].redirect, "error"); + assert.ok(github.calls[0].headers.Authorization.startsWith("Bearer ")); +}); + +test("a different or suspended App installation is rejected before minting a token", async () => { + for (const invalid of [ + { ...installation, app_slug: "invalid slug" }, + { ...installation, app_slug: undefined }, + { ...installation, app_id: 999 }, + { ...installation, suspended_at: new Date(now).toISOString() }, + ]) { + const github = mockGitHub([invalid]); + await assert.rejects(mintInstallationToken(credentials, github), /active installation/); + assert.equal(github.calls.length, 1); + } +}); + +test("JWT errors never include the supplied key material", () => { + assert.throws(() => createAppJwt("bad-id", privateKey, now), /numeric App ID/); + assert.throws( + () => createAppJwt("123", "test-private-material-must-not-be-printed", now), + { message: "Could not sign the App JWT; check the private key outside chat." }, + ); +}); + +test("GitHub error bodies and fetch exceptions are not exposed", async () => { + await assert.rejects(mintInstallationToken(credentials, { + now, + fetchImpl: async () => Response.json({ token: access.token }, { status: 403 }), + }), { message: "GitHub API request failed (HTTP 403)." }); + await assert.rejects(mintInstallationToken(credentials, { + now, + fetchImpl: async () => { throw new Error(access.token); }, + }), { message: "GitHub API request failed; check connectivity and authentication." }); +}); + +test("missing and expired installation tokens are rejected", async () => { + for (const invalid of [{ expires_at: access.expires_at }, { ...access, expires_at: new Date(now).toISOString() }]) { + await assert.rejects(mintInstallationToken(credentials, mockGitHub([installation, invalid])), /valid, unexpired installation token/); + } +}); + +function mockPublication({ branch = "feat/bot-helper", staged = ["README.md"], indexed = ["README.md", ".env.example"], pullRequests = [] } = {}) { + const github = mockGitHub([installation, access, repository, pullRequests, new Response(null, { status: 204 })]); + const commands = []; + let message; + let keyReads = 0; + const dependencies = { + ...github, + cwd, + env: { + GITHUB_APP_ID: "123", + GITHUB_APP_PRIVATE_KEY_PATH: "not-read.pem", + GIT_AUTHOR_NAME: "Human identity must not be used", + GIT_COMMITTER_EMAIL: "human@example.com", + GIT_TRACE: "1", + GIT_TRACE_CURL: "1", + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "credential.helper", + GIT_CONFIG_VALUE_0: "inherited-helper", + GH_TOKEN: "inherited-human-token", + GH_DEBUG: "api", + }, + readPrivateKey: () => { keyReads += 1; return privateKey; }, + run: (command, args, options) => { + commands.push({ command, args, ...options }); + if (command === "gh") return "suppressed command output"; + if (args[0] === "rev-parse") return cwd; + if (args[0] === "symbolic-ref") return branch; + if (args[0] === "remote") return "git@github.com:example-owner/example-repo.git\n"; + if (args[0] === "config") return ""; + if (args[0] === "diff") return staged.map((file) => `${file}\0`).join(""); + if (args[0] === "ls-files" || args[0] === "ls-tree") return indexed.map((file) => `${file}\0`).join(""); + if (args.includes("commit")) { message = options.input; return "commit output"; } + if (args[0] === "log") return [commitSha, BOT_NAME, BOT_EMAIL, BOT_NAME, BOT_EMAIL, message].join("\0"); + if (args[0] === "push" || args[0] === "add") return ""; + throw new Error("Unexpected command"); + }, + }; + return { dependencies, commands, requests: github.calls, keyReads: () => keyReads }; +} + +test("origin parsing supports GitHub SSH and HTTPS without exposing credentials", () => { + for (const origin of [ + "git@github.com:example-owner/example-repo.git", + "ssh://git@github.com/example-owner/example-repo.git", + "https://github.com/example-owner/example-repo", + ]) { + assert.deepEqual(parseOrigin(origin), { owner: "example-owner", repository: "example-repo" }); + } + for (const origin of [ + "https://user:test-secret@github.com/owner/repo.git", + "https://github.com.example.com/owner/repo.git", + "file:///somewhere/repo.git", + "https://github.com/owner/repo.git?token=test-secret", + ]) { + assert.throws(() => parseOrigin(origin), (error) => !error.message.includes("test-secret")); + } +}); + +test("CLI builds canonical trailers with unknown or a selected model", () => { + assert.equal(buildCommitMessage("feat: helper", undefined, AGENT), `feat: helper\n\nAI-Agent: ${AGENT}\nAI-Model: unknown\n`); + assert.match(buildCommitMessage("feat: helper", "test-model", AGENT), /AI-Model: test-model\n$/); + assert.throws(() => buildCommitMessage("feat: helper"), /verified App slug/); + assert.deepEqual(parseArgs(["--message", "feat: helper", "--model", "test-model", "--files", "README.md"]), { + message: "feat: helper", model: "test-model", files: ["README.md"], + }); + assert.throws(() => parseArgs(["--message", "feat: helper", "--files"]), /--files must be last/); + assert.throws(() => parseArgs([]), /--message/); + assert.throws(() => buildCommitMessage("feat: helper", "unknown\nAI-Agent: someone-else"), /single-line/); +}); + +test("publication commits both bot identities, pushes without token arguments, and creates a draft PR", async () => { + const mock = mockPublication(); + const output = []; + const status = await main(["--message", "feat: helper", "--model", "test-model"], { + ...mock.dependencies, + stdout: { write: (text) => output.push(text) }, + stderr: { write: (text) => output.push(text) }, + }); + assert.equal(status, 0); + const commit = mock.commands.find((call) => call.args.includes("commit")); + assert.equal(commit.env.GIT_AUTHOR_NAME, BOT_NAME); + assert.equal(commit.env.GIT_COMMITTER_NAME, BOT_NAME); + assert.equal(commit.env.GIT_AUTHOR_EMAIL, BOT_EMAIL); + assert.equal(commit.env.GIT_COMMITTER_EMAIL, BOT_EMAIL); + assert.equal(commit.input, buildCommitMessage("feat: helper", "test-model", AGENT)); + const identityRequest = mock.requests.find((call) => call.url.includes("/users/")); + assert.equal(identityRequest.url, `https://api.github.com/users/${encodeURIComponent(BOT_NAME)}`); + assert.equal(identityRequest.headers.Authorization, `Bearer ${access.token}`); + assert.equal(commit.env.GH_TOKEN, undefined); + const push = mock.commands.find((call) => call.args[0] === "push"); + assert.deepEqual(push.args, ["push", "--no-follow-tags", "https://github.com/example-owner/example-repo.git", `${commitSha}:refs/heads/feat/bot-helper`]); + const encodedToken = Buffer.from(`x-access-token:${access.token}`).toString("base64"); + assert.equal(push.env.GIT_CONFIG_VALUE_4, `AUTHORIZATION: basic ${encodedToken}`); + assert.equal(push.env.GIT_CONFIG_KEY_6, "protocol.allow"); + assert.equal(push.env.GIT_CONFIG_VALUE_6, "never"); + assert.equal(push.env.GIT_CONFIG_KEY_7, "protocol.https.allow"); + assert.equal(push.env.GIT_CONFIG_VALUE_7, "always"); + const create = mock.commands.find((call) => call.command === "gh" && call.args[0] === "pr"); + assert.ok(create.args.includes("--draft")); + assert.equal(create.args[create.args.indexOf("--title") + 1], "[agent] helper"); + assert.equal(create.env.GH_TOKEN, access.token); + assert.equal(create.env.GH_DEBUG, undefined); + assert.equal(push.env.GIT_TRACE, undefined); + assert.equal(push.env.GIT_TRACE_CURL, undefined); + assert.ok(mock.requests.some((call) => call.url.endsWith("/pulls?state=open&head=example-owner%3Afeat%2Fbot-helper"))); + assert.equal(mock.requests.at(-1).method, "DELETE"); + assert.equal(mock.requests.at(-1).url, "https://api.github.com/installation/token"); + for (const secret of [access.token, encodedToken, "inherited-human-token"]) { + assert.ok(!JSON.stringify(mock.commands.map((call) => call.args)).includes(secret)); + assert.ok(!output.join("").includes(secret)); + } +}); + +test("an existing open PR is reused without running gh pr create", async () => { + const mock = mockPublication({ pullRequests: [{ number: 7 }] }); + const result = await publishAgentPr({ message: "fix: helper" }, mock.dependencies); + assert.equal(result.createdPullRequest, false); + assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[0] === "pr")); +}); + +test("an invalid or human account cannot stand in for the configured App bot", async () => { + for (const invalid of [{ ...bot, type: "User" }, { ...bot, login: "another-app[bot]" }, { ...bot, id: 0 }]) { + const mock = mockPublication(); + const originalFetch = mock.dependencies.fetchImpl; + let revoked = false; + mock.dependencies.fetchImpl = (url, options) => { + if (url.includes("/users/")) return Response.json(invalid); + if (options.method === "DELETE") { + revoked = true; + return new Response(null, { status: 204 }); + } + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /bot identity for the configured App/); + assert.ok(revoked); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); + } +}); + +test("the onboarding manifest is owner-only with explicit minimal permissions and placeholder callbacks", () => { + const manifest = JSON.parse(readFileSync(new URL("../docs/app-manifest.json", import.meta.url), "utf8")); + assert.equal(manifest.name, "YOUR-ACCOUNT-agent-coder"); + assert.equal(manifest.url, "https://github.com/R4yHarris/github-agent-contracts"); + 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", + }); + assert.deepEqual(manifest.default_events, []); + assert.equal(manifest.hook_attributes.active, false); + assert.equal(new URL(manifest.hook_attributes.url).hostname, "example.invalid"); + assert.equal(new URL(manifest.redirect_url).hostname, "example.invalid"); + assert.deepEqual(Object.keys(manifest).sort(), [ + "name", "url", "description", "public", "hook_attributes", "redirect_url", + "request_oauth_on_install", "default_permissions", "default_events", + ].sort()); +}); + +test("both PR workflows expose the documented required-check name", () => { + for (const path of [ + "../.github/workflows/check-agent-trailers.yml", + "../examples/consumer-repo/.github/workflows/check-agent-trailers.yml", + ]) { + const workflow = readFileSync(new URL(path, import.meta.url), "utf8").replace(/\r\n/g, "\n"); + assert.match(workflow, /jobs:\n trailers:\n name: check-agent-trailers\n/); + } +}); + +test("the environment template lists only the two empty publisher settings", () => { + const lines = readFileSync(new URL("../.env.example", import.meta.url), "utf8") + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith("#")); + assert.deepEqual(lines, ["GITHUB_APP_ID=", "GITHUB_APP_PRIVATE_KEY_PATH="]); +}); + +test("specified files are staged literally, without including unrelated staged files", async () => { + const mock = mockPublication(); + await publishAgentPr({ message: "docs: helper", files: ["README.md"] }, mock.dependencies); + const add = mock.commands.find((call) => call.args[0] === "add"); + assert.deepEqual(add.args, ["add", "--", "README.md"]); + assert.equal(add.env.GIT_LITERAL_PATHSPECS, "1"); + const unrelated = mockPublication({ staged: ["AGENTS.md"] }); + await assert.rejects(publishAgentPr({ message: "docs: helper", files: ["README.md"] }, unrelated.dependencies), /Unrelated files are already staged/); + assert.equal(unrelated.keyReads(), 0); +}); + +test("protected files and paths outside the repository are rejected before reading the key", async () => { + for (const file of [".env", ".env.local", "app.pem", "signing.key", "../outside.txt", ".git/config"]) { + const mock = mockPublication({ staged: [file], indexed: [file] }); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /Refusing to commit|inside this repository/); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.requests.length, 0); + } + const mock = mockPublication({ indexed: ["README.md", ".env"] }); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /Refusing to commit/); +}); + +test("main and master are rejected before authentication", async () => { + for (const branch of ["main", "master"]) { + const mock = mockPublication({ branch }); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /feature branch/); + assert.equal(mock.keyReads(), 0); + } +}); + +test("push failures with secret-bearing output are sanitized and still revoke the token", async () => { + const mock = mockPublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + if (args[0] === "push") throw new Error(`failure with ${access.token}`); + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), (error) => { + assert.match(error.message, /Branch push failed/); + assert.match(error.message, /local commit remains/); + assert.ok(!error.message.includes(access.token)); + return true; + }); + assert.equal(mock.requests.at(-1).method, "DELETE"); + assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[0] === "pr")); +}); + +test("help needs no environment or key and does not publish", async () => { + const output = []; + 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/); +}); + +test("missing environment and an empty index fail before key access or network calls", async () => { + const missing = mockPublication(); + delete missing.dependencies.env.GITHUB_APP_ID; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, missing.dependencies), /Set GITHUB_APP_ID/); + assert.equal(missing.keyReads(), 0); + const empty = mockPublication({ staged: [] }); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, empty.dependencies), /Stage reviewed changes/); + assert.equal(empty.requests.length, 0); +}); + +test("the configured private-key path is blocked even without a key extension", async () => { + const mock = mockPublication({ staged: ["app-secret"], indexed: ["app-secret"] }); + mock.dependencies.env.GITHUB_APP_PRIVATE_KEY_PATH = "app-secret"; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /private-key path/); + assert.equal(mock.keyReads(), 0); +}); + +test("a nonstandard default branch is rejected and its token revoked", async () => { + const mock = mockPublication({ branch: "release" }); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (url.endsWith("/example-repo")) return Response.json({ ...repository, default_branch: "release" }); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /default branch/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit"))); + assert.equal(mock.requests.at(-1).method, "DELETE"); +}); + +test("a branch switch during authentication prevents commit and push", async () => { + const mock = mockPublication(); + const originalRun = mock.dependencies.run; + let branchReads = 0; + mock.dependencies.run = (command, args, options) => { + if (args[0] === "symbolic-ref" && ++branchReads > 1) return "feat/another-task"; + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /branch changed/); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); +}); + +test("Git URL rewrites cannot switch the App-authenticated push to human SSH credentials", async () => { + for (const rewrite of ["insteadof", "pushinsteadof"]) { + const mock = mockPublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => args[0] === "config" + ? `url.ssh://git@github.com/.${rewrite}\nhttps://github.com/\0` + : originalRun(command, args, options); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /Git URL rewrite/); + assert.equal(mock.keyReads(), 0); + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push")); + } +}); + +test("post-commit identity or protected-file changes are rejected before push", async () => { + for (const changed of ["identity", "files"]) { + const mock = mockPublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + if (changed === "files" && args[0] === "ls-tree") return "README.md\0.env\0"; + const output = originalRun(command, args, options); + return changed === "identity" && args[0] === "log" ? output.replace(BOT_EMAIL, "human@example.com") : output; + }; + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), /bot identity|environment file/); + assert.ok(!mock.commands.some((call) => call.args[0] === "push")); + assert.equal(mock.requests.at(-1).method, "DELETE"); + } +}); + +test("a failed PR lookup is not mistaken for a missing PR", async () => { + const mock = mockPublication({ pullRequests: Response.json({ message: access.token }, { status: 403 }) }); + await assert.rejects(publishAgentPr({ message: "feat: helper" }, mock.dependencies), (error) => { + assert.match(error.message, /HTTP 403/); + assert.ok(!error.message.includes(access.token)); + return true; + }); + assert.ok(!mock.commands.some((call) => call.command === "gh" && call.args[0] === "pr")); + assert.equal(mock.requests.at(-1).method, "DELETE"); +}); + +test("local Git integration commits selected and staged files with bot provenance while publication stays mocked", async (context) => { + const directory = mkdtempSync(join(cwd, ".agent-pr-test-")); + context.after(() => rmSync(directory, { recursive: true, force: true, maxRetries: 3 })); + const commands = []; + const gitEnvironment = Object.fromEntries(Object.entries(process.env).filter(([name]) => + !/^(GIT_|GH_|GITHUB_APP_)/i.test(name) && !/^(GITHUB_TOKEN|GITHUB_ENTERPRISE_TOKEN)$/i.test(name) + )); + const localGit = (args, options = {}) => execFileSync("git", [ + "-c", "core.fsmonitor=false", + "-c", `core.hooksPath=${join(directory, "no-hooks")}`, + ...args, + ], { cwd: directory, env: gitEnvironment, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], ...options }); + localGit(["init", "--quiet", "--initial-branch=feat/test-publication", "--object-format=sha1"]); + const github = mockGitHub([ + installation, access, repository, [], new Response(null, { status: 204 }), + installation, access, repository, [{ number: 1 }], new Response(null, { status: 204 }), + ]); + const dependencies = { + ...github, + cwd: directory, + env: { ...gitEnvironment, GITHUB_APP_ID: "123", GITHUB_APP_PRIVATE_KEY_PATH: "never-read.pem" }, + readPrivateKey: () => privateKey, + run: (command, args, options) => { + commands.push({ command, args }); + if (command === "gh" || args[0] === "push") return ""; + if (args[0] === "remote") return "https://github.com/example-owner/example-repo.git"; + return localGit(args, options); + }, + }; + writeFileSync(join(directory, "selected.txt"), "selected contents\n"); + writeFileSync(join(directory, "untouched.txt"), "not part of this commit\n"); + const first = await publishAgentPr({ message: "feat: selected files", files: ["selected.txt"] }, dependencies); + assert.match(first.commit, /^[0-9a-f]{40}$/); + assert.equal(first.createdPullRequest, true); + assert.equal(localGit(["ls-tree", "-r", "--name-only", "HEAD"]).trim(), "selected.txt"); + assert.equal(localGit(["log", "-1", "--format=%an%n%ae%n%cn%n%ce"]).trim(), [BOT_NAME, BOT_EMAIL, BOT_NAME, BOT_EMAIL].join("\n")); + assert.ok(localGit(["log", "-1", "--format=%B"]).includes(`AI-Agent: ${AGENT}\nAI-Model: unknown`)); + writeFileSync(join(directory, "selected.txt"), "updated contents\n"); + localGit(["add", "--", "selected.txt"]); + const second = await publishAgentPr({ message: "fix: staged file", model: "test-model" }, dependencies); + assert.notEqual(second.commit, first.commit); + assert.equal(second.createdPullRequest, false); + assert.match(localGit(["log", "-1", "--format=%B"]), /AI-Model: test-model/); + assert.equal(localGit(["status", "--porcelain"]).trim(), "?? untouched.txt"); + assert.deepEqual(commands.filter((call) => call.args[0] === "push").map((call) => call.args.at(-1)), [ + `${first.commit}:refs/heads/feat/test-publication`, + `${second.commit}:refs/heads/feat/test-publication`, + ]); + assert.equal(commands.filter((call) => call.command === "gh" && call.args[0] === "pr").length, 1); +}); \ No newline at end of file