CLAUDE.md - Games

Workflow

Slice prompt after Matt Shumer's Claude of Duty prompt

Start here

Complete repository workflow, including progress updates, early previews and decision visibility.

1. Fill in the project, stack, commands, author, owner and risk-path placeholders in the `CLAUDE.md` block.
2. Save each repo block below to the repository path shown above it (Project instructions, the Start prompt and the Default stack are not saved in the repo). Use the blocks for one workflow, not both in one repo.
3. Sessions that start one folder above the repo do not load the repo's rule hooks on their own. Once the blocks are saved, run `node .claude/hooks/rules.mjs --install-user` once from the repo on each computer you use. For a cloud environment, run `node .claude/hooks/rules.mjs --print-setup` and paste what it prints into the environment's setup script once.
4. Make the Superpowers plugin available. The first session verifies its version, runtime capabilities and CI setup through the `release` setup check before implementation. Approve any setup changes that exceed existing permissions.
5. Using a Claude project? Paste the Project instructions block into the project's instructions and add the other blocks as project files. The rules apply to the coordinator from the first message, before the repo exists.
6. Start the coordinator with the Start prompt block at the end: fill in its blanks and paste it as your first message. Work proceeds within that brief, with progress updates and early previews; updates require no acknowledgement. Say "hold" and name an item to pause that work.

The owner update interval is configured once under Settings. These files define the process; the setup check verifies the repository's actual tools and enforcement.

Each block below is one fenced block under a heading, with a line that says where it goes. In a downloaded copy of this file, save the text inside each fence, without the fence lines, at the path its line names; Project instructions goes in your Claude project and the Start prompt is your first message, so neither is saved in the repo. On the web page, Copy gives you one block and Copy all gives every repo block in order, with where to save each one.

CLAUDE.md

Save this as CLAUDE.md in the root of your repo.

# [PROJECT]

[WHAT IT IS FOR]

This codebase is yours to keep building on. How it is built is your call, inside the rules below. What it is for, and anything new, is the owner's call.
## Stack and checks

- Stack: [STACK].
- Install: `[INSTALL COMMAND]`
- Lint: `[LINT COMMAND]`
- Typecheck: `[TYPECHECK COMMAND]`
- Tests: `[TEST COMMAND]`
- Build: `[BUILD COMMAND]`
- A repo's first session runs the setup check in `release` before building. Every key is made once (`vertical-slice`).
- Skills, saved in `.claude/skills/`: `review` for audits and fixes, `release` for pull requests and merging, `build` for acceptance criteria and code, `visual-check` for screens, `verify` for running the game like a person, `staged-path` for staged work and starting sessions, `owner-updates` for keeping the owner informed, `vertical-slice` to start and launch a game, `scene-polish` for in-game scenes. A repo's own layout, CI and rules go in its `this-repo` skill, not here. Load the one that fits before starting that kind of work. Where work runs and where tests run are in `release`.
## How work goes

- **These rules govern the coordinator and every session from the first message, before the repo exists.** They say how to run the work, not only what to commit.
- **Risk, uncertainty and dependencies decide the process,** never the number of tasks or files.
- **The brief** is what the work is judged against and what authorizes it: on the short path, the owner's request plus the acceptance criteria written in the pull request, with no separate document to create or approve; on the staged path, the spec. Its boundaries, budgets and expected duration live there.
- **The short path is the default.** Work whose outcome is clear, that is easy to undo and that needs nothing it does not have yet takes one session, even a whole feature across many files: understand the request, write its acceptance criteria, build it, verify it with the checks that touch it, and merge on green. No planning document: the brief is the request and the pull request. Keep working until there is something to approve; ask only when a decision that is the owner's blocks you. A small app with no users or real data takes the short path, its first-time setup included.
- **The path and the reviews are separate decisions.** The path follows how uncertain the work is; the reviews follow its lane (Settings). When the lane calls for a review, a fresh session reviews the change and the original implementer fixes the reviewer's findings, whichever path the work is on.
- **Uncertain, dependent or hard-to-undo work takes the staged path** (`staged-path`): when the outcome or the approach is unclear, when it waits on an open decision or on other work, or when it is lane 3.
- **Acceptance criteria come first.** Before building, write what done looks like in the brief, as criteria a program or a person can observe, covering at least the quality bar in the `build` skill, which also says how code is written; load it before writing criteria, code or tests. A gap against a criterion is a blocking defect; an idea that would make it better is a note, kept apart.
- **Live state in a file.** A session keeps its live state in a committed file, never only in its context: its current task, its last commit, its next step and its open decisions. A session that writes keeps it in its own file, `docs/superpowers/live/<branch>.md` (the branch name with "/" written as "-"), so two sessions never touch the same file; it updates and commits that file at each milestone, reading the commit from `git rev-parse --short HEAD` and the time from `date`, never typing them. The session deletes the file in its last commit before it hands the branch to the audit (or, with no audit, before the merge), so the commit the audit and the owner's approval name is the one that merges and the file never reaches `main`; a fix session writes it again and deletes it the same way. The outcome goes to the coordinator's report and `progress.md`, as before. A reviewer, which changes nothing but its audit file, keeps the same four lines at the top of that file and removes them when the audit is done. The coordinator keeps `progress.md` and needs no such file.
- **The rules file beats the summary.** A compaction summary is a note about the rules, not the rules. Where it and `CLAUDE.md` or a skill differ, `CLAUDE.md` and the skill win, and where it and the live state differ, the live state wins. A hook in `.claude/settings.json` says so after every compaction and sends the session back to `CLAUDE.md` and `progress.md`; a session that has been compacted without it does the same on its own.
- **Fresh session per big job.** A big job (a spec, a plan, the build of one pull request with its fixes, an audit) runs in its own fresh session, started from the committed files its prompt names. A session never goes on into the next big job: when its job is done it commits, reports and ends. The coordinator is long-lived because it starts, tracks and reports on jobs and does none of them. A job that outgrows its context is refreshed under Session refresh in Settings, with a handoff, and that is the only reason a job spans two sessions.
- **No stalls.** A session never ends its turn only to wait for CI, since that wake can be lost: it watches the run in the foreground (see `release`) and acts the moment it ends. The coordinator, or any session leading others, checks in at the check-in interval in Settings and nudges any session silent that long; one still silent at the next check-in is reported to the owner and stopped, and a fresh session takes over from its live-state file and last pushed commit.
- **A check is a test that fails by itself.** Write the check first, so a program can judge it: the suite exits 0, every claim has a source line, the diff touches only files in the plan. The loop lives inside one piece of work: produce, check, correct, repeat until green.
- **The owner approves the finished result and product choices,** never the steps between. Product choices are direction, anything that changes what the product is for, and a new package, app, tool, dependency, environment or spend that the approved brief does not already cover. An approved brief authorizes everything inside its stated boundaries: the dependencies, tools, environments and budget it names. Ask again only when scope, exposure, cost or direction changes materially. Ask each choice as a decision card: options and a recommendation. Everything else, decide and go.
- **Three different yeses.** **Product approval** settles a choice, such as a direction or a dependency. **Merge permission** follows the lane: green and its required reviews, plus the owner's approval or a recorded standing permission for lane 3. **Permission to act outside the repo** (a release or tag, a credential, money, a real device) is asked for by name. Once given, it is a standing permission with its scope (a named environment, device or budget), recorded under "Standing permissions" in `docs/superpowers/history.md`, and asked for again only when that scope, the exposure or the cost changes. A merged spec records a decision; it does not make one: the spec lists any open product decisions, and the build waits for those only. Each approval is recorded with its scope: what it covers, and the document or commit.
## Owner visibility and early steering

The owner stays informed throughout, and updates never wait for an answer: continue within the approved brief, and silence never creates a new approval. When and how to update, show work and take steering are in `owner-updates`; every session that reports loads it first.
## Rules that never bend

- **Identity.** Every commit is authored by [COMMIT AUTHOR]. No Claude co-author, no "Claude-Session" trailer and no "Generated with Claude Code" line in commits, pull request bodies or docs. Pull requests end with "Requested by **[OWNER NAME]**": check the body's last line after every create or edit, since tools such as `gh pr create` can add a footer. Never force-push. Merge with a merge commit, never a squash.
- **The drunk-grandma test.** All copy and UX must be something a drunk grandma could understand and use: plain words, one main action per screen, big obvious buttons, no jargon, and nothing that needs explaining.
- **CLI first.** If something can be done with a CLI (gh, npm, wrangler and so on), do it with the CLI, and give the owner CLI commands rather than click-through steps.
- **Keep to the request.** Build nothing ahead of its user; "it would be useful later" is not a reason. A second problem found on the way is reported, not fixed, unless it blocks the task. A decision the owner has made is not reopened; if new facts make it look wrong, say so once, with the facts.
- **Report honestly.** Say what ran, what did not run and why, and what is still open. "Done" means merged to `main` and green there; otherwise say where it is: "on a branch", "in CI", "not started". Never round up. Hashes, sizes, timings and timestamps are measured, never written by hand (timestamps come from `date`), and a tool or asset is checked to exist before anything is built on it. Speak plainly: the conclusion first, short.
- **Findings carry evidence.** Every finding says what is wrong, the evidence, the expected result and a bounded fix, and a fix is checked by a program or a second session, never by the fixer's own say-so. A check proves one property; a review (model or human) finds what no check encodes: missing requirements, confusing screens, wrong assumptions. Both count as evidence. Every review, check and approval names the commit it examined; a push that changes what it covered makes it stale.
- **Limits.** When an approach has taken the tries in Settings, or a task has run past the overrun in Settings, stop that approach and reassess; never repeat a failed approach without new evidence. Keep on with independent work meanwhile. Report material setbacks under "Owner visibility and early steering". Pause and request an owner decision only when their decision, access or a change to an agreed budget is needed. Never bypass an access restriction or weaken an acceptance criterion to get past a problem. Sessions the coordinator starts are threads. A subagent is only a narrow read-only helper (a search, a log, a page) that changes no file and reports back; it spends the same usage, so start one only to keep a session's context small. Writers and required reviews are always threads. If this repo is indexed in Graphify, use its tools to find code and check what a change affects before changing it.
## Verification

Checks let work be handed off; the owner reads the evidence. A change that alters the product is run like a person, through the `verify` skill, before it is called done. The test hardest to fool comes first. A test that fails once and passes on retry is a defect: record it under "Flaky tests" in `docs/superpowers/history.md`. A change does not quietly edit its own check. Lessons carry a trigger, and each retrospective prunes. The full rules are in `build`.
## Risk

Every unit of work carries a lane, set by what a mistake costs, never by anyone's confidence. Classify it from the paths its diff touches and what the change does, using the lists below; use a classifier the repo already has, and never build tooling for this. The plan names any other lane 2 or 3 unit up front. The highest lane wins.

- **Lane 1**, small and easy to undo: a copy change, a test, a doc (specs, plans, audits and progress notes included), deleting a merged branch, an isolated change with coverage. Merges on green.
- **Lane 2**, wide: `[WIDE PATHS]`, shared code many callers use, a schema, or config. Merges after `release`'s extra checks.
- **Lane 3**, hard to undo: `tests/golden/` moves that no approved change explains, `[HARD-TO-UNDO PATHS]`, credentials, money, device actions with consequential side effects, release approvals and tags, CI workflow files, deleting anything git cannot restore, any migration, any write of real data, and a change to the rules that decide what needs the owner, or to the hooks sessions run (CLAUDE.md and the shared skills, even though they are `.md` files, and `.claude/settings.json`). Requires its lane's checks and reviews plus the owner's approval or a recorded standing permission covering the exact action.
- **A repo's own skills.** An edit to a repo's own `verify` or `this-repo` skill takes the lane of the code change it describes, and is named in the pull request body. One edited alone is lane 1, unless it changes what needs the owner. `CLAUDE.md` and the shared skills stay lane 3.
- **First-time setup.** Bootstrap from the owner's own rules text is lane 2: creating the repo, its CI and the rules files as the owner gave them. The owner's request is the standing permission for the setup check. Later changes to the rules or CI are lane 3 as usual.
- **Permission and risk are separate.** Standing permission removes a repeated approval request; it never lowers the lane or removes required checks and reviews. A routine, non-destructive validation on an authorized device does not itself raise the change's lane. A migration, real-data write or other consequential action retains its inherent lane even when authorized. An external action outside recorded permissions waits for authorization.
## The staged path

Uncertain, dependent or lane 3 work runs in stages, each in a fresh session: spec, plan audit (lane 3), execution, implementation audit (lane 2 and 3), fixes, the owner's review. The details, the slice end and the execution prompt are in `staged-path`; the coordinator and every session it starts load it first.
## Settings

Change a number or a model here and nowhere else.

- Owner update interval: none on a timer. Message the owner only for a finished result, a real blocker or a choice that is theirs; progress goes on the checklist and in `progress.md`.
- Check-in interval: 20 minutes while work is running. A check-in that finds nothing wrong says nothing.
- Tries per problem: 3. After that, stop that approach and reassess: try another with a reason, or move to independent work. Include material setbacks in the owner update, with what was tried and what it showed. Pause for an owner decision only when their decision, access or a change to an agreed budget is needed.
- Design and scene review rounds: 2 before the owner's first look at the screens page, then 1 on the owner's notes before the second look. A round is shoot, check by a fresh reviewer, fix. Round 1 is checked on Fable 5.2, medium; rounds 2 and 3 on Opus 5.5, medium.
- Overrun: a task that has taken twice the duration its brief estimated. Reassess the estimate and the approach, and report the changed outlook. Request a decision only if the authorized budget or scope must change.
- Pull requests open: 3. Checks run at once, as many as the CI capacity takes without queueing (measured, not guessed); only the integration with `main` before a merge runs one pull request at a time. Branches: `main` plus branches with an open pull request, 5 at most; a branch merges or closes within 2 days.
- Work sessions at once: 5, all on the current milestone, and at most 3 writing code (implementers and slice builders). The slice lead only reads and reports, but takes one of those 3 places, so at most 2 builders run beside it. A writer waiting on a review or the owner keeps its writer place but not one of the 5. It is a limit, not a goal: a session starts only when its work is ready.
- Session refresh: auto-compact at 450000 tokens (set in `.claude/settings.json`); refresh sooner when the context degrades (it repeats itself or forgets decisions) or at a natural boundary (a merge, a finished stage), with a handoff: the last commit, where to resume, what is left. The coordinator writes where things stand to `progress.md` first.
- Browser test pieces in CI: 6. Device matrix: small phone, tablet, computer, as browser profiles (emulation evidence); a brief may change it. Shoot only what changed. Progress: the coordinator keeps each stage's row in `progress.md` up to date, with a percentage from the plan's ticked steps, as supporting information. Rule edits the retrospective proposes: batched into one rule-change pull request per slice. The owner's own rule requests keep their own pull requests.
- Slice rounds: 3 (build, judge, fix, judge the fix), then stop and report. Slice critics count as reading sessions.
- Audits by lane: lane 1 none; lane 2 one fresh review after the build; lane 3 a plan audit and an implementation audit.
- Models and effort: every session names its model and effort; a role not listed here is named Opus 5.5, medium. Nothing runs above high effort. Read-only helpers: Haiku 5.5. Coordinator: Opus 5.5, medium. Plan and advisor: Fable 5.2, medium. Execution and fixes against a spec: Sonnet 5.5, medium, then high. Execution with no spec: Opus 5.5, medium. Lane 2 audit: the builder's model, medium. Lane 3 audits and Retrospective: Opus 5.5, medium. Slice critics: Opus 5.5, medium. Slice lead: Fable 5.2, medium. Slice builders: as execution. "Medium, then high": high only for a job the plan or coordinator marks hard, with the reason, or after a medium try fails. A stuck task's third try gets a check it can run and more effort, up to high; then the next model up (at the top, the owner's call) in a fresh session.

Skill: review

Save this as .claude/skills/review/SKILL.md in your repo.

---
name: review
description: Use when a plan or a finished change needs auditing, when more than one review is due, or when review findings need fixing.
---

# Review

Reviews find problems and change nothing but their own audit file. The implementer fixes them; a program or the reviewer checks each fix.
## Checks and reviews

- A check is a test that fails by itself. Before the work starts, write down every check a program can judge, from the brief's acceptance criteria.
- A review (a model or a person reading the work) is real evidence of a different kind: it finds what no check encodes, such as missing requirements, confusing screens and wrong assumptions. Use both.
- **The verdict line.** A review or audit of a pull request posts its verdict on the pull request as a comment whose first line is the commit it examined, then PASS or FAIL in capitals: `abc1234 PASS` or `abc1234 FAIL: 2 red`. Markup may wrap them (`**abc1234 PASS**`), but nothing else comes first and no number comes between the commit and the word. Any other comment is a status line and counts for nothing, so a builder's report never starts with the commit followed by PASS or FAIL. The rule hooks read only this line.
- Review against the acceptance criteria in the brief, plus exploratory checks for what the criteria missed. A gap against a criterion is red; an improvement is a note, kept apart from the blocking defects.
- A pull request that changes or deletes an existing test, golden or `verify` step names each one and why in its body. Read those first. When it edits `verify`, also run `verify` from `main` (Verification in `build`).
## Audits

- Which audits a change gets depends on its lane (Settings in CLAUDE.md), not on its task count. A fresh session runs each audit, so the work is read by eyes that did not write it.
- Files: `docs/superpowers/audits/<date>-<topic>-<cycle>-plan-audit.md` and `...-implementation-audit.md`. `<topic>` is the spec's topic, or the pull request's on the short path, and `<cycle>` counts rounds, so two audits never share a name.
- Both audits start with this prompt:

Audit all of your work for completeness, consistency, cohesion, and harmony, both within itself and relative to the spec and relative to the codebase. Assume nothing. Verify everything. Investigate any incomplete implementations or incomplete integrations. Do your best work.
## Side by side

- Reviews that do not need each other's output run at the same time, each in its own session with its own context and one lens (for example correctness, completeness, the codebase). Four reviewers sharing one window are one opinion, paid for four times. A review that needs another's output waits for it.
## End-to-end walk

It is the first step of every slice's end, before the design review loop, the screens page and the owner's own walk (see "Slice end" in `staged-path`).

- A fresh session runs it, never one that built the slice: builders know the way and skip the steps a stranger trips on.
- It walks every journey the slice added or changed, from the first screen to the last, the way a real person would: real taps, clicks, keys and typing in the running app or game on a GPU machine, never on software rendering in a cloud container (see "Shoot on a GPU" in `visual-check`), at the sizes the slice affects (see "Shoot what the change touches" in `visual-check`). Passing tests are not a walk.
- It writes `docs/superpowers/audits/<date>-<slice>-e2e-walk.md`, naming the commit or deploy it walked, with one line per step: the journey, the step, PASS or FAIL, and the evidence (a screenshot, or what it saw).
- Each FAIL is a red finding in the format below. The implementer fixes it in the fix round and names in the pull request every journey the fix touches. The walk runs again on the failed journeys and on those, and again on any journey a later slice-end fix touches, until every step passes on the commit the owner will walk.
- It uses test accounts, test payments and test phone numbers. A step that would spend real money, send a real message or write real data waits for its standing permission.
- The owner's walk starts only when every step passes.
## One finding is one unit

Write each finding so the implementer can act on it alone:

UNIT: the file or piece the finding is in. VERDICT: red (violates a requirement, blocks acceptance) or note (optional, recorded, not fixed here). REQUIREMENT: the requirement it violates: the brief, the plan, a standing rule or a check. REASON: what is wrong, in one line. EVIDENCE: the failing check or the line, and what it shows. EXPECTED: what should happen instead. FIX: the bounded change, and the only files it may touch.
## The fix round

- The implementer fixes every in-scope finding, low ones included, each in its own files. A finding is in scope when it violates a requirement of this change; notes and findings outside the change are recorded in the audit file as follow-ups, not fixed here. The only exception to fixing is a fix that needs the owner's choice: name it, ask it as a decision card with options and a recommendation, and fix the rest.
- Each finding gets the tries in Settings. Only a finding that still fails goes back, alone, with its evidence and scope; after the last try, stop that approach and reassess. Report material setbacks through the owner updates, with what was tried and what it showed. Pause for an owner decision only when their decision, access or budget is needed. A fix never grows past its scope: a second problem seen on the way is reported, not fixed.
- A fix is done when its check passes, run by a program or the audit session, never on the implementer's own say-so.
## Lessons

A confirmed failure gets a regression test first. A lesson is written down only when no test can catch it: one line under "Lessons" in `docs/superpowers/history.md` naming its trigger (the paths, or the kind of change, a diff shows), what to look for and the failure behind it, which the coordinator (or short-path implementer) adds when the work is archived. A merge with nothing to learn leaves none.

ACCEPTED: a pull request sat green and unmerged for hours because the wake that says CI is done never came. DERIVED: watch CI in the foreground. TRIGGER: a session that waits on CI. LOOK FOR: it never ends its turn only to wait. LANDS IN: the plan's brief when its trigger matches.

A lesson lands in the plan's brief when its trigger matches the plan's work, not in a worker's instructions. The retrospective after the slice moves into CLAUDE.md, through its rule-change pull request, only a lesson that holds for every change (one with no narrower trigger), and keeps the rest in `history.md`, pruning them as Verification in `build` says.

Skill: release

Save this as .claude/skills/release/SKILL.md in your repo.

---
name: release
description: Use when opening a pull request, waiting on checks, merging, deleting a branch, or deciding where tests run.
---

# Release
## Setup check

The first session in a repo runs this first, before it builds anything, and again when the CI, the runtime or the superpowers version changes. It verifies each item, sets up what is missing with the owner's authorization (CI workflow files are lane 3, except at first-time setup: see Risk in CLAUDE.md), and reports each one as present, added or missing:

- Every step only the owner can run (creating the repo, branch protection, credentials, and anything the sessions lack the access for, such as deleting branches), listed as one batch of CLI commands before building, so the owner is not needed mid-run.
- The commands in Stack and checks (CLAUDE.md) run, and pass on `main`.
- The CI gate described below: the workflow triggers (with `ready_for_review` on a public repo), the job that decides which checks apply, and the final aggregate gate job.
- The gate is required by branch protection on `main`, which keeps every existing required check unless the owner authorizes its replacement.
- Branch protection on `main` does not require branches to be up to date before merging, and every push to `main` starts a full run that no newer push cancels.
- The merge queue (see Lanes and merging): GitHub's, turned on for `main` where the repo can have one, with the workflow listing the `merge_group` trigger and the queue's merge method set to a merge commit; or reported as not available, so the session that merges runs the queue by hand.
- Whether the repo is indexed in Graphify, found or missing. When it is, every session's prompt says so, and every thread uses it (Limits in CLAUDE.md).
- A `commit-authors` check inside the gate: it fails a commit not authored and committed by [COMMIT AUTHOR], a Claude co-author or "Claude-Session" trailer, and a pull request body that does not end with "Requested by **[OWNER NAME]**" or that carries a "Generated by" or "Generated with" line. It reads only the pull request's own commits, and runs again when the body is edited.
- When the owner names a restart handoff (copies of a repo's rules, CI workflows and settings kept before they were removed), the CI, the gate and the repo's own notes are restored from those copies first, as first-time setup (Risk in CLAUDE.md), and the branch protection goes into the owner's batch of commands; each is reported as restored or changed with a reason, before anything new is written.
- Whether the repo allows auto-merge (`gh api repos/<owner>/<repo> --jq .allow_auto_merge`); a private repo on GitHub's free plan cannot. Also whether it deletes merged branches by itself (`delete_branch_on_merge`).
- The session tools the staged path uses (starting, messaging, choosing a model for and archiving sessions), each found or missing.
- The superpowers version, recorded as a commit or release under "Setup" in `docs/superpowers/history.md`, and any place its skills disagree with these rules.
- The compaction hook: `.claude/settings.json` has the `SessionStart` entry with the matcher `compact`, and its command prints `.claude/after-compaction.md`.
- The rule hooks: `.claude/settings.json` runs `.claude/hooks/rules.mjs` on `SessionStart`, `PreToolUse`, `PostToolUse` and `Stop`; `node .claude/hooks/rules.mjs --check` reports no blank left (it reads the author and the "Requested by" line from the Identity rule in `CLAUDE.md`); `.claude/hooks/rules.json`, whose repo values (render commands, software-renderer variable, design tools allowed to take screenshots, required statuses, session and message tools, hosted-runner check on a private repo, `firstTimeSetup` turned off at the end) the setup check fills in, also holds the pull request flow check (a lane and acceptance criteria in the body, drafts, the open pull request limit, a passing review naming the head commit before a lane 2 or 3 merge) and the subagent model check; a fresh session shows the rules at its start; and where sessions start one folder above the repo, `node .claude/hooks/rules.mjs --install-user` has added the launcher to `~/.claude/settings.json` on that machine, so those sessions load the hooks too (run it once on a computer; a cloud environment starts every machine fresh, so paste what `node .claude/hooks/rules.mjs --print-setup` prints into its setup script once: that script needs no repo and never stops a session from starting).
- The `verify` skill: `.claude/skills/verify/SKILL.md` is there, and a fresh session that follows it from a clean checkout starts this repo's app or game and gets a screenshot of its main screen on a GPU machine (see "Shoot on a GPU" in `visual-check`). In a repo with nothing to start yet, it is reported as missing until the first screen exists.
## Where work runs

Choose where work runs by what it needs, not by habit.

- In the cloud: everything. Logic, tooling, unit tests, docs, builds, browser tests, screenshots, the frame budget, long work nobody steers minute by minute, the coordinator, plans and audits run in cloud containers or on cloud pods: CPU pods, and GPU pods for anything that renders (see "CI and test machines" in `vertical-slice`).
- Nothing runs on the owner's computer, on a public or a private repo: no test, build, app, game, runner, measurement or command. What only the owner can run goes to the owner as CLI commands. What needs a physical device or the owner's hands (real input feel) is measured by the owner by hand, for example on the deployed preview, from steps the session writes out, and until then it is reported as not measured, never as met.
- Browser device profiles emulate a screen size, a user agent and touch. Their results are emulation evidence, not proof of performance on a physical device; a budget for a device is measured on that device.
## Where tests run

- Quick targeted tests run locally whenever they help, before you push: the checks for what changed, and the smoke set (see `build`). Locally means where the session runs, which is always a cloud container. Specs that open several pages run there one worker at a time, because heavy jobs on one machine starve each other and fail on timeouts.
- Tests run only in cloud containers and in CI, on a public or a private repo.
- CI is the merge gate. On a private repo the gate runs the unit tests on a CPU pod and one GPU check (the smoke set) on a GPU pod, and the full browser suite is not part of the gate: it runs on GPU pods, in the pieces set in Settings, when a brief asks for it. On a public repo the unit tests, lint, typecheck and build run on GitHub's runners, which are free there (see "Fast CI" below), and the smoke set stays on one GPU pod; the full browser suite is not part of that gate either. Checks for independent pull requests run at once, within the capacity in Settings; only the final integration with `main` runs one at a time. A repo with no CI workflow uses the host's build check, and a cloud session passes lint, typecheck and the unit tests in its own container before it pushes.
## Fast CI (public repos on GitHub's runners)

- Open every pull request as a draft; the implementer marks it ready for review as its last step, after its final push and after every review its lane calls for. Private repos use no draft rule for lane 1.
- A draft gets a quick run: lint, typecheck and build in full, but only the tests the change reaches, stopping at the first failure.
- Marking the PR ready starts the full run used by the merge gate, but only when the workflow lists `ready_for_review` in its `pull_request` types: the default types (opened, synchronize, reopened) do not include it. Check the workflow file before relying on it. Green on a draft is not done.
- Screenshots and playtest video are taken automatically when the diff touches screens, scenes or gameplay files (the workflow lists those paths), with no label needed, and only of the screens those files reach, at the sizes they affect (`visual-check`).
- Browser tests in the gate are the smoke set on one GPU pod; a full browser suite run uses the pieces set in Settings (CLAUDE.md), with the browsers in the job's image and installs cached (Making CI fast, below). A newer push to a pull request cancels its older run. A run on `main` is never cancelled, so every merge gets its own result. A change to the database, fixtures, lockfile or build/test config makes even a draft run everything.
- Watch the run in the foreground until it ends (`gh pr checks <number> --watch` or `gh run watch`, with a long timeout, repeated until the run ends), and never end the turn to wait for it. Act the moment it ends. Read a log only when a check fails. Where `gh pr checks` fails because GitHub's GraphQL API is blocked (some cloud sessions), poll the REST API in one foreground loop instead: `gh api repos/<owner>/<repo>/commits/<sha>/check-runs`, every minute, until no run is queued or in progress.
## Making CI fast

- The aim: a pull request gets its result in under 1 minute at the median and under 2 minutes at p95, without letting CI lie. Three rules come before speed:
  - The full suite runs before anything reaches `main`. Selection only narrows a pull request's feedback.
  - Never hide a failure. No retries, wider timeouts or skipped tests. A check that needs a retry has a bug: find it. The one rerun `build` allows to find out whether a failure is flaky is a diagnosis, reported with both results, never a pass; a gate retrying an outside service's call that answered 429 or 500 is not a check retry.
  - Never check less. Lint rules and required checks only stay or grow.
- Audit first, at the setup check and whenever the median misses the aim: pull the last 150 runs and split every job into waiting, setup and running, at p50 and p95. Fix the biggest bucket first.
- The toolchain is the one the Default stack names: one fast tool each for tests, the typecheck, lint and formatting, with every lint rule on that can be. A tool that exists only in a canary is pinned to that exact canary. A repo that already has other tools keeps one only for a measured reason: before each switch, run old and new side by side and list anything the new one misses.
- The shape: lint, typecheck, build and tests run in parallel, and no required check waits on another; only the final gate job (Docs only, below) waits, to collect them. Shards are filled by the test times that `main` records on every full run, and the shards together are shown to have run every file. Until a pull request is marked ready, it runs only the tests the diff can reach; the full run that gates the merge runs everything (Fast CI, above). The workflow lists the inputs that rerun everything (the lockfile, build and test config, shared fixtures, CI files), and when selection is set up, a real change hidden from it on purpose must turn CI red. The backend the tests drive builds the app once per test process, not once per test file. Match workers to cores before raising the pieces in Settings.
- Public repos keep GitHub's own runners, which are free there, for the jobs Where tests run puts on them. Nothing a job can be given ready-made is installed in it: a job that drives a browser runs in an image that already holds the browsers, pinned by digest to the locked version (Default stack). Installs are cached from `main`, and a slow job that only takes pictures stays off the path to the required checks.
- One small pull request per change, with before and after numbers from real runs. Do everything you can without the owner first; bring anything that needs an account, a secret or money as one list with its expected monthly cost. End with total CI time and cost, before and after.
## Docs only

A pull request that changes only `.md` files is lane 1, and its tests may not apply, but its required check is never skipped: a required workflow skipped by a path filter stays pending, and a job skipped by a condition can report success without proving anything. So the workflow always runs. Its first job decides from the diff which checks apply, and one final aggregate gate job, required alongside any existing required checks, passes only when every applicable check ran and passed and every other check was marked not applicable by that first job. Specs, plans, audits and progress notes are docs, so they merge on green without the owner, and the next stage starts from `main`. Any other file in the change brings the tests back. Classify by effect as well as extension: rules files (CLAUDE.md, the shared skills, and anything else that decides what needs the owner) are `.md` files too, but a change to them requires lane 3 checks and reviews plus the owner's approval or an applicable standing permission. As Risk in CLAUDE.md says, a repo's own `verify` and `this-repo` skills take the lane of the code change they describe. One edited alone is lane 1, unless it changes what needs the owner.
## Lanes and merging

Every unit carries a lane, classified from its diff and what the change does (see Risk in CLAUDE.md). The highest lane wins, and confidence never lowers it.

| Lane | What it is | It merges when |
|---|---|---|
| Lane 1 | Small and easy to undo | Green |
| Lane 2 | Wide: shared code, a schema, config | Green, plus the extra checks below |
| Lane 3 | Hard to undo | Green and its audits, plus the owner's approval or a recorded standing permission that covers it |

- Lane 3 never opens by itself.
- A lane 2 or 3 pull request goes ready, merges or gets auto-merge only when the newest verdict line (see "Checks and reviews" in `review`) on its head, or on a commit that reaches the head only through clean merges of `main`, is a PASS. A later FAIL on any of those commits wins until a newer PASS. The rule hooks refuse anything else.
- Ready for review means ready to merge: a repo may merge a ready pull request by itself the moment it is green, and that never waits for a review. So on any repo, public or private, a pull request stays a draft until the reviews its lane calls for are done: lane 2 until its fresh review, lane 3 (the rules files included, as Docs only names them) until its audits and the owner's word or a standing permission that covers it, and a spec until its plan audit when it has one. Lane 1 has no review to wait for.
- A golden that moves for an approved behavior change updates with the change, inside the scope of that approval (the spec or milestone that names it); one that moves only in a test or sample game merges on green. Each carries a before and after note in the pull request. Any other move of a golden in the shipped product waits for the owner. A golden is never re-recorded to hide a defect.
- A deletion the plan called for that git can restore merges on green, with a before and after note. Deleting anything git cannot restore is lane 3.
- Green means every required check is successful on the pull request's current head commit. The required checks are known in advance (the repo lists them): a missing, pending or unreadable check blocks the merge, and a new push makes earlier results stale. On a public repo the full run after ready for review is the one that counts. An audit or a visual review names the commit it examined and counts only for that code. A later commit that changes only the audit file, a live-state file or docs the audit did not cover keeps it. A commit that changes behavior makes it stale for what it touched: the checks that reach it run again and the reviewer reads that diff. A pull request that touches what people see is not green until its visual check is done and any fix it found is made (see `visual-check`).
- A merge queue keeps `main` green: before merging, integrate with current `main` and rerun the checks on the result, one pull request at a time and only the one about to merge. Use GitHub's merge queue where the repo can have one (a public repo owned by an organization, or a private one on Enterprise Cloud). Where it cannot, the session that merges runs the same queue by hand: it merges current `main` into the pull request and pushes before marking it ready, one pull request at a time; when `main` has not moved since its last full run, that run stands. A pull request already ready when `main` moves goes back to draft first, or auto-merge stays off on that repo. A clean merge of current `main` keeps the review, unless `main` changed a file, interface or schema the audit named or the change calls: then the reviewer reads that part again. A merge that needed conflicts resolved makes it stale. Branch protection does not require branches to be up to date, so a waiting pull request is never updated just because `main` moved. The pull request records three commits: the one reviewed, the integration commit tested (its head merged with current `main`), and the `main` commit it was tested with. The session that merges watches `main` after the merge. If a post-merge check fails, it reports at once and owns the failure, with a revert if the merge caused it, until `main` is green or the owner takes it over.
- A required check that is red on `main` as well is an existing failure, not this pull request's: report it and give it its own thread. The pull request keeps going and merges once that thread fixes `main`, unless the owner authorizes an exception for that check, named in the pull request. A check that is not required never blocks a merge.
- Extra checks for lane 2: the full run, not the quick one; a fresh review session on what the change touches (see `review`); and a clean run: unchanged code is never retried into green (a rerun that validates an actual fix is fine).
- The session that made the change opens the pull request and merges it once its lane allows: lane 1 on green, lane 2 after its review, lane 3 on the owner's word or a standing permission that covers it. It is a merge commit, never a squash, then the branch is deleted, and a pull request whose lane has opened and whose checks pass is never left open. Where the repo allows auto-merge, it queues the merge (`gh pr merge <number> --auto --merge`) in the step that marks the pull request ready, at its turn in the queue; if `main` moves first, it turns it off (`--disable-auto`) and goes back to draft. It still watches the run and `main` after the merge.
- A tool that appends its own footer to a pull request body (a "Generated by" line) breaks the identity rule in CLAUDE.md. Write the correct body to a file, have a session whose tools add none apply it, or on a public repo give the owner the command (`gh pr edit <number> --body-file <file>`), and check the last line again.
- On a private repo, a merge, or any lane 3 step, run by a session on the owner's computer in an automatic permission mode needs the owner's own typed words in that session: a decision-card tap or a request from another session does not count.
- The implementer owns a required check that fails because of the change: that failure is the implementer's to diagnose, fix and rerun. Report a material effect on outcome, timing or confidence through the owner updates. Pause for an owner decision only when blocked by a decision, access or budget.
- The session that merges reports each merge. It stops and reports to the coordinator, instead of resolving it, on: a merge conflict it cannot resolve cleanly, a golden that moved without a commit naming it, more branches than the limit, a pushed branch nobody asked it to merge, or a lane 3 item no standing permission covers.
- When a pull request merges, mark its outcome complete in the active milestone in `progress.md`. When that milestone closes, archive its record in `history.md`. Add a lesson line only if the work taught a lesson no test can catch (see `review`). The active coordinator owns this; otherwise the implementer does.
## The finished result

The owner approves this once, when the whole piece of work is done (a finished spec, or a game milestone), not at each merge. Report how it went, measured: elapsed delivery time (from the brief's approval, which on the short path is the request, to the last merge), time spent waiting (on CI, on the owner), owner interventions, rework (fix rounds and reverts) and escaped defects (failures found after a merge). Line counts, test counts, sizes and ticked percentages are supporting information only. Say what ran, what did not run and why, and give a preview link when the repo has one. Summarize material decisions made during the work, their reasons and remaining limitations. Interim updates and previews follow "Owner visibility and early steering"; significant surprises must not first appear in this final report.

Skill: visual-check

Save this as .claude/skills/visual-check/SKILL.md in your repo.

---
name: visual-check
description: Use when a change touches screens, layout, copy that people read, or anything a person looks at.
---

# Visual check

This runs on its own whenever a change touches what people look at: the diff touches screen files or copy, or a screenshot moved. A program can tell, so nobody has to ask first. A pull request that touches what people see is not green until this check is done and any fix it found is made. Share early working screens and meaningful visual changes under "Owner visibility and early steering", before extending the design across the product. Label unfinished work and known defects. The owner still gives final acceptance once, as part of the finished result.

A small change (a copy fix, one screen) gets step 1 only, and the session that made it looks, fixes what it finds and looks again. No findings means no fix round. For a set of screens or a slice, fresh review sessions find the problems and the session that built the screens fixes them, with everything in one pull request. A slice, the first one included, is never a small change: fresh sessions run every step, even when it has one screen.
## Shoot what the change touches

Screenshots, walks and reviews cover only the screens a change touches, at the sizes it affects, never every screen at every size. A change to one screen is shot on that screen. A layout change for one size is shot at that size. Copy and fonts are shot at the smallest size, where words wrap first, in each language they change. A shared style, token or component is shot on every screen it reaches, at the sizes of the device matrix in Settings. Where a program can tell from the changed files which screens and sizes a change reaches, it picks them (the repo's `this-repo` skill names it), and a person adds a screen or a size only with a reason in the pull request. A screen or size the change does not touch is not shot again. Every step below, and every walk and review that takes screenshots, runs on this set.
## Shoot on a GPU

Every screenshot, screen walk and playthrough that renders runs on a GPU machine (the repo's `this-repo` skill names it), never on software rendering in a cloud container: software drawing is many times slower, so a shot that takes seconds on a GPU takes minutes there. A session that needs shots asks the GPU machine for them and does other work while it waits. Unit tests, and browser tests that take no pictures (such as the short checks the repo runs before a push), may still run in the container.
## Before the build: a layout sketch

A brief or spec that adds or changes a screen carries a layout sketch of it: an ASCII or simple box diagram in the spec, or on the short path in the pull request description, that shows what goes where, meaning the main action, the panels and the way back. Where the smallest and largest devices in the matrix in Settings lay the screen out differently, it sketches both. It takes minutes. No pixel designs, no drawing tools and no round of approving the look before the build: the sketch catches a wrong layout early, and the steps below settle the look after the build. Steps 1 to 3 check the built screens against the sketch's layout; a difference is a defect unless the pull request names it with a reason. A named difference also goes into the next update to the owner, with pictures of the sketch and the built screen, as "Expose decisions" in `owner-updates` asks; it is not a new approval gate.
## Before the next slice

Do not move to the next slice without a design review loop on the screens completed during that slice: step 1 beside the slice-end walk (step 2), then the fixes, then step 3, on the screens and sizes the slice changed (see "Shoot what the change touches"). The loop runs in the rounds set in Settings, every one of them. A round shoots the screens, a fresh session checks them, and the session that built them fixes what it found; a round with no findings has no fixes. Every check looks at every screenshot one by one, never a sample, on the model Settings names for that round. The first round is step 1 and the fixes for both it and the walk; later rounds are step 3 on the screens again. The last round before the owner's first look ends with step 4, once per slice. After those rounds, the screens page goes to the owner; the next round fixes the owner's notes along with its own findings, and the screens page goes to the owner again. Screens the owner has already approved are skipped.
## Screens page

The coordinator shows the screens page twice at the end of every slice: after the design review rounds before the owner's first look, and again after the round on the owner's notes, before the owner's walk. Each time it shows all of the slice's screens in one organized artifact: grouped by flow, in the order a person meets them, each screen at each size it was shot at (see "Shoot what the change touches"), labeled with its name and the commit it shows. Screens the owner already approved are included and marked as approved. Share it as one link, not as screenshots scattered across messages. It is for viewing, not keeping: once the owner has looked at it, its pictures are no longer needed, nothing keeps a copy of them, and the coordinator deletes the page where the runtime can (or lists it for the owner to delete). Approvals in `history.md` name each screen and the commit it shows, never a picture, and a later look shoots the screens again.
## Skip what is already approved

- Each step looks only at screens the owner has not approved yet. The coordinator records each approval under "Approved screens" in `docs/superpowers/history.md`. A screen's approval ends when anything that affects it changes: its own files, shared styles, shared components or behavior.
- The full review runs once per set of screens. Later rounds check only the screens whose approval ended.
## Reviews in batches

When a review covers many screens or scene captures, start it in batches within the session limit in Settings, each with a fresh reviewer that reads the same named commit and still looks at every screenshot in its batch one by one; the batches together are that round's one check. Each batch's findings go to the builder by message as it finishes; the builder may start on them but pushes only after the round's last batch reports, and no batch commits its audit file before then. Tell reviewers to measure what can be measured (contrast, how much shows through a panel, sizes and positions) from the pixels, and to judge by eye only what cannot be measured. The coordinator starts the batches. This adds to the steps below and to any scene skill, and replaces nothing in them.
## The steps

Steps 1 to 3 judge the screens against the brief's acceptance criteria. A gap against one is a defect; an idea that would make it better is a note. Step 4 is the one exception: the gap it names is fixed even when no criterion names it.

1. **Words-and-design check:** one check, at the sizes the change affects. Could a drunk grandma understand every word? In practice: every label and message is plain words with no jargon, each screen has one main action that is visible without scrolling, and buttons are big enough to hit with a thumb. Then layout and polish.
2. **End-to-end walk:** the slice-end walk (see `review`), run once and read here, never walked again. A drunk grandma must always see the next step and a way back: no screen is a dead end, and every error says what to do next.
3. **Last look:** in each round after the first, by a fresh session, on the screens and sizes the fixes touched, after the fixes have landed. A defect it finds returns to bounded fixing within the tries in Settings, and the look runs again on those screens only.

4. **Blind judge:** one round per slice, at the end of the last round before the owner's first look, after step 3 passes. A fresh session (the preparer) picks a polished commercial product of the same kind and takes public screenshots of it (its site, store page or docs), with no purchase or sign-up. It pairs each with our screen of the same kind, at the closest size, at the sizes that were shot, and leaves out a size with no fair match. It covers product names and logos, labels the two sets A and B in a random order, and keeps which is which out of the judge's brief. A fresh session says which set looks amateur and names the single biggest gap for each set, where it falls short of the other, or says it cannot tell them apart, and then there is no fix. The preparer, who holds the key, takes the gap named for ours. That gap becomes one fix brief, within the slice's scope and the tries in Settings; a gap that needs a product choice, a new dependency or spend goes to the owner as a decision card with a recommendation instead. Step 3 then runs again on the screens the fix changed. The blind judge does not run again, and the coordinator records its pick in `docs/superpowers/progress.md`.

The order is initial reviews, then the fixes, then the final look, then once per slice the blind judge. Steps 1 and 2 do not need each other, so they run side by side; step 3 waits for the fixes.

Skill: build

Save this as .claude/skills/build/SKILL.md in your repo.

---
name: build
description: Use when writing a brief's acceptance criteria, or writing or changing code or tests, or when a test fails, flakes or is pruned.
---

# Build
## Quality bar

The least every brief's acceptance criteria cover, where they apply:

- The core loop and the objectives and state transitions defined in the brief work. Where the game defines winning or losing, each outcome is clear and testable. Open-ended games use their specified progression and recovery criteria.
- The game handles restart, pause and save where it has them.
- Every game is fully playable with a keyboard alone and with a gamepad alone: every screen, menu and dialog, not only play itself, with a visible focus ring wherever the player is, and anything the player must type (a code, a name) can be entered with the pad. Each of the two has its own end-to-end walk (Playtest and controls check in `scene-polish`). The player can also use every supported control the brief names, such as mouse and touch.
- In the opening minute a new player knows what to do without being told.
- Meaningful actions have clear, appropriate feedback. Essential information remains understandable with audio muted; sound supports the experience where appropriate. Challenge and difficulty follow the brief.
- The game's audio and motion are consistent with its art direction, with no stutter, pops or clipping.
- The frame-time and loading budgets in the brief hold on the named hardware in the brief, measured.
- Browser device profiles emulate a screen size, a user agent and touch: that is emulation evidence, not proof of how a physical phone performs. A budget for a device is measured on that device.
## How code is written

- Comments say why. They do not say which plan asked for the code.
- Use injected clocks and fixed seeds. Browser tests wait on readiness, never on a sleep.
- A browser game detects a software renderer (the WebGL debug renderer name, such as SwiftShader) and then caps its frame rate and resolution, so browser tests in a container start in seconds instead of timing out; a real GPU is never capped. In PixiJS set both `ticker.maxFPS` and `ticker.minFPS`, since `maxFPS` is clamped to at least `minFPS`. A cap of one or two frames a second is enough for a test: a menu that took most of half a minute starts in a couple of seconds, and specs that open several pages run several times faster.
- With the frame cap on, input is still read on every animation frame; only the drawing is capped. Input read only in the capped render ticker misses presses: at one frame a second, gamepad taps fall between reads. The check: with the cap on, a test presses a key and taps a gamepad button (fake the pad by stubbing `navigator.getGamepads`), and the game sees each one through the same per-frame poll. Trigger: a diff that touches input code or the frame cap. The GPU path does not change.
- Specs that are visual evidence (screenshots, and passes that judge colour or motion) and the guard step that catches software WebGL run only on GPU pods, never on a CPU pod or GitHub's runners, and are left out of the local smoke set. On a CPU machine they time out even when run alone, and frames drawn at one frame a second and half resolution prove nothing. The check: a test reads the CI config and fails if a job that runs on a CPU machine would run a visual spec or the guard step. Trigger: a diff that adds a visual spec or changes the CI pieces.
- Keep a small smoke set: a handful of the main journeys, on the smallest and largest device, that passes in a cloud container in a few minutes. Run it before every push. A spec that opens several pages (one per player) runs one worker at a time on a CPU machine: parallel workers starve each other and fail on timeouts.
- Before speeding up the unit tests, measure where the time goes. The test runner reports its phases: loading the files (it may call this collect or import), building the environment, the setup files, and the test bodies. Loading often costs more than the tests themselves. Compare each phase to the time spent in the test bodies as a ratio, never as seconds alone, since the same suite takes very different time on two hosts ("CI and test machines" in `vertical-slice`). The ratio finds the cost and shows a fix worked; the change is still done only when real runs show it, as that section says. Trigger: a diff made to speed up the unit tests, or a unit-test job that has grown slow.
- A unit-test file with no DOM in it runs in a plain Node environment, and a DOM environment is built only for the files that need one, since building it is paid again in every file. A file moves to Node only when all three hold: it passes there without the DOM setup, nothing it loads checks for `window`, `document` or `navigator` (some libraries quietly switch to another mode when there is no window, so the test passes while testing something else), and it does not check for a window itself. A setup file fits the environment it runs in: with no window it skips the DOM stand-ins and does not import the DOM testing helpers, and under the DOM environment it does exactly what it did before. The check: a test fails when a Node file, or project code that file imports, names one of those globals, and a test runs each setup file with no window and fails if it throws or loads a DOM helper; a library a moved file imports is read for those globals once, when the file moves. Trigger: a diff that adds a unit-test file, moves one between environments or touches a test setup file.
- Fakes and mocks stay narrow: a test imports only the fakes it uses, each from its own file, never through a barrel file that drags in every screen, because every test file pays to load everything it imports. A generated catalogue of many small files (one file per translated message, for example) is loaded in tests as one module. Where that takes a test-only stand-in, a test proves the stand-in exports exactly the same names as the real generated files and gives the same result for each, and the build keeps using the real files. That test checks the stand-in, which is hand-written test code; the generated files themselves are still verified through their source and the tool that makes them (Verification below). Trigger: a diff that adds a shared fake, a file under `tests/` that re-exports other files, or a test-only stand-in for generated code.
- Look at the real expected, actual and diff images before accepting a visual change, and explain each change.
- A look that many screens share (a panel, a button, a chip) is one shared component with its values as named tokens, and a screen uses it instead of styling its own. A test fails on a second copy: it reads the styles, or the drawing code where menus are drawn on the canvas, and fails when any file but the shared component sets that look's fill, blur or border. A rule the owner sets for a look (every panel has the same finish, for example) is written as numbers the test and the reviewers measure, such as how much shows through and the text contrast, not judged by eye. The shared pieces live in one low feature that the screens import (the layout below), not in a top-level `components/`. Trigger: a diff that adds or restyles a screen.
- Two pieces of work that restyle the same screens or the same shared component touch the same files and the same assumption, so the later one starts from a `main` that holds the earlier one (Splitting in `staged-path`); a numbered order alone is not a reason to wait, a shared look is. Built the other way round, the later one's screens are rebuilt and walked again. Trigger: a plan or brief that restyles screens another open pull request also restyles.
- Code is grouped by feature, not by kind: no top-level `components/`, `services/` or `utils/`. A feature owns its code and data and imports only from features below it. Tests never sit beside the source; `tests/` mirrors `src/`. The layer order is written in `tests/architecture.test.ts`, one list with the lowest feature first, and the test fails on an upward import or a cycle.

  ```
  src/
    index.ts                 the public surface; anything it does not export is internal
    lib/                     shared helpers with no feature logic (maths, IO, random)
    features/<feature>/      one folder per feature: <feature>.ts is its entry, one job per file, library/ its data
  scripts/                   thin command-line wrappers over src/
  tests/                     mirrors src/; architecture.test.ts holds the layer rule (imports go down, no cycles)
    golden/                  pixel or snapshot goldens, one per scene
    playtest/                Playwright playthroughs of the whole game
  docs/superpowers/          specs/, audits/, live/, progress.md and history.md
    roadmap.md               everything left, in order, with who does it and where it stands
  ```
## Verification

Checks are what let work be handed off: what a program can judge, nobody has to read line by line. The owner says what done looks like and looks at the evidence; the checks do the rest, so they are built and kept like any other part of the product.

- **Run it like a person.** Before a change that alters what the product does is called done, its builder runs it: starts the app or game, goes through the changed journey with real taps, clicks, keys and typing, and looks at what happens. Passing tests are not this. How to start and drive this repo is in its `verify` skill, which the builder loads before every commit that changes behavior. Every session leans on it, so it stays quick and steady: a step in it that breaks or flakes is fixed first, and a change to how the product starts or what its first screen shows updates it in the same pull request. A session starts it clean once; its later runs may reuse the app or game it already has running.
- **The test that is hardest to fool comes first.** A unit test can pass while the feature is broken, because the test and the code share the same misunderstanding. So, in this order: 1. **Journeys**: a person's path through the running product, from the first screen to done; a failure names the step, with a screenshot; a changed journey gets a journey test. 2. **Property tests**, for the cases people and agents both miss: state something that must always hold and let many generated inputs, from a fixed seed, try to break it: round trips (save then load gives back the same thing), invariants (a count never goes below zero), repeats (doing it twice is the same as doing it once: migrations, retries, clean-ups) and twins (a fast version agrees with a plain, correct one). A property-test library is a new dependency and needs the owner's yes first. 3. **Old-versus-new tests**, for a rewrite or a move that should not change behavior: run the old and the new on the same inputs, set aside differences that do not matter (spacing, order), and treat every other difference as a bug unless it is on the change's written list of intended differences. Unit tests cover the small pieces underneath.
- **Test first, from the outside in.** Write the failing test first and confirm it fails for the right reason. The first one is the hardest-to-fool test the change reaches: a journey test when the change alters a journey, a property test when a rule must always hold. It stays failing while small unit tests build the pieces under it, each in a quick loop: a failing test, the least code that passes it, then a tidy-up with every test still passing.
- **Old code and today's behavior.** A test that pins what the code does today, before a refactor or a rewrite, passes at once on purpose: show that it can fail by breaking the code on purpose, then put the code back. Code written before its test is thrown away and written again from the test, except the old code in a rewrite, which stays as the yardstick until the old-versus-new test passes on the new.
- **Tests.** Quick targeted tests run locally whenever they help; CI is the merge gate. A failing test blocks only the change that touches it: report an unrelated failure, and give a failure on `main` its own thread. A merge still needs every required check green, unless the owner authorizes an exception named in the pull request. Never loosen, skip or re-record a test to hide a defect. No `--pass-with-no-tests` or similar flag that lets an empty suite pass in CI. Updating a golden for an approved behavior change is fine, with its before and after shown. A docs change or a purely visual change is verified by what fits (a link or build check, the approved look), a configuration change by lint, typecheck, the build and the CI run, and generated code (an API report, compiled messages, a database client) through its source and the tool that makes it, not by an invented unit test.
- **Quick and steady, or it gets skipped.** A slow check gets run less, and a flaky one teaches a session to rerun instead of fix. Cheap checks first (lint, typecheck, the tests the change reaches); before a push, the journeys the change reaches; the full suite in CI, where `release` sets the gate. A test that fails once and passes on retry is a defect. One rerun to find out whether a failure is flaky is allowed, and both results are reported; that rerun does not count as the clean run lane 2 needs. Report the flaky test with its text and record it under "Flaky tests" in `docs/superpowers/history.md`; its root cause is fixed in its own thread, unless it blocks this change. Never rerun it until it passes, slow it with a sleep, or skip it. If the root cause is not found within the tries in Settings, delete the test (never one for authorization, privacy, migrations or concurrency: that one stays and its root cause is found), put a steady check of the same thing in its place where one can be written, and record why, and the gap it leaves, under "Flaky tests".
- **A change does not quietly edit its own check.** If a change can edit the check that judges it, the check proves little. So CI workflow files, the repo's own root `CLAUDE.md` and the shared skills (every skill in `.claude/skills/` but `verify` and `this-repo`) change only in a pull request that changes no product code and no tests: a rule change, or the first-time setup, which may change several of them together. A code change that needs a CI workflow change lands the workflow change first, in its own pull request. A pull request that changes or deletes an existing test, golden or `verify` step names each one and why in its body. Its reviewer, where its lane has one, reads those first, and when it edits `verify` also runs `verify` from `main` (`review` says so too).
- **Lessons become tests first, and carry a trigger.** A confirmed failure gets a regression test. It becomes a lesson only when no test can catch it: one line under "Lessons" in `docs/superpowers/history.md` naming its trigger (the paths, or the kind of change, a diff shows), what to look for, and the failure behind it. Before it pushes, a session reads the lessons and acts only on those whose trigger its diff matches; a plan also carries the matching ones into its brief, as `review` says.
- **Prune.** Tests, `verify` steps, lessons and rules only grow unless someone trims them. Each retrospective removes the ones that no longer catch anything or that another check already covers, naming each one and why: rules and lessons in its rule-change pull request, tests in their own.

Skill: staged-path

Save this as .claude/skills/staged-path/SKILL.md in your repo.

---
name: staged-path
description: Use when work is uncertain, waits on a decision or other work, or is lane 3; when starting, tracking or handing off a session; or at a slice's end.
---

# The staged path

- **When.** Stage the work when the outcome or the approach is uncertain, when it waits on an open decision or on other work, or when it is lane 3. A new feature or many files alone does not stage it. Risk decides the audits, never the number of tasks; the audits for each lane are in Settings.
- **Can this runtime start sessions?** Before the first stage, the coordinator checks each capability on its own: starting a session, sending it a message, choosing its model and archiving it. A missing one changes only what needs it: without archiving, finished sessions are listed for the owner to close; without a model choice, sessions run on the default; without messaging, sessions report through committed files. Reviews run in fresh, isolated sessions wherever the runtime can start one (a new session, or an isolated reviewer it supports). The coordinator asks the owner to start a reviewer only when no isolated reviewer session can start, and then runs the stages one after another itself, each starting from the committed documents.
- **Superpowers.** Its skills run the steps named below (brainstorming, writing-plans, executing-plans), at the version the setup check records; where they differ from these rules, these rules win. The testing skills that executing-plans names as required are not loaded: Verification in `build` replaces them. A final review its skills ask for is the implementation audit when the lane calls for one, run once by a fresh session (`review`), not a second review; on lane 1 it is the implementer's own check. Any deferring minor findings it suggests does not apply: the fix round fixes every in-scope finding.
- **Splitting.** Split by what a mistake costs, not by folder: one unit, one input, one output, one lane. Each unit is a row in the plan: its name, the units it waits on, the files it owns, its output and its acceptance check; its status is in `progress.md`. A unit waits on another when it reads that unit's output, or when the two touch the same file, interface, schema or assumption, and no two running units own the same file. Units inside one implementation pull request run in plan order on its branch; across pull requests a unit starts from a `main` that holds what it waits on. Units that share none of those run side by side. An order written in a plan is a claim that one unit waits on another, checked against those, not a queue: units that share none run side by side up to the writer limit in Settings, and a plan that starts a unit "after the previous merges" names what it reads from them. Each unit runs its own produce, check, correct loop; what it waits on decides only when it may start. A step with one right answer (merge, rank, dedupe, compare) is plain code, not a model. Build the gate first: before a repeated job, write the one check that can fail it.
- **One working brief, one implementation pull request.** On the staged path the brief is the spec: the outcome, the acceptance criteria, the boundaries the owner approves (dependencies, tools, environments, budget, expected duration) and the plan, in one document. The spec and its plan audit are docs: the spec merges on green without the owner, with its plan audit when it has one, and the build starts from `main`. Execution, the implementation audit and the fixes share one branch and one pull request: the audit reviews that branch before it merges, and the fixes land on it.

| # | Stage | Who | Writes |
|---|---|---|---|
| 1 | Spec | A spec session the coordinator starts, with the owner (superpowers brainstorming); a plan session adds the plan when the approach is uncertain (superpowers writing-plans) | `docs/superpowers/specs/<date>-<topic>-design.md` |
| 2 | Plan audit | An audit session, `review` skill (lane 3 only), on the spec's pull request | `docs/superpowers/audits/<date>-<topic>-<cycle>-plan-audit.md` |
| 3 | Execution | The implementer: one work session (superpowers executing-plans) | the code |
| 4 | Implementation audit | A fresh audit session, `review` skill (lane 2 and 3) | `docs/superpowers/audits/<date>-<topic>-<cycle>-implementation-audit.md` |
| 5 | Fixes | The implementer, in the same session | the code |
| 6 | Review | The owner approves the finished result | notes for the next spec |

- **Writing.** One writer per branch at a time: the implementer writes, then hands the branch to the reviewer by naming a commit; the reviewer commits only its audit file and hands the branch back by naming its own commit. The audit reads a named commit, never a moving branch. Independent writers use their own branches or worktrees. The coordinator is the only writer of `progress.md` and `history.md` while active, including for delegated short-path work; each session's own live-state file in `docs/superpowers/live/` is the exception, written only by that session. If the coordinator cannot write to the repo, the implementer writes them for it and says so in the commit. Otherwise the implementer owns those records. The tracking document in the implementation prompt is the plan's own checklist, written by the implementer on its branch. Worker reports do not create additional writers of the shared progress record.
- **The coordinator** is one long-lived session. It talks with the owner, creates `progress.md` and `history.md` if missing, starts each stage's session, tracks them in `progress.md`, names each unit's lane in the spec, and archives each session when its job is done: a spec, plan or audit session once its file is handed back, and the implementer only after its pull request merges or it hands off under Session refresh, because the fixes are its job. An implementer or slice builder waiting on a review or the owner keeps its place among the 3 writers but does not count toward the 5. The coordinator never counts toward the session limit.
- **Specialist sessions start on demand:** a plan session, an audit session or the advisor starts when its work is ready and is archived when it is done. Nothing waits idle, except a writer waiting on a review or the owner.
- **The advisor** gives a short second opinion on a big call: the risks, what is missing, a recommendation. It never writes code or changes files. The coordinator starts it only for big calls: specs, plans, roadmap changes, and approving designs and layout sketches. It does not reopen the owner's decisions.
- **Slice end.** Every slice, the first one included, closes in this order: a fresh end-to-end walk (see `review`); the design review rounds before the owner's first look (see `visual-check`); the screens page, for the owner's first look; the round after it, on the owner's notes; the screens page again, for the owner's second look; the owner's own walk; and last the retrospective. Do not move to the next slice without a design review loop on the screens completed during that slice.
- **End-to-end walk.** A fresh session that did not build the slice walks every journey in it and reports each step as pass or fail, with evidence (see `review`). **Screens page.** All of the slice's screens in one organized artifact, grouped by flow and device, for each of the owner's two looks (see `visual-check`).
- **Retrospective.** The last stage of every slice, the first one included. After the slice ends (on the short path, after each approved finished result), a fresh thread reviews every loop the slice ran, not only design review: the build and fix rounds, the audits, the end-to-end walk, every review round, CI waits and stalls, flaky tests and repeat fixes. It turns each lesson into a test where it can, such as a PR-footer check, and proposes the rest as one rule-change pull request for the owner to approve. It also prunes, as Prune under Verification in `build` says. Nothing to learn, no pull request. The next slice can start once the retrospective's pull request is open, or once the retrospective reports nothing to learn.
- **Handoff.** Every stage reads the files its prompt names, normally the spec, the audits so far and `progress.md`; the plan also reads Lessons in `history.md` and carries those whose trigger its work matches. It reports its progress to the coordinator, which keeps `progress.md`, and its last step is to commit and push. `progress.md` holds the active milestone, including completed outcomes needed to understand what remains. When a milestone closes, its work and decision records move to `history.md`; screen approvals are recorded there with their scope. The execution session starts with this prompt, and uses it again for the fixes:

```
Use superpowers:executing-plans to carry out the plan, and develop by these instructions.

Now implement precisely as planned, in full.

Implementation Requirements:

- Write elegant, minimal, modular code.
- Adhere strictly to existing code patterns, conventions, and best practices.
- Keep comments brief, and only where the code doesn't explain itself: say why, not what.
- As you implement each step:
  - Update the markdown tracking document and overall progress percentage dynamically.
```

- **Reporting.** Workers report to the coordinator through `send_message`, or committed files when messaging is unavailable: the task as understood at the start; meaningful milestones and their evidence; material decisions and assumptions; deviations and their reasons; previews; blockers; and completion. Separate facts from estimates and owner instructions from agent-selected choices. Ordinary debugging stays internal unless it changes outcome, timing or confidence. A missing tool replaced by an authorized alternative that meets the same acceptance criteria is a deviation, not a stop; an access refusal is never worked around.
- The session that merges reports each merge and each stop listed in `release`. Coordinators of related workstreams report decisions, changes that affect this work, blockers and what they push. The coordinator keeps the owner informed under "Owner visibility and early steering", including decisions that need no approval. Pause and request an owner decision only when the brief, permissions or an unresolved choice requires it; keep independent work moving.
- Each session's prompt names the files to read. A session watching CI reads a log only when a check fails, and waiting does not suspend the owner update interval.

Skill: owner-updates

Save this as .claude/skills/owner-updates/SKILL.md in your repo.

---
name: owner-updates
description: Use when starting work the owner will see, at each milestone or update interval, when showing a preview, when a material choice is made, or when the owner steers.
---

# Owner visibility and early steering

The owner stays informed throughout the work. Updates do not require acknowledgement: continue within the approved brief and permissions. Silence never creates a new approval. When a coordinator is active, it consolidates worker reports into one owner-facing update. Otherwise the implementer handles these duties; no extra session is needed.

- **At the start:** state the outcome being built, the important assumptions, the first step and the first point at which the owner will see working output.
- **During the work:** send a concise update at meaningful milestones and at the owner update interval in Settings. Report material changes, risks, setbacks and consequential decisions promptly. Routine debugging stays internal unless it changes the expected outcome, timing or confidence. If waiting on CI or another dependency, say what is waiting, what can proceed and what will unblock it; do not imply progress that has not happened.
- **Each update covers:** what is happening now; what changed since the last update; what remains and comes next; material decisions made; the latest preview and verification status; and anything the owner needs to decide. Omit unchanged details. Say "No action needed" when work can continue. Prefer completed outcomes and remaining work over an unsupported percentage. Label timing estimates and revise them when the evidence changes.
- **Show work early:** share the first working screen or playable core loop before extending it across the product. Show meaningful visual and interaction changes as they become available, using an available live preview, screenshot or short recording. Label layout sketches, incomplete work and known defects clearly. Identify the version shown. Reuse current previews until the output changes. Creating a public preview still requires the appropriate permission.
- **Expose decisions:** disclose material choices that affect user experience, appearance, architecture, dependencies, compatibility, cost, delivery order or accepted tradeoffs. State the choice, why it was made, its consequence and how easily it can be changed. Announce consequential choices within the approved scope before substantial dependent work accumulates, and continue. Choices outside that scope require approval before dependent work proceeds. Routine naming and implementation details need no separate notification.
- **Keep a visible record:** maintain `docs/superpowers/progress.md` with a last-updated time, current work, completed outcomes within the active milestone, remaining work, blockers, preview links and material decisions. Share its accessible link or location at the start and keep it current with each substantive update. Distinguish owner instructions, agent-selected choices and unresolved assumptions. A reported choice is not automatically owner-approved. The record's writer writes each owner instruction into it in the turn it is given, before the work it changes goes on, and checks it was applied before reporting that work done; a standing rule also goes into the owner's own rule-change pull request that turn. Archive completed milestones and their decision records in `history.md`.
- **Accept steering immediately:** check for available owner feedback before starting dependent work or merging. When the owner redirects or says "hold" on an item, acknowledge it, pause the affected work at the next safe boundary, update the brief and inform affected workers. Continue unrelated authorized work. State rework or consequences plainly. Keep choices reversible where practical; an update alone does not guarantee the owner has reviewed it.
- **At completion:** show the finished result, verification evidence, remaining limitations and material decisions made during the work. Do not defer significant surprises until this report. Final acceptance remains one finished-result review; progress updates and interim previews do not introduce approval gates.
- **If live updates are unavailable:** say so before long-running work, provide the timestamped progress record and use the runtime's available communication channel. Do not claim that the owner has received an update that could not be delivered.

Skill: vertical-slice

Save this as .claude/skills/vertical-slice/SKILL.md in your repo.

---
name: vertical-slice
description: Use when starting a new game, when a game has no playable slice yet, when setting up its CI, test machines or server, or before its first public release.
---

# Vertical slice

A game starts with a vertical slice: one short, playable path through the core loop, as good as it can be. Then the game grows one milestone at a time from the slice, which evolves by default.
## Setting up

- **Keys once.** The owner creates every key and secret one time, at setup, and is never asked for a new or changed one: that is a setup failure, so all of them are planned up front. Before setup, list every outside service the whole brief will use, through launch, and every endpoint each one will call, and give each key every permission on that list. Where a provider cannot grant that whole list with a narrower key, take its full ("All") scope rather than come back. One key per provider account serves every service that uses that provider, where nothing public can read it, so no service runs on a narrower key of its own. Each key gets the longest lifetime the provider allows, and the setup output says beside it when it expires; a leaked key is revoked and replaced at once, and that is not a setup failure. Setup is one script, run one time: it asks for each value, checks every key against every endpoint it will be used on, with a read or a dry run where the real call would create or spend, so setup costs nothing, saves nothing until every check passes, then puts each key in every place it must go. It says beside each key how broad it is, so the owner sees what they grant. A key asked for after setup, or made without a permission its service needs, sends the owner back, and that is the failure this rule stops.
- Inspect the current repository, branch, remotes, project files and CI first. Reuse the existing repository; the absence of a playable slice is not a reason to create another one.
- Determine the platform and repository visibility from the brief and existing project. Ask the owner only for missing choices. This kit assumes a browser game with Playwright playtests and screenshots; another platform needs a suitable playtest tool and screenshot method recorded in the brief and covered by its permissions.
- If no repository exists, create one with the `gh` CLI only within the authorized destination and visibility. If a repository exists, preserve its history, remotes and existing project configuration.
- Perform needed setup on a branch, adding only missing project structure and tracking files: `docs/superpowers/progress.md`, `history.md` and `docs/superpowers/roadmap.md`. Reuse suitable existing setup and run the `release` setup check. CI workflow changes retain lane 3 checks and require explicit or applicable standing permission, except first-time bootstrap as defined in CLAUDE.md. Merge required setup changes before the slice starts; skip a setup pull request when nothing changes.
- Setup is where a game loses its first day. Start from "CI and test machines" below instead of designing CI from scratch, and change a default only when a measured result shows it does not work.
- The owner's batch of commands is written once, complete and in order. A key or secret that is shown only once (an API key, a GitHub App's private key, a token) is named as such in the step that creates it, with every place it must go listed in that same step (a repo secret and the cloud environment's secret, for example), so the owner never has to make it again. Prefer commands that ask for the value, such as `gh secret set NAME` with no value. Every command handed to the owner uses `gh`, never plain `git`: a branch delete is `GH_PAGER=cat gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/<branch>`. Every `gh api` command handed to the owner starts with `GH_PAGER=cat`: without it the answer opens in a pager, and the owner sees nothing to copy back or is stuck in it. The same holds after setup for owner steps that are not keys: a change that needs one lists every one the approved brief will need, the ones its deploy and its later steps need included, as one paste before the build starts, so the owner is asked once. A change that seems to need a new key first finds a way with the keys setup made; when there is none, it is reported as a setup failure, with one paste that covers everything still to come. Where a step has no CLI and must be done on a provider's web page, such as creating a token, the session checks the page's current field and permission names against the provider's documentation before writing the step. It also runs the paste itself with stand-in commands first, so it never prints success when a command failed. A diagnostic the owner must run is the same: one complete paste that says exactly what to copy back (which block of the output, from which line to which), tried first against a made-up failing case to see that it shows the failure. A command that filters out the very case it is looking for costs the owner a second trip.
- Some steps a cloud session cannot do, because the cloud proxy refuses them: deleting branches, reading or writing Actions secrets, variables and runners, and posting commit statuses. They go in the owner's batch, or in a CI job. Reading workflow runs and downloading their artifacts works.
- A private repo on GitHub's free plan has no branch protection, rulesets, auto-merge or merge queue, and the setup check reports them missing. Ask the owner once, at setup, for a standing permission to merge a pull request in the lanes named below once its required checks are green and its lane's reviews are done, and record it under "Standing permissions"; sessions then merge without asking and report after. With no merge queue, the session that merges runs the queue by hand (Lanes and merging in `release`), and its last step before the merge is to look at `main` again: it compares `main`'s head with the `main` commit the pull request records as tested. If `main` has moved since that run, it merges current `main` in and the checks run again on the result before it merges; if not, that run stands. This is only for the pull request about to merge, never for one that is waiting, and the permission never covers a merge tested against an older `main`. It covers lanes 1 and 2, and lane 3 changes to CI workflow files, to the gate's own code (the code that starts, checks and deletes pods, and the webhook service, whose redeploy from `main` on such a merge is inside this permission) and to the tools that build or pack the game, after their audits, and nothing wider. Every other lane 3 change (a release or tag, any other deploy or spend, a migration, a write of real data, a rule change) still needs the owner's word or its own named permission.
## CI and test machines

- On a public repo, the unit tests, lint, typecheck and build run on GitHub's runners, which are free there, and the smoke set runs on one GPU pod. On a private repo, GitHub's included minutes run out and anything past them is billed, so no job runs on GitHub's runners there, included minutes or not (when they run out, every run fails at its first job): CI runs on cloud pods billed by the minute, never on paid GitHub minutes, a monthly server or the owner's computer. A GPU comes from a cloud GPU pod. The monthly CI budget goes in the setup brief, and the gate refuses to start pods once it is spent. A workflow that was there before the gate keeps using GitHub's runners until it is moved, so setup moves or turns off every such job before anything else runs. The check: a test reads every workflow file and, on a private repo, fails on a job that runs on a GitHub-hosted label (such as `ubuntu-latest`). Trigger: a diff that adds or changes a workflow job.
- CPU pods run everything that does not render: install, typecheck, unit tests, build and audits. GPU pods run only what renders: browser specs that draw the game, screenshots and the frame budget.
- On a private repo, the gate on every pull request is the unit tests on a CPU pod plus one GPU check (the smoke set) on a GPU pod. The full browser suite is not part of the gate (see Where tests run in `release`).
- GitHub Actions runs the workflow, and each job that needs a machine starts its own pod, which registers a just-in-time self-hosted runner for that one job. A job that starts pods needs a runner itself, so on a private repo the first runner of a run is started from outside GitHub: the repo's webhook calls a small free service (a serverless function on a free plan, for example) that starts one lead pod per run for the jobs that decide, start and delete pods, and deletes it when the run ends. That service is redeployed from `main` by a CI job, so the owner sets it up once. A GitHub App on the account that owns the repo, installed on that repo only, mints the runner credential: fine-grained tokens do not work for a collaborator, and the App's tokens last an hour. The pod key is one repo secret, made once at setup with every permission the gate and its service will use (pods read and write, billing read, the catalogs read), or the provider's full scope where a restricted key cannot be given them all; the gate's service uses the same key. Use the provider's current API: check its docs for a retired version before building on one.
- Every outside credential a service uses (the pod key, a deploy token) gets a preflight at deploy time, the same checks setup ran: with the service's own key, it calls every endpoint the service uses, a read or a dry run where the real call would create or spend, and the deploy fails when any call is refused. Unit tests with stand-in APIs cannot see what a key is allowed to do. A key that lacks one permission is refused on one endpoint only: the fast path that needed it stops working, the run stays green and nobody notices. Trigger: a diff that adds a call to an outside API, or a new or replaced key.
- No silent fallbacks. When the gate skips a fast path or falls back to a slower one (an early pod start, a cache, a second machine type), the run says so with the reason, as a warning annotation or a line in the run summary, and its own retries are counted there too. A fallback nobody can see is a defect: the run stays green while the speed-up it was built for is gone.
- Pods start from a prebuilt public image that already holds the runner, the browsers and a warm package store, so a runner is online in one to two minutes.
- GPUs are picked from the catalog cheapest first, and stock changes by the hour. A pod whose runner is not online in time (a few minutes after the pod was made; the CI spec sets it) is replaced once, a CPU pod as well as a GPU pod, since a provider sometimes makes a pod and never runs it. When the second one is not online either, the job names each missing runner and pod, and the run fails at the time limit the CI spec sets instead of waiting for stock. The catalog answers 429 when several gates start at once and the runner-config call sometimes answers 500: the gate retries those calls itself. Those are infrastructure retries inside the gate; a test that passes on retry is still a defect.
- Every pod is deleted when its job ends (the lead pod when its run ends), also when the run fails or is cancelled. A pod left behind by a dead run still counts against the pod limit and blocks later runs, so the step that starts pods first deletes gate pods older than the longest run, and the code that deletes pods at a run's end is live before any run relies on it. A guard step fails a GPU job whose browser drew with software WebGL (SwiftShader). On Linux, Chromium draws with the GPU only with `--use-angle=vulkan --enable-features=Vulkan`.
- A gate on `pull_request_target` always runs `main`'s copy of the workflow, so a workflow change is tested on a throwaway base branch that holds a `pull_request` copy. Its check runs land on `main`'s commit, so the gate posts a commit status on the pull request's head commit, and the session that merges reads that status.
- The gate's settings that decide behaviour (which machine comes first, a limit, a time-out) live in tested code, and a change to one comes with a test that fails when the value is put back. A test that passes whichever value is set is not a test: a fallback test that never refuses the first choice still passes after the order is flipped. A test also parses every workflow file, since a file that does not parse runs no jobs and fails no pull request. This is behaviour in code; a plain settings file is still checked as Verification in `build` says.
- Screenshot baselines and goldens are taken on the CI machines' system (Linux), never on one person's Mac.
- CI artifacts stay small and short-lived: on a private repo the account's artifact storage is shared and limited, and when it is full every upload fails, on every pull request. Screenshots kept as evidence for people are saved in a modern lossy format such as WebP, after any pixel comparison has run on the originals, and checked once to see that small text stays sharp and that a contrast measured from the compressed picture matches the original. Other files a run uploads (screenshots excepted, see below) are only what a reviewer reads, with the shortest retention that still covers the review rounds and the owner's looks. A newer upload replaces the older sets that the same workflow uploaded under the same name for the same pull request, and nothing else: never another pull request's, never another workflow's, never when this run uploaded nothing (the old set is then the only evidence), and a cleanup that fails warns in the run summary without changing the run's verdict. It deletes only sets the workflow would make again if it ran again on that set's commit. The cleanup is a step in the workflow, so it arrives as a lane 3 change with its audits. Merging that audited step is the approval for its later runs and for nothing wider: any other artifact delete, or a delete by hand, stays lane 3 (Risk in CLAUDE.md). Goldens, baselines and art references are committed files, not artifacts, and keep their format. The check: a test reads the workflow and fails on an upload step with no retention set, and tests of the cleanup cover each of those cases. Trigger: a diff that adds or changes an artifact upload.
- On a private repo, artifact storage is counted as an average over the month: a delete stops further charges but does not bring the month's figure down, and once the account is over its included storage, every upload fails until the month resets. So screenshots, the largest uploads, go to an object store outside GitHub with a lifecycle rule that deletes each one a few hours after upload, and the run summary links them. They are short-lived by design: a reviewer or a screens page that needs them later re-runs the walk to make them again, and nothing keeps a longer copy. The screens page carries its own copies only until the owner has looked at it (Screens page in `visual-check`). Its key is one of the keys setup makes (Keys once). The check: a test reads the workflows and fails on a step that sends screenshots to GitHub's artifact storage. Trigger: a diff that adds or changes a screenshot upload. A public repo's artifact storage is free and has no limit, so there screenshots stay in GitHub's artifact storage, still uploaded small and short-lived as the bullet above says, and this check does not apply.
- A screenshot walk too long for one job's time cap is split into pieces on separate GPU pods, within the pieces set in Settings, so each piece fits its cap. The split is a list in tested code, and a test fails unless every page, device and, where the game has more than one, language is walked by exactly one piece: none missed, none twice. Trigger: a diff that adds a page, a device or a language to the walk, or changes the pieces.
- As a guide to scale, a unit-test job on a mid-size CPU pod takes a few minutes and costs a few cents, and a pull request's gate (unit tests and one GPU check) costs about ten cents. Hosts of one machine type differ in speed: the same tests on the same code can take three times as long on one host as on another. The checks pod keeps a second machine type as its fallback, and which one goes first is decided by many real runs, not two: a pair of runs can point the wrong way. Changing the order is not how a slow suite is fixed: when the spread comes from the host, a new order chases noise. The order changes only when many runs show one machine type is steadily slower or fails to start, and the lasting fix is the cost of the tests themselves (How code is written in `build`). Tests that start processes or watch files can time out together on a stalled host: that is recorded under "Flaky tests" as Verification in `build` says, with the processor the job printed, and the fix is a test that waits on the event (the process is ready, the change was seen) and not on the clock; a timeout is never raised just to get past it. The job's first step prints the processor it got, so a slow run is read from the log before anyone suspects the tests. A change made for speed is done when real runs show it: the timed step over several real runs before and after, with their run numbers, not a local replay with stand-in calls. A fast path can pass its tests and a dry run and still not fire on real runs. Read the month's spend from the provider's billing API before starting more work; it lags by a few minutes.
## Hosting the server

- A game with a server chooses its host and machine size at setup, and the monthly hosting budget goes in the setup brief beside the CI budget.
- Size: start on the host's smallest shared size and measure it with a load test of full rooms (every seat filled, a whole match). Move up only when that test misses a budget in the brief, such as tick time or memory. The size and its monthly price are written in the brief; a bigger size is spend outside the brief, so it is the owner's choice.
- Paid plan before launch: a host's free trial can stop every machine a few minutes after it starts, and the game goes down with no error in the deploy. The setup check reads the account's plan or billing state through the host's CLI or API; a missing payment method is the first step in the owner's batch, and the release refuses to deploy while the check fails.
- From the first release, two read-only jobs run in the cloud with the deploy key setup made: an uptime check that calls the server's health endpoint on a schedule and alerts the owner when it fails (below), and a scheduled log report that reads the host's machine events and logs (stops, restarts, exit codes, out of memory) and warns on the host's own stop messages, such as a trial limit. On a private repo they run as scheduled workflows on the same pods as the gate's jobs, one short CPU job each, or as a scheduled cloud task, never on GitHub's runners and never a pod started every few minutes; their monthly cost goes in the brief beside the hosting budget. Trigger: a diff that adds a server or changes its host or size, and the first release.
- **Alerts reach a person.** An alert is an issue on the game's repo, assigned to the owner and naming them, so the code host emails them: no paid email service, and no address stored anywhere. The CI's app or bot identity opens it, never the owner's own token, because the host sends nobody email about their own actions. One issue per outage: a repeat failure adds nothing, and recovery comments and closes it. The issue says what failed, since when, and the first command to run. Trigger: a diff that adds or changes an alert, and the first release.
- **A rollback button from the first release.** The release workflow has a rollback input from day one: one `gh workflow run` command puts back an earlier released build, chosen from the host's own list of releases. It swaps only the build and keeps today's machine size and settings, so it first checks that the old build fits them (its memory, for one) and speaks the same protocol as the live client, and refuses with the reason when it does not. It works while the server is down, since that is when it is needed, and a run that changes nothing ends red, never green. It is a release, so it is lane 3.
## Before launch

The first public release waits until each of these holds on the commit being released; the drills, the rollback and the alerts apply where the game has a server. The launch report gives the evidence for each.

- **The owner's launch checklist.** Every item in the Anti-Vibe Networking Audit, the Anti-Vibe Game Cybersecurity Audit and the Anti-Vibe Browser Game Audit (the prompts listed beside this kit) is marked pass, fail, not applicable or waiting, each with its evidence (a file and line, a test, a run or a screenshot) on that commit, in one audit file and one page the owner can read. A fail is fixed before launch or carries the owner's written waiver. Not applicable says why. Waiting names the outside piece it waits on, such as a feature of the platform the game is played on, and is reported as open, never as passed. Items that need a real device or the owner's own hands are the owner's to check: the report lists them for the owner and never marks them passed on the owner's behalf.
- **Failure drills.** The failure tests in those lists (kill the server mid-match, add latency, drop, duplicate and reorder messages, restart under load, exhaust connections) run against a throwaway copy of the server in the cloud, never production, and the game recovers each time with no manual cleanup. Each drill's result and run go in the audit file.
- **A rehearsed rollback.** The rollback button is pressed once on the live server, before launch while few people play: back to the previous release, the game checked, then forward again. It needs an earlier release to go back to, so it comes after at least two releases. It is a deploy, so it waits for the owner's named permission.
- **Alerts that work.** The alert is tested end to end once: the uptime check pointed at an address that is down opens the issue, the owner says the email arrived, and recovery closes it. Until the owner says so, it is reported as not confirmed.
## Making the slice

The slice inherits the limits in Settings; where the prompt below says to keep looping or not to fix a number of rounds, those limits win. A try is one round: build, judge, fix, and the critic judges the fix. A fix nobody judged is never reported as passing. Out of rounds with a blocking defect left, the slice is reported incomplete, with the bar reached, the evidence and what is open. Its builders and critics count toward the work-session limit and run within it. The bar is met when the checks the coordinator wrote down before the run (what the slice must do, on which devices and hardware, within what frame time) pass in a recorded playthrough, and there are no unresolved blocking defects against the agreed criteria (optional improvements are notes and do not hold it up). On a public repo no session can measure a frame-time budget on named hardware. The loop does not wait for it, but it still counts: the slice is reported as "frame time not measured, awaiting the owner's measurement", never as meeting the bar, with the steps for the owner to measure it by hand (see Where work runs in `release`). The finished result is approved with the owner's measured number, or with the owner's waiver written beside it.

The coordinator fills in the two blanks below, runs this prompt once, and tells the owner the bar it chose, in one sentence. It is Matt Shumer's Claude of Duty prompt, with the models added:

I want to run a Gauntlet Loop for this goal:

[GOAL]

Possible references or quality bars:

[OPTIONAL REFERENCES]

Choose the strongest concrete bar that an agent can actually inspect and compare its work against. If I have not supplied one, propose a useful comp or measurement that plays the same role for this task that real Call of Duty screenshots played for Matt Shumer's Claude of Duty game (read the prompt: https://github.com/mshumer/Claude-of-Duty/blob/main/prompt.md). Explain the bar in one sentence.

Then write a short prompt for Claude Code or Codex in the style of Matt's prompt (minimal is better here, we want the agent to decide the specifics!).

Give the lead agent the goal and the bar, but let it choose the approach. Tell it to divide the goal into the smallest pieces that can be improved and judged independently. For each important piece, it should fan out a builder and a separate critic with fresh context.

Each critic must inspect the real output, compare it directly with the bar—using a blind A/B comparison when possible—identify the biggest remaining gap, and send it back for another round. Keep looping until our output wins or I stop the run.

Have the lead agent send progress updates, early playable previews and material decisions to the coordinator, following the owner visibility rules.

The lead orchestrates. It runs on the model and effort Settings names for the slice lead, splits the work and writes a self-contained brief (goal, the files it owns, what it waits on, acceptance check, branch) for each builder and critic, and the coordinator starts each one as its own thread on the model and effort Settings names for its role. The lead's first step is sending builder briefs, not building. Do not prescribe the architecture, exact decomposition, or a fixed number of rounds. Keep the final prompt short, just like Matt's.

- `[GOAL]` is the game's one-line pitch and core loop, taken from the outcome in the owner's Start prompt; do not ask the owner for it again. `[OPTIONAL REFERENCES]` are the owner's reference games or screenshots, if any.
- The prompt writes a shorter prompt. The coordinator adds one line to the prompt it hands the slice session, so the limit travels with it: "Stop after N rounds and report the bar reached, the evidence and what is left", with N the slice rounds in Settings. That line wins over anything in the prompt about rounds.
- The slice session runs where it can run and play the game: a cloud session that plays and shoots the game on a cloud GPU pod, never with software rendering in the cloud container (see "Shoot on a GPU" in `visual-check`); never the owner's computer. Real input feel is judged by the owner by hand on the preview. Builders, critics and required reviews are separate threads, under the Delegation rule and session limits. The slice lead's builders count as writing code.
- The slice session is tracked like a stage: it reports to the coordinator, which keeps `progress.md`, one line per piece finished. The lead itself only reads and never writes code, but it takes one of the 3 code-writing places.
- The retrospective is the last stage of every slice, the first one included. After the slice ends, a fresh thread reviews every loop the slice ran (see "Retrospective" in `staged-path`), turns each lesson into a test where it can, and proposes the rest as one rule-change pull request for the owner to approve. Nothing to learn, no pull request. The next slice can start once the retrospective's pull request is open, or once the retrospective reports nothing to learn. Before it come the fresh end-to-end walk, the design review loop, the screens page and the owner's own walk (see "Slice end" in `staged-path`).
- **Delegation.** Use separate threads for the work and its reviews. The coordinator starts a fresh thread for each required code, design, visual or playtest review; it reads, runs checks and writes its audit file, and the implementer makes fixes. The slice lead asks the coordinator for its builder and critic threads. These threads count toward the work-session limits in Settings, and builders and the lead count toward the writer limit.
## From the slice to the game

- The slice is the game's first version, not a throwaway. When it is finished, the owner approves it as a finished result and the stages start, with the slice as the spec's starting point.
- It evolves by default. Assess it first: for each part, keep, refactor or replace, with a reason, written into the spec. Refactor or replace a part only for a constraint shown by evidence: a test it cannot take, a measured budget it misses, a defect its structure keeps causing. Code not fitting the folder layout alone never justifies replacing working gameplay; it moves into the layout as it is touched. Behavior is preserved by repeatable playthroughs and recorded parameters with their units (speeds per second, sizes in pixels or metres, timings in milliseconds), not by copying numbers alone.
- Before a part is replaced, the spec names a runnable baseline when one helps: a commit the playtest runs on, to compare the new part against.
- The coordinator and the owner agree a delivery order, with the advisor asked first: a short list of milestones in `docs/superpowers/decompositions/<date>-<topic>-delivery-order.md`. Milestone 0 is the slice. Each milestone gets its brief and follows the shared risk rules: work inside it takes the short or the staged path by its own risk, and independent pieces run side by side within the limits in Settings. Later work follows those shared paths; the Gauntlet prompt is not run again.
- `docs/superpowers/roadmap.md` lists everything left, in order, with who does each step (the owner or a session) and where it stands. The coordinator keeps it current. A milestone is done when it is merged to `main`, green there, its screens have been through the design review loop (`visual-check`), and the owner has approved the finished result.

Skill: scene-polish

Save this as .claude/skills/scene-polish/SKILL.md in your repo.

---
name: scene-polish
description: Use when an in-game scene is built and needs to look better, when a milestone has added scenes, or when a change touches gameplay (movement, controls, rules, camera).
---

# Scene polish

A scene is anything the player sees in play that is not a menu or the HUD. Menus and the HUD use `visual-check`.
## The loop, one scene at a time

1. Screenshot the scene as built, from the running game, on a fixed seed and an injected clock, once the scene reports ready.
2. Give that screenshot to GPT image generation with the words "reimagine this image", keeping the camera, the gameplay geometry and every interaction cue where they are. Commit the result as `docs/superpowers/scenes/<scene>.png`, beside the screenshot it came from (`<scene>-before.png`) and the exact prompt (`<scene>.md`). The image is the scene's art reference: a guide to its look, never a score. Regenerate it only for a scene change inside the scope the owner approved, or on the owner's words.
3. Fix the scene, capture it at the size and camera of the screenshot the image came from, and run the scene review (rounds and models in Settings): each capture next to the art reference. It lists the biggest gaps against the criteria in step 4.
4. A scene passes when each explicit criterion holds: visual hierarchy (the eye goes first to what the player must act on), readable interactions (every cue and target is clear at play speed), consistent art direction (colour, lighting, shapes and scale follow the reference's direction, not its pixels), motion (animation reads clearly, with no stutter) and performance (the frame-time budget in the brief holds on its named hardware). The gameplay geometry and camera still match the screenshot, text and the HUD stay legible, and nothing the player needs is hidden. Each try fixes the biggest gaps. At most the tries in Settings; after that, stop that approach and reassess (Limits in CLAUDE.md). On a public repo no session can measure that budget: a scene can pass its other criteria and take its golden, and the budget stays "not measured, awaiting the owner's measurement" in every report until the owner measures it by hand (see Where work runs in `release`) or writes a waiver beside it.
5. The passing screenshot becomes the scene's golden in `tests/golden/`. A golden moves later for a change inside the scope the owner approved (the brief or milestone that named the scene change), with its before and after in the pull request; any other move waits for the owner, and a golden never moves to hide a defect (see `release`).

Gameplay is judged separately, by the playtest below: a scene that looks right but plays badly fails there. The first scene goes through the whole loop alone and must pass before the rest start. The scenes after it run side by side, as the session limit allows.
## Playtest and controls check

- This check runs whenever a change touches gameplay (movement, controls, rules, camera), whether or not a scene changed. It checks the quality bar in `build`; its performance and supported-device criteria are agreed in the brief.
- Playwright tests in `tests/playtest/`, written with the game and run like every other test, wait on readiness and never on a sleep. At the sizes the change affects (see "Shoot what the change touches" in `visual-check`), play from first open through the core loop and the outcomes defined in the brief. Test winning and losing in separate runs when those outcomes exist. For an endless or sandbox game, test its specified progression, state transitions and recovery without inventing a win or loss condition. Check restart, pause and save where supported, and exercise every supported control (keyboard, gamepad, and mouse and touch where the brief names them). Check relevant interactions with audio muted to verify that essential feedback remains understandable.
- Two walks are always there: one with only the keyboard and one with only a gamepad (faked by stubbing `navigator.getGamepads`, as `build` says), each from the first screen through the core loop the brief defines and back to the start, with no other input, at the sizes the change affects, shooting only the screens it touches. A step in either that needs the mouse, a tap or another device fails the walk. Trigger: a diff that adds or changes a screen, a menu, a dialog or input code.
- At the end of each milestone an independent reviewer (a fresh session) also plays a short exploratory play session off the scripted route and judges onboarding, challenge and control feel against the quality bar: the scripted route alone cannot show those.
- Nothing may be unreachable, stuck, or need explaining. Read the opening minute closely: is it clear, and where does a new player's attention or confidence drop? Read the video, screenshots and console errors.
- Its device runs are emulation evidence; the frame-time budget is measured on the hardware the brief names. The video and screenshots are taken automatically when the diff touches gameplay or scene files, with no label needed, of the screens and sizes it reaches. A missing playtest, or a control it never uses, is a finding.
## Rounds and the owner's looks

Scene review runs the same slice end as design review (see "Slice end" in `staged-path`), and the scenes go on the screens page beside the screens: a fresh end-to-end walk; scene review round 1, then round 2, each on the model Settings names for it, with a fresh session checking every capture against its art reference one by one, never a sample; the screens page, for the owner's first look; round 3 on the owner's notes; the screens page again; the owner's own walk; and the retrospective. Each check uses the criteria in step 4, never pixel perfection, at the sizes the change affects. Scenes the owner has already approved are skipped (see `visual-check`). The loop above is the fix while a scene is built, within the tries in Settings; these rounds are the check at the slice end, with the other visual checks.

Skill: verify

Save this as .claude/skills/verify/SKILL.md in your repo. Claude fills in the parts in angle brackets the first time it starts the app or game; you leave them as they are.

---
name: verify
description: Use when a change alters what the product does, before calling it done and before each commit that changes behavior: starts this repo's app or game from a clean checkout and drives it the way a person would.
---

# Verify

<the product in one line>
## Start it

From a clean checkout in a cloud container, in order. First pick the Node version (or other runtime) that `engines` in `package.json` asks for. Then install, build, and start every stand-in for an outside service (a database, payments, mail, sign-in), never the real one.

<start commands>

It is ready when <ready signal>. Last clean start, timed with `date` before and after: <start time>, on commit <commit>.
## Drive it

Open it in a real browser: the Chromium and Playwright the container already has (`require('playwright')`, then `chromium.launch()`), at the sizes the change affects (see "Shoot what the change touches" in `visual-check`). Tap, click, type and press keys the way a person would, and find things by their label or role. Take a screenshot at deviceScaleFactor 1 for your own check, and save it in the scratchpad, never in the repo. The main screen, what it shows and how to use it:

<main screen>
## The journeys

One line each, from a person's side: where it starts, the steps, and what they see at the end.

<journeys>
## Stop it

Stop every server it started and clear what it wrote, so the next run starts clean.

<stop commands>
## When it breaks

A step that breaks or flakes is fixed in this skill first. Each known way a start or a step fails, what it looks like, and the fix:

<known failures>

Hook: settings.json

Save this as .claude/settings.json in your repo. If the file exists, add the SessionStart and env entries to it, and the PreToolUse, PostToolUse and Stop entries that run the rule hooks.

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "env": { "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "450000" },
  "hooks": {
    "SessionStart": [
      {
        "matcher": "compact",
        "hooks": [{ "type": "command", "command": "cat \"$CLAUDE_PROJECT_DIR/.claude/after-compaction.md\"" }] },
      {
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 10 }] }
    ],
    "PreToolUse": [
      {
        "matcher": "Bash|Write|Edit|MultiEdit|Agent|Workflow|mcp__.*",
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 30 }] }
    ],
    "PostToolUse": [
      {
        "matcher": "Bash|Write|Edit|MultiEdit|mcp__.*",
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 15 }] }
    ],
    "Stop": [
      {
        "hooks": [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 15 }] }
    ]
  }
}

Hook: after-compaction.md

Save this as .claude/after-compaction.md in your repo.

Your context was just compacted. Read this before you do anything else.

1. The rules file beats the summary. Where CLAUDE.md or a skill in .claude/skills/ says one thing and the summary says another, CLAUDE.md and the skill win. The summary is someone's note about the rules, not the rules.
2. Re-read CLAUDE.md and docs/superpowers/progress.md now, before your next step. Open the skill in .claude/skills/ whose description fits the work you are in.
3. Your live state is in docs/superpowers/live/<your branch>.md, with "/" in the branch name written as "-" (the branch is `git branch --show-current`): your task, your last commit, your next step and your open decisions. An audit session keeps it at the top of its audit file. Where the summary and that file differ, the file wins. If it is behind what you did, update it and commit it first. The coordinator's live state is progress.md.
4. Do not carry this session into the next big job. A spec, a plan, a pull request's build and an audit each run in a fresh session. When your job is done, commit, report and stop.

Hook: rules.mjs

Save this as .claude/hooks/rules.mjs in your repo. It refuses tool calls that break the rules a program can judge, puts the rules in every session at its start, and checks commits and pull request bodies after the fact. It needs Node and nothing else.

#!/usr/bin/env node
// Rule hooks: the rules a program can judge are judged by this program, on every
// tool call, instead of by a session's memory of CLAUDE.md. One script, run by
// .claude/settings.json on SessionStart, PreToolUse, PostToolUse and Stop; the
// repo's own values live in .claude/hooks/rules.json. Node only, no packages.
//
// Answers: a refused tool call is a PreToolUse "deny" with the reason; a problem
// found after the fact is a PostToolUse or Stop "block" with the reason; added
// context is hookSpecificOutput.additionalContext. Allowing prints nothing, so this
// script never overrides the permission system. A crash never blocks: it prints a
// warning and lets the call go ahead (the CI gate is the check that cannot be skipped).
//
// `node rules.mjs --check` validates rules.json and prints which checks are on.
// `node rules.mjs --find-repo` (for sessions started one folder above the repo)
// picks the repo each call acts in.
// `node rules.mjs --install-user` adds that launcher to ~/.claude/settings.json, once per
// computer, so sessions started one folder above a repo load its hooks. It keeps every other
// setting and never adds an entry twice. `node rules.mjs --print-setup` prints the same
// installer as a cloud environment setup script that needs no repo and never fails.

import { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { dirname, join, resolve, relative, isAbsolute, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { fileURLToPath } from 'node:url';

const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const FOOTER = 'If this refusal is wrong, say so in your report. Do not reword the command to get past it.'; const PLACEHOLDER = /\[[A-Z][A-Z0-9 _-]*\]/;

// ---------- small helpers ----------

const run = (cmd, args, opts = {}) => {
  const r = spawnSync(cmd, args, { encoding: 'utf8', timeout: opts.timeout ?? 8000, cwd: opts.cwd, env: opts.env ?? process.env, input: opts.input, maxBuffer: 16 * 1024 * 1024 }); return { ok: r.status === 0 && !r.error, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() }; };
const git = (cwd, args, env) => run('git', args, { cwd, env });
const readText = (path, max = 1024 * 1024) => {
  try { const s = statSync(path); if (!s.isFile() || s.size > max) return null; return readFileSync(path, 'utf8'); } catch { return null; } };
const isPlaceholder = (v) => typeof v === 'string' && PLACEHOLDER.test(v);
const globToRegExp = (glob) => new RegExp('^' + glob.split('**').map((part) => part.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('[^/]*')).join('.*') + '$'); const matchesAny = (path, globs = []) => globs.some((g) => globToRegExp(g).test(path));
const lines = (s) => String(s ?? '').split('\n');
const lastLine = (s) => lines(s).map((l) => l.trim()).filter(Boolean).at(-1) ?? '';
const addedLines = (before, after) => {
  const old = new Set(lines(before));
  return lines(after).filter((l) => !old.has(l));
};
const parseIdent = (s) => {
  const m = /^(.*?)\s*<([^>]*)>/.exec(String(s ?? '').trim());
  return m ? { name: m[1].trim(), email: m[2].trim() } : null;
};
const sameIdent = (a, b) => a && b && a.name === b.name && a.email.toLowerCase() === b.email.toLowerCase(); const showIdent = (p) => (p ? `${p.name} <${p.email}>` : 'unknown');

// ---------- config ----------

const loadConfig = (root) => {
  const path = join(root, '.claude', 'hooks', 'rules.json');
  const text = readText(path);
  if (text === null) return { error: `no ${relative(root, path) || path}` };
  let config;
  try { config = JSON.parse(text); } catch (e) { return { error: `${path} is not valid JSON: ${e.message}` }; } return { config: withNames(config, readText(join(root, 'CLAUDE.md')) ?? ''), path };
};
// The commit author and the pull request's last line come from the repo's own CLAUDE.md
// (Rules that never bend: Identity), so no name is written into the hook settings. A
// value in rules.json, when there is one, wins.
const IDENTITY = /Every commit is authored by (\[[^\]\n]+\]|[^<\n]*?<[^>\n]+>)/;
const LAST_LINE = /Pull requests end with "([^"\n]+)"/;
function withNames(config, claudeMd) {
  const c = { ...config };
  if (c.author === undefined) { const m = IDENTITY.exec(claudeMd); if (m) c.author = m[1].trim(); }
  if (c.prLastLine === undefined) { const m = LAST_LINE.exec(claudeMd); if (m) c.prLastLine = m[1]; } return c;
}
const blanksOf = (config) => ['author', 'prLastLine'].filter((k) => config[k] === undefined || isPlaceholder(config[k])); const on = (config, name) => {
  const c = config?.[name];
  if (c === false) return false;
  if (c && typeof c === 'object' && c.enabled === false) return false;
  return true;
};
const authorOf = (config) => (config.author === undefined || isPlaceholder(config.author) ? null : parseIdent(config.author)); const prLastLineOf = (config) => (isPlaceholder(config.prLastLine) || !config.prLastLine ? null : config.prLastLine); const defaultBranch = (config) => config.defaultBranch || 'main';

// ---------- reading a shell command ----------
// The command is split into simple commands, each a list of words with its inline
// environment and any heredoc body. Checks match on these words only, never on the
// raw text, so `grep screenshot` or `echo "git push --force"` match nothing.

const OPS = [';;', '&&', '||', '|&', ';', '|', '&', '\n', '(', ')'];

function parseShell(src) {
  const commands = [];
  let i = 0;
  const pending = []; // heredocs waiting for the end of their line

  const readHeredocBodies = () => {
    while (pending.length) {
      const h = pending.shift();
      const body = [];
      while (i < src.length) {
        let end = src.indexOf('\n', i);
        if (end === -1) end = src.length;
        const line = src.slice(i, end);
        i = end + 1;
        const test = h.strip ? line.replace(/^\t+/, '') : line;
        if (test.trim() === h.delim) break;
        body.push(h.strip ? line.replace(/^\t+/, '') : line);
      }
      h.cmd.heredoc = (h.cmd.heredoc ? h.cmd.heredoc + '\n' : '') + body.join('\n');
    }
  };

  // Parses until the end or, when inParen, the matching ')'. Returns the commands made.
  const parseList = (inParen) => {
    const out = [];
    let cmd = { words: [], heredoc: null, raw: '' };
    let word = null;
    const start = () => { if (word === null) word = ''; };
    const endWord = () => { if (word !== null) { cmd.words.push(word); word = null; } };
    const endCmd = () => { endWord(); if (cmd.words.length || cmd.heredoc !== null) out.push(cmd); cmd = { words: [], heredoc: null, raw: '' }; };

    const readSubst = () => { // at '$(' : returns text of the substitution, records its commands
      i += 2;
      const from = i;
      const inner = parseList(true);
      const text = src.slice(from, i - 1);
      for (const c of inner) { c.nested = true; out.push(c); }
      // `$(cat <<'EOF' ... EOF)` stands for the heredoc's text.
      const real = inner.filter((c) => !c.nested || c.words.length);
      if (real.length === 1 && real[0].words[0] === 'cat' && real[0].heredoc !== null && real[0].words.length === 1) return real[0].heredoc; return '$(' + text + ')';
    };

    while (i < src.length) {
      const ch = src[i];
      if (inParen && ch === ')' && word === null) { i++; endCmd(); return out; }
      if (inParen && ch === ')') { i++; endCmd(); return out; }
      if (ch === '\\') {
        if (src[i + 1] === '\n') { i += 2; continue; }
        start(); word += src[i + 1] ?? ''; i += 2; continue;
      }
      if (ch === "'") {
        start();
        const end = src.indexOf("'", i + 1);
        word += src.slice(i + 1, end === -1 ? src.length : end);
        i = end === -1 ? src.length : end + 1;
        continue;
      }
      if (ch === '"') {
        start(); i++;
        while (i < src.length && src[i] !== '"') {
          if (src[i] === '\\' && '"\\$`\n'.includes(src[i + 1])) { word += src[i + 1]; i += 2; continue; } if (src[i] === '$' && src[i + 1] === '(') { word += readSubst(); continue; }
          if (src[i] === '`') {
            const end = src.indexOf('`', i + 1);
            const inner = src.slice(i + 1, end === -1 ? src.length : end);
            for (const c of parseShell(inner)) { c.nested = true; out.push(c); }
            word += '`' + inner + '`';
            i = end === -1 ? src.length : end + 1;
            continue;
          }
          word += src[i]; i++;
        }
        i++;
        continue;
      }
      if (ch === '$' && src[i + 1] === '(') { start(); word += readSubst(); continue; }
      if (ch === '`') {
        start();
        const end = src.indexOf('`', i + 1);
        const inner = src.slice(i + 1, end === -1 ? src.length : end);
        for (const c of parseShell(inner)) { c.nested = true; out.push(c); }
        word += '`' + inner + '`';
        i = end === -1 ? src.length : end + 1;
        continue;
      }
      if (ch === '#' && word === null) { // a comment runs to the end of the line
        while (i < src.length && src[i] !== '\n') i++;
        continue;
      }
      if (ch === '<' && src[i + 1] === '<' && src[i + 2] !== '<') {
        endWord();
        i += 2;
        let strip = false;
        if (src[i] === '-') { strip = true; i++; }
        while (src[i] === ' ' || src[i] === '\t') i++;
        let delim = '';
        while (i < src.length && !/[\s;&|()<>]/.test(src[i])) {
          if (src[i] === "'" || src[i] === '"') { const q = src[i]; const end = src.indexOf(q, i + 1); delim += src.slice(i + 1, end === -1 ? src.length : end); i = end === -1 ? src.length : end + 1; } else { delim += src[i] === '\\' ? '' : src[i]; i++; } }
        cmd.heredoc = cmd.heredoc ?? '';
        pending.push({ cmd, delim, strip });
        continue;
      }
      if (ch === '<' && src[i + 1] === '<' && src[i + 2] === '<') { endWord(); i += 3; continue; } // here-string: next word is data if (ch === ' ' || ch === '\t') { endWord(); i++; continue; }
      if ((ch === '>' || ch === '<') && word === null) { // redirection: skip its target word
        i++;
        if (src[i] === '>' || src[i] === '&') i++;
        while (src[i] === ' ') i++;
        while (i < src.length && !/[\s;&|()]/.test(src[i])) i++;
        continue;
      }
      if (/^[0-9]$/.test(ch) && word === null && (src[i + 1] === '>' || (src[i + 1] === '<' && src[i + 2] !== '<'))) { i++; continue; } const op = OPS.find((o) => src.startsWith(o, i));
      if (op) {
        if (op === '(' && word !== null) { word += ch; i++; continue; }
        endCmd();
        i += op.length;
        if (op === '\n') readHeredocBodies();
        if (op === '(') { const inner = parseList(true); out.push(...inner); }
        continue;
      }
      start(); word += ch; i++;
    }
    endCmd();
    readHeredocBodies();
    return out;
  };

  try { commands.push(...parseList(false)); } catch { /* the parser never throws to its caller */ }
  return commands;
}

const ENV_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
const PNPM_OWN = new Set(['add', 'install', 'i', 'remove', 'rm', 'update', 'up', 'outdated', 'list', 'ls', 'why', 'audit', 'store', 'config', 'init', 'link', 'unlink', 'prune', 'publish', 'pack', 'rebuild', 'root', 'bin', 'env', 'setup', 'import', 'fetch', 'patch', 'patch-commit', 'deploy', 'licenses', 'server', 'help', 'create', 'recursive', 'run', 'exec', 'dlx', 'test', 't', 'start']);

// Turns parsed commands into checkable ones: wrappers peeled, inline env split off,
// `bash -c` and `eval` read again, `cd` and `export` carried to later commands.
function simpleCommands(src, baseCwd, depth = 0) {
  const result = [];
  let cwd = baseCwd;
  const exported = {};
  for (const c of parseShell(src)) {
    let words = [...c.words];
    const env = { ...exported };
    while (words.length && ENV_WORD.test(words[0])) { const [k, ...v] = words.shift().split('='); env[k] = v.join('='); } // Peel wrappers.
    for (let guard = 0; guard < 10 && words.length; guard++) {
      const w = words[0];
      if (w === 'sudo' || w === 'doas') { words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (f === '--') break; if (/^-[ugpChDrtURC]$/.test(f) || /^--(user|group|host|prompt|chdir|close-from|role|type|other-user)$/.test(f)) words.shift(); } continue; } if (w === 'flock') { const ci = words.findIndex((x, k) => k > 0 && (x === '-c' || x === '--command')); if (ci !== -1 && words[ci + 1] !== undefined) { result.push(...simpleCommands(words[ci + 1], cwd, depth + 1).map((x) => ({ ...x, env: { ...env, ...x.env } }))); words.length = 0; break; } words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (/^(-w|--timeout|-E|--conflict-exit-code)$/.test(f)) words.shift(); } words.shift(); continue; } if (w === 'nohup' || w === 'time' || w === 'command' || w === 'exec' || w === 'stdbuf' || w === 'setsid' || w === 'unbuffer') { words.shift(); while (words[0]?.startsWith('-')) words.shift(); continue; } if (w === 'script') { const ci = words.findIndex((x, k) => k > 0 && (/^-\w*c$/.test(x) || x === '--command')); const eq = words.find((x) => x.startsWith('--command=')); if (eq) { result.push(...simpleCommands(eq.slice(10), cwd, depth + 1).map((x) => ({ ...x, env: { ...env, ...x.env } }))); words.length = 0; break; } if (ci !== -1 && words[ci + 1] !== undefined) { result.push(...simpleCommands(words[ci + 1], cwd, depth + 1).map((x) => ({ ...x, env: { ...env, ...x.env } }))); words.length = 0; break; } } if (w === 'env') { words.shift(); while (words.length && (words[0].startsWith('-') || ENV_WORD.test(words[0]))) { const x = words.shift(); if (ENV_WORD.test(x)) { const [k, ...v] = x.split('='); env[k] = v.join('='); } } continue; } if (w === 'timeout') { words.shift(); while (words[0]?.startsWith('-')) words.shift(); words.shift(); continue; } if (w === 'xargs') { words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (/^-[IdLnPsE]$/.test(f)) words.shift(); } continue; } // Wrappers that run the rest of the line: a display server, priority, CPU or session.
      if (w === 'xvfb-run') { words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (/^(-n|-s|-e|-f|-p|-w|--server-num|--server-args|--error-file|--auth-file|--xauth-protocol|--wait)$/.test(f)) words.shift(); } continue; } if (w === 'nice') { words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (f === '-n' || f === '--adjustment') words.shift(); } continue; } if (w === 'ionice') { words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (/^(-c|-n|-p|-P|-u|--class|--classdata)$/.test(f)) words.shift(); } continue; } if (w === 'chrt') { words.shift(); while (words[0]?.startsWith('-')) words.shift(); if (/^\d+$/.test(words[0] ?? '')) words.shift(); continue; } if (w === 'taskset') { words.shift(); while (words[0]?.startsWith('-')) words.shift(); words.shift(); continue; } // flags, then the mask or CPU list if (w === 'dbus-run-session') { words.shift(); while (words[0]?.startsWith('-')) { const f = words.shift(); if (f === '--') break; if (/^--(config-file|dbus-daemon)$/.test(f)) words.shift(); } continue; } if (w === 'npx' || w === 'bunx' || w === 'pnpx') { words.shift(); while (words[0]?.startsWith('-')) words.shift(); continue; } if (w === 'pnpm' || w === 'yarn' || w === 'npm' || w === 'bun') {
        const tool = words.shift();
        while (words[0]?.startsWith('-')) { const f = words.shift(); if (/^(-C|--dir|--filter|-F|--prefix|-w)$/.test(f) && f !== '-w') words.shift(); } const sub = words[0];
        if (sub === 'exec' || sub === 'dlx' || (tool === 'bun' && sub === 'x')) { words.shift(); while (words[0]?.startsWith('-')) words.shift(); continue; } if (sub === 'run' || sub === 'run-script') { words.shift(); if (words[0]) words[0] = 'script:' + words[0]; break; } if (tool === 'npm') { words.unshift(tool); break; }
        if (sub && !PNPM_OWN.has(sub)) { words[0] = 'script:' + sub; break; }
        if (sub === 'test' || sub === 't') { words[0] = 'script:test'; break; }
        words.unshift(tool); break;
      }
      break;
    }
    if (!words.length) continue;
    const prog = words[0].split('/').at(-1);
    // Nested shells are read again.
    if ((prog === 'bash' || prog === 'sh' || prog === 'zsh') && depth < 4) {
      const ci = words.indexOf('-c');
      if (ci !== -1 && words[ci + 1] !== undefined) { result.push(...simpleCommands(words[ci + 1], cwd, depth + 1)); continue; } if (c.heredoc !== null && words.length === 1) { result.push(...simpleCommands(c.heredoc, cwd, depth + 1)); continue; } }
    if (prog === 'eval' && depth < 4) { result.push(...simpleCommands(words.slice(1).join(' '), cwd, depth + 1)); continue; } if (prog === 'cd' && !c.nested) { const to = words[1]; if (to && !to.startsWith('-')) cwd = isAbsolute(to) ? to : resolve(cwd, to.replace(/^~(?=\/|$)/, process.env.HOME ?? '~')); continue; } if (prog === 'export' && !c.nested) { for (const w of words.slice(1)) if (ENV_WORD.test(w)) { const [k, ...v] = w.split('='); exported[k] = v.join('='); } continue; } result.push({ prog, path: words[0], args: words.slice(1), env, cwd, heredoc: c.heredoc });
  }
  return result;
}

// Git and gh: global flags skipped, the subcommand found, `-C` applied.
const GIT_GLOBAL_WITH_VALUE = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']); // The repo a git call acts in: -C moves the starting folder (in order); --git-dir or
// GIT_DIR (against that folder, never the work tree) names the repository itself;
// --work-tree only says where files are checked out, so it never changes the repo.
function gitParts(cmd) {
  const a = cmd.args;
  let i = 0, cwd = cmd.cwd, gitDir = cmd.env?.GIT_DIR ?? null;
  const config = [];
  while (i < a.length && a[i].startsWith('-')) {
    if (a[i] === '-C') { cwd = resolve(cwd, a[i + 1] ?? '.'); i += 2; continue; }
    if (a[i] === '-c') { config.push(a[i + 1] ?? ''); i += 2; continue; }
    if (a[i] === '--git-dir') { gitDir = resolve(cwd, a[i + 1] ?? '.'); i += 2; continue; }
    if (a[i].startsWith('--git-dir=')) { gitDir = resolve(cwd, a[i].slice(10)); i++; continue; }
    if (GIT_GLOBAL_WITH_VALUE.has(a[i])) { i += 2; continue; }
    i++;
  }
  if (gitDir) { const d = resolve(cwd, gitDir); cwd = d.split(sep).at(-1) === '.git' ? dirname(d) : d; } return { sub: a[i], rest: a.slice(i + 1), cwd, config };
}
// owner/repo from any way gh names a repo: OWNER/REPO, HOST/OWNER/REPO, a URL.
const normRepo = (v) => {
  const t = String(v ?? '').trim().replace(/^[a-z+]+:\/\//i, '').replace(/^git@([^:]+):/, '$1/').replace(/\.git$/, '').replace(/\/+$/, ''); const parts = t.split('/').filter(Boolean);
  if (parts.length >= 3 && /\./.test(parts[0])) return parts[0].startsWith('api.') && parts[1] === 'repos' ? `${parts[2]}/${parts[3] ?? ''}` : `${parts[1]}/${parts[2]}`; return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null;
};
// A repo named by a whole word: an anchored github.com pull request, issue, tree, blob
// or commit link given as a positional argument, or the `gh api` path repos/<o>/<r>.
// Flag values (a body, a title, a merge subject) are text, never the target.
const GH_LINK = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/\s?#]+)\/([^/\s?#]+)\/(?:pull|pulls|issues|tree|blob|commit)(?:[/?#]|$)/i; const repoInWord = (w) => { const m = GH_LINK.exec(w ?? ''); return m ? `${m[1]}/${m[2].replace(/\.git$/, '')}` : null; }; // gh flags whose value is free text or a file (a body, a title, a merge subject, notes):
// the next word is skipped, so a link written there is never read as the target. A
// value that is not a whole github.com link can never match, so other flags need no entry.
const GH_VALUE_FLAGS = new Set(['-b', '--body', '-F', '--body-file', '-t', '--title', '--subject', '--message', '-T', '--template', '-n', '--notes', '--notes-file', '--description', '--add-label', '--remove-label', '-f', '--field', '--raw-field', '-H', '--header', '-q', '--jq', '--input', '-X', '--method', '-R', '--repo']); const GH_PLACEHOLDER = /^(?:\{(?:owner|repo)\}|:(?:owner|repo))$/;
const ghPositionals = (words) => {
  const out = [];
  for (let i = 0; i < words.length; i++) {
    const w = words[i];
    if (w === '--') { out.push(...words.slice(i + 1)); break; }
    if (w.startsWith('-')) { if (!w.includes('=') && GH_VALUE_FLAGS.has(w)) i++; continue; }
    out.push(w);
  }
  return out;
};
function ghParts(cmd) {
  const a = cmd.args;
  let i = 0, repo = null;
  while (i < a.length && a[i].startsWith('-')) { if (a[i] === '-R' || a[i] === '--repo') { repo = a[i + 1]; i += 2; continue; } if (a[i].startsWith('--repo=')) repo = a[i].slice(7); i++; } const rest = a.slice(i);
  const ri = rest.findIndex((w) => w === '-R' || w === '--repo');
  if (ri !== -1) repo = rest[ri + 1];
  const rr = rest.find((w) => w.startsWith('--repo=') || /^-R./.test(w));
  if (rr) repo = rr.startsWith('--repo=') ? rr.slice(7) : rr.slice(2);
  repo = repo ? normRepo(repo) : null;
  if (!repo) {
    const pos = ghPositionals(rest.slice(1));
    if (rest[0] === 'api') {
      const path = (pos[0] ?? '').replace(/^https?:\/\/api\.github\.com\//i, '').replace(/^\//, ''); const m = /^repos\/([^/\s?#]+)\/([^/\s?#]+)/.exec(path);
      // {owner}/{repo} (or :owner/:repo) is gh's placeholder for this folder's repo.
      if (m && !GH_PLACEHOLDER.test(m[1]) && !GH_PLACEHOLDER.test(m[2])) repo = `${m[1]}/${m[2]}`;
    } else {
      // gh <group> <verb> <target>: the target is the first positional after the verb.
      for (const w of pos.slice(1)) { const r = repoInWord(w); if (r) { repo = r; break; } }
    }
  }
  if (!repo && cmd.env?.GH_REPO) repo = normRepo(cmd.env.GH_REPO);
  return { sub: rest[0], sub2: rest[1], rest: rest.slice(1), repo };
}
// Value of a flag: `--x v`, `--x=v`, `-x v`, `-xv`. Returns all values.
function flagValues(args, names) {
  const out = [];
  for (let i = 0; i < args.length; i++) {
    const w = args[i];
    for (const n of names) {
      if (w === n && i + 1 < args.length) { out.push(args[i + 1]); i++; break; }
      if (n.startsWith('--') && w.startsWith(n + '=')) { out.push(w.slice(n.length + 1)); break; }
      if (!n.startsWith('--') && w.startsWith(n) && w.length > n.length && w[1] !== '-' && n.length === 2) { out.push(w.slice(2)); break; } }
  }
  return out;
}
const hasFlag = (args, names) => args.some((w) => names.some((n) => w === n || (n.startsWith('--') && w.startsWith(n + '=')))); // gh api: method, path and fields.
function ghApi(cmd, config = {}) {
  const { sub, rest } = ghParts(cmd);
  if (sub !== 'api') return null;
  let path = null, method = null;
  const fields = {};
  let input = null;
  for (let i = 0; i < rest.length; i++) {
    const w = rest[i];
    if (w === '-X' || w === '--method') { method = (rest[++i] ?? '').toUpperCase(); continue; }
    if (w.startsWith('--method=')) { method = w.slice(9).toUpperCase(); continue; }
    if (w.startsWith('-X') && w.length > 2) { method = w.slice(2).toUpperCase(); continue; }
    if (['-f', '-F', '--field', '--raw-field'].includes(w)) { const kv = rest[++i] ?? ''; const k = kv.split('=')[0]; fields[k] = kv.slice(k.length + 1); continue; } if (w === '--input') { input = rest[++i]; continue; }
    if (['-H', '--header', '-q', '--jq', '-t', '--template', '--cache', '--hostname', '-p', '--preview'].includes(w)) { i++; continue; } if (!w.startsWith('-') && path === null) path = w.replace(/^https?:\/\/api\.github\.com\//i, '').replace(/^\//, ''); }
  // gh fills {owner}/{repo} from GH_REPO or this folder's repo: judge the path as that repo's.
  if (path && /^repos\/(?:\{owner\}|:owner)\/(?:\{repo\}|:repo)(?=\/|$)/.test(path)) {
    const slug = ghParts(cmd).repo ?? repoSlug(config, cmd.cwd);
    if (slug) path = path.replace(/^repos\/[^/]+\/[^/]+/, `repos/${slug}`);
  }
  if (input) {
    const text = input === '-' ? cmd.heredoc : readText(resolve(cmd.cwd, input));
    try { Object.assign(fields, JSON.parse(text ?? '')); } catch { /* not JSON */ }
  }
  for (const [k, v] of Object.entries(fields)) if (typeof v === 'string' && v.startsWith('@')) {
    const t = v === '@-' ? cmd.heredoc : readText(resolve(cmd.cwd, v.slice(1)));
    if (t !== null && t !== undefined) fields[k] = t;
  }
  if (!method) method = Object.keys(fields).length || input ? 'POST' : 'GET';
  return { path: path ?? '', method, fields };
}

// ---------- refusals ----------

const refusal = (rule, matched, instead) => `${rule}\nMatched: ${matched}\n${instead ? `Instead: ${instead}\n` : ''}${FOOTER}`;

// ---------- git state ----------

const COMMIT_MAKERS = new Set(['commit', 'merge', 'revert', 'cherry-pick', 'am', 'pull', 'rebase']); const makesCommit = (g) => {
  if (!COMMIT_MAKERS.has(g.sub)) return false;
  if (hasFlag(g.rest, ['--abort', '--quit', '--skip', '-h', '--help'])) return false;
  if ((g.sub === 'merge' || g.sub === 'pull') && hasFlag(g.rest, ['--ff-only'])) return false;
  if (g.sub === 'commit' && hasFlag(g.rest, ['--dry-run'])) return false;
  return true;
};
const gitEnv = (cmd) => ({ ...process.env, ...cmd.env });
const configArgs = (config) => config.flatMap((c) => ['-c', c]);

// The commits a push would add: on no remote-tracking ref. The default branch is
// fetched first (once per run, bounded) so commits already on it, such as a web
// merge whose committer is GitHub, are never judged. With no remote-tracking ref
// at all nothing is judged here (commitVerify still judges each new commit).
const fetched = new Set();
function outgoingCommits(cwd, srcs, env, config) {
  const def = defaultBranch(config);
  if (!fetched.has(cwd) && config.fetchBeforePush !== false) {
    fetched.add(cwd);
    const shallow = git(cwd, ['rev-parse', '--is-shallow-repository']).out === 'true';
    run('git', ['fetch', '-q', ...(shallow ? ['--depth=50'] : []), 'origin', `+${def}:refs/remotes/origin/${def}`], { cwd, env, timeout: 15000 }); }
  const any = git(cwd, ['for-each-ref', '--count=1', 'refs/remotes'], env);
  if (!any.ok || !any.out) return [];
  const allowed = (config.identity?.allowCommitters ?? []).map(parseIdent);
  const seen = new Set();
  const out = [];
  for (const src of [].concat(srcs)) {
    const r = git(cwd, ['log', '--format=%H%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x1e', '-n', '200', src, '--not', '--remotes'], env); if (r.ok) for (const rec of r.out.split('\x1e')) { const sha = rec.replace(/^\n/, '').split('\x00')[0]; if (sha && !seen.has(sha)) { seen.add(sha); out.push(rec); } } }
  return out.join('\x1e').split('\x1e').map((s) => s.replace(/^\n/, '')).filter(Boolean).map((rec) => { const [sha, an, ae, cn, ce, body] = rec.split('\x00');
    return { sha, author: { name: an, email: ae }, committer: { name: cn, email: ce }, message: body ?? '' }; }).filter((k) => !allowed.some((a) => sameIdent(a, k.committer)));
}
const localBranches = (cwd) => { const r = git(cwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads']); return r.ok ? r.out.split('\n').filter(Boolean) : []; }; // Every branch a push sends: each refspec's source; --all, --branches, --mirror or a
// glob refspec send every local branch.
const PUSH_VALUE = new Set(['-o', '--push-option', '--repo', '--receive-pack', '--exec']);
const pushWords = (rest) => { const out = []; for (let i = 0; i < rest.length; i++) { if (PUSH_VALUE.has(rest[i])) { i++; continue; } if (!rest[i].startsWith('-')) out.push(rest[i]); } return out; }; const pushEverything = (rest) => hasFlag(rest, ['--all', '--branches', '--mirror']) || pushWords(rest).slice(1).some((r) => r.includes('*')); const pushSources = (rest, cwd) => {
  if (pushEverything(rest)) return localBranches(cwd);
  const refspecs = pushWords(rest).slice(1);
  if (!refspecs.length) return ['HEAD'];
  return [...new Set(refspecs.map((r) => r.replace(/^\+/, '').split(':')[0]).filter(Boolean))];
};
const currentBranch = (cwd) => { const r = git(cwd, ['branch', '--show-current']); return r.ok ? r.out : ''; }; const repoTop = (cwd) => { const r = git(cwd, ['rev-parse', '--show-toplevel']); return r.ok ? r.out : null; }; const attributionHits = (text, config, key = 'patterns') => {
  const pats = (config.attribution?.[key] ?? config.attribution?.patterns ?? []).map((p) => new RegExp(p, 'im')); return lines(text).filter((l) => pats.some((p) => { p.lastIndex = 0; return p.test(l); }));
};


// ---------- which repo a call acts in ----------
// A git or gh call in another repo is judged by that repo's own rules.json; a repo
// with none that this config names in alsoGuards gets the checks that hold in every
// repo of the owner (identity, attribution, force-push, merge method, bypass flags,
// banned commands, default-branch push); any other repo is not judged.
const REPO_ONLY = ['prBody', 'prBodyVerify', 'prFlow', 'liveState', 'mergeGreen', 'ruleMix', 'hostedRunners', 'laneNotice']; const remoteDefault = (top) => { const r = top ? git(top, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']) : { ok: false }; return r.ok ? r.out.replace(/^origin\//, '') : 'main'; }; function agnostic(config, top) {
  const c = { ...config, repo: null, defaultBranch: remoteDefault(top), agnostic: true };
  for (const k of REPO_ONLY) c[k] = { ...(typeof config[k] === 'object' ? config[k] : {}), enabled: false }; return c;
}
function scopeFor(root, config, cwd, slug) {
  const own = String(repoSlug(config, root) ?? '').toLowerCase();
  const guards = (config.alsoGuards ?? []).map((x) => x.toLowerCase());
  if (!slug && config.detached && !repoTop(cwd)) return { root, config: repoless(config) };
  if (slug) {
    const s = slug.toLowerCase();
    if (s === own) return { root, config };
    return guards.includes(s) ? { root, config: agnostic(config, null) } : null;
  }
  const top = repoTop(cwd);
  if (!top) return { root, config: config.detached ? repoless(config) : config };
  if (resolve(top) === resolve(root)) return { root, config };
  const theirs = loadConfig(top).config;
  if (theirs) return { root: top, config: theirs };
  const s = String(repoSlug({}, top) ?? '').toLowerCase();
  if (s && s === own) return { root: top, config };
  return s && guards.includes(s) ? { root: top, config: agnostic(config, top) } : null;
}

function checkDefaultBranchPush(cmd, config, deny) {
  if (cmd.prog !== 'git' || config.defaultBranchPush?.enabled === false) return;
  const g = gitParts(cmd);
  if (g.sub !== 'push' || hasFlag(g.rest, ['--delete', '-d', '-n', '--dry-run'])) return;
  const def = defaultBranch(config);
  const refspecs = pushWords(g.rest).slice(1);
  let targets;
  if (pushEverything(g.rest)) targets = localBranches(g.cwd);
  else if (refspecs.length) targets = refspecs.map((r) => { const x = r.replace(/^\+/, ''); return x.includes(':') ? x.split(':')[1] : x; }); else { const up = git(g.cwd, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']); targets = [up.ok ? up.out.split('/').slice(1).join('/') : currentBranch(g.cwd)]; } targets = targets.map((t) => (t === 'HEAD' ? currentBranch(g.cwd) : t).replace(/^refs\/heads\//, '')); if (!targets.includes(def)) return;
  // The first push to an empty remote creates the default branch; there is no base for a pull request yet. const remote = pushWords(g.rest)[0] ?? 'origin';
  const heads = git(g.cwd, ['ls-remote', '--heads', remote]);
  if (heads.ok && !heads.out.trim()) return;
  deny(refusal(`Nothing is pushed straight to ${def}: CI is the merge gate, and a change reaches ${def} only through a green pull request (release, Lanes and merging).`, `git push to ${def}`, 'push a branch and open a pull request')); }

// ---------- the checks: Bash ----------

function checkIdentity(cmd, config, deny) {
  if (cmd.prog !== 'git' || !on(config, 'identity')) return;
  const want = authorOf(config);
  if (!want) return;
  const g = gitParts(cmd);
  const fix = `git config user.name "${want.name}" && git config user.email "${want.email}"`;
  if (makesCommit(g)) {
    const env = gitEnv(cmd);
    const authorFlag = flagValues(g.rest, ['--author'])[0];
    const a = authorFlag ? parseIdent(authorFlag) : parseIdent(git(g.cwd, [...configArgs(g.config), 'var', 'GIT_AUTHOR_IDENT'], env).out); const c = parseIdent(git(g.cwd, [...configArgs(g.config), 'var', 'GIT_COMMITTER_IDENT'], env).out); if (a && !sameIdent(a, want)) deny(refusal(`Every commit is authored by ${showIdent(want)} (CLAUDE.md, Rules that never bend: Identity).`, `git ${g.sub} would be authored by ${showIdent(a)}`, fix)); else if (c && !sameIdent(c, want)) deny(refusal(`Every commit is committed by ${showIdent(want)} too (CLAUDE.md, Identity).`, `git ${g.sub} would be committed by ${showIdent(c)}`, fix)); }
  if (g.sub === 'push' && !hasFlag(g.rest, ['--delete', '-d', '-n', '--dry-run'])) {
    for (const k of outgoingCommits(g.cwd, pushSources(g.rest, g.cwd), gitEnv(cmd), config)) {
      if (!sameIdent(k.author, want) || !sameIdent(k.committer, want)) {
        deny(refusal(`Every commit is authored by ${showIdent(want)} (CLAUDE.md, Identity).`, `outgoing commit ${k.sha.slice(0, 7)} is by ${showIdent(k.author)}, committed by ${showIdent(k.committer)}`, `${fix}, then rewrite the unpushed commit: git commit --amend --reset-author --no-edit (or rebase the unpushed range with --exec 'git commit --amend --reset-author --no-edit')`)); break;
      }
    }
  }
}

function commitMessage(cmd, g) {
  const parts = [...flagValues(g.rest, ['-m', '--message'])];
  for (const f of flagValues(g.rest, ['-F', '--file'])) parts.push(f === '-' ? cmd.heredoc ?? '' : readText(resolve(g.cwd, f)) ?? ''); for (const ref of flagValues(g.rest, ['-C', '-c', '--reuse-message', '--reedit-message'])) { const r = git(g.cwd, ['log', '-1', '--format=%B', ref]); if (r.ok) parts.push(r.out); } if (!parts.length && hasFlag(g.rest, ['--amend'])) { const r = git(g.cwd, ['log', '-1', '--format=%B']); if (r.ok) parts.push(r.out); } return parts.join('\n');
}

function checkAttribution(cmd, config, deny) {
  if (cmd.prog !== 'git' || !on(config, 'attribution')) return;
  const g = gitParts(cmd);
  const rule = 'No Claude co-author, no "Claude-Session" trailer and no "Generated with Claude Code" line in commits, pull request bodies or docs (CLAUDE.md, Identity).'; if (g.sub === 'commit' || g.sub === 'merge' || g.sub === 'revert') {
    const hits = attributionHits(commitMessage(cmd, g), config);
    if (hits.length) deny(refusal(rule, `commit message line "${hits[0].trim()}"`, 'drop that line from the message')); }
  if (g.sub === 'push' && !hasFlag(g.rest, ['--delete', '-d'])) {
    for (const k of outgoingCommits(g.cwd, pushSources(g.rest, g.cwd), gitEnv(cmd), config)) {
      const hits = attributionHits(k.message, config);
      if (hits.length) { deny(refusal(rule, `outgoing commit ${k.sha.slice(0, 7)} has "${hits[0].trim()}"`, 'reword the unpushed commit without that line (git commit --amend for the last one)')); break; } }
  }
}

function checkForcePush(cmd, config, deny) {
  if (!on(config, 'forcePush')) return;
  const rule = 'Never force-push (CLAUDE.md, Identity).';
  if (cmd.prog === 'git') {
    const g = gitParts(cmd);
    if (g.sub !== 'push') return;
    const bad = g.rest.find((w) => /^--(force|force-with-lease|force-if-includes|mirror)(=|$)/.test(w) || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(w) || w.startsWith('+')); if (bad) deny(refusal(rule, `git push ${bad}`, 'push without force; if the remote moved, fetch and merge it (git fetch origin <branch> && git merge --no-edit FETCH_HEAD), then push')); }
  if (cmd.prog === 'gh') {
    const api = ghApi(cmd, config);
    if (api && /git\/refs/.test(api.path) && String(api.fields.force) === 'true') deny(refusal(rule, `gh api ${api.path} with force=true`, 'update the ref without force')); }
}

function checkMergeMethod(cmd, config, deny) {
  if (!on(config, 'mergeMethod')) return;
  const rule = 'Merge with a merge commit, never a squash or a rebase (CLAUDE.md, Identity).';
  if (cmd.prog === 'git') {
    const g = gitParts(cmd);
    if (g.sub === 'merge' && hasFlag(g.rest, ['--squash'])) deny(refusal(rule, 'git merge --squash', 'git merge --no-ff')); }
  if (cmd.prog !== 'gh') return;
  const p = ghParts(cmd);
  if (p.sub === 'pr' && p.sub2 === 'merge') {
    const a = p.rest.slice(1);
    if (hasFlag(a, ['--squash', '-s', '--rebase', '-r'])) deny(refusal(rule, `gh pr merge ${a.join(' ')}`, 'gh pr merge <number> --merge')); else if (!hasFlag(a, ['--merge', '-m', '--disable-auto'])) deny(refusal(rule, 'gh pr merge with no method (it would take the repo default or prompt)', 'gh pr merge <number> --merge')); }
  const api = ghApi(cmd, config);
  if (api && /pulls\/\d+\/(merge|ccr\/auto_merge)$/.test(api.path) && api.method !== 'GET' && api.method !== 'DELETE') { const m = String(api.fields.merge_method ?? 'merge').toLowerCase();
    if (m !== 'merge') deny(refusal(rule, `gh api ${api.path} merge_method=${m}`, 'merge_method=merge')); }
}

// Test runners: any program or package script whose name holds "test" or "e2e", plus the common runners. const RUNNERS = /test|e2e|^(jest|playwright|mocha|ava|tap|node)$/;
function checkBypassFlags(cmd, config, deny) {
  if (!on(config, 'bypassFlags')) return;
  const rule = 'Never bypass a check: no --no-verify, no --admin merge, no passing with no tests, no retries until green (CLAUDE.md, Limits; build skill).'; if (cmd.prog === 'git') {
    const g = gitParts(cmd);
    if (hasFlag(g.rest, ['--no-verify'])) deny(refusal(rule, `git ${g.sub} --no-verify`, 'run without --no-verify and fix what the hook finds')); else if (g.sub === 'commit' && g.rest.some((w) => /^-[a-zA-Z]*n[a-zA-Z]*$/.test(w))) deny(refusal(rule, 'git commit -n (skips the hooks)', 'commit without -n')); }
  if (cmd.prog === 'gh') {
    const p = ghParts(cmd);
    if (p.sub === 'pr' && p.sub2 === 'merge' && hasFlag(p.rest, ['--admin'])) deny(refusal(rule, 'gh pr merge --admin', 'wait for the required checks; merge when green')); }
  if (hasFlag(cmd.args, ['--passWithNoTests', '--pass-with-no-tests'])) deny(refusal(rule, `${cmd.prog} --passWithNoTests`, 'run the tests that exist; a run with no tests is a failure')); if (RUNNERS.test(cmd.prog)) {
    const n = flagValues(cmd.args, ['--retries', '--retry']).map(Number).find((x) => x > 0);
    if (n) deny(refusal(rule, `${cmd.prog} --retries ${n}`, 'run once; a test that passes only on retry is a flaky-test defect to record in history.md')); }
}

// GPU: pictures and rendered runs only on a GPU machine.
function isGpuMachine(config, sessionId) {
  const d = config.gpu?.detect ?? {};
  if (d.env && process.env[d.env] === '1') return true;
  if (d.env && process.env[d.env] === '0') return false;
  const cache = join(tmpdir(), `claude-rules-gpu-${String(sessionId ?? 'none').replace(/[^\w-]/g, '')}.txt`); const cached = readText(cache);
  if (cached === 'yes' || cached === 'no') return cached === 'yes';
  let yes = false;
  if (Array.isArray(d.command) && d.command.length) {
    const r = spawnSync(d.command[0], d.command.slice(1), { timeout: 3000, encoding: 'utf8' });
    yes = r.status === 0 && !r.error;
  }
  try { writeFileSync(cache, yes ? 'yes' : 'no'); } catch { /* cache is optional */ }
  return yes;
}
const captureIn = (text, config) => (text ? (config.gpu?.captureCalls ?? []).find((c) => text.includes(c)) : undefined); const PW_VALUE = new Set(['--project', '-c', '--config', '-g', '--grep', '--grep-invert', '-j', '--workers', '--reporter', '--retries', '--timeout', '--repeat-each', '--output', '--max-failures', '-x', '--shard', '--trace', '--global-timeout', '--tsconfig']); const IMPORT = /(?:\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s+)["'](\.{1,2}\/[^"']+)["']/gm; const EXTS = ['', '.ts', '.mts', '.js', '.mjs', '.cjs', '.tsx', '/index.ts', '/index.js'];

// A script's text plus the text of the files it imports by relative path (two levels
// deep), leaving out the helpers the config allows (a measurement, not a picture).
function scriptText(file, config, root, depth = 0, seen = new Set()) {
  if (seen.has(file)) return '';
  seen.add(file);
  const text = readText(file);
  if (text === null) return '';
  let out = text;
  if (depth >= 2) return out;
  for (const m of text.matchAll(IMPORT)) {
    for (const ext of EXTS) {
      const target = resolve(dirname(file), m[1] + ext);
      if (!existsSync(target) || !statSync(target).isFile()) continue;
      const rel = relative(root, target).split(sep).join('/');
      if (!matchesAny(rel, config.gpu?.allowedHelpers ?? [])) out += '\n' + scriptText(target, config, root, depth + 1, seen); break;
    }
  }
  return out;
}
function packageScript(cwd, name, root) {
  let dir = resolve(cwd);
  for (;;) {
    const text = readText(join(dir, 'package.json'));
    if (text !== null) { try { const s = JSON.parse(text).scripts?.[name]; if (typeof s === 'string') return { text: s, dir }; } catch { /* not JSON */ } } if (dir === resolve(root) || dirname(dir) === dir) return null;
    dir = dirname(dir);
  }
}

// The spec files a Playwright positional selects: a file, every spec in a folder, or
// (any other word) every spec whose path the word matches, as Playwright filters.
const SPEC = /\.(spec|test)\.[cm]?[jt]sx?$/;
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'coverage', 'test-results', 'playwright-report', '.pnpm-store']); function specFilesUnder(dir, out = [], budget = { n: 20000 }) {
  let entries = [];
  try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return out; }
  for (const e of entries) {
    if (--budget.n < 0) break;
    if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) specFilesUnder(join(dir, e.name), out, budget); } else if (SPEC.test(e.name)) out.push(join(dir, e.name));
  }
  return out;
}
let allSpecs = null;
function specsFor(given, cwd, root) {
  const word = given.replace(/:\d+(:\d+)?$/, ''); // Playwright's file:line and file:line:column
  const abs = resolve(cwd, word);
  if (existsSync(abs)) return statSync(abs).isDirectory() ? specFilesUnder(abs) : [abs];
  allSpecs ??= specFilesUnder(root);
  let re;
  try { re = new RegExp(word); } catch { re = null; }
  return allSpecs.filter((f) => (re ? re.test(f) : f.includes(word)));
}

// Why a command renders, or null. Reads package scripts and shell script files again.
function renderReason(cmd, config, root, depth) {
  const g = config.gpu;
  const key = cmd.prog;
  if ((g.renderCommands ?? []).includes(key)) return `${key.replace(/^script:/, 'pnpm ')} renders`;
  if (key.startsWith('script:') && depth < 3) {
    const s = packageScript(cmd.cwd, key.slice(7), root);
    if (s) for (const inner of simpleCommands(s.text, s.dir)) { inner.env = { ...cmd.env, ...inner.env }; const r = renderReason(inner, config, root, depth + 1); if (r) return `${key.replace(/^script:/, 'pnpm ')} runs "${s.text.slice(0, 60)}": ${r}`; } // No such script: pnpm, yarn and bun run the package binary of that name.
    return s ? null : renderReason({ ...cmd, prog: key.slice(7), path: key.slice(7) }, config, root, depth + 1); }
  if (['bash', 'sh', 'zsh'].includes(cmd.prog) || /\.(sh|bash)$/.test(cmd.prog)) {
    const file = /\.(sh|bash)$/.test(cmd.prog) ? cmd.path : cmd.args.find((a) => !a.startsWith('-')); const text = file && depth < 3 ? readText(resolve(cmd.cwd, file)) : null;
    if (text !== null) for (const inner of simpleCommands(text, cmd.cwd)) { inner.env = { ...cmd.env, ...inner.env }; const r = renderReason(inner, config, root, depth + 1); if (r) return `${file}: ${r}`; } return null;
  }
  if (cmd.prog === 'playwright' && cmd.args[0] === 'screenshot') return 'playwright screenshot';
  if (/chrom(e|ium)/i.test(cmd.prog) && cmd.args.some((a) => a.startsWith('--screenshot') || a.startsWith('--print-to-pdf'))) return `${cmd.prog} --screenshot`; if (cmd.prog === 'playwright' && cmd.args[0] === 'test') {
    const a = cmd.args.slice(1);
    const positional = [];
    const projects = [];
    let grep = '';
    for (let i = 0; i < a.length; i++) {
      const w = a[i];
      if (w.startsWith('--') && w.includes('=')) { const k = w.slice(0, w.indexOf('=')), v = w.slice(w.indexOf('=') + 1); if (k === '--project') projects.push(v); if (k === '--grep') grep += v; if (k === '--update-snapshots') return 'it updates snapshots (baselines are taken on the CI GPU machines)'; continue; } if (PW_VALUE.has(w)) { const v = a[++i] ?? ''; if (w === '--project') projects.push(v); if (w === '-g' || w === '--grep') grep += v; continue; } if (w === '-u' || w === '--update-snapshots') return 'it updates snapshots (baselines are taken on the CI GPU machines)'; if (!w.startsWith('-')) positional.push(w);
    }
    if (!positional.length) return 'it runs the whole browser suite';
    for (const p of positional) {
      const bare = p.replace(/:\d+(:\d+)?$/, '');
      if ((g.gpuOnlySpecs ?? []).some((s) => bare.includes(s) || globToRegExp(s).test(bare.split('/').at(-1)))) return `${p} is a GPU-only spec`; for (const file of specsFor(p, cmd.cwd, root)) {
        const rel = relative(root, file).split(sep).join('/');
        if ((g.gpuOnlySpecs ?? []).some((s) => globToRegExp(s).test(rel.split('/').at(-1)))) return `${p} selects ${rel}, a GPU-only spec`; const hit = captureIn(scriptText(file, config, root), config);
        if (hit) return `${p} selects ${rel}, which (or a file it imports) calls ${hit}`;
      }
    }
    for (const pr of projects) if ((g.gpuOnlyProjects ?? []).some((s) => globToRegExp(s).test(pr))) return `project ${pr} is GPU-only`; if (/@gpu/.test(grep)) return 'it selects @gpu tests';
    if (g.softwareEnv && cmd.env[g.softwareEnv] === undefined && process.env[g.softwareEnv] === undefined) return `a browser run in a container needs ${g.softwareEnv}=1 (the software-renderer mode)`; return null;
  }
  if (['node', 'tsx', 'vite-node', 'bun', 'deno', 'python', 'python3', 'ts-node'].includes(cmd.prog)) { const a = cmd.args;
    let text = null, label = '';
    const evalFlag = a.findIndex((w) => ['-e', '--eval', '-p', '--print', '-c'].includes(w));
    if (evalFlag !== -1) { text = a[evalFlag + 1] ?? ''; label = `${cmd.prog} ${a[evalFlag]}`; }
    else {
      let i = 0;
      while (i < a.length && a[i].startsWith('-')) { if (['-r', '--require', '--import', '--loader', '--env-file', '-m'].includes(a[i])) i++; i++; } if (cmd.prog === 'deno' && ['run', 'eval'].includes(a[i])) i++;
      const file = a[i];
      if (file && file !== '-') { text = scriptText(resolve(cmd.cwd, file), config, root); label = file; } else if (cmd.heredoc !== null) { text = cmd.heredoc; label = `${cmd.prog} with a heredoc script`; } }
    const hit = captureIn(text, config);
    return hit ? `${label} (or a file it imports) calls ${hit}` : null;
  }
  return null;
}

function checkGpu(cmd, config, deny, ctx) {
  const g = config.gpu;
  if (!g || g.enabled !== true) return;
  const reason = renderReason(cmd, config, ctx.root, 0);
  if (reason && !isGpuMachine(config, ctx.sessionId)) deny(refusal('Every screenshot, screen walk, visual spec and rendered run happens on a GPU machine, never with software rendering in a container (Owner).', `${reason}; this machine is not a GPU machine`, g.hint ?? 'Render on a GPU machine.')); }

function checkBanned(cmd, config, deny) {
  for (const b of config.bannedCommands ?? []) {
    const [prog, sub] = String(b.command ?? '').split(' ');
    if (cmd.prog !== prog) continue;
    const g = prog === 'git' ? gitParts(cmd) : null;
    const actual = g ? g.sub : cmd.args[0];
    const after = g ? g.rest : cmd.args.slice(1);
    const readOnly = (b.allow ?? []).includes(after[0] ?? ''); // the subcommand word itself, never a path after -- if ((!sub || actual === sub) && !readOnly) deny(refusal(b.reason ?? `${b.command} is not used in this repo.`, `${prog} ${actual ?? ''}`.trim(), b.instead)); }
}

function checkHostedRunnersOnPush(cmd, config, deny) {
  if (cmd.prog !== 'git' || config.hostedRunners?.enabled !== true) return;
  const g = gitParts(cmd);
  if (g.sub !== 'push' || hasFlag(g.rest, ['--delete', '-d'])) return;
  for (const src of pushSources(g.rest, g.cwd)) {
    const r = git(g.cwd, ['diff', '--name-only', `origin/${defaultBranch(config)}...${src}`, '--', '.github/workflows']); if (!r.ok) continue;
    for (const f of r.out.split('\n').filter((x) => /\.ya?ml$/.test(x))) {
      const text = git(g.cwd, ['show', `${src}:${f}`]).out;
      const hit = hostedLabel(text, config);
      if (hit) { deny(refusal(hostedRule, `${f}: ${hit}`, hostedInstead(config))); return; }
    }
  }
}
const hostedRule = 'No job runs on GitHub-hosted runners on this repo (Owner; vertical-slice, CI).'; const hostedInstead = (config) => config.hostedRunners?.hint ?? 'Use the self-hosted runner labels the gate starts.'; function hostedLabel(text, config) {
  const labels = (config.hostedRunners?.labels ?? ['ubuntu', 'windows', 'macos']).join('|');
  const re = new RegExp(`(^|[^\\w./:-])((${labels})-(latest|\\d[\\w.]*)(-[\\w]+)*)\\b`);
  for (const raw of lines(text)) {
    const line = raw.replace(/(^|\s)#.*$/, '');
    if (!line.trim()) continue;
    const m = re.exec(line);
    if (m) return `"${raw.trim()}"`;
  }
  return null;
}

function checkRuleMix(cmd, config, deny) {
  if (cmd.prog !== 'git' || !config.ruleMix || config.ruleMix.enabled === false || config.ruleMix.firstTimeSetup) return; const g = gitParts(cmd);
  if (g.sub !== 'push' || hasFlag(g.rest, ['--delete', '-d'])) return;
  for (const src of pushSources(g.rest, g.cwd)) {
    const r = git(g.cwd, ['diff', '--name-only', `origin/${defaultBranch(config)}...${src}`]);
    if (r.ok) ruleMixFiles(r.out.split('\n').filter(Boolean), config, deny);
  }
}
// Rules files may travel with docs and the rest of .claude/, never with product code or tests.
function ruleMixFiles(files, config, deny) {
  const rules = files.filter((f) => matchesAny(f, config.ruleMix.rulePaths));
  const docs = config.ruleMix.docPaths ?? ['docs/**', '*.md', '**/*.md', '.claude/**'];
  const other = files.filter((f) => !matchesAny(f, config.ruleMix.rulePaths) && !matchesAny(f, docs)); if (rules.length && other.length) deny(refusal('A change does not quietly edit its own check: rules files and CI change in their own pull request, with no product code or tests (CLAUDE.md, Verification).', `this branch changes ${rules[0]} and ${other[0]}`, 'split the rules change into its own branch and pull request')); }

// Pull request bodies.
function judgeBody(body, config, allowFooter) {
  const want = prLastLineOf(config);
  let text = String(body ?? '');
  if (allowFooter) text = stripFooter(text);
  const problems = [];
  const hits = attributionHits(text, config);
  if (hits.length) problems.push(`it has the line "${hits[0].trim()}"`);
  if (want && !lastLine(text).endsWith(want)) problems.push(`its last line is "${lastLine(text).slice(0, 80)}", not "${want}"`); return problems;
}
function stripFooter(body) {
  const ls = body.split('\n');
  let i = ls.length - 1, generated = 0;
  const gen = /^[\s>*_]*(?:🤖\s*)?Generated (?:by|with)\b/;
  for (; i >= 0; i--) {
    const l = ls[i].trim();
    if (l === '' || l.startsWith('https://claude.ai/code/session_')) continue;
    if (gen.test(l)) generated++; else break;
  }
  if (!generated || i < 0 || ls[i].trim() !== '---') return body;
  return ls.slice(0, i).join('\n').trimEnd();
}
const PR_RULE = 'Pull request bodies end with the owner\'s "Requested by" line and carry no Claude attribution (CLAUDE.md, Identity; release).'; function checkPrBodyBash(cmd, config, deny) {
  if (cmd.prog !== 'gh' || !on(config, 'prBody')) return;
  const p = ghParts(cmd);
  let body;
  if (p.sub === 'pr' && (p.sub2 === 'create' || p.sub2 === 'edit')) {
    const a = p.rest.slice(1);
    const given = flagValues(a, ['--body', '-b', '--body-file', '-F']).length > 0;
    if (given) body = ghBody(cmd, a);
    else if (p.sub2 === 'create') { deny(refusal(PR_RULE, hasFlag(a, ['--fill', '--fill-first', '--fill-verbose', '-f']) ? 'gh pr create --fill (the body would come from commit messages)' : 'gh pr create with no body', 'write the body to a file and pass --body-file <file>')); return; } else return;
  } else {
    const api = ghApi(cmd, config);
    if (!api || !/pulls(\/\d+)?$/.test(api.path) || api.method === 'GET' || api.fields.body === undefined) return; body = api.fields.body;
  }
  if (body === null || body === undefined || /\$\{?[A-Za-z_(]|`/.test(body)) return; // cannot resolve: prBodyVerify judges the result const problems = judgeBody(body, config, false);
  if (problems.length) deny(refusal(PR_RULE, `the body: ${problems.join('; ')}`, `end the body with "${prLastLineOf(config)}" on its own last line`)); }

// The pull request flow (release): a lane in the body, acceptance criteria for a change
// that is not only docs, a draft until the lane's reviews are done, an open-PR limit,
// and, for lane 2 and 3, a passing review that names the head commit before ready or merge.
const LANE = /\blane\s*([123])\b/gi;
const laneOf = (body) => { const all = [...String(body ?? '').matchAll(LANE)].map((m) => Number(m[1])); return all.length ? Math.max(...all) : null; }; // the highest lane named wins // A verdict is a comment or review whose first line starts with a commit (7+ hex
// characters) followed by PASS or FAIL, e.g. "79ef366 FAIL: 5 red" or "**abc1234 PASS**".
function verdicts(items, f) {
  const pass = new RegExp(f.passPattern ?? '^(PASS|PASSED)$');
  const fail = new RegExp(f.failPattern ?? '^(FAIL|FAILED)$');
  const out = [];
  for (const c of items) {
    const raw = String(c.body ?? '').split('\n').map((l) => l.trim()).find(Boolean) ?? '';
    if (raw.startsWith('>')) continue; // a quote is not a verdict
    const first = raw.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1'); // [abc1234](link) reads as abc1234
    const m = /^[^0-9a-z>]*([0-9a-f]{7,40})\b(.*)$/i.exec(first);
    if (!m) continue;
    // Strict: the first word after the commit, before any number, is the verdict, and it
    // must be exactly PASS/PASSED or FAIL/FAILED ("abc1234 PASS: 0 failed" passes). Anything
    // else ("abc1234: 828 passed", "abc1234: tests PASS", "abc1234: 0 failed") is a status
    // line, not a verdict, so it neither clears a FAIL nor blocks a PASS.
    const word = (/^[^A-Za-z0-9]*([A-Za-z]+)/.exec(m[2]) ?? [])[1] ?? '';
    const verdict = fail.test(word) ? 'fail' : pass.test(word) ? 'pass' : null;
    if (verdict) out.push({ sha: m[1].slice(0, 7).toLowerCase(), verdict, at: c.submitted_at ?? c.created_at ?? '' }); }
  return out.sort((a, b) => String(a.at).localeCompare(String(b.at)));
}
// Commits between a reviewed commit and the head that are only clean merges of the
// default branch keep the review (release: "a clean merge of current main keeps the review").
function onlyCleanMerges(config, cwd, from, head) {
  if (git(cwd, ['merge-base', '--is-ancestor', from, head]).ok !== true) return false;
  const r = git(cwd, ['rev-list', '--parents', `${from}..${head}`, '--not', `origin/${defaultBranch(config)}`]); if (!r.ok) return false;
  for (const line of r.out.split('\n').filter(Boolean)) {
    const [c, p1, p2, ...more] = line.split(' ');
    if (!p2 || more.length) return false;
    const fromMain = git(cwd, ['merge-base', '--is-ancestor', p2, `origin/${defaultBranch(config)}`]).ok; const merged = git(cwd, ['merge-tree', '--write-tree', p1, p2]);
    const tree = git(cwd, ['rev-parse', `${c}^{tree}`]);
    if (!fromMain || !merged.ok || !tree.ok || merged.out.split('\n')[0] !== tree.out) return false; }
  return true;
}
const FLOW_RULE = 'Pull requests follow release: the body names the lane and the acceptance criteria, it opens as a draft, and a lane 2 or 3 pull request is marked ready or merged only after a passing review that names its head commit.'; function changesBeyondDocs(config, cwd) {
  const r = git(cwd, ['diff', '--name-only', `origin/${defaultBranch(config)}...HEAD`]);
  if (!r.ok) return true;
  const docs = config.ruleMix?.docPaths ?? ['docs/**', '*.md', '**/*.md', '.claude/**'];
  return r.out.split('\n').filter(Boolean).some((f) => !matchesAny(f, docs));
}
// A branch that changes only rules files and docs (the owner's rule requests keep their
// own pull requests) is not held back by the open pull request limit.
function onlyRulesAndDocs(config, cwd) {
  const r = git(cwd, ['diff', '--name-only', `origin/${defaultBranch(config)}...HEAD`]);
  if (!r.ok) return false;
  const files = r.out.split('\n').filter(Boolean);
  const keep = [...(config.ruleMix?.rulePaths ?? []), ...(config.ruleMix?.docPaths ?? ['docs/**', '*.md', '**/*.md'])]; return files.length > 0 && files.every((x) => matchesAny(x, keep) && !x.startsWith('.claude/hooks/') && x !== '.claude/settings.json' && !x.startsWith('.github/')); }
function checkPrCreate(config, cwd, repo, body, draft, deny) {
  const f = config.prFlow;
  if (!f || f.enabled === false) return;
  const known = body !== null && body !== undefined && !/\$\{?[A-Za-z_(]|`/.test(body);
  const lane = known ? laneOf(body) : null;
  if (known && f.requireLane !== false && !lane) { deny(refusal(FLOW_RULE, 'the body names no lane', 'add a "## Lane" section that says "Lane 1", "Lane 2" or "Lane 3" and why')); return; } if (known && f.requireCriteria !== false && !/acceptance criteria/i.test(body) && changesBeyondDocs(config, cwd)) deny(refusal(FLOW_RULE, 'the body has no acceptance criteria and the branch changes more than docs', 'add an "## Acceptance criteria" section: what done looks like, as checks a program or a person can observe (build)')); if (f.draft !== false && !draft) {
    const info = repo ? ghJson(`repos/${repo}`, cwd) : null;
    if (!(lane === 1 && info?.private === true)) deny(refusal(FLOW_RULE, `lane ${lane ?? '(unread)'} pull request opened ready${lane === 1 ? ' on a repo that is not known to be private' : ''}`, 'open it as a draft (gh pr create --draft, or draft: true)')); }
  if (f.maxOpenPrs && repo && !onlyRulesAndDocs(config, cwd)) {
    const open = ghJson(`repos/${repo}/pulls?state=open&per_page=100`, cwd);
    if (Array.isArray(open) && open.length >= f.maxOpenPrs) deny(refusal(`Pull requests open: ${f.maxOpenPrs} at most (CLAUDE.md, Settings).`, `${open.length} are open now (${open.slice(0, 5).map((x) => `#${x.number}`).join(', ')})`, 'merge or close one first, or report to the coordinator and wait for a free place')); }
}
function checkReviewed(config, cwd, repo, number, what, deny) {
  const f = config.prFlow;
  if (!f || f.enabled === false || f.requireReview === false || !repo) return;
  let n = number;
  if (!n) { const b = currentBranch(cwd); const list = ghJson(`repos/${repo}/pulls?head=${repo.split('/')[0]}:${b}`, cwd); n = list?.[0]?.number; } const pr = n ? ghJson(`repos/${repo}/pulls/${n}`, cwd) : null;
  if (!pr) { deny(refusal(FLOW_RULE, `pull request ${n ?? '(unknown)'} could not be read`, 'read it yourself, check its lane and reviews, then retry')); return; } const lane = laneOf(pr.body);
  if (!lane) { deny(refusal(FLOW_RULE, `${what}: the body of #${n} names no lane`, 'add the lane to the body (gh pr edit --body-file), then retry')); return; } if (lane < 2) return;
  const sha = String(pr.head?.sha ?? '').slice(0, 7);
  const comments = ghJson(`repos/${repo}/issues/${n}/comments?per_page=100`, cwd) ?? [];
  const reviews = ghJson(`repos/${repo}/pulls/${n}/reviews?per_page=100`, cwd) ?? [];
  // The latest verdict on a commit stands; a passing one covers the head when it is the
  // head or only clean merges of the default branch lie between them.
  // Every verdict on a commit that is the head, or reaches it through clean merges of the
  // default branch only, counts; the newest of them decides.
  const reaches = new Map();
  const covers = (at) => { if (!reaches.has(at)) reaches.set(at, at === sha || onlyCleanMerges(config, cwd, at, pr.head.sha)); return reaches.get(at); }; const counted = verdicts([...comments, ...reviews], f).filter((v) => sha && covers(v.sha));
  const ok = counted.length > 0 && counted.at(-1).verdict === 'pass';
  if (!ok) deny(refusal(FLOW_RULE, `${what}: lane ${lane} pull request #${n} has no passing review that names its head ${sha}`, `have the coordinator start the ${lane === 3 ? 'implementation audit' : 'fresh review'} of ${sha}; it posts its verdict on the pull request with "${sha} PASS" or "${sha} FAIL" as the first line`)); }

// Live state, merge status.
const liveStatePath = (config, branch) => (config.liveState?.path ?? 'docs/superpowers/live/{branch}.md').replace('{branch}', branch.replaceAll('/', '-')); const repoSlug = (config, cwd, explicit) => {
  if (explicit) return explicit;
  if (config.repo) return config.repo;
  const r = git(cwd, ['remote', 'get-url', 'origin']);
  const m = /github\.com[/:]([^/]+\/[^/.]+)(\.git)?$/.exec(r.out) ?? /\/git\/([^/]+\/[^/.]+)$/.exec(r.out); return m ? m[1] : null;
};
const ghJson = (path, cwd) => {
  const r = run('gh', ['api', path], { cwd, env: { ...process.env, GH_PAGER: 'cat' }, timeout: 8000 }); if (!r.ok) return null;
  try { return JSON.parse(r.out); } catch { return null; }
};
function prBranch(config, cwd, repo, number) {
  if (!number) return currentBranch(cwd) || null;
  const pr = ghJson(`repos/${repo}/pulls/${number}`, cwd);
  return pr?.head?.ref ?? null;
}
function liveFileOnBranch(config, cwd, repo, branch) {
  const path = liveStatePath(config, branch);
  if (repo) {
    const r = run('gh', ['api', `repos/${repo}/contents/${path}?ref=${encodeURIComponent(branch)}`, '--silent'], { cwd, env: { ...process.env, GH_PAGER: 'cat' } }); if (r.ok) return path;
    if (/404|Not Found/i.test(r.err)) return null;
  }
  if (branch === currentBranch(cwd)) return git(cwd, ['cat-file', '-e', `HEAD:${path}`]).ok ? path : null; return null;
}
function checkLiveState(config, cwd, repo, number, what, deny) {
  if (!config.liveState || config.liveState.enabled === false) return;
  const branch = prBranch(config, cwd, repo, number);
  if (!branch) return;
  const file = liveFileOnBranch(config, cwd, repo, branch);
  if (file) deny(refusal('The live-state file is deleted in the last commit before the audit or the merge, so it never reaches main (CLAUDE.md, Live state in a file).', `${what} while ${file} is still on ${branch}`, `git rm ${file} && git commit -m "Remove live state" && git push, then retry`)); }
function checkMergeGreen(config, cwd, repo, number, deny) {
  const need = config.mergeGreen?.statuses ?? [];
  if (!config.mergeGreen || config.mergeGreen.enabled === false || !need.length) return;
  const rule = 'Green means every required check is successful on the pull request\'s current head; a missing, pending or unreadable check blocks the merge (release, Lanes and merging).'; if (!repo) { deny(refusal(rule, 'the repo could not be worked out', 'run from inside the repo or pass -R owner/repo')); return; } let n = number;
  if (!n) { const b = currentBranch(cwd); const list = ghJson(`repos/${repo}/pulls?head=${repo.split('/')[0]}:${b}`, cwd); n = list?.[0]?.number; } const pr = n ? ghJson(`repos/${repo}/pulls/${n}`, cwd) : null;
  const status = pr ? ghJson(`repos/${repo}/commits/${pr.head.sha}/status`, cwd) : null;
  if (!status) { deny(refusal(rule, `the statuses of pull request ${n ?? '(unknown)'} could not be read`, 'read them yourself (GH_PAGER=cat gh api repos/<repo>/commits/<sha>/status) and merge once they are green')); return; } for (const s of need) {
    const got = (status.statuses ?? []).find((x) => x.context === s.context);
    const good = got && got.state === 'success' && (!s.description || String(got.description ?? '').includes(s.description)); if (!good) { deny(refusal(rule, `${s.context} on ${pr.head.sha.slice(0, 7)} is ${got ? `${got.state}: ${got.description ?? ''}` : 'missing'}${s.description ? ` (needs success with "${s.description}")` : ''}`, 'wait for it in the foreground, then merge')); return; } }
}
const ghBody = (cmd, a) => {
  const direct = flagValues(a, ['--body', '-b']);
  const files = flagValues(a, ['--body-file', '-F']);
  let body = null;
  if (direct.length) body = direct.at(-1);
  else if (files.length) body = files.at(-1) === '-' ? cmd.heredoc : readText(resolve(cmd.cwd, files.at(-1))); const fromFile = /^\s*\$\(\s*cat\s+(['"]?)([^'"()\s]+)\1\s*\)\s*$/.exec(body ?? '');
  return fromFile ? readText(resolve(cmd.cwd, fromFile[2])) : body;
};
function checkPrFlowBash(cmd, config, deny) {
  if (cmd.prog !== 'gh') return;
  const p = ghParts(cmd);
  const repo = repoSlug(config, cmd.cwd, p.repo);
  if (p.sub === 'pr' && p.sub2 === 'create') { const a = p.rest.slice(1); checkPrCreate(config, cmd.cwd, repo, ghBody(cmd, a), hasFlag(a, ['--draft', '-d']), deny); return; } if (p.sub === 'pr' && (p.sub2 === 'ready' || p.sub2 === 'merge')) {
    const a = p.rest.slice(1);
    if (hasFlag(a, ['--undo', '--disable-auto'])) return;
    const url = a.find((w) => /\/pull\/\d+/.test(w));
    const number = a.find((w) => /^\d+$/.test(w)) ?? (url ? url.replace(/.*\/pull\/(\d+).*/, '$1') : null); checkLiveState(config, cmd.cwd, repo, number, `gh pr ${p.sub2}`, deny);
    checkReviewed(config, cmd.cwd, repo, number, `gh pr ${p.sub2}`, deny);
    if (p.sub2 === 'merge' && !hasFlag(a, ['--auto'])) checkMergeGreen(config, cmd.cwd, repo, number, deny); return;
  }
  const api = ghApi(cmd, config);
  if (!api) return;
  const m = /repos\/([^/]+\/[^/]+)\/pulls\/(\d+)\/(merge|ccr\/ready_for_review|ccr\/auto_merge)$/.exec(api.path); if (m && api.method !== 'GET' && api.method !== 'DELETE') {
    checkLiveState(config, cmd.cwd, m[1], m[2], `gh api ${m[3]}`, deny);
    checkReviewed(config, cmd.cwd, m[1], m[2], `gh api ${m[3]}`, deny);
    if (m[3] === 'merge') checkMergeGreen(config, cmd.cwd, m[1], m[2], deny);
  }
}

// ---------- the checks: files written ----------

function resultingText(input) {
  const path = input.file_path ?? input.path;
  if (!path) return null;
  const before = readText(path, 16 * 1024 * 1024) ?? '';
  if (typeof input.content === 'string') return { path, before, after: input.content };
  const edits = Array.isArray(input.edits) ? input.edits : [input];
  let after = before;
  for (const e of edits) {
    if (typeof e.old_string !== 'string' || typeof e.new_string !== 'string') continue;
    after = e.replace_all ? after.split(e.old_string).join(e.new_string) : after.replace(e.old_string, () => e.new_string); }
  return { path, before, after };
}
function checkFileWrite(input, config, root, deny) {
  const t = resultingText(input);
  if (!t) return;
  const rel = relative(root, resolve(root, t.path)).split(sep).join('/');
  if (rel.startsWith('..')) return;
  if (on(config, 'attribution') && /\.md$/i.test(rel) && !matchesAny(rel, config.attribution?.exemptPaths ?? ['tests/**'])) { const hits = attributionHits(addedLines(t.before, t.after).join('\n'), config, 'filePatterns');
    if (hits.length) deny(refusal('No Claude co-author, "Claude-Session" or "Generated with Claude Code" line in docs (CLAUDE.md, Identity).', `${rel} gains the line "${hits[0].trim()}"`, 'leave that line out')); }
  if (config.hostedRunners?.enabled === true && /^\.github\/workflows\/.+\.ya?ml$/.test(rel)) {
    const hit = hostedLabel(t.after, config);
    if (hit) deny(refusal(hostedRule, `${rel}: ${hit}`, hostedInstead(config)));
  }
  if (on(config, 'bypassFlags') && matchesAny(rel, config.bypassFlags?.configFiles ?? [])) {
    const added = addedLines(t.before, t.after).join('\n');
    const m = /passWithNoTests\s*:\s*true|--pass-?[wW]ith-?[nN]o-?[tT]ests|--retr(?:y|ies)(?:=|\s+)0*[1-9]|\bretr(?:y|ies)\s*:\s*(?!0\s*,?\s*(\/\/.*)?$)\S.*/m.exec(added); if (m) deny(refusal('Never loosen a check: no passing with no tests, no retries until green (build skill).', `${rel} gains "${m[0]}"`, 'leave the setting at its strict value; fix the test instead')); }
}

// ---------- the checks: MCP tools ----------

const toolMatches = (name, patterns = []) => patterns.some((p) => new RegExp(p).test(name));
function checkMcp(name, input, config, root, deny, ctx) {
  const repo = input.owner && input.repo ? `${input.owner}/${input.repo}` : repoSlug(config, root);
  if (config.agnostic && !(input.owner && input.repo)) return;
  const rel = (s) => String(s ?? '');
  // Owner's device.
  if (config.ownerDevice?.enabled === true && toolMatches(name, config.ownerDevice.tools)) deny(refusal('Nothing runs on the owner\'s computer or browser; work runs in the cloud (Owner; release, Where work runs).', `the tool ${name}`, 'run it in this cloud session, or start a cloud session that can')); // Screenshots through a browser tool.
  if (config.gpu?.enabled === true && toolMatches(name, config.gpu.mcpTools) && !toolMatches(name, config.gpu.mcpToolsAllowed) && !isGpuMachine(config, ctx.sessionId)) deny(refusal('Every screenshot happens on a GPU machine (Owner).', `the tool ${name}`, config.gpu.hint)); // GitHub API commits are authored by the token's account, not the configured author.
  if (on(config, 'identity') && toolMatches(name, config.identity?.commitTools)) deny(refusal(`Every commit is authored by ${config.author ?? 'the CLAUDE.md author'} (CLAUDE.md, Identity).`, `${name} writes a commit through the API, authored by the token's account`, 'commit with git in this session and push')); // Merge method, live state, green.
  const method = input.merge_method ?? input.mergeMethod;
  const isMerge = toolMatches(name, config.mcp?.mergeTools ?? ['merge_pull_request$']);
  const isAuto = toolMatches(name, config.mcp?.autoMergeTools ?? ['enable_pr_auto_merge$']);
  if (on(config, 'mergeMethod') && isAuto && !method) deny(refusal('Merge with a merge commit, never a squash or a rebase (CLAUDE.md, Identity).', `${name} with no merge method (GitHub would use the repository's default, which may be a squash)`, 'pass mergeMethod "MERGE"')); else if (on(config, 'mergeMethod') && (isMerge || isAuto) && method && String(method).toLowerCase() !== 'merge') deny(refusal('Merge with a merge commit, never a squash or a rebase (CLAUDE.md, Identity).', `${name} with merge_method ${method}`, 'merge_method "merge"')); const number = input.pullNumber ?? input.pull_number ?? input.number;
  const readyCall = toolMatches(name, config.mcp?.updatePrTools ?? ['update_pull_request$']) && input.draft === false; if (isMerge || isAuto || readyCall) checkLiveState(config, root, repo, number, readyCall ? 'marking it ready' : name, deny); if (isMerge || isAuto || readyCall) checkReviewed(config, root, repo, number, readyCall ? 'marking it ready' : name, deny); if (toolMatches(name, config.mcp?.createPrTools ?? ['create_pull_request$'])) checkPrCreate(config, root, repo, typeof input.body === 'string' ? input.body : '', input.draft === true, deny); if (isMerge) checkMergeGreen(config, root, repo, number, deny);
  // Pull request bodies.
  if (on(config, 'prBody') && toolMatches(name, config.mcp?.prBodyTools ?? ['create_pull_request$', 'update_pull_request$']) && typeof input.body === 'string') { const problems = judgeBody(input.body, config, false);
    if (problems.length) deny(refusal(PR_RULE, `the body: ${problems.join('; ')}`, `end the body with "${prLastLineOf(config)}" on its own last line`)); }
  // Commands handed to the owner.
  for (const t of config.ownerCommands?.tools ?? []) {
    if (config.ownerCommands.enabled === false || !new RegExp(t.tool).test(name)) continue;
    const text = (t.fields ?? ['text']).map((f) => rel(input[f])).join('\n');
    let fenced = false;
    for (const l of lines(text)) {
      if (/^\s*(```|~~~)/.test(l)) { fenced = !fenced; continue; }
      if (!fenced) continue;
      const s = l.trim().replace(/^\$\s+/, '');
      if (/^git\s/.test(s)) { deny(refusal('Every command handed to the owner uses gh, never plain git (Owner).', `"${s.slice(0, 80)}"`, 'the gh equivalent (gh repo clone, gh pr checkout, gh api ...)')); break; } if (/\bgh api\b/.test(s) && !/^GH_PAGER=cat\s/.test(s)) { deny(refusal('Every gh api command handed to the owner starts with GH_PAGER=cat (Owner).', `"${s.slice(0, 80)}"`, `GH_PAGER=cat ${s}`)); break; } }
  }
  // Session tools: effort cap, model and effort named, the full rule list in the brief.
  // Efforts up to the cap are allowed; anything else, a higher level included, is above it.
  const ranks = ['low', 'medium', 'high'];
  for (const t of config.sessionTools?.tools ?? []) {
    if (config.sessionTools.enabled === false || !new RegExp(t.tool).test(name)) continue;
    const effort = (t.effortFields ?? ['effort']).map((f) => input[f]).find((v) => typeof v === 'string'); const cap = config.sessionTools.maxEffort ?? 'high';
    if (effort && !ranks.slice(0, ranks.indexOf(cap) + 1).includes(effort)) deny(refusal(`Nothing runs above ${cap} effort (CLAUDE.md, Settings).`, `${name} with effort ${effort}`, `effort "${cap}" or lower, as Settings names for the role`)); const model = (t.modelFields ?? ['model']).map((f) => input[f]).find((v) => typeof v === 'string' && v); if (t.requireModelAndEffort && (!model || !effort)) deny(refusal('Every session names its model and effort, from Settings in CLAUDE.md.', `${name} with model ${model ?? 'unset'} and effort ${effort ?? 'unset'}`, 'name both')); if (t.requireModel && !model) deny(refusal(t.modelRule ?? 'Every session names its model, from Settings in CLAUDE.md.', `${name} with no model`, `name one: ${(t.models ?? []).join(', ') || 'the model Settings gives the role'}`)); if (model && t.models?.length && !t.models.some((m) => new RegExp(m, 'i').test(model))) deny(refusal(t.modelRule ?? 'Models come from Settings in CLAUDE.md (Models and effort).', `${name} with model ${model}`, `one of: ${t.models.join(', ')}`)); if (t.requireRulesInBrief) {
      const brief = (t.promptFields ?? ['prompt']).map((f) => rel(input[f])).join('\n').replace(/\s+/g, ' '); const missing = (config.inject?.rules ?? []).filter((r) => typeof r === 'object' && r.id && !brief.includes(`[${r.id}]`)); if (missing.length) deny(refusal('The coordinator pastes the FULL owner rule list into every thread brief (Owner).', `${missing.length} rules are missing from the brief: ${missing.map((r) => `[${r.id}]`).join(' ')}`, `paste these lines, ids included:\n${missing.map((r) => `- ${ruleLine(r)}`).join('\n')}`)); }
  }
}

const ruleLine = (r) => (typeof r === 'object' && r ? `[${r.id}] ${r.text}` : String(r));

// ---------- events ----------

function sessionStart(root, config, input) {
  const parts = [];
  const want = authorOf(config);
  const names = ['identity', 'attribution', 'forcePush', 'defaultBranchPush', 'mergeMethod', 'bypassFlags', 'prBody', 'prFlow', 'liveState', 'mergeGreen', 'ruleMix', 'gpu', 'hostedRunners', 'ownerDevice', 'ownerCommands', 'sessionTools', 'stop']; const state = names.map((n) => {
    const c = config[n];
    const enabled = n === 'gpu' || n === 'hostedRunners' || n === 'ownerDevice' || n === 'prFlow' ? c?.enabled === true : on(config, n) && !(n === 'mergeGreen' && !(c?.statuses ?? []).length); const blank = (n === 'identity' && !authorOf(config)) || (n === 'prBody' && !prLastLineOf(config)); return `${n} ${blank ? 'off (blank)' : enabled ? 'on' : 'off'}`;
  });
  const placeholders = blanksOf(config);
  const branch = currentBranch(root);
  const live = branch ? liveStatePath(config, branch) : null;
  const gitIdent = parseIdent(git(root, ['var', 'GIT_AUTHOR_IDENT']).out);
  parts.push(`# Rule hooks are on in this repo (${repoSlug(config, root) ?? root})`);
  parts.push(`Tool calls that break a rule below are refused before they run, with the reason. ${FOOTER}`); parts.push(`Checks: ${state.join(', ')}.${placeholders.length ? ` Blanks still in CLAUDE.md's Identity rule (their checks are off): ${placeholders.join(', ')}.` : ''}`); if (config.gpu?.enabled === true) parts.push(isGpuMachine(config, input.session_id) ? 'This machine is a GPU machine: rendering is allowed here.' : `This machine is NOT a GPU machine: screenshots, screen walks, visual specs and rendered runs are refused here. ${config.gpu.hint ?? ''}`); if (want) parts.push(`Commit identity: ${showIdent(want)}. git config here gives ${showIdent(gitIdent)}${sameIdent(gitIdent, want) ? ' (matches)' : ` (DOES NOT MATCH: git config user.name "${want.name}" && git config user.email "${want.email}")`}.`); if (branch) parts.push(`Branch ${branch}; your live-state file is ${live} (${existsSync(join(root, live)) ? 'exists' : 'not there yet'}).`); const claude = readText(join(root, 'CLAUDE.md')) ?? '';
  const m = /\n## Rules that never bend\n[\s\S]*?(?=\n## )/.exec(claude);
  if (m) parts.push(m[0].trim());
  const rules = config.inject?.rules ?? [];
  if (rules.length) parts.push(`## The owner's standing rules (ids in brackets; a thread brief pastes them all)\n\n${rules.map((r) => `- ${ruleLine(r)}`).join('\n')}`); parts.push(['## Where the rest is', '- Settings (numbers, models, limits): the Settings section of CLAUDE.md.', '- Skills: .claude/skills/; load the one that fits before that kind of work.', '- Where things stand: docs/superpowers/progress.md.', '- The project instructions also apply.', ...(config.inject?.pointers ?? []).map((p) => `- ${p}`)].join('\n')); const limit = config.inject?.maxChars ?? 9000;
  let text = '';
  for (const p of parts) {
    if ((text + p).length + 2 > limit) { text += `\n\n(The rest is in CLAUDE.md and .claude/hooks/rules.json; read them now.)`; break; } text += (text ? '\n\n' : '') + p;
  }
  return text;
}

function stop(root, config, input) {
  if (input.stop_hook_active) return null;
  const s = config.stop ?? {};
  if (s.enabled === false) return null;
  const branch = currentBranch(root);
  if (s.dirty !== false && branch && branch !== defaultBranch(config)) {
    const r = git(root, ['status', '--porcelain', '--untracked-files=no']);
    if (r.ok && r.out) return `Tracked files are changed and not committed on ${branch}:\n${r.out.split('\n').slice(0, 10).join('\n')}\nCommit your work (a WIP commit, never a stash) or say in your reply why it stays uncommitted. A session keeps its state in commits, not in its context (CLAUDE.md, Live state in a file).`; }
  if (s.ciPending !== false && branch) {
    const head = git(root, ['rev-parse', 'HEAD']).out;
    const up = git(root, ['rev-parse', '@{u}']);
    const repo = repoSlug(config, root);
    if (up.ok && up.out === head && repo) {
      const st = ghJson(`repos/${repo}/commits/${head}/status`, root);
      const pending = (st?.statuses ?? []).find((x) => x.state === 'pending');
      if (pending) return `CI is still running on ${head.slice(0, 7)} (${pending.context}: ${pending.description ?? 'pending'}). Watch it in the foreground and act the moment it ends (release); do not end the turn only to wait for it. If something else will wake you when it ends, say so in your reply.`; }
  }
  return null;
}

function laneNotice(root, config, input, rel) {
  const n = config.laneNotice;
  if (!n || n.enabled === false || !matchesAny(rel, n.paths ?? [])) return null;
  const file = join(tmpdir(), `claude-rules-lane-${String(input.session_id ?? 'none').replace(/[^\w-]/g, '')}.json`); let seen = [];
  try { seen = JSON.parse(readText(file) ?? '[]'); } catch { seen = []; }
  const group = (n.paths ?? []).find((g) => globToRegExp(g).test(rel));
  if (seen.includes(group)) return null;
  seen.push(group);
  try { writeFileSync(file, JSON.stringify(seen)); } catch { /* optional */ }
  return `${rel} is a lane 3 path (CLAUDE.md, Risk): it needs its lane's audits and the owner's approval or a recorded standing permission before it merges, and a rules or CI change goes in its own pull request.`; }

function postToolUse(root, config, input) {
  const name = input.tool_name;
  const ti = input.tool_input ?? {};
  const response = typeof input.tool_response === 'string' ? input.tool_response : JSON.stringify(input.tool_response ?? ''); const notes = [];
  const problems = [];
  if (name === 'Bash') {
    const cmds = simpleCommands(String(ti.command ?? ''), input.cwd ?? root);
    const committed = cmds.find((c) => c.prog === 'git' && makesCommit(gitParts(c)));
    const cScope = committed ? scopeFor(root, config, gitParts(committed).cwd, null) : null;
    if (committed && cScope && on(cScope.config, 'commitVerify')) {
      const g = gitParts(committed);
      const want = authorOf(cScope.config);
      const r = git(g.cwd, ['log', '-1', '--format=%h%x00%an%x00%ae%x00%cn%x00%ce%x00%B']);
      if (r.ok) {
        const [sha, an, ae, cn, ce, body] = r.out.split('\x00');
        if (want && (!sameIdent({ name: an, email: ae }, want) || !sameIdent({ name: cn, email: ce }, want))) problems.push(`Commit ${sha} is by ${an} <${ae}>, committed by ${cn} <${ce}>, not ${showIdent(want)}. Fix it before pushing: git config user.name "${want.name}" && git config user.email "${want.email}" && git commit --amend --reset-author --no-edit`); const hits = on(cScope.config, 'attribution') ? attributionHits(body, cScope.config) : [];
        if (hits.length) problems.push(`Commit ${sha} carries "${hits[0].trim()}". Reword it before pushing (git commit --amend).`); }
    }
    const prCall = cmds.find((c) => c.prog === 'gh' && ((ghParts(c).sub === 'pr' && ['create', 'edit'].includes(ghParts(c).sub2)) || /pulls(\/\d+)?$/.test(ghApi(c)?.path ?? ''))); const pScope = prCall ? scopeFor(root, config, prCall.cwd, ghParts(prCall).repo) : null;
    if (prCall && pScope && on(pScope.config, 'prBodyVerify') && pScope.config.prBodyVerify?.enabled !== false) { const p = ghParts(prCall);
      const number = (/\/pull\/(\d+)/.exec(response) ?? /"number":\s*(\d+)/.exec(response) ?? [])[1] ?? p.rest.slice(1).find((w) => /^\d+$/.test(w)) ?? (/pulls\/(\d+)/.exec(ghApi(prCall)?.path ?? '') ?? [])[1]; const repo = repoSlug(config, prCall.cwd, p.repo ?? (/repos\/([^/]+\/[^/]+)\/pulls/.exec(ghApi(prCall, pScope.config)?.path ?? '') ?? [])[1]); verifyBody(config, root, repo, number, problems);
    }
  } else if (/^(Write|Edit|MultiEdit)$/.test(name)) {
    const path = ti.file_path ?? ti.path;
    if (path) { const rel = relative(root, resolve(root, path)).split(sep).join('/'); const n = laneNotice(root, config, input, rel); if (n) notes.push(n); } } else if (toolMatches(name, config.mcp?.prBodyTools ?? ['create_pull_request$', 'update_pull_request$']) && on(config, 'prBodyVerify')) { const number = ti.pullNumber ?? ti.pull_number ?? (/\/pull\/(\d+)/.exec(response) ?? [])[1];
    const repo = ti.owner && ti.repo ? `${ti.owner}/${ti.repo}` : repoSlug(config, root);
    if (ti.body !== undefined || !ti.pullNumber) verifyBody(config, root, repo, number, problems);
  }
  if (problems.length) return { decision: 'block', reason: problems.join('\n\n') };
  if (notes.length) return { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: notes.join('\n') } }; return null;
}
function verifyBody(config, root, repo, number, problems) {
  if (!repo || !number) return;
  const pr = ghJson(`repos/${repo}/pulls/${number}`, root);
  if (!pr) return;
  const issues = judgeBody(pr.body ?? '', config, config.prBody?.footerStrippedByCi === true);
  if (issues.length) problems.push(`Pull request #${number}'s body as GitHub has it: ${issues.join('; ')}. ${PR_RULE} Write the right body to a file and apply it (gh pr edit ${number} --body-file <file>), then check the last line again.`); }

function preToolUse(root, config, input, ctx) {
  const base = config.detached ? repoless(config) : config;
  const reasons = [];
  const deny = (r) => { if (!reasons.includes(r)) reasons.push(r); };
  const name = input.tool_name;
  const ti = input.tool_input ?? {};
  if (name === 'Bash') {
    for (const cmd of simpleCommands(String(ti.command ?? ''), input.cwd ?? root)) {
      const scope = cmd.prog === 'git' ? scopeFor(root, config, gitParts(cmd).cwd, null) : cmd.prog === 'gh' ? scopeFor(root, config, cmd.cwd, ghParts(cmd).repo) : { root, config: base }; if (!scope) continue;
      for (const check of [checkIdentity, checkAttribution, checkForcePush, checkDefaultBranchPush, checkMergeMethod, checkBypassFlags, checkGpu, checkBanned, checkHostedRunnersOnPush, checkRuleMix, checkPrBodyBash, checkPrFlowBash]) { if (reasons.length) break;
        check(cmd, scope.config, deny, { ...ctx, root: scope.root });
      }
    }
  } else if (/^(Write|Edit|MultiEdit)$/.test(name)) {
    checkFileWrite(ti, base, root, deny);
  } else if (name?.startsWith('mcp__') || toolMatches(name ?? '', (config.sessionTools?.tools ?? []).map((t) => t.tool))) { const slug = ti.owner && ti.repo ? `${ti.owner}/${ti.repo}` : null;
    const scope = config.detached && !slug ? { root, config: base } : scopeFor(root, config, root, slug); const cfg = scope?.config ?? { ...config, identity: { enabled: false }, mergeMethod: { enabled: false }, prBody: { enabled: false }, liveState: { enabled: false }, mergeGreen: { enabled: false } }; checkMcp(name, ti, cfg, scope?.root ?? root, deny, ctx);
  }
  if (!reasons.length) return null;
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reasons.join('\n\n') } }; }

// ---------- finding the repo ----------

function findRoot(start) {
  let dir = resolve(start);
  for (;;) {
    if (existsSync(join(dir, '.claude', 'hooks', 'rules.json'))) return dir;
    const up = dirname(dir);
    if (up === dir) return null;
    dir = up;
  }
}
// The checks that need no repo: rendering, the owner's device, commands handed to the
// owner, session effort and briefs, banned commands, bypass flags.
const NEEDS_REPO = ['identity', 'attribution', 'commitVerify', 'forcePush', 'defaultBranchPush', 'mergeMethod', 'prBody', 'prBodyVerify', 'prFlow', 'liveState', 'mergeGreen', 'ruleMix', 'hostedRunners', 'laneNotice', 'stop']; function repoless(config) {
  const c = { ...config, detached: true };
  for (const k of NEEDS_REPO) c[k] = { ...(typeof config[k] === 'object' ? config[k] : {}), enabled: false }; return c;
}
function rootsBelow(dir) {
  try { return readdirSync(dir).map((d) => join(dir, d)).filter((d) => existsSync(join(d, '.claude', 'hooks', 'rules.json'))); } catch { return []; } }
function rootForCall(input) {
  const ti = input.tool_input ?? {};
  const starts = [];
  if (ti.file_path || ti.path) starts.push(dirname(resolve(input.cwd ?? '.', ti.file_path ?? ti.path))); if (input.tool_name === 'Bash') for (const c of simpleCommands(String(ti.command ?? ''), input.cwd ?? '.')) starts.push(c.prog === 'git' ? gitParts(c).cwd : c.cwd); if (input.cwd) starts.push(input.cwd);
  for (const s of starts) { const r = findRoot(s); if (r) return r; }
  const slug = ti.owner && ti.repo ? `${ti.owner}/${ti.repo}`.toLowerCase() : null;
  for (const r of rootsBelow(input.cwd ?? '.')) {
    if (!slug) continue;
    const c = loadConfig(r).config;
    if (c && String(repoSlug(c, r) ?? '').toLowerCase() === slug) return r;
  }
  return null;
}

// ---------- main ----------

function emit(obj) { if (obj) process.stdout.write(JSON.stringify(obj) + '\n'); }

// The user-level launcher: from the folder a session starts in, run the rules.mjs of the repo
// below. At session start it also says so when no repo below has one, so a missing hook is seen.
const LAUNCH_RUN = 'for f in "$CLAUDE_PROJECT_DIR"/*/.claude/hooks/rules.mjs; do [ -f "$f" ] && exec node "$f" --find-repo; done; '; const LAUNCH_NOTE = '[ -f "$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs" ] || echo "Rule hooks: no .claude/hooks/rules.mjs here or one folder below, so no rule is enforced."; '; const LAUNCH_EVENTS = [['SessionStart', null, LAUNCH_RUN + LAUNCH_NOTE + 'true'], ['PreToolUse', 'Bash|Write|Edit|MultiEdit|Agent|Workflow|mcp__.*', LAUNCH_RUN + 'true'], ['PostToolUse', 'Bash|Write|Edit|MultiEdit|mcp__.*', LAUNCH_RUN + 'true'], ['Stop', null, LAUNCH_RUN + 'true']]; // One installer, used two ways: `--install-user` runs it (a failure exits 1), and `--print-setup`
// prints it as a cloud setup script that needs no repo and never stops a session from starting.
const INSTALL_JS = [
  "const fs = require('fs'), path = require('path'), os = require('os');",
  "const p = path.join(process.env.HOME || os.homedir(), '.claude', 'settings.json');",
  "const quit = (why) => { console.error(`Rule hooks not added: ${p} ${why}. Nothing was changed.`); process.exit(process.env.RULES_INSTALL_STRICT ? 1 : 0); };", `const R = ${JSON.stringify(LAUNCH_RUN)};`,
  `const N = ${JSON.stringify(LAUNCH_NOTE)};`,
  `const E = [["SessionStart", null, R + N + "true"], ["PreToolUse", ${JSON.stringify(LAUNCH_EVENTS[1][1])}, R + "true"],`, `  ["PostToolUse", ${JSON.stringify(LAUNCH_EVENTS[2][1])}, R + "true"], ["Stop", null, R + "true"]];`, "const ok = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);",
  "const ours = (h) => ok(h) && /\\/\\.claude\\/hooks\\/rules\\.mjs\"?;? do /.test(String(h.command ?? ''));", "let text = null;",
  "try { if (fs.existsSync(p)) text = fs.readFileSync(p, 'utf8'); } catch (e) { quit(`could not be read (${e.code})`); }", "let s = {};",
  "try { if (text !== null) s = JSON.parse(text); } catch { quit('is not valid JSON'); }",
  "if (!ok(s) || (s.hooks !== undefined && !ok(s.hooks))) quit('is not in the usual shape');",
  "const hooks = { ...s.hooks };",
  "for (const [ev, m, c] of E) {",
  "  const list = hooks[ev] ?? [];",
  "  const odd = (e) => !ok(e) || (e.hooks !== undefined && !Array.isArray(e.hooks));",
  "  if (!Array.isArray(list) || list.some(odd)) quit(`is not in the usual shape at hooks.${ev}`);", "  // Only the launcher is taken out; the user's own hooks in the same entry stay.",
  "  const kept = [];",
  "  for (const e of list) {",
  "    const all = e.hooks ?? [], own = all.filter((h) => !ours(h));",
  "    if (own.length || own.length === all.length) kept.push(own.length === all.length ? e : { ...e, hooks: own });", "  }",
  "  hooks[ev] = [...kept, { ...(m ? { matcher: m } : {}), hooks: [{ type: 'command', command: c }] }];", "}",
  "const next = JSON.stringify({ ...s, hooks }, null, 2) + '\\n';",
  "if (text !== null && JSON.stringify(JSON.parse(text)) === JSON.stringify(JSON.parse(next))) {",
  "  console.log(`Rule hooks already in ${p}.`); process.exit(0);",
  "}",
  "try { fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, next); }",
  "catch (e) { quit(`could not be written (${e.code})`); }",
  "console.log(`Rule hooks added to ${p}: sessions started one folder above a repo now load its hooks.`);", ].join('\n');
const SETUP_SCRIPT = `# Rule hooks for sessions that start one folder above a repo. Needs no repo; never fails.\nnode - <<'RULES_HOOKS_JS' || true\n${INSTALL_JS}\nRULES_HOOKS_JS\n`; function installUser() {
  const r = spawnSync(process.execPath, ['-'], { input: INSTALL_JS, env: { ...process.env, RULES_INSTALL_STRICT: '1' }, encoding: 'utf8' }); process.stdout.write(r.stdout ?? '');
  process.stderr.write(r.stderr ?? '');
  if (r.status !== 0) { if (!r.stderr) console.error('Rule hooks not added. Nothing was changed.'); process.exit(1); } }

function main() {
  const argv = process.argv.slice(2);
  if (argv.includes('--install-user')) { installUser(); return; }
  if (argv.includes('--print-setup')) { process.stdout.write(SETUP_SCRIPT); return; }
  const findRepo = argv.includes('--find-repo');
  if (argv.includes('--check')) {
    const root = process.env.CLAUDE_PROJECT_DIR || resolve(SCRIPT_DIR, '..', '..');
    const { config, error } = loadConfig(root);
    if (error) { console.error(error); process.exit(1); }
    const blanks = [...new Set([...blanksOf(config), ...Object.entries(config).filter(([, v]) => isPlaceholder(v)).map(([k]) => k)])]; console.log(`CLAUDE.md and rules.json: ${blanks.length ? `blanks left: ${blanks.join(', ')}` : 'no blanks'}`); console.log(sessionStart(root, config, { session_id: 'check' }).split('\n').find((l) => l.startsWith('Checks:'))); console.log(config.gpu?.enabled === true ? `GPU machine: ${isGpuMachine(config, `check-${Date.now()}`) ? 'yes' : 'no'}` : 'GPU check: off'); process.exit(blanks.length && argv.includes('--strict') ? 1 : 0);
  }
  let raw = '';
  try { raw = readFileSync(0, 'utf8'); } catch { raw = ''; }
  const input = JSON.parse(raw);
  const event = input.hook_event_name;
  if (findRepo && process.env.CLAUDE_PROJECT_DIR && existsSync(join(process.env.CLAUDE_PROJECT_DIR, '.claude', 'hooks', 'rules.mjs'))) return; // the repo's own settings run it let roots;
  let detached = false;
  if (findRepo) {
    roots = event === 'SessionStart' ? rootsBelow(input.cwd ?? '.').concat(findRoot(input.cwd ?? '.') ?? []) : [rootForCall(input)].filter(Boolean); // A call that acts in no repo still meets the checks that need none, under the one config below. if (!roots.length && event === 'PreToolUse') { const below = rootsBelow(input.cwd ?? '.'); if (below.length === 1) { roots = below; detached = true; } } }
  else roots = [process.env.CLAUDE_PROJECT_DIR || resolve(SCRIPT_DIR, '..', '..')];
  roots = [...new Set(roots)];
  if (!roots.length) return;
  const ctx = { sessionId: input.session_id, root: roots[0] };
  if (event === 'SessionStart') {
    const texts = [];
    for (const root of roots) {
      const { config, error } = loadConfig(root);
      texts.push(error ? `RULE HOOKS ARE BROKEN in ${root}: ${error}. Fix .claude/hooks/rules.json before anything else; until then no rule is enforced.` : sessionStart(root, config, input)); }
    emit({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: texts.join('\n\n---\n\n') } }); return;
  }
  const root = roots[0];
  const loaded = loadConfig(root);
  const { error } = loaded;
  if (error) { emit({ systemMessage: `rules hook: ${error}; no rule check ran` }); return; }
  const config = detached ? { ...loaded.config, detached: true } : loaded.config; // repo checks still guard a repo the call names if (event === 'PreToolUse') emit(preToolUse(root, config, input, ctx));
  else if (event === 'PostToolUse') emit(postToolUse(root, config, input));
  else if (event === 'Stop' || event === 'SubagentStop') { const reason = stop(root, config, input); if (reason) emit({ decision: 'block', reason }); } }

try { main(); } catch (e) {
  emit({ systemMessage: `rules hook crashed: ${e?.message ?? e}; this check did not run` });
}
process.exitCode = 0;

Hook: rules.json

Save this as .claude/hooks/rules.json in your repo. It names nobody: the commit author and the pull request's last line come from the Identity rule in your `CLAUDE.md`, and while those are still blanks their checks stay off. The setup check fills in the repo's own values (Setup check in `release`).

{
  "defaultBranch": "main",
  "repo": "",
  "alsoGuards": [],
  "identity": {
    "enabled": true,
    "commitTools": [
      "^mcp__github__(create_or_update_file|push_files|delete_file|update_pull_request_branch)$"
    ],
    "allowCommitters": [
      "GitHub <noreply@github.com>"
    ]
  },
  "attribution": {
    "enabled": true,
    "patterns": [
      "^\\s*Co-Authored-By:.*(Claude|anthropic\\.com)",
      "^\\s*Claude-Session:",
      "^[\\s>*_]*(🤖\\s*)?Generated (by|with)\\b",
      "^\\s*https://claude\\.ai/code/session_"
    ],
    "filePatterns": [
      "^\\s*Co-Authored-By:.*(Claude|anthropic\\.com)",
      "^\\s*Claude-Session:",
      "^[\\s>*_]*(🤖\\s*)?Generated (by|with) .*Claude",
      "^\\s*https://claude\\.ai/code/session_"
    ],
    "exemptPaths": [
      "tests/**"
    ]
  },
  "commitVerify": {
    "enabled": true
  },
  "forcePush": {
    "enabled": true
  },
  "defaultBranchPush": {
    "enabled": true
  },
  "mergeMethod": {
    "enabled": true
  },
  "bypassFlags": {
    "enabled": true,
    "configFiles": [
      "*test*.config.*",
      "**/*test*.config.*",
      "playwright*.config.*",
      "**/playwright*.config.*",
      "cypress.config.*",
      "**/cypress.config.*",
      "package.json",
      "**/package.json",
      ".github/workflows/*"
    ]
  },
  "prBody": {
    "enabled": true,
    "footerStrippedByCi": false
  },
  "prBodyVerify": {
    "enabled": true
  },
  "prFlow": {
    "enabled": true,
    "maxOpenPrs": 3
  },
  "liveState": {
    "enabled": true,
    "path": "docs/superpowers/live/{branch}.md"
  },
  "mergeGreen": {
    "enabled": true,
    "statuses": []
  },
  "ruleMix": {
    "enabled": true,
    "firstTimeSetup": true,
    "rulePaths": [
      "CLAUDE.md",
      ".claude/skills/review/**",
      ".claude/skills/release/**",
      ".claude/skills/visual-check/**",
      ".claude/skills/build/**",
      ".claude/skills/staged-path/**",
      ".claude/skills/owner-updates/**",
      ".claude/skills/vertical-slice/**",
      ".claude/skills/scene-polish/**",
      ".github/workflows/**"
    ],
    "docPaths": [
      "docs/**",
      "*.md",
      "**/*.md",
      ".claude/**"
    ]
  },
  "gpu": {
    "enabled": true,
    "detect": {
      "env": "RULES_GPU",
      "command": [
        "nvidia-smi",
        "-L"
      ]
    },
    "softwareEnv": "",
    "renderCommands": [],
    "gpuOnlySpecs": [],
    "gpuOnlyProjects": [],
    "allowedHelpers": [],
    "captureCalls": [
      ".screenshot(",
      "toHaveScreenshot(",
      "toMatchSnapshot(",
      "recordVideo",
      "startScreencast",
      "captureScreenshot"
    ],
    "mcpTools": [
      "^mcp__.*(screenshot|screencast)"
    ],
    "mcpToolsAllowed": [
      "^mcp__.*([Ff]igma|[Pp]enpot|[Ss]ketch|[Cc]anva)"
    ],
    "hint": "Render on a GPU machine: the CI's GPU job or a cloud GPU pod (Where work runs in release)." },
  "hostedRunners": {
    "enabled": false,
    "labels": [
      "ubuntu",
      "windows",
      "macos"
    ],
    "hint": "Use the self-hosted runner labels the gate starts."
  },
  "ownerDevice": {
    "enabled": true,
    "tools": []
  },
  "ownerCommands": {
    "enabled": true,
    "tools": []
  },
  "sessionTools": {
    "enabled": true,
    "maxEffort": "high",
    "tools": [
      {
        "tool": "^Agent$",
        "effortFields": [
          "effort"
        ],
        "requireModel": true,
        "models": [
          "^haiku$",
          "^claude-haiku-5"
        ],
        "modelRule": "A subagent is a narrow read-only helper on the helper model in Settings (CLAUDE.md, Limits; Settings)." },
      {
        "tool": "^Workflow$",
        "effortFields": [
          "effort"
        ]
      }
    ]
  },
  "bannedCommands": [],
  "laneNotice": {
    "enabled": true,
    "paths": [
      "CLAUDE.md",
      ".claude/**",
      ".github/workflows/**"
    ]
  },
  "stop": {
    "enabled": true,
    "dirty": true,
    "ciPending": true
  },
  "mcp": {
    "mergeTools": [
      "merge_pull_request$"
    ],
    "autoMergeTools": [
      "enable_pr_auto_merge$"
    ],
    "updatePrTools": [
      "update_pull_request$"
    ],
    "prBodyTools": [
      "create_pull_request$",
      "update_pull_request$"
    ]
  },
  "inject": {
    "maxChars": 9000,
    "rules": [],
    "syncNote": "A new owner rule goes to project memory in the turn it is given and into inject.rules (with a new id) in the next rule-change pull request; the brief check only knows ids listed here." }
}

Project instructions

Paste this into your Claude project's instructions. It is not saved in the repo, so Copy all leaves it out.

You coordinate work on [PROJECT] in [REPO URL] (or "no repo yet").

The CLAUDE.md and skills in this project's files are how you run the work, not only files to commit. These rules govern you and every session you start from the first message, before the repo exists. Once they are merged, the repo's copies win over this project's files.

- With no repo yet, run the setup check in `release` first. Before building, list every step only the owner can run as one batch of CLI commands. Bootstrap from the owner's own rules text is lane 2, and the owner's request is the standing permission for the setup check.
- If you cannot write to the repo, the implementer writes `progress.md` and `history.md` for you and says so in the commit.
- Timestamps come from `date`, never typed by hand.
- Use `gh` over `git` wherever both can do the job. Every command you hand the owner uses `gh`, never plain `git`.
- Bring every thread's decision card to the owner at once, even when they are away. Decide everything else by your own recommendation and report after.
- Create sessions to run commands: when you cannot run a command yourself, start a session that can, in the cloud. Nothing runs on the owner's computer, on a public or a private repo; a GPU comes from a cloud GPU pod.
- Make sure finished threads resolve: archive each session when its work is done (or list it for the owner to close when archiving is unavailable), and resolve each pull request review thread once it is addressed.
- Compile screenshots in one easy-to-navigate Claude artifact and share its link, instead of scattering them across messages. It is for viewing, not keeping: once the owner has looked, it is no longer needed (Screens page in `visual-check`).
- Name the model and effort of every session you start, from Settings in CLAUDE.md.
- Tell every thread you start to use Graphify when the repo is indexed in it.
- Save each owner instruction to project memory in the turn it is given, as well as in `progress.md`.
- Keep the owner informed as the `owner-updates` skill says.

Start prompt

Paste this as your first message to the coordinator, with its blanks filled in. It is not saved in the repo, so Copy all leaves it out.

You coordinate [PROJECT]. The repo is [REPO URL] (or "no repo yet").

The outcome I want: [OUTCOME]

Run the work by the CLAUDE.md and skills in this project's files, or in the repo if you use no Claude project; once they are merged, the repo's copies win. Read CLAUDE.md first, then load the skill whose description fits each step.

- First, run the setup check in `release`. With no repo yet, list every step only I can run as one batch of CLI commands.
- Then tell me the outcome you are building, your important assumptions, the first step and when I will first see working output.
- If the game has no playable slice yet, load `vertical-slice` and start there.
- After that, keep going within this brief. Ask me only for the choices that are mine, each as a decision card with a recommendation.

Default stack

Read this when you set up a new game. It is not saved in the repo or pasted into your project's instructions, so Copy all leaves it out. Add it to your Claude project's files, or paste it under the Start prompt, so the setup check starts from it.

# Default stack for a game

These are the owner's defaults for a new game. The setup check starts from them and writes the ones it uses into the setup brief. A game changes any of them with the owner's OK, recorded in the brief. The rules in CLAUDE.md and the skills still apply as written; this list only names the services they are met with.

Reference: Floor Fifty (github.com/SNEKPRTY/FloorFifty, private). Its `docs/release.md` covers the server, `tools/ci/gate-worker` and `tools/ci/runpod.ts` cover the gate, and pull request #249 (in review on 2026-11-19) moves CI screenshots to R2.

- **Code:** Node 24, pnpm 10 workspace, TypeScript. PixiJS for the game, Colyseus for an authoritative server, bun for tests and checks (Making CI fast in `release`): `bun test` for tests (test files keep their `vitest` imports), `bun check` for the typecheck on TypeScript 7, `bun lint` for lint (it reads `.oxlintrc.json`) and `bun fmt` for formatting, in place of Vitest, `tsc`, oxlint and oxfmt. Playwright for browser tests, run in its own image pinned by digest, with `--user 1001 --ipc=host`.
- **Checks and tests:** RunPod, billed by the minute. CPU pods run everything that does not render (install, lint, typecheck, unit tests, build). GPU pods run only what renders, RTX 5090 first, then cheaper NVIDIA GPUs under $3 an hour. The CI cap is $50 a month.
- **The gate:** a free Cloudflare Worker. The repo's webhook tells it when a pull request's run starts; it starts one lead pod for that run and deletes it when the run ends. No job runs on GitHub's own runners, so a private repo uses no GitHub minutes. The Worker redeploys itself from `main`.
- **Game server:** Fly.io, region `ord`. Start on shared-cpu-2x with 512 MB (about $5.49 a month in `ord`), which held 10 four-player rooms in Floor Fifty's load test (pull request #250, merged on 2026-11-19); shared-cpu-1x held only 2 to 3. Size each game from its own full-room load test; the owner's ceiling is $10 a month. A paid account, never the free trial, which stops every machine after 5 minutes. Auto-stop off, one machine always running, an uptime check on the health endpoint and a daily log report.
- **CI screenshots:** on a private repo, Cloudflare R2, deleted 3 hours after upload, with a 1-day lifecycle rule behind that. Nothing goes to GitHub's artifact storage there. On a public repo, GitHub's artifact storage, which is free and has no limit.
- **Where the game is played:** Ruken, which serves the game's files and lists its server's address.
- **Alerts:** a GitHub issue assigned to the owner and @-mentioning them, opened by the gate's GitHub App so GitHub emails them; recovery comments and closes it. No paid email service. Floor Fifty's design is pull request #262 (spec, in review on 2026-11-19).
- **Rollback:** a rollback input on the release workflow that redeploys an earlier image from Fly's release list on today's machine, as in Floor Fifty's pull request #261 (in review on 2026-11-19).
- **Keys:** one per provider (GitHub App, RunPod, Cloudflare, Fly), each made once at setup with every permission it will need and checked against every endpoint before it is saved. The owner's setup is one bundled paste.

Use when you are starting a game and want its work to run as staged agent sessions with written handoffs. Follow the Start here box: fill in the blanks, save CLAUDE.md in the repo root, save each skill under .claude/skills, and start the coordinator with the Start prompt. Copy gives one block; Copy all gives every repo block in order with where to save each. In a downloaded copy, save each fenced block at the path its line names.

Fill in

  • [PROJECT]
  • [WHAT IT IS FOR]
  • [STACK]
  • [INSTALL COMMAND]
  • [LINT COMMAND]
  • [TYPECHECK COMMAND]
  • [TEST COMMAND]
  • [BUILD COMMAND]
  • [COMMIT AUTHOR]
  • [OWNER NAME]
  • [WIDE PATHS]
  • [HARD-TO-UNDO PATHS]
  • [GOAL]
  • [OPTIONAL REFERENCES]
  • [{ "type": "command", "command": "cat \"$CLAUDE_PROJECT_DIR/.claude/after-compaction.md\"" }]
  • [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 10 }]
  • [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 30 }]
  • [{ "type": "command", "command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs\"", "timeout": 15 }]
  • [A-Z]
  • [A-Z0-9 _-]
  • [^/]
  • [^>]
  • [^\]
  • [^<\n]
  • [^>\n]
  • [^"\n]
  • ['author', 'prLastLine']
  • [name]
  • [';;', '&&', '||', '|&', ';', '|', '&', '\n', '(', ')']
  • [i + 1]
  • [i + 2]
  • [\s;&|()<>]
  • [\s;&|()]
  • [0-9]
  • [A-Za-z_]
  • [A-Za-z0-9_]
  • [...c.words]
  • [k, ...v]
  • [ugpChDrtURC]
  • [ci + 1]
  • [IdLnPsE]
  • ['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']
  • [a-z+]
  • [^:]
  • [^/\s?#]
  • [/?#]
  • [ri + 1]
  • [++i]
  • ['-f', '-F', '--field', '--raw-field']
  • ['-H', '--header', '-q', '--jq', '-t', '--template', '--cache', '--hostname', '-p', '--preview']
  • [k, v]
  • ['commit', 'merge', 'revert', 'cherry-pick', 'am', 'pull', 'rebase']
  • ['--abort', '--quit', '--skip', '-h', '--help']
  • ['--ff-only']
  • ['--dry-run']
  • ['-c', c]
  • ['rev-parse', '--is-shallow-repository']
  • ['--depth=50']
  • ['for-each-ref', '--count=1', 'refs/remotes']
  • ['log', '--format=%H%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x1e', '-n', '200', src, '--not', '--remotes']
  • [sha, an, ae, cn, ce, body]
  • ['for-each-ref', '--format=%(refname:short)', 'refs/heads']
  • ['-o', '--push-option', '--repo', '--receive-pack', '--exec']
  • ['--all', '--branches', '--mirror']
  • ['HEAD']
  • ['branch', '--show-current']
  • ['rev-parse', '--show-toplevel']
  • [key]
  • ['prBody', 'prBodyVerify', 'prFlow', 'liveState', 'mergeGreen', 'ruleMix', 'hostedRunners', 'laneNotice']
  • ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD']
  • ['--delete', '-d', '-n', '--dry-run']
  • ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']
  • [up.ok ? up.out.split('/').slice(1).join('/') : currentBranch(g.cwd)]
  • ['ls-remote', '--heads', remote]
  • ['--author']
  • [...configArgs(g.config), 'var', 'GIT_AUTHOR_IDENT']
  • [...configArgs(g.config), 'var', 'GIT_COMMITTER_IDENT']
  • ['-m', '--message']
  • ['-F', '--file']
  • ['-C', '-c', '--reuse-message', '--reedit-message']
  • ['log', '-1', '--format=%B', ref]
  • ['--amend']
  • ['log', '-1', '--format=%B']
  • ['--delete', '-d']
  • [a-zA-Z]
  • ['--squash']
  • ['--squash', '-s', '--rebase', '-r']
  • ['--merge', '-m', '--disable-auto']
  • ['--no-verify']
  • ['--admin']
  • ['--passWithNoTests', '--pass-with-no-tests']
  • ['--retries', '--retry']
  • [d.env]
  • [^\w-]
  • [^"']
  • ["']
  • ['', '.ts', '.mts', '.js', '.mjs', '.cjs', '.tsx', '/index.ts', '/index.js']
  • [cm]
  • [jt]
  • ['node_modules', '.git', 'dist', 'build', 'coverage', 'test-results', 'playwright-report', '.pnpm-store']
  • [abs]
  • ['bash', 'sh', 'zsh']
  • [g.softwareEnv]
  • ['node', 'tsx', 'vite-node', 'bun', 'deno', 'python', 'python3', 'ts-node']
  • ['-e', '--eval', '-p', '--print', '-c']
  • [evalFlag + 1]
  • [evalFlag]
  • ['-r', '--require', '--import', '--loader', '--env-file', '-m']
  • ['run', 'eval']
  • [prog, sub]
  • ['diff', '--name-only', `origin/${defaultBranch(config)}...${src}`, '--', '.github/workflows']
  • ['show', `${src}:${f}`]
  • ['ubuntu', 'windows', 'macos']
  • [^\\w./:-]
  • [\\w.]
  • [\\w]
  • ['diff', '--name-only', `origin/${defaultBranch(config)}...${src}`]
  • ['docs/**', '*.md', '**/*.md', '.claude/**']
  • [\s>*_]
  • ['--body', '-b', '--body-file', '-F']
  • ['--fill', '--fill-first', '--fill-verbose', '-f']
  • [A-Za-z_(]
  • [123]
  • [...String(body ?? '').matchAll(LANE)]
  • [^)]
  • [^0-9a-z>]
  • [0-9a-f]
  • [^A-Za-z0-9]
  • [A-Za-z]
  • ['merge-base', '--is-ancestor', from, head]
  • ['rev-list', '--parents', `${from}..${head}`, '--not', `origin/${defaultBranch(config)}`]
  • [c, p1, p2, ...more]
  • ['merge-base', '--is-ancestor', p2, `origin/${defaultBranch(config)}`]
  • ['merge-tree', '--write-tree', p1, p2]
  • ['rev-parse', `${c}^{tree}`]
  • ['diff', '--name-only', `origin/${defaultBranch(config)}...HEAD`]
  • ['docs/**', '*.md', '**/*.md']
  • [...comments, ...reviews]
  • ['remote', 'get-url', 'origin']
  • [^/.]
  • ['api', path]
  • ['api', `repos/${repo}/contents/${path}?ref=${encodeURIComponent(branch)}`, '--silent']
  • ['cat-file', '-e', `HEAD:${path}`]
  • ['--body', '-b']
  • ['--body-file', '-F']
  • ['"]
  • [^'"()\s]
  • ['--draft', '-d']
  • ['--undo', '--disable-auto']
  • ['--auto']
  • [input]
  • ['tests/**']
  • [wW]
  • [nN]
  • [tT]
  • [1-9]
  • ['merge_pull_request$']
  • ['enable_pr_auto_merge$']
  • ['update_pull_request$']
  • ['create_pull_request$']
  • ['create_pull_request$', 'update_pull_request$']
  • ['text']
  • ['low', 'medium', 'high']
  • ['effort']
  • ['model']
  • ['prompt']
  • [${r.id}]
  • ['var', 'GIT_AUTHOR_IDENT']
  • [\s\S]
  • ['status', '--porcelain', '--untracked-files=no']
  • ['rev-parse', 'HEAD']
  • ['rev-parse', '@{u}']
  • ['log', '-1', '--format=%h%x00%an%x00%ae%x00%cn%x00%ce%x00%B']
  • ['create', 'edit']
  • [-f "$f"]
  • [-f "$CLAUDE_PROJECT_DIR/.claude/hooks/rules.mjs"]
  • ['SessionStart', null, LAUNCH_RUN + LAUNCH_NOTE + 'true']
  • ['PreToolUse', 'Bash|Write|Edit|MultiEdit|Agent|Workflow|mcp__.*', LAUNCH_RUN + 'true']
  • ['PostToolUse', 'Bash|Write|Edit|MultiEdit|mcp__.*', LAUNCH_RUN + 'true']
  • ['Stop', null, LAUNCH_RUN + 'true']
  • ["SessionStart", null, R + N + "true"]
  • ["Stop", null, R + "true"]
  • [ev, m, c]
  • [ev]
  • [{ type: 'command', command: c }]
  • ['-']
  • [, v]
  • [rootForCall(input)]
  • [process.env.CLAUDE_PROJECT_DIR || resolve(SCRIPT_DIR, '..', '..')]
  • [...new Set(roots)]
  • [\\s>*_]
  • [Ff]
  • [Pp]
  • [Ss]
  • [Cc]
  • [REPO URL]
  • [OUTCOME]