diff --git a/.claude/workflow.yml b/.claude/workflow.yml new file mode 100644 index 0000000..5f3239d --- /dev/null +++ b/.claude/workflow.yml @@ -0,0 +1,11 @@ +# How this project is worked. Read by claude-shared skills. +# Guide: claude-shared docs/guides/workflow-modes.md +schema: 1 +mode: factory +standard: unversioned +workspace: factory + +factory: + runtime: devbox-dispatcher + digest: 135 + claim-label: run:interactive diff --git a/.github/acceptance/extract.py b/.github/acceptance/extract.py new file mode 100644 index 0000000..1c1ba18 --- /dev/null +++ b/.github/acceptance/extract.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""Print the acceptance commands of the issue a pull request closes. + +The commands come from the linked issue, never from the PR: the PR's author +controls the PR body (plan v1, W0-7; ADR-028). The PR must close exactly one +issue in the same repository with a closing keyword such as `Closes #12`. The +issue's `## Acceptance` section must hold a fenced bash block. + +Standard library only, so CI can run it from the base commit without +installing anything. + + extract.py --repo owner/name --pr 51 # reads GITHUB_TOKEN + extract.py --pr-body-file pr.md --issue-body-file issue.md +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import urllib.request + + +class AcceptanceError(Exception): + """The PR or issue doesn't give a usable set of acceptance commands.""" + + +class NoLinkedIssue(AcceptanceError): + """The PR body closes no issue.""" + + +# Operator setup PRs (tier 3 files, settings) close no issue. One labeled this +# passes with a no-op block. The label is ignored on a PR that closes an issue, +# and agent PRs always close their issue, so an agent can't skip its own +# acceptance by adding the label. +OPERATOR_SETUP_LABEL = "operator-setup" +OPERATOR_SETUP_BLOCK = ( + f"# No acceptance commands: a PR labeled {OPERATOR_SETUP_LABEL} that closes no issue.\ntrue\n" +) + + +# A closing keyword followed by a same-repo reference. `owner/repo#12` doesn't +# match, because the `#` must follow whitespace. +_CLOSING = re.compile( + r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b:?\s+#(\d+)\b", + re.IGNORECASE, +) +_FENCED = re.compile(r"^(```|~~~).*?^\1[ \t]*$", re.MULTILINE | re.DOTALL) +_HTML_COMMENT = re.compile(r"", re.DOTALL) +_ACCEPTANCE_HEADING = re.compile(r"^##[ \t]+Acceptance[ \t]*$", re.MULTILINE | re.IGNORECASE) +_NEXT_HEADING = re.compile(r"^#{1,2}[ \t]+\S", re.MULTILINE) +_BASH_BLOCK = re.compile( + r"^(```|~~~)[ \t]*(?:bash|sh|shell)[ \t]*\n(.*?)^\1[ \t]*$", + re.MULTILINE | re.DOTALL, +) + + +def linked_issue(pr_body: str) -> int: + """Return the one issue number the PR body closes.""" + text = _HTML_COMMENT.sub("", pr_body or "") + text = _FENCED.sub("", text) + numbers = sorted({int(n) for n in _CLOSING.findall(text)}) + if not numbers: + raise NoLinkedIssue("The PR body doesn't close an issue (for example `Closes #12`).") + if len(numbers) > 1: + listed = ", ".join(f"#{n}" for n in numbers) + raise AcceptanceError( + f"The PR body closes more than one issue ({listed}). Close exactly one." + ) + return numbers[0] + + +def acceptance_block(issue_body: str) -> str: + """Return the first fenced bash block in the issue's `## Acceptance` section.""" + body = (issue_body or "").replace("\r\n", "\n") + heading = _ACCEPTANCE_HEADING.search(body) + if not heading: + raise AcceptanceError("The issue has no `## Acceptance` section.") + rest = body[heading.end() :] + # The section ends at the next level 1 or 2 heading outside a code block. + end = len(rest) + fences = [(m.start(), m.end()) for m in _FENCED.finditer(rest)] + for m in _NEXT_HEADING.finditer(rest): + if not any(start <= m.start() < stop for start, stop in fences): + end = m.start() + break + block = _BASH_BLOCK.search(rest[:end]) + if not block: + raise AcceptanceError("The issue's `## Acceptance` section has no fenced bash block.") + if not commands(block.group(2)): + raise AcceptanceError("The issue's acceptance block has no commands.") + return block.group(2) + + +def commands(block: str) -> list[str]: + """Split a bash block into logical commands. + + Backslash continuations are joined. Blank lines and comment-only lines are + dropped. Each command is run on its own, so a failure anywhere in a line + (including the left side of `&&`) fails that command. + """ + result: list[str] = [] + pending = "" + for raw in block.splitlines(): + line = raw.rstrip() + if line.endswith("\\"): + pending += line[:-1] + " " + continue + line = (pending + line).strip() + pending = "" + if line and not line.startswith("#"): + result.append(line) + if pending.strip(): + result.append(pending.strip()) + return result + + +def _get(url: str, token: str | None) -> dict: + request = urllib.request.Request( + url, + headers={ + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "devbox-acceptance/0.1", + **({"Authorization": f"Bearer {token}"} if token else {}), + }, + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response) + + +def from_github(repo: str, pr: int, token: str | None) -> tuple[int | None, str]: + """Return the linked issue number and its acceptance block. + + An `operator-setup` PR that closes no issue returns (None, a no-op block). + """ + api = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/") + pull = _get(f"{api}/repos/{repo}/pulls/{pr}", token) + labels = {label.get("name") for label in pull.get("labels") or []} + try: + number = linked_issue(pull.get("body") or "") + except NoLinkedIssue: + if OPERATOR_SETUP_LABEL in labels: + return None, OPERATOR_SETUP_BLOCK + raise + issue = _get(f"{api}/repos/{repo}/issues/{number}", token) + if "pull_request" in issue: + raise AcceptanceError(f"#{number} is a pull request, not an issue.") + return number, acceptance_block(issue.get("body") or "") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--repo", help="owner/name, with --pr") + parser.add_argument("--pr", type=int, help="pull request number, with --repo") + parser.add_argument("--pr-body-file", help="read the PR body from a file instead") + parser.add_argument("--issue-body-file", help="read the issue body from a file instead") + parser.add_argument("--output", help="write the block here instead of stdout") + args = parser.parse_args(argv) + + try: + if args.repo and args.pr: + token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") + number, block = from_github(args.repo, args.pr, token) + elif args.pr_body_file and args.issue_body_file: + with open(args.pr_body_file, encoding="utf-8") as f: + number = linked_issue(f.read()) + with open(args.issue_body_file, encoding="utf-8") as f: + block = acceptance_block(f.read()) + else: + parser.error("give --repo and --pr, or --pr-body-file and --issue-body-file") + except AcceptanceError as error: + print(f"acceptance: {error}", file=sys.stderr) + return 1 + + if number is None: + print( + f"acceptance: {OPERATOR_SETUP_LABEL} PR with no linked issue; nothing to run", + file=sys.stderr, + ) + else: + print(f"acceptance: commands from #{number}", file=sys.stderr) + if args.output: + with open(args.output, "w", encoding="utf-8") as f: + f.write(block) + else: + sys.stdout.write(block) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/acceptance/run.py b/.github/acceptance/run.py new file mode 100644 index 0000000..197d800 --- /dev/null +++ b/.github/acceptance/run.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Run each command of an acceptance block and fail if any fails. + +Each logical command runs in its own `bash -o pipefail -c`, from the given +directory, and every command runs even after a failure, so the log shows all +of them. Running the block as one script under `bash -e` would let a failure +on the left of `&&` pass unnoticed. + + run.py acceptance.sh [--cwd repo] +""" + +from __future__ import annotations + +import argparse +import subprocess +import sys + +from extract import commands + + +def run(block: str, cwd: str = ".") -> list[str]: + """Run every command and return the ones that failed.""" + failed: list[str] = [] + for command in commands(block): + print(f"::group::$ {command}", flush=True) + result = subprocess.run(["bash", "-o", "pipefail", "-c", command], cwd=cwd) + print("::endgroup::", flush=True) + status = "ok" if result.returncode == 0 else f"failed (exit {result.returncode})" + print(f"acceptance: {status}: {command}", flush=True) + if result.returncode != 0: + failed.append(command) + return failed + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("block", help="file holding the acceptance block") + parser.add_argument("--cwd", default=".", help="directory to run the commands in") + args = parser.parse_args(argv) + with open(args.block, encoding="utf-8") as f: + block = f.read() + if not commands(block): + print("acceptance: the block has no commands", file=sys.stderr) + return 1 + failed = run(block, args.cwd) + if failed: + print(f"acceptance: {len(failed)} command(s) failed:", file=sys.stderr) + for command in failed: + print(f" {command}", file=sys.stderr) + return 1 + print("acceptance: every command passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/always-review.yaml b/.github/always-review.yaml new file mode 100644 index 0000000..b735fc1 --- /dev/null +++ b/.github/always-review.yaml @@ -0,0 +1,27 @@ +# PRs touching `paths` are never merged by the devbox dispatcher. They come to +# the operator labeled `needs-operator` (diligence-kit ADR-028). Tier 3 paths in +# .github/self-tier-map.yml always do too, and an agent may not author them. +# +# Here that's every tier 2 path as well: the owner approves design decisions, +# agent instructions and the console's build and security settings. The +# dispatcher merges tier 1 only. +# +# The dispatcher reads this file at the PR's base commit, never from the PR +# (its `always_review_path` setting, diligence-kit #178). + +paths: + - CLAUDE.md + - docs/adr/** + - docs/specs/** + - docs/plans/** + - infra/** + - "**/*.tf" + - "**/*.tofu" + - "**/.terraform.lock.hcl" + - console/package.json + - console/tsconfig.json + - console/wrangler.* + - console/public/** + - console/deploy.sh + +release_review: [] diff --git a/.github/self-tier-map.yml b/.github/self-tier-map.yml index bb69434..a4177f3 100644 --- a/.github/self-tier-map.yml +++ b/.github/self-tier-map.yml @@ -46,6 +46,17 @@ tiers: - "**/*.tf" - "**/*.tofu" - "**/.terraform.lock.hcl" + # The console's build and security settings (console-phase-1.md, operator + # task 1): its dependencies, Worker config and the CSP in public/_headers. + - console/package.json + - console/tsconfig.json + - console/wrangler.* + - console/public/** 1: + # Console UI code: no credential and no authority (ADR-010), so low risk. + # Lets the console wave merge after checks and review (console-phase-1.md). + - console/src/** + - console/test/** + - console/index.html - docs/** - "**/*.md" diff --git a/.github/workflows/acceptance.yml b/.github/workflows/acceptance.yml new file mode 100644 index 0000000..5dea138 --- /dev/null +++ b/.github/workflows/acceptance.yml @@ -0,0 +1,73 @@ +# Acceptance check for PRs the devbox dispatcher opens (#127; diligence-kit +# ADR-028). The extractor and runner are copied from diligence-kit +# tools/acceptance into .github/acceptance. Make `acceptance` a required check +# on `main` once this merges. +# +# It runs the acceptance commands of the issue the PR closes. The commands come +# from the issue, never the PR, and the extractor and runner come from the PR's +# base commit, so a PR can't change what judges it. The PR's code runs only in +# the last step, with no secrets and no token in its environment. +# +# Editing the PR body re-runs the check. Editing the issue doesn't: re-run the +# check by hand after changing an issue's acceptance section. + +name: acceptance + +on: + pull_request: + types: [opened, synchronize, reopened, edited, ready_for_review] + +permissions: {} + +concurrency: + group: acceptance-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + acceptance: + name: acceptance + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + issues: read + pull-requests: read + steps: + - name: Check out the base commit (extractor and runner) + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: base + persist-credentials: false + + - name: Read the acceptance commands from the linked issue + env: + GITHUB_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + python3 base/.github/acceptance/extract.py \ + --repo "$REPO" --pr "$PR_NUMBER" --output "$RUNNER_TEMP/acceptance.sh" + cat "$RUNNER_TEMP/acceptance.sh" + + - name: Check out the PR + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: repo + persist-credentials: false + + + # Node 24 for the same reason as the gate: it enables pnpm with corepack, + # which Node 25 and later don't bundle. + - name: Set up Node + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + + - name: Enable pnpm + run: corepack enable + + + + - name: Run each acceptance command + run: python3 base/.github/acceptance/run.py "$RUNNER_TEMP/acceptance.sh" --cwd repo