From dd24294d85800b6fcfae8c1cf9b5d0a2ae925c05 Mon Sep 17 00:00:00 2001 From: "r4yharris-agent-coder[bot]" <334673250+r4yharris-agent-coder[bot]@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:34:52 -0400 Subject: [PATCH] fix(publish): resume exact-head App publication without republishing Authorized dependency repair R4yHarris/github-agent-contracts#12 for R4yHarris/github-agent-roster#578, tracing Roster FEATURE_SPEC 5.1/5.5/5.8 and respecting 3/7. Explicit --resume SHA preserves existing App bot author/committer/model/run; no new commit, push or PR. Require clean exact local/remote/PR head, reviewed policy, App check identity and complete green required checks before restoring missing run metadata. Conflicting metadata, genuine drift, unavailable permission/checks, merged/missing PR and changed state deny. Optional conditional merge retains its separate grants and existing conservative cleanup. Original default publishing unchanged. Parent reviewed exclusively handed-off child implementation and found/repaired actual ruleset-only branch shape: Roster main protected:true, legacy status-check protection404, required rules integration15368. Validated ruleset protections now work; missing/malformed/ambiguous protections still deny. No workflow, active policy or Roster vendor edits. Child Auto-selected model identity was unavailable; this publication follows the known parent continuation review, not invented child model/usage. Metadata here describes parent review/publication; no measured token counts asserted. Final independent parent Windows Node20v20.20.2 full contracts suite126/126pass0fail0skip53181.1799ms; child specifiedNode20 full126/126pass. Syntax, staged whitespace and policy gates pass. Existing publication fixtures remain green; new exact-head/no-republication/metadata/policy/checks/permission/drift tests include realistic ruleset-only branch fixtures. Roster consumes only the reviewed merged upstream revision in a separate change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> AI-Agent: r4yharris-agent-coder AI-Model: GPT-6.1-Sol AI-Run: 1|github-copilot|GPT-6.1-Sol@-|x|-/1000000|-|ghcp-120708|issue-12 --- docs/METRICS.md | 2 + docs/POLICY.md | 16 ++ docs/ROLES.md | 2 + scripts/agent-pr.mjs | 276 ++++++++++++++++++----- skills/signed-bot-commit/SKILL.md | 8 +- tests/agent-pr.test.mjs | 359 ++++++++++++++++++++++++++++++ 6 files changed, 605 insertions(+), 58 deletions(-) diff --git a/docs/METRICS.md b/docs/METRICS.md index 09baf89..d626b16 100644 --- a/docs/METRICS.md +++ b/docs/METRICS.md @@ -66,6 +66,8 @@ There is no closing marker or second document. An existing ` The commit receives one `AI-Run` footer line; the PR body receives the tagged pair rather than another copy of that footer line. Evaluation comments are separate from both. +For interrupted publication, `agent-pr.mjs --resume ` uses the existing bot commit's model and run rather than the retrying harness environment. After policy, identity, exact-head, and required-check validation, it restores a missing tagged pair, leaves an identical pair unchanged, and refuses conflicting existing metadata. It never rewrites the commit or replaces an earlier session/model record. An absent committed `AI-Run` remains absent. See [POLICY.md](POLICY.md#resume-an-exact-published-head) for the resume-only gates and optional authorized merge. + ## Validate and export locally The default [trailer checker](../scripts/check-agent-trailers.mjs) still checks only `AI-Agent` and `AI-Model`. Opt in to requiring a valid, model-matching run trailer on agent-classified commits: diff --git a/docs/POLICY.md b/docs/POLICY.md index a9be7f4..d7990b7 100644 --- a/docs/POLICY.md +++ b/docs/POLICY.md @@ -129,6 +129,22 @@ Only after GitHub confirms the merge does it delete the remote feature branch. I On failure, the published commit and PR can remain, and a timed-out flow may have marked a draft ready. Inspect the PR and both remote and local branches before retrying; do not create a duplicate commit just to retry a merge. Human-only merge remains the default, and deploys and direct protected pushes stay disabled. See [ROLES.md](ROLES.md) for credential separation. +## Resume an exact published head + +After an interrupted publication, use the existing commit's full lowercase SHA: + +```bash +node scripts/agent-pr.mjs --resume +``` + +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. + +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. + +`--resume --merge-when-green` additionally requires the same explicit human merge/cleanup authorization, separate approved credential context, and `merger.merge` gates described above. Resume revalidates exact heads, current coder grants, required checks, and worktree state during the merge wait and immediately before merging. It reuses the existing SHA-guarded merge and conservative cleanup flow with the original commit message and provenance. Without the merge flag, draft readiness, merging, and cleanup are not attempted. + ## Limits This is not a sandbox against a malicious human, compromised runner, or an agent that can replace its own trusted executor. Protect the default branch, loader, publisher, harness launch configuration, and credential storage. The policy checker does not create GitHub branch rules, scan all history for secrets, or independently prevent API calls made outside an approved executor. App permissions and GitHub protection rules remain necessary enforcement boundaries. \ No newline at end of file diff --git a/docs/ROLES.md b/docs/ROLES.md index 56432ac..4ecec43 100644 --- a/docs/ROLES.md +++ b/docs/ROLES.md @@ -16,6 +16,8 @@ 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. + 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. Merger and deploy Apps, if ever approved, must have only the permissions their independently reviewed executor requires. Keep deployment credentials behind protected environments with human approval and approved branch restrictions. Do not add administration, secret-management, workflow-editing, or organization-member permissions to the coder App to work around a failed operation. diff --git a/scripts/agent-pr.mjs b/scripts/agent-pr.mjs index 2d17672..64e1fb7 100644 --- a/scripts/agent-pr.mjs +++ b/scripts/agent-pr.mjs @@ -199,22 +199,37 @@ export function parseArgs(argv, env = {}) { throw new AgentPrError("--files must be last and followed by literal file paths."); } break; - } else if (argument === "--message" || argument === "-m" || argument === "--model") { + } else if (argument === "--message" || argument === "-m" || argument === "--model" || argument === "--resume") { const value = argv[++index]; if (value === undefined || value.startsWith("--")) { - throw new AgentPrError("--message and --model each need a value."); + throw new AgentPrError("--message, --model, and --resume each need a value."); } - options[argument === "--model" ? "model" : "message"] = value; + options[argument === "-m" ? "message" : argument.slice(2)] = value; } else if (["--merge", "--push-protected", "--push_protected", "--deploy"].includes(argument)) { throw new AgentPrError("Use --merge-when-green only with an approved merger merge grant. Protected pushes and deploys are unsupported."); } else { throw new AgentPrError("Unknown argument; use --help for usage."); } } - if (!options.help) validateCommitInput(options.message, options.model); + if (!options.help) { + if (options.resume !== undefined) { + if (argv.includes("--model")) throw new AgentPrError("--resume preserves the committed model; do not supply --model."); + delete options.model; + validateResumeInput(options); + } else validateCommitInput(options.message, options.model); + } return options; } +function validateResumeInput(options) { + if (typeof options.resume !== "string" || !/^[0-9a-f]{40}$/.test(options.resume)) { + throw new AgentPrError("--resume requires the exact existing 40-character lowercase commit SHA."); + } + if (options.message !== undefined || options.model !== undefined || (options.files ?? []).length) { + throw new AgentPrError("--resume cannot accept --message, --model, or --files; it preserves the existing commit."); + } +} + function safeFile(file, cwd, privateKeyPath) { if (typeof file !== "string" || !file || file.includes("\0")) { throw new AgentPrError("Only literal repository file paths may be committed."); @@ -260,14 +275,78 @@ async function readReviewedPolicy(repoPath, defaultBranch, token, fetchImpl) { return parseAgentPolicy(Buffer.from(file.content, "base64").toString("utf8")); } +async function requireGreenResumeChecks(repoPath, defaultBranch, headSha, token, fetchImpl) { + const basePath = `${repoPath}/branches/${encodeURIComponent(defaultBranch)}`; + const protection = await githubRequest(`${basePath}/protection/required_status_checks`, token, { fetchImpl, allowMissing: true }); + const rules = await githubRequest(`${repoPath}/rules/branches/${encodeURIComponent(defaultBranch)}`, token, { fetchImpl }); + if (!Array.isArray(rules)) throw new AgentPrError("Cannot verify required checks; refusing resume."); + const required = [{ context: "check-agent-trailers", appSlug: "github-actions" }]; + const addChecks = (checks, appKey) => { + if (!Array.isArray(checks)) throw new AgentPrError("Cannot verify required checks; refusing resume."); + for (const check of checks) { + if (typeof check?.context !== "string" || !check.context || + (check[appKey] !== null && check[appKey] !== undefined && !Number.isSafeInteger(check[appKey]))) { + throw new AgentPrError("Cannot verify required check identity; refusing resume."); + } + required.push({ context: check.context, appId: check[appKey] }); + } + }; + if (protection !== undefined) { + addChecks(protection.checks, "app_id"); + if (!Array.isArray(protection.contexts) || protection.contexts.some((context) => typeof context !== "string" || !context)) { + throw new AgentPrError("Cannot verify required check contexts; refusing resume."); + } + for (const context of protection.contexts) { + if (!protection.checks.some((check) => check.context === context)) required.push({ context }); + } + } + let hasRequiredRules = false; + for (const rule of rules) { + if (typeof rule?.type !== "string") throw new AgentPrError("Cannot verify required rules; refusing resume."); + if (rule.type === "required_status_checks") { + addChecks(rule.parameters?.required_status_checks, "integration_id"); + if (rule.parameters.required_status_checks.length) hasRequiredRules = true; + } + } + if (protection === undefined) { + const base = await githubRequest(basePath, token, { fetchImpl }); + if (base?.name !== defaultBranch || typeof base.protected !== "boolean" || + (base.protected && !hasRequiredRules)) { + throw new AgentPrError("Cannot verify required checks on the protected base branch; refusing resume."); + } + } + const checks = await githubRequest(`${repoPath}/commits/${headSha}/check-runs?filter=latest&per_page=100`, token, { fetchImpl }); + const statuses = await githubRequest(`${repoPath}/commits/${headSha}/status?per_page=100`, token, { fetchImpl }); + if (!Array.isArray(checks?.check_runs) || checks.total_count !== checks.check_runs.length || checks.total_count > 100 || + !Array.isArray(statuses?.statuses) || statuses.sha !== headSha || statuses.total_count !== statuses.statuses.length || statuses.total_count > 100) { + throw new AgentPrError("Cannot verify complete exact-head check results; refusing resume."); + } + for (const expected of required) { + const runs = checks.check_runs.filter((check) => check?.name === expected.context && + (!expected.appSlug || check.app?.slug === expected.appSlug) && + (expected.appId === undefined || expected.appId === null || expected.appId === -1 || check.app?.id === expected.appId)); + const legacy = statuses.statuses.filter((status) => status?.context === expected.context); + const pinnedApp = expected.appSlug || (expected.appId !== undefined && expected.appId !== null && expected.appId !== -1); + if (runs.length) { + if (runs.some((check) => check.head_sha !== headSha || check.status !== "completed" || check.conclusion !== "success") || + (!pinnedApp && legacy.some((status) => status.state !== "success"))) { + throw new AgentPrError("Required checks have not succeeded on the exact head SHA; refusing resume."); + } + } else if (pinnedApp || !legacy.length || legacy.some((status) => status.state !== "success")) { + throw new AgentPrError("Required checks have not succeeded on the exact head SHA; refusing resume."); + } + } +} + async function waitForGreenPullRequest({ repoPath, slug, branch, defaultBranch, headSha, pullNumber, token, - fetchImpl, invoke, baseEnv, checkMergePolicy, wait, clock, + fetchImpl, invoke, baseEnv, checkMergePolicy, checkResume, wait, clock, }) { const deadline = clock() + 600_000; let markedReady = false; for (let attempt = 0; attempt < 120 && clock() < deadline; attempt += 1) { await checkMergePolicy(); + if (checkResume) await checkResume(); const pull = await githubRequest(`${repoPath}/pulls/${pullNumber}`, token, { fetchImpl }); if ( pull?.number !== pullNumber || pull.state !== "open" || pull.merged !== false || typeof pull.draft !== "boolean" || @@ -326,9 +405,14 @@ export async function publishAgentPr(options, { requireCapability(policy, "coder", "commit_branch"); requireCapability(policy, "coder", "open_pr"); if (options.mergeWhenGreen) requireCapability(policy, "merger", "merge"); - const model = options.model ?? env.AI_MODEL; - validateCommitInput(options.message, model); - const agentRun = packAgentRun(env, model.trim()); + const resuming = options.resume !== undefined; + let model = options.model ?? env.AI_MODEL; + let agentRun = null; + if (resuming) validateResumeInput(options); + else { + validateCommitInput(options.message, model); + agentRun = packAgentRun(env, model.trim()); + } 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."); @@ -404,7 +488,19 @@ export async function publishAgentPr(options, { 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."); + const checkResumeWorktree = () => { + checkBranch(); + if (JSON.stringify(parseOrigin(git(["remote", "get-url", "origin"], "Resume origin verification").trim())) !== JSON.stringify(origin) || + git(["remote", "get-url", "--push", "--all", "origin"], "Resume push origin verification").trim() !== pushOrigins[0]) { + throw new AgentPrError("origin changed during resume; refusing to continue."); + } + if (git(["rev-parse", "--verify", "HEAD"], "Resume head verification").trim() !== options.resume || + git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], "Resume cleanliness verification")) { + throw new AgentPrError("Resume requires a clean worktree at the exact existing head SHA."); + } + }; + if (resuming) checkResumeWorktree(); + else if (!files.length && !staged.length) throw new AgentPrError("Stage reviewed changes or supply --files before publishing."); let key; let token; @@ -415,7 +511,7 @@ export async function publishAgentPr(options, { } catch { throw new AgentPrError("Could not load the App private key from GITHUB_APP_PRIVATE_KEY_PATH."); } - ({ token, appSlug } = await mintInstallationToken({ ...origin, appId, privateKey: key, readChecks: options.mergeWhenGreen === true }, { fetchImpl, now })); + ({ token, appSlug } = await mintInstallationToken({ ...origin, appId, privateKey: key, readChecks: resuming || options.mergeWhenGreen === true }, { fetchImpl, now })); } finally { if (Buffer.isBuffer(key)) key.fill(0); key = undefined; @@ -433,7 +529,7 @@ export async function publishAgentPr(options, { 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, model, appSlug, agentRun); + let message = resuming ? null : buildCommitMessage(options.message, model, appSlug, agentRun); const repository = await githubRequest(repoPath, token, { fetchImpl }); if ( repository?.full_name?.toLowerCase() !== slug.toLowerCase() || @@ -469,36 +565,45 @@ export async function publishAgentPr(options, { }; await checkProtectedBranch(); checkBranch(); - if (files.length) { - git(["add", "--", ...files], "Staging selected files", { env: { ...baseEnv, GIT_LITERAL_PATHSPECS: "1" } }); - } - const selected = readStaged(); - rejectHumanOwnedChanges(selected); - 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."); + if (!resuming) { + if (files.length) { + git(["add", "--", ...files], "Staging selected files", { env: { ...baseEnv, GIT_LITERAL_PATHSPECS: "1" } }); + } + const selected = readStaged(); + rejectHumanOwnedChanges(selected); + 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; } - 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, "", agentRun !== null); + let checked = checkMessage(actual[5] ?? "", true, "", agentRun !== null); + if (resuming && Object.hasOwn(checked.trailers, "AI-Run")) checked = checkMessage(actual[5] ?? "", true, "", 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"] !== model.trim() || - (checked.trailers["AI-Run"] ?? null) !== agentRun + checked.trailers["AI-Agent"] !== appSlug || + (resuming ? actual[0] !== options.resume : checked.trailers["AI-Model"] !== model.trim() || + (checked.trailers["AI-Run"] ?? null) !== agentRun) ) { - throw new AgentPrError("The new commit does not have the required bot identity and trailers; refusing to push."); + throw new AgentPrError("The commit does not have the required bot identity and trailers or exact head SHA; refusing publication."); + } + if (resuming) { + message = actual[5]; + model = checked.trailers["AI-Model"]; + agentRun = checked.trailers["AI-Run"] ?? null; } 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); @@ -519,31 +624,77 @@ export async function publishAgentPr(options, { GIT_CONFIG_KEY_6: "protocol.allow", GIT_CONFIG_VALUE_6: "never", GIT_CONFIG_KEY_7: "protocol.https.allow", GIT_CONFIG_VALUE_7: "always", }; - git(["push", "--no-follow-tags", pushUrl, `${actual[0]}:refs/heads/${branch}`], "Branch push", { env: authenticatedEnv }); + if (!resuming) git(["push", "--no-follow-tags", pushUrl, `${actual[0]}:refs/heads/${branch}`], "Branch push", { env: authenticatedEnv }); const pullRequestPath = `${repoPath}/pulls?state=open&head=${encodeURIComponent(`${origin.owner}:${branch}`)}`; const pullRequests = await githubRequest(pullRequestPath, token, { fetchImpl }); if (!Array.isArray(pullRequests)) throw new AgentPrError("GitHub returned an invalid pull-request list."); - 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", upsertAgentRun(buildCommitMessage(options.message, model, appSlug), agentRun), - ], "Draft pull-request creation", { env: { ...baseEnv, GH_TOKEN: token } }); - } else if (agentRun !== null) { + const checkResume = resuming ? async () => { + checkResumeWorktree(); + const currentPolicy = loadPolicy({ cwd }); + requireCapability(currentPolicy, "coder", "commit_branch"); + requireCapability(currentPolicy, "coder", "open_pr"); + verifyApprovedPolicy(currentPolicy); + const reviewed = await readReviewedPolicy(repoPath, repository.default_branch, token, fetchImpl); + requireCapability(reviewed, "coder", "commit_branch"); + requireCapability(reviewed, "coder", "open_pr"); + verifyApprovedPolicy(reviewed); + await checkProtectedBranch(); if (pullRequests.length !== 1 || !Number.isSafeInteger(pullRequests[0]?.number) || pullRequests[0].number <= 0) { - throw new AgentPrError("Expected exactly one open PR before updating AI-Run metadata."); + throw new AgentPrError("Resume requires exactly one existing open PR; no PR was created."); } - const pullPath = `${repoPath}/pulls/${pullRequests[0].number}`; - const pull = await githubRequest(pullPath, token, { fetchImpl }); - if (pull?.number !== pullRequests[0].number || pull.state !== "open" || pull.head?.sha !== actual[0] || - pull.head.ref !== branch || pull.head.repo?.full_name?.toLowerCase() !== slug.toLowerCase()) { - throw new AgentPrError("The PR no longer matches the published branch and head SHA; metadata was not updated."); + const readExactPull = async () => { + const reference = await githubRequest(`${repoPath}/git/ref/heads/${encodeURIComponent(branch)}`, token, { fetchImpl }); + if (reference?.ref !== `refs/heads/${branch}` || reference.object?.type !== "commit" || reference.object.sha !== actual[0]) { + throw new AgentPrError("The remote branch does not match the exact resume head SHA."); + } + const pull = await githubRequest(`${repoPath}/pulls/${pullRequests[0].number}`, token, { fetchImpl }); + if (pull?.number !== pullRequests[0].number || pull.state !== "open" || pull.merged !== false || typeof pull.draft !== "boolean" || + pull.head?.sha !== actual[0] || pull.head.ref !== branch || pull.head.repo?.full_name?.toLowerCase() !== slug.toLowerCase() || + pull.base?.ref !== repository.default_branch || pull.base.repo?.full_name?.toLowerCase() !== slug.toLowerCase()) { + throw new AgentPrError("The existing PR does not match the exact resume head, branch, base, and repository."); + } + return pull; + }; + await readExactPull(); + await requireGreenResumeChecks(repoPath, repository.default_branch, actual[0], token, fetchImpl); + const pull = await readExactPull(); + checkResumeWorktree(); + return pull; + } : undefined; + if (resuming) { + const pull = await checkResume(); + if (agentRun !== null) { + const body = upsertAgentRun(pull.body, agentRun); + if (body !== (pull.body ?? "")) { + if ((pull.body ?? "").includes("")) { + throw new AgentPrError("Existing AI-Run metadata differs from the committed run; resume will not replace it."); + } + await githubRequest(`${repoPath}/pulls/${pull.number}`, token, { method: "PATCH", body: { body }, fetchImpl }); + } + } + } else { + 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", upsertAgentRun(buildCommitMessage(options.message, model, appSlug), agentRun), + ], "Draft pull-request creation", { env: { ...baseEnv, GH_TOKEN: token } }); + } else if (agentRun !== null) { + if (pullRequests.length !== 1 || !Number.isSafeInteger(pullRequests[0]?.number) || pullRequests[0].number <= 0) { + throw new AgentPrError("Expected exactly one open PR before updating AI-Run metadata."); + } + const pullPath = `${repoPath}/pulls/${pullRequests[0].number}`; + const pull = await githubRequest(pullPath, token, { fetchImpl }); + if (pull?.number !== pullRequests[0].number || pull.state !== "open" || pull.head?.sha !== actual[0] || + pull.head.ref !== branch || pull.head.repo?.full_name?.toLowerCase() !== slug.toLowerCase()) { + throw new AgentPrError("The PR no longer matches the published branch and head SHA; metadata was not updated."); + } + const body = upsertAgentRun(pull.body, agentRun); + if (body !== pull.body) await githubRequest(pullPath, token, { method: "PATCH", body: { body }, fetchImpl }); } - const body = upsertAgentRun(pull.body, agentRun); - if (body !== pull.body) await githubRequest(pullPath, token, { method: "PATCH", body: { body }, fetchImpl }); } - result = { commit: actual[0], botName, createdPullRequest: !pullRequests.length }; + result = { commit: actual[0], botName, createdPullRequest: !pullRequests.length, ...(resuming ? { resumed: true } : {}) }; if (options.mergeWhenGreen) { const candidates = pullRequests.length ? pullRequests : await githubRequest(pullRequestPath, token, { fetchImpl }); if (!Array.isArray(candidates) || candidates.length !== 1 || !Number.isSafeInteger(candidates[0]?.number) || candidates[0].number <= 0) { @@ -560,9 +711,10 @@ export async function publishAgentPr(options, { }; await waitForGreenPullRequest({ repoPath, slug, branch, defaultBranch: repository.default_branch, headSha: actual[0], pullNumber, token, - fetchImpl, invoke, baseEnv, checkMergePolicy, wait, clock, + fetchImpl, invoke, baseEnv, checkMergePolicy, checkResume, wait, clock, }); await checkMergePolicy(); + if (checkResume) await checkResume(); const mergeResult = await githubRequest(`${repoPath}/pulls/${pullNumber}/merge`, token, { method: "PUT", body: { sha: actual[0], merge_method: "merge", commit_message: message }, fetchImpl, }); @@ -628,7 +780,13 @@ export async function main(argv, { stdout = process.stdout, stderr = process.std } if (options.help) { stdout.write(`Usage: node scripts/agent-pr.mjs --message TEXT [--model NAME] [--merge-when-green] [--files PATH ...] + 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. +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. --model overrides AI_MODEL; one must name the actual model id (not unknown). Missing or invalid model input exits 2 before publication. Never invent a model. @@ -646,14 +804,18 @@ exact head SHA, marks drafts ready, merges with a merge commit, then deletes tha After remote deletion it fetches origin with the App token, fast-forwards the local default branch, and deletes the unchanged local feature branch only if clean. No self-approval, squash, role/policy override, protected push, deploy, or auto-merge mode. -An invocation authorizes commit, push, and PR creation. Keep secrets out of arguments. +Normal mode performs commit, push, and PR creation; resume mode does not. +Use only with explicit authorization for the selected operations. 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"); + if (result.resumed) stdout.write(`Resumed existing ${result.commit.slice(0, 7)} as ${result.botName}; no commit, push, or PR creation.\n`); + else { + stdout.write(`Committed ${result.commit.slice(0, 7)} as ${result.botName} and pushed to origin.\n`); + stdout.write(result.createdPullRequest ? "Created a draft pull request.\n" : "Updated the branch for its existing pull request.\n"); + } if (result.merged) stdout.write(`Merged PR #${result.pullRequest} with a merge commit, removed its remote and local feature branches, and checked out ${result.checkedOutBranch}.\n`); return 0; } catch (error) { diff --git a/skills/signed-bot-commit/SKILL.md b/skills/signed-bot-commit/SKILL.md index 78f7bfb..c6b7158 100644 --- a/skills/signed-bot-commit/SKILL.md +++ b/skills/signed-bot-commit/SKILL.md @@ -48,7 +48,13 @@ 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. Only the merge flag adds Checks read to the token request. After checking the approved policy and branch protections, it makes an unsigned bot commit, pushes with in-memory authentication, reuses an open PR for the branch or runs `gh pr create --draft`, then revokes the token. New PR titles follow the repository's `[area] summary` convention with `[agent]` as the default area. +`--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. + +## Resume without republishing + +For an interrupted publication, inspect the existing commit and PR before retrying. With authorization for metadata recovery, use `node scripts/agent-pr.mjs --resume `. This creates no commit, push, or PR. It requires a clean worktree, the configured App's original bot author/committer and valid trailers, matching local/remote/PR heads, current reviewed policy grants, and all required exact-head checks green. Checks permission errors (including HTTP 422), missing/merged PRs, or genuine head drift stop without a fallback. + +Do not pass `--message`, `--model`, or `--files`: resume preserves the existing model and optional run, ignoring current `AI_*` environment input. It restores only a missing PR run block, leaves an identical block alone, and refuses conflicting earlier metadata. Adding `--merge-when-green` still requires the separate authorization, credential context, merge grants, and conservative cleanup gates below. See [POLICY.md](../../docs/POLICY.md#resume-an-exact-published-head). ## Merge when green diff --git a/tests/agent-pr.test.mjs b/tests/agent-pr.test.mjs index c10c805..afc8007 100644 --- a/tests/agent-pr.test.mjs +++ b/tests/agent-pr.test.mjs @@ -501,6 +501,365 @@ function mockMergePublication({ draft = false, existing = true, checkRuns } = {} return { ...mock, pull, elapsed: () => elapsed }; } +function mockResumePublication({ agentRun = compactRun, ...setup } = {}) { + const mock = mockMergePublication(setup); + const message = buildCommitMessage("fix: original publication", "claude-sonnet-4.5", AGENT, agentRun); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + const output = originalRun(command, args, options); + if (args[0] === "log") return [commitSha, BOT_NAME, BOT_EMAIL, BOT_NAME, BOT_EMAIL, message].join("\0"); + if (args[0] === "diff") return ""; + return output; + }; + Object.assign(mock.dependencies.env, runEnvironment, { AI_MODEL: "different-retry-model", AI_SESSION: "different-session", AI_EFFORT: "invalid" }); + mock.pull.body = "Original human description."; + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = async (url, options) => { + let response; + if (url.endsWith("/protection/required_status_checks")) response = new Response(null, { status: 404 }); + else if (url.includes("/status?")) response = { sha: commitSha, total_count: 0, statuses: [] }; + else if (url.endsWith("/pulls/7") && options.method === "PATCH") { + mock.pull.body = JSON.parse(options.body).body; + response = mock.pull; + } else return originalFetch(url, options); + mock.requests.push({ url, ...options }); + return response instanceof Response ? response : Response.json(response); + }; + return { ...mock, message }; +} + +function assertNoResumePublication(mock, { metadata = false, merge = false } = {}) { + assert.ok(!mock.commands.some((call) => call.args.includes("commit") || ["add", "push"].includes(call.args[0]) || + (call.command === "gh" && call.args[1] === "create"))); + if (!metadata) assert.ok(!mock.requests.some((call) => call.method === "PATCH")); + if (!merge) { + assert.ok(!mock.requests.some((call) => call.method === "PUT" || call.url.includes("/git/refs/heads/"))); + assert.ok(!mock.commands.some((call) => ["fetch", "switch", "update-ref"].includes(call.args[0]) || + (call.command === "gh" && call.args[1] === "ready"))); + } +} + +test("--resume CLI pins an existing SHA and refuses new commit inputs before any effects", async () => { + assert.deepEqual(parseArgs(["--resume", commitSha], runEnvironment), { resume: commitSha, files: [] }); + for (const args of [ + ["--resume"], ["--resume", "abc"], ["--resume", "A".repeat(40)], + ["--resume", commitSha, "--message", "new commit"], ["--resume", commitSha, "--model", "gpt-5"], + ["--resume", commitSha, "--files", "README.md"], + ]) { + const mock = mockResumePublication(); + assert.equal(await main(args, { ...mock.dependencies, stderr: { write() {} } }), 2); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.commands.length, 0); + assert.equal(mock.requests.length, 0); + } +}); + +test("--resume restores only committed metadata, preserves model/session/unknowns, and never republishes", async () => { + for (const agentRun of [compactRun, "1|-|claude-sonnet-4.5@unknown|-|-/-|-|-|-", null]) { + const mock = mockResumePublication({ agentRun }); + const output = []; + assert.equal(await main(["--resume", commitSha], { + ...mock.dependencies, stdout: { write: (text) => output.push(text) }, stderr: { write: (text) => output.push(text) }, + }), 0); + assertNoResumePublication(mock, { metadata: agentRun !== null }); + assert.equal(mock.pull.body, agentRun === null ? "Original human description." : upsertAgentRun("Original human description.", agentRun)); + assert.ok(!mock.pull.body.includes("different-session")); + 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" }); + assert.equal(mock.requests.at(-1).url, "https://api.github.com/installation/token"); + } +}); + +test("a post-push stale PR head refusal can resume the identical published commit without another publication", async () => { + const failed = mockPublication({ pullRequests: [{ number: 7 }] }); + Object.assign(failed.dependencies.env, runEnvironment); + const originalFetch = failed.dependencies.fetchImpl; + failed.dependencies.fetchImpl = (url, options) => url.endsWith("/pulls/7") + ? Response.json({ number: 7, state: "open", head: { sha: "c".repeat(40) } }) : originalFetch(url, options); + await assert.rejects(publishAgentPrRaw({ message: "fix: original publication" }, failed.dependencies), + /metadata was not updated.*local commit remains/); + assert.equal(failed.commands.filter((call) => call.args.includes("commit")).length, 1); + assert.equal(failed.commands.filter((call) => call.args[0] === "push").length, 1); + assert.ok(!failed.requests.some((call) => call.method === "PATCH")); + const resumed = mockResumePublication(); + assert.equal(resumed.message, failed.commands.find((call) => call.args.includes("commit")).input); + const result = await publishAgentPrRaw({ resume: commitSha }, resumed.dependencies); + assert.equal(result.commit, commitSha); + assert.equal(result.resumed, true); + assert.equal(result.createdPullRequest, false); + assert.equal(resumed.pull.body, upsertAgentRun("Original human description.", compactRun)); + assertNoResumePublication(resumed, { metadata: true }); +}); + +test("--resume is idempotent and refuses to replace earlier PR run metadata", async () => { + const mock = mockResumePublication(); + mock.pull.body = upsertAgentRun(mock.pull.body, compactRun); + await publishAgentPrRaw({ resume: commitSha }, mock.dependencies); + assertNoResumePublication(mock); + const conflicting = mockResumePublication(); + conflicting.pull.body = upsertAgentRun("Human text.", compactRun.replace("ses_01K8", "earlier-session")); + const original = conflicting.pull.body; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, conflicting.dependencies), /will not replace/); + assert.equal(conflicting.pull.body, original); + assertNoResumePublication(conflicting); +}); + +test("--resume refuses dirty worktrees and local head drift before reading credentials", async () => { + for (const fault of ["staged", "unstaged", "untracked", "head"]) { + const mock = mockResumePublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + if (fault === "head" && args[0] === "rev-parse" && args[1] === "--verify") return "c".repeat(40); + if (fault !== "head" && args[0] === "status") return `${fault === "untracked" ? "??" : fault === "staged" ? "M " : " M"} README.md\0`; + return originalRun(command, args, options); + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /clean worktree/); + assert.equal(mock.keyReads(), 0); + assert.equal(mock.requests.length, 0); + assertNoResumePublication(mock); + } +}); + +test("--resume verifies original author, committer, App slug, model, run, and protected paths", async () => { + for (const change of [ + (output) => output.replace(BOT_NAME, "Human"), + (output) => output.replaceAll(BOT_EMAIL, "human@example.com"), + (output) => output.replace(`\0${BOT_NAME}\0${BOT_EMAIL}\0fix:`, "\0Human\0human@example.com\0fix:"), + (output) => output.replace(`AI-Agent: ${AGENT}`, "AI-Agent: another-app"), + (output) => output.replace("AI-Model: claude-sonnet-4.5", "AI-Model: unknown"), + (output) => output.replace("|claude-sonnet-4.5@", "|another-model@"), + (output) => output.replace(/AI-Run:.*\n/, "AI-Run: invalid\n"), + (output) => output.replace(commitSha, "c".repeat(40)), + ]) { + const mock = mockResumePublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + const output = originalRun(command, args, options); + return args[0] === "log" ? change(output) : output; + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /required bot identity and trailers/); + assertNoResumePublication(mock); + } + for (const file of ["agent-policy.yml", ".github/workflows/check.yml", "secret.pem"]) { + const mock = mockResumePublication(); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => args[0] === (file === "secret.pem" ? "ls-tree" : "diff-tree") + ? `${file}\0` : originalRun(command, args, options); + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /human|private-key/); + assertNoResumePublication(mock); + } +}); + +test("--resume refuses absent/ambiguous PRs, delivered PRs, forks, target drift, and remote head drift", async () => { + for (const fault of ["absent", "ambiguous", "merged", "closed", "head", "branch", "fork", "base", "base-repo", "remote"]) { + const mock = mockResumePublication(); + if (fault === "merged") mock.pull.merged = true; + if (fault === "closed") mock.pull.state = "closed"; + if (fault === "head") mock.pull.head.sha = "c".repeat(40); + if (fault === "branch") mock.pull.head.ref = "feat/other"; + if (fault === "fork") mock.pull.head.repo.full_name = "another/repo"; + if (fault === "base") mock.pull.base.ref = "another-base"; + if (fault === "base-repo") mock.pull.base.repo.full_name = "another/repo"; + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (["absent", "ambiguous"].includes(fault) && url.includes("/pulls?")) return Response.json(fault === "absent" ? [] : [{ number: 7 }, { number: 8 }]); + if (fault === "remote" && url.includes("/git/ref/heads/")) return Response.json({ ref: "refs/heads/feat/bot-helper", object: { type: "commit", sha: "c".repeat(40) } }); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /existing open PR|exact resume head/); + assertNoResumePublication(mock); + } +}); + +test("--resume requires successful complete exact-head checks from the required App", async () => { + for (const change of [ + () => [], + (check) => [{ ...check, status: "in_progress", conclusion: null }], + (check) => [{ ...check, conclusion: "failure" }], + (check) => [{ ...check, conclusion: "neutral" }], + (check) => [{ ...check, head_sha: "c".repeat(40) }], + (check) => [{ ...check, app: { slug: "another-app" } }], + ]) { + const mock = mockResumePublication({ checkRuns: change }); + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /Required checks/); + assertNoResumePublication(mock); + } + for (const endpoint of ["/check-runs?", "/status?"]) { + const mock = mockResumePublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = async (url, options) => { + const response = await originalFetch(url, options); + if (!url.includes(endpoint)) return response; + return Response.json({ ...await response.json(), total_count: 101 }); + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /complete exact-head/); + assertNoResumePublication(mock); + } +}); + +test("--resume enforces legacy and ruleset required checks, including App identity and statuses", async () => { + for (const fault of [null, "missing", "wrong-app", "pending-status"]) { + const mock = mockResumePublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = async (url, options) => { + if (url.endsWith("/protection/required_status_checks")) return Response.json({ contexts: ["legacy"], checks: [{ context: "legacy", app_id: null }] }); + if (url.endsWith("/rules/branches/main")) return Response.json([{ type: "required_status_checks", parameters: { required_status_checks: [{ context: "tests", integration_id: 99 }] } }]); + if (url.includes("/status?")) return Response.json({ sha: commitSha, total_count: 1, statuses: [{ context: "legacy", state: fault === "pending-status" ? "pending" : "success" }] }); + const response = await originalFetch(url, options); + if (!url.includes("/check-runs?")) return response; + const checks = await response.json(); + if (fault !== "missing") checks.check_runs.push({ name: "tests", head_sha: commitSha, status: "completed", conclusion: "success", app: { id: fault === "wrong-app" ? 100 : 99 } }); + return Response.json({ ...checks, total_count: checks.check_runs.length }); + }; + if (fault === null) await publishAgentPrRaw({ resume: commitSha }, mock.dependencies); + else await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /Required checks/); + assertNoResumePublication(mock, { metadata: fault === null }); + } +}); + +test("--resume refuses revoked policy, changed committed grants, and permission errors without fallback", async () => { + for (const fault of ["local-policy", "reviewed-policy", "committed-policy", "checks-422", "checks-403", "rules-403"]) { + const mock = mockResumePublication(); + const originalLoad = mock.dependencies.loadPolicy; + let reads = 0; + if (fault === "local-policy") mock.dependencies.loadPolicy = () => ++reads > 1 ? parseAgentPolicy("version: 1\ndefault: deny\n") : originalLoad(); + const originalRun = mock.dependencies.run; + if (fault === "committed-policy") mock.dependencies.run = (command, args, options) => args[0] === "show" ? policySource : originalRun(command, args, options); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (fault === "reviewed-policy" && url.includes("/contents/agent-policy.yml") && ++reads > 1) return Response.json(approvedPolicyFile); + if (fault === "checks-422" && url.endsWith("/access_tokens")) return Response.json({ message: access.token }, { status: 422 }); + if ((fault === "checks-403" && url.includes("/check-runs?")) || (fault === "rules-403" && url.endsWith("/rules/branches/main"))) return Response.json({}, { status: 403 }); + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), (error) => { + assert.match(error.message, /policy denies|differs from|HTTP 422|HTTP 403/); + assert.ok(!error.message.includes(access.token)); + return true; + }); + assertNoResumePublication(mock); + } +}); + +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); + assert.equal(result.resumed, true); + assert.equal(result.merged, true); + assert.equal(result.createdPullRequest, false); + assert.equal(result.localBranchDeleted, true); + assertNoResumePublication(mock, { metadata: true, merge: true }); + assert.deepEqual(JSON.parse(mock.requests.find((call) => call.url.endsWith("/merge")).body), + { sha: commitSha, merge_method: "merge", commit_message: mock.message }); +}); + +test("--resume stops on head drift after readiness and before merge", async () => { + const mock = mockResumePublication({ draft: true, agentRun: null }); + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => { + const output = originalRun(command, args, options); + if (command === "gh" && args[1] === "ready") mock.pull.head.sha = "c".repeat(40); + return output; + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha, mergeWhenGreen: true }, mock.dependencies), /exact resume head/); + assert.ok(!mock.requests.some((call) => call.method === "PUT")); + assertNoResumePublication(mock, { merge: true }); +}); + +test("--resume refuses remote or repository drift during check reads before metadata writes", async () => { + for (const fault of ["remote", "origin"]) { + const mock = mockResumePublication(); + let checking = false; + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = async (url, options) => { + const response = await originalFetch(url, options); + if (url.includes("/check-runs?")) checking = true; + if (checking && fault === "remote" && url.includes("/git/ref/heads/")) return Response.json({ ref: "refs/heads/feat/bot-helper", object: { type: "commit", sha: "c".repeat(40) } }); + return response; + }; + const originalRun = mock.dependencies.run; + mock.dependencies.run = (command, args, options) => checking && fault === "origin" && args[0] === "remote" + ? "https://github.com/other/repository.git\n" : originalRun(command, args, options); + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /exact resume head|origin changed/); + assertNoResumePublication(mock); + } +}); + +test("--resume cannot treat an unreadable protected base as having no required checks", async () => { + const mock = mockResumePublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => url.endsWith("/branches/main") && !url.includes("/rules/") + ? Response.json({ name: "main", protected: true }) : originalFetch(url, options); + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /protected base branch/); + assertNoResumePublication(mock); +}); + +test("--resume accepts ruleset-only protected bases and enforces exact-head required App checks", async () => { + for (const fault of [null, "missing", "pending", "failed", "wrong-app", "wrong-head"]) { + const mock = mockResumePublication({ + checkRuns: (check) => fault === "missing" ? [] : [{ + ...check, + app: { slug: "github-actions", id: fault === "wrong-app" ? 999 : 15368 }, + head_sha: fault === "wrong-head" ? "c".repeat(40) : commitSha, + status: fault === "pending" ? "in_progress" : "completed", + conclusion: fault === "pending" ? null : fault === "failed" ? "failure" : "success", + }], + }); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (url.endsWith("/protection/required_status_checks")) return Response.json({ message: "Branch not protected" }, { status: 404 }); + if (url.endsWith("/rules/branches/main")) return Response.json([{ + type: "required_status_checks", + parameters: { required_status_checks: [{ context: "check-agent-trailers", integration_id: 15368 }] }, + }]); + if (url.endsWith("/branches/main")) return Response.json({ name: "main", protected: true }); + return originalFetch(url, options); + }; + if (fault === null) { + const result = await publishAgentPrRaw({ resume: commitSha }, mock.dependencies); + assert.equal(result.resumed, true); + assert.equal(mock.pull.body, upsertAgentRun("Original human description.", compactRun)); + } else await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), /Required checks/); + assertNoResumePublication(mock, { metadata: fault === null }); + } +}); + +test("--resume refuses ruleset-only protected bases with missing, ambiguous, or unavailable controls", async () => { + for (const fault of ["no-rules", "empty-checks", "unrelated-rule", "missing-parameters", "bad-context", "bad-app", + "malformed-rules", "rules-403", "rules-404", "rules-422", "base-403", "unknown-protection", "wrong-base"]) { + const mock = mockResumePublication(); + const originalFetch = mock.dependencies.fetchImpl; + mock.dependencies.fetchImpl = (url, options) => { + if (url.endsWith("/protection/required_status_checks")) return Response.json({ message: "Branch not protected" }, { status: 404 }); + if (url.endsWith("/rules/branches/main")) { + if (fault.startsWith("rules-")) return Response.json({}, { status: Number(fault.slice(6)) }); + if (fault === "malformed-rules") return Response.json({}); + if (fault === "no-rules") return Response.json([]); + if (fault === "unrelated-rule") return Response.json([{ type: "pull_request" }]); + if (fault === "missing-parameters") return Response.json([{ type: "required_status_checks" }]); + return Response.json([{ + type: "required_status_checks", + parameters: { required_status_checks: fault === "empty-checks" ? [] : [{ + context: fault === "bad-context" ? "" : "check-agent-trailers", + integration_id: fault === "bad-app" ? "15368" : 15368, + }] }, + }]); + } + if (url.endsWith("/branches/main")) { + if (fault === "base-403") return Response.json({}, { status: 403 }); + return Response.json({ name: fault === "wrong-base" ? "other" : "main", + protected: fault === "unknown-protection" ? null : true }); + } + return originalFetch(url, options); + }; + await assert.rejects(publishAgentPrRaw({ resume: commitSha }, mock.dependencies), + /Cannot verify required|HTTP 403|HTTP 404|HTTP 422/); + assertNoResumePublication(mock); + } +}); + test("--merge-when-green merges a ready or draft PR by exact SHA and only then deletes its branch", async () => { for (const setup of [{}, { draft: true }, { draft: true, existing: false }]) { const mock = mockMergePublication(setup);