Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/ONBOARDING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ This link is a **static template, not a working registration service**. Replace

The manifest sets `public: false`, disables webhooks and user OAuth, and requests repository permissions **Metadata: read**, **Checks: read-only**, **Contents: write**, **Issues: write**, **Pull requests: write**, **Repository projects: write**, **Actions: read**, **Deployments: read**, **Environments: read**, and **Variables: read**, plus the organization permission **Organization projects: write**. GitHub names the two project permissions `repository_projects` and `organization_projects`; `projects` is not a valid manifest or installation-token permission. Remove any scope you do not need and keep the App on a least-privilege path for the repository and task. Organization project access is installation-wide and is not narrowed by selecting repositories, so omit it unless the agent must manage organization projects. GitHub has **no manifest field to default repository selection**; selecting repositories during installation is a required human step, not something the JSON enforces. Existing App installations must have permission changes accepted by a human before the new access is available.

If using `agent-pr.mjs --resume`, configure **Administration: read** on the App and have a human accept it for the installation. Resume requests this permission only for its repository-scoped installation token to inspect branch-protection required checks; normal publishing and `--merge-when-green` alone do not request it. A successful operator approval is not evidence that GitHub accepted the permission: a token-minting 403/422 stops resume without a reduced-scope retry.

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
Expand Down
2 changes: 1 addition & 1 deletion docs/POLICY.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ node scripts/agent-pr.mjs --resume <existing-head-sha>

This operation creates **no commit, push, or PR**. It requires a clean worktree on an unprotected feature branch, an existing commit with the configured App's verified bot author and committer, valid provenance trailers, and exactly one open, unmerged PR targeting origin's default branch. Local HEAD, the remote branch, and the PR head must all equal the supplied SHA. A missing PR or any drift is a refusal, not a reason to publish again. Committed protected paths and policy are checked as for normal publication; local, committed, and currently reviewed default-branch grants must agree.

Resume requests Checks read even without merging. Before recovering metadata it requires successful GitHub Actions `check-agent-trailers` on that exact SHA and every status check required by the base branch's protection and active rules, including configured App identities. Legacy commit statuses are accepted only for requirements without a pinned App. Missing, pending, failed, incomplete (more than 100 results), or unverifiable check results stop immediately; run resume again only after the same head is green. A legacy protection endpoint returning 404 is accepted when the base branch is confirmed unprotected, or when it is protected by rulesets with successfully fetched and validated nonempty required-status-check rules. A protected base with missing, empty, malformed, or unavailable required rules remains refused. API errors, including HTTP 422 when minting a Checks-scoped token, remain hard stops: an authorized human must resolve installation permissions, not an agent changing scopes or using human credentials.
Resume requests Checks read and Administration read only on its repository-scoped installation token; the latter is required to inspect branch-protection required checks and is not requested for normal publishing or `--merge-when-green` alone. An authorized human must accept the Administration read permission for the App installation before resume can proceed. A human's approval does not prove GitHub has accepted the installation permission: HTTP 403/422 responses while minting the token remain explicit hard stops, with no narrower-token retry or human-credential fallback. Before recovering metadata, resume requires successful GitHub Actions `check-agent-trailers` on that exact SHA and every status check required by the base branch's protection and active rules, including configured App identities. Legacy commit statuses are accepted only for requirements without a pinned App. Missing, pending, failed, incomplete (more than 100 results), or unverifiable check results stop immediately; run resume again only after the same head is green. A legacy protection endpoint returning 404 is accepted when the base branch is confirmed unprotected, or when it is protected by rulesets with successfully fetched and validated nonempty required-status-check rules. A protected base with missing, empty, malformed, or unavailable required rules remains refused.

The operation reads the original model and optional `AI-Run` from the existing commit, ignoring the retrying process's `AI_*` environment. It rejects `--message`, `--model`, and `--files`. A missing PR run block can be restored from that commit without replacing other text; an identical block is untouched and a conflicting existing block is refused. No absent metadata, counts, session, or task values are invented.

Expand Down
2 changes: 1 addition & 1 deletion docs/ROLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ The optional [merge-when-green flow](POLICY.md#opt-in-merge) requires coder `com

The manifest specifies Metadata read, Checks read-only, and the repository scopes used for branch publication and review: Contents write, Issues write, and Pull requests write. If a broader agent workflow needs project or environment orchestration, add `repository_projects: write`, `organization_projects: write`, `actions: read`, `deployments: read`, `environments: read`, and `variables: read` only after the owner reviews the use case; these are not implicit requirements for every installation. Repository and organization projects are separate GitHub App permissions, and organization project access is not narrowed by the installation's selected repositories. Normal publishing requests only its core permissions; an approved orchestration token may request the reviewed subset, while the opt-in merge flag also requests Checks read-only. A human must accept permission changes on existing installations. Keep repositories explicitly selected and retain required human reviews and merge controls. Staged or selected `.github/workflows/**` paths are refused before token minting and published by humans; the coder App needs no Workflows permission.

The resume-only operation also requests Checks read-only so it can verify every required exact-head check before recovering metadata. It does not grant merge authority or switch credentials; `--merge-when-green` still requires the separately approved context and policy gates.
The resume-only operation requests Checks read-only and Administration read-only on its repository-scoped token so it can verify every required exact-head check, including branch-protection requirements, before recovering metadata. Administration read is not requested for normal publishing or by `--merge-when-green` alone. A human must accept that permission on the App installation; a denied token request fails closed rather than retrying with fewer scopes. Resume does not grant merge authority or switch credentials; `--merge-when-green` still requires the separately approved context and policy gates.

GitHub does not expose a separate draft-only or merge-only version of pull requests write. A coder token may technically call broader endpoints than the helper permits. Do not put the coder App on branch-rule bypass lists; restrict protected-branch updates and merges to authorized humans. Separate Apps reduce shared-key exposure but do not replace these controls.

Expand Down
35 changes: 29 additions & 6 deletions scripts/agent-pr.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ const OPTIONAL_ORCHESTRATION_PERMISSIONS = new Map([
["variables", new Set(["read"])],
]);

export function buildInstallationPermissions({ readChecks = false, additionalPermissions = {} } = {}) {
export function buildInstallationPermissions({
readChecks = false,
readAdministration = false,
additionalPermissions = {},
} = {}) {
if (
additionalPermissions === null ||
typeof additionalPermissions !== "object" ||
Expand All @@ -95,11 +99,20 @@ export function buildInstallationPermissions({ readChecks = false, additionalPer
...additionalPermissions,
};
if (readChecks) permissions.checks = "read";
if (readAdministration) permissions.administration = "read";
return permissions;
}

export async function mintInstallationToken(
{ appId, privateKey, owner, repository, readChecks = false, additionalPermissions = {} },
{
appId,
privateKey,
owner,
repository,
readChecks = false,
readAdministration = false,
additionalPermissions = {},
},
{ fetchImpl = globalThis.fetch, now = Date.now() } = {},
) {
const jwt = createAppJwt(appId, privateKey, now);
Expand All @@ -113,7 +126,7 @@ export async function mintInstallationToken(
) {
throw new AgentPrError("The repository needs an active installation matching GITHUB_APP_ID.");
}
const permissions = buildInstallationPermissions({ readChecks, additionalPermissions });
const permissions = buildInstallationPermissions({ readChecks, readAdministration, additionalPermissions });
const access = await githubRequest(`/app/installations/${installation.id}/access_tokens`, jwt, {
method: "POST",
body: { repositories: [repository], permissions },
Expand Down Expand Up @@ -511,7 +524,16 @@ export async function publishAgentPr(options, {
} catch {
throw new AgentPrError("Could not load the App private key from GITHUB_APP_PRIVATE_KEY_PATH.");
}
({ token, appSlug } = await mintInstallationToken({ ...origin, appId, privateKey: key, readChecks: resuming || options.mergeWhenGreen === true }, { fetchImpl, now }));
({
token,
appSlug,
} = await mintInstallationToken({
...origin,
appId,
privateKey: key,
readChecks: resuming || options.mergeWhenGreen === true,
readAdministration: resuming,
}, { fetchImpl, now }));
} finally {
if (Buffer.isBuffer(key)) key.fill(0);
key = undefined;
Expand Down Expand Up @@ -783,8 +805,9 @@ export async function main(argv, { stdout = process.stdout, stderr = process.std
node scripts/agent-pr.mjs --resume SHA [--merge-when-green]

--resume requires a clean worktree and an existing App bot commit, remote branch,
and open PR at that exact SHA. It creates no commit, push, or PR. Checks read is
required; all required exact-head checks must be green before metadata recovery.
and open PR at that exact SHA. It creates no commit, push, or PR. Checks read and
Administration read are required for resume; all required exact-head checks must
be green before metadata recovery. A human must accept installation permissions.
It preserves committed model/run metadata, ignores current AI_* environment data,
and refuses --message, --model, --files, head drift, or conflicting PR run metadata.
Without --files, commits the reviewed staged changes. --files must be last.
Expand Down
2 changes: 1 addition & 1 deletion skills/signed-bot-commit/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ To stage and commit named files, put `--files` last:
node scripts/agent-pr.mjs --message "docs: clarify agent contracts" --model gpt-5 --files README.md AGENTS.md
```

`--help` does not read policy, the key, or contact GitHub. Normal invocation first requires the local coder grants, then signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. The merge flag or resume mode adds Checks read to the token request. After checking the approved policy and branch protections, it makes an unsigned bot commit, pushes with in-memory authentication, reuses an open PR for the branch or runs `gh pr create --draft`, then revokes the token. New PR titles follow the repository's `[area] summary` convention with `[agent]` as the default area.
`--help` does not read policy, the key, or contact GitHub. Normal invocation first requires the local coder grants, then signs an App JWT, discovers the repository installation, and requests an installation token scoped to that repository with contents and pull requests write permissions. The merge flag or resume mode adds Checks read to the token request. Resume alone additionally requests Administration read to inspect required branch-protection checks; a human must accept that permission on the installation. Denied token requests stop without reduced-scope retry. After checking the approved policy and branch protections, normal publication 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.

## Resume without republishing

Expand Down
47 changes: 46 additions & 1 deletion tests/agent-pr.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,20 @@ test("installation token is scoped to the origin repository and required write p
assert.ok(github.calls[0].headers.Authorization.startsWith("Bearer "));
});

test("installation tokens request administration read only for resume checks", async () => {
const github = mockGitHub([installation, access]);
await mintInstallationToken({ ...credentials, readChecks: true, readAdministration: true }, github);
assert.deepEqual(JSON.parse(github.calls[1].body), {
repositories: ["example-repo"],
permissions: { contents: "write", pull_requests: "write", checks: "read", administration: "read" },
});
assert.deepEqual(buildInstallationPermissions({ readChecks: true }), {
contents: "write",
pull_requests: "write",
checks: "read",
});
});

test("GitHub App installation tokens can opt into orchestration scopes while keeping core publication permissions", async () => {
const github = mockGitHub([installation, access]);
const token = await mintInstallationToken({
Expand Down Expand Up @@ -567,7 +581,7 @@ test("--resume restores only committed metadata, preserves model/session/unknown
assert.ok(output.join("").includes("no commit, push, or PR creation"));
assert.ok(!output.join("").includes("Committed"));
assert.deepEqual(JSON.parse(mock.requests.find((call) => call.url.endsWith("/access_tokens")).body).permissions,
{ contents: "write", pull_requests: "write", checks: "read" });
{ contents: "write", pull_requests: "write", checks: "read", administration: "read" });
assert.equal(mock.requests.at(-1).url, "https://api.github.com/installation/token");
}
});
Expand Down Expand Up @@ -743,6 +757,37 @@ test("--resume refuses revoked policy, changed committed grants, and permission
}
});

for (const status of [403, 422]) {
test(`--resume stops on HTTP ${status} when administration read is not accepted`, async () => {
const mock = mockResumePublication();
const originalFetch = mock.dependencies.fetchImpl;
mock.dependencies.fetchImpl = (url, options) => {
if (url.endsWith("/access_tokens")) {
mock.requests.push({ url, ...options });
return Response.json({ message: "Resource not accessible by integration" }, { status });
}
return originalFetch(url, options);
};
await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), {
message: `GitHub API request failed (HTTP ${status}).`,
});
const tokenRequest = mock.requests.find((call) => call.url.endsWith("/access_tokens"));
assert.deepEqual(JSON.parse(tokenRequest.body), {
repositories: ["example-repo"],
permissions: {
contents: "write",
pull_requests: "write",
checks: "read",
administration: "read",
},
});
assert.equal(mock.requests.length, 2);
assert.deepEqual(mock.requests.map((call) => call.url.split("/").at(-1)), ["installation", "access_tokens"]);
assert.equal(mock.keyReads(), 1);
assert.ok(!mock.commands.some((call) => call.args.includes("commit") || call.args[0] === "push"));
});
}

test("--resume --merge-when-green reuses the merge gates and original provenance without republishing", async () => {
const mock = mockResumePublication({ draft: true });
const result = await publishAgentPrRaw({ resume: commitSha, mergeWhenGreen: true }, mock.dependencies);
Expand Down
Loading